Home >Backend Development >PHP Tutorial >Managing API Rate Limits in Laravel Through Job Throttling

Managing API Rate Limits in Laravel Through Job Throttling

James Robert Taylor
James Robert TaylorOriginal
2025-03-06 01:44:08326browse

Managing API Rate Limits in Laravel Through Job Throttling

Efficiently managing API rate limits is crucial when integrating with external services like AWS SES for email delivery. Laravel offers a streamlined solution using Redis::throttle to control the flow of queued jobs, preventing API flooding and potential service disruptions. Let's explore a practical implementation.

Leveraging Redis::throttle

Laravel's Redis::throttle provides a robust mechanism for regulating queued job execution. This ensures adherence to API rate limits, avoiding temporary or permanent service blocks. The basic structure is as follows:

Redis::throttle('key-name')
    ->allow(10) // Allow 10 requests
    ->every(5) // Within a 5-second window
    ->then(function () {
        // Your job logic here
    });

Practical Example: AWS SES Email Delivery

Let's create a middleware system for managing email sending rates with AWS SES:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Redis;

class EmailRateLimit
{
    public function handle($job, Closure $next)
    {
        Redis::throttle('email-throttle')
            ->allow(10)
            ->every(2)
            ->block(2) // Wait 2 seconds if throttled
            ->then(function () use ($job, $next) {
                $next($job);
            }, function () use ($job) {
                $job->release(30); // Release after 30 seconds
            });
    }
}

This middleware will be applied to our email notification system:

<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Notification;
use Illuminate\Notifications\Messages\MailMessage;
use App\Http\Middleware\EmailRateLimit;

class EmailDispatch extends Notification implements ShouldQueue
{
    use Queueable;

    public $content;

    public function __construct($content)
    {
        $this->content = $content;
    }

    // ... (rest of the Notification class remains the same) ...

    public function middleware(): array
    {
        return [new EmailRateLimit];
    }
}

Finally, integrating this into a controller:

<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Notifications\EmailDispatch;
use Illuminate\Http\Request;

class MailController extends Controller
{
    public function dispatch(Request $request)
    {
        $content = [
            'subject' => 'Important Update',
            'body' => 'Your account has been updated successfully.'
        ];

        $user = User::find($request->user_id);
        $user->notify(new EmailDispatch($content));

        return response()->json(['message' => 'Email queued for delivery']);
    }
}

This comprehensive approach ensures your application respects API rate limits while maintaining efficient email delivery via AWS SES or any compatible email service provider. The use of middleware cleanly separates the rate-limiting logic from your core application code.

The above is the detailed content of Managing API Rate Limits in Laravel Through Job Throttling. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn