ENGINEERING JOURNAL

API Rate Limiting with Redis in Laravel

How to add API rate limiting in Laravel with Redis: throttle middleware, named limiters, and Redis throttling for queue workers.

THE ARTICLE 01 — 03

An API without rate limiting is an open invitation. One buggy client in a retry loop, one scraper hitting every endpoint, or one bad deploy hammering your login route, and your database is doing work for requests that should never have reached it. Laravel ships with rate limiting built in, and pairing it with Redis makes it fast enough to sit in front of every request without becoming a bottleneck itself.

Start with the throttle middleware

Laravel's throttle middleware is the quickest win. Attach it to a route group and every request to those routes counts against a limit:

Route::middleware('throttle:60,1')->group(function () {
    Route::get('/api/orders', [OrderController::class, 'index']);
    Route::post('/api/orders', [OrderController::class, 'store']);
});

That allows 60 requests per minute per client. When the limit is hit, Laravel returns a 429 response with a Retry-After header, so well-behaved clients back off on their own. The default limiter keys by IP address for guests and by user ID for authenticated users, which is a sensible default for most APIs.

Why Redis instead of the file or database cache

Rate limiting is a counter problem: increment a key, check the value, expire it when the window ends. That has to happen on every single request, so the store behind it must be fast and atomic. The file cache driver does a disk read and write per request. The database driver adds a query per request to the very database you are trying to protect. Redis does an atomic increment in memory, which is exactly the operation you want here.

Set it in .env:

CACHE_STORE=redis
REDIS_CLIENT=phpredis
REDIS_HOST=127.0.0.1
REDIS_PORT=6379

With the cache store on Redis, Laravel's built-in limiters use it automatically. No extra package, no extra service to run beyond the Redis instance you probably already have for queues. If you have used Redis locks to stop a cache stampede, the same instance can carry your rate limits too. I wrote about that pattern in preventing a Redis cache stampede with locks in Laravel.

Define a named limiter for the routes that matter

A single global limit is rarely right. Login attempts deserve a much tighter limit than a read-only list endpoint, and an expensive report endpoint deserves a tighter limit than a cheap lookup. Define named limiters in bootstrap/app.php (Laravel 11) or in your RouteServiceProvider (Laravel 10 and earlier):

use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;

RateLimiter::for('login', function (Request $request) {
    return Limit::perMinute(5)->by($request->ip());
});

RateLimiter::for('api', function (Request $request) {
    return Limit::perMinute(120)->by($request->user()?->id ?: $request->ip());
});

Then attach them by name:

Route::post('/login', [AuthController::class, 'login'])
    ->middleware('throttle:login');

Route::middleware(['auth:sanctum', 'throttle:api'])->group(function () {
    // your API routes
});

Keying the login limiter by IP stops brute force attempts. Keying the API limiter by user ID means one abusive account cannot eat the allowance of everyone behind the same office NAT.

Rate limit inside your code, not just on routes

Some actions are not tied to a route. Sending a password reset email, triggering an export, or calling a paid third-party API from a queued job are all places where an unbounded loop hurts. Use the RateLimiter facade directly:

use Illuminate\Support\Facades\RateLimiter;

$executed = RateLimiter::attempt(
    'send-reset:' . $user->id,
    $perMinute = 3,
    function () use ($user) {
        $user->sendPasswordResetNotification();
    }
);

if (! $executed) {
    return back()->withErrors(['email' => 'Too many reset emails. Try again in a minute.']);
}

The same facade gives you RateLimiter::tooManyAttempts($key, $maxAttempts) and RateLimiter::remaining($key, $maxAttempts) when you need to check before doing work, and RateLimiter::clear($key) to reset a key after a successful login, so a user who finally remembers their password is not locked out by their own failed attempts.

Use Redis throttling for jobs and shared resources

When several queue workers can run the same job at once, a route limiter does not help. Laravel's Redis throttler gives you a distributed lock with a rate:

use Illuminate\Support\Facades\Redis;

Redis::throttle('stripe-sync')->allow(10)->every(60)->then(function () {
    // call the third-party API, at most 10 times a minute
}, function () {
    // could not obtain the lock; release the job back to the queue
    $this->release(30);
});

This is the same tool for a different problem: protecting a downstream service with its own limits, rather than protecting your own API from callers. If your workers share one Redis instance, the limit holds across all of them, which is the whole point.

What to watch after you ship it

Rate limiting fails in boring ways, and you want to catch them early. Check three things in the first week. First, confirm 429s are actually happening by watching your logs for the status code, because a misconfigured limiter that never fires is worse than none at all. Second, watch for legitimate users hitting the limit, which usually means the limit is too low for a real workflow, or the key is wrong, such as keying by a shared corporate IP instead of by user. Third, check the Redis memory usage for the limiter keys. Laravel expires them automatically, but if you build custom keys, make sure they carry a TTL or they will accumulate.

One more thing: tell your API consumers the limits exist. Document the per-minute allowance and the 429 response in the same place you document the endpoints. A client that knows the limit can implement backoff. A client that discovers it by accident will file a bug report.

Takeaway

Rate limiting is cheap insurance. Laravel gives you the middleware, the named limiters, and the facade; Redis gives you the atomic counters to make it fast. Start with the throttle middleware on your API routes, give sensitive actions like login their own tight limiter, and use the Redis throttler wherever queue workers share a downstream service. Your database will thank you the first time a client goes wrong.

Muhammad Aqib ← ALL ARTICLES
KEEP EXPLORING

More ideas.
Better engineering.

Explore the journal ↗