CodeBodh

API Rate Limiting at Scale: Redis Token Bucket & Lua Scripts

Implement distributed API rate limiting at scale using Redis token buckets, atomic Lua scripts, sliding windows, and HTTP 429 headers in production.

Team CodeBodh By Team CodeBodh
Nov 22, 2026
10 min read
11 views
API Rate Limiting at Scale: Redis Token Bucket & Lua Scripts

Executive Summary: Distributed API Rate Limiting Under High Concurrency

When a misconfigured webhook client or credential-stuffing botnet fires 12,000 requests per second at an unthrottled endpoint, database connection pools saturate within seconds and legitimate tenants experience cascading timeouts. In-memory rate limiters inside individual PHP-FPM workers or container replicas fail in horizontally scaled clusters because each node tracks only a fraction of incoming traffic, allowing attackers to multiply their effective quota by the replica count.

Implementing distributed API rate limiting with Redis and atomic Lua scripts solves this split-brain problem while keeping quota checks under 0.6 ms at p99. By combining edge pre-filtering in Nginx with a Redis-backed Token Bucket or Sliding Window Counter, backend teams can absorb legitimate traffic bursts, enforce per-tenant fairness, and return standards-compliant HTTP 429 responses without burning application compute.


1. Why Naive Rate Limiters Fail in Distributed Backends

Many teams start with a simple Fixed Window Counter using separate Redis INCR and EXPIRE calls from application code. That pattern breaks under two distinct failure modes: race conditions between commands and boundary burst amplification. If a worker crashes or times out between INCR and EXPIRE, the counter key persists indefinitely without a TTL, permanently locking out a paying customer until manual intervention.

Even when wrapped in a MULTI/EXEC transaction, Fixed Window Counters suffer from the 2x boundary spike problem. A client limited to 100 requests per minute can fire 100 requests at 12:00:59 and another 100 requests at 12:01:01, pushing 200 requests through your modular monolith SaaS architecture in PHP 8 within two seconds. Production gateways require algorithms that smooth bursts and execute state transitions atomically inside Redis.

+-----------------------------------------------------------------------+

|             Distributed API Rate Limiting Request Pipeline            |
|---|+-----------------------------------------------------------------------+
  Client Request (API Key / Tenant ID / IP)
                      |
                      v
+-----------------------------------------------------------------------+
|  1. Edge Pre-Filter (Nginx limit_req_zone - Shared Memory Ring)       |
|     - Drops obvious DDoS / flood spikes before touching PHP-FPM       |
+-----------------------------------------------------------------------+
                      | (Passes edge threshold)
                      v
+-----------------------------------------------------------------------+
|  2. Application Middleware (PHP 8.3 PSR-15 RateLimiter)               |
|     - Resolves composite key: rl:{tier}:{tenant_id}:{route_group}     |
|     - Calls Redis EVALSHA (Cached Token Bucket Lua Script)            |
+-----------------------------------------------------------------------+
                      |
        +-------------+-------------+
        |                           |
  [Tokens >= 1]               [Tokens < 1]
        |                           |
        v                           v
  Forward to Handler          Return HTTP 429 Too Many Requests
  + X-RateLimit-Remaining     + Retry-After & RateLimit-Reset Headers

2. Rate Limiting Algorithms Compared: Token Bucket vs. Sliding Window

Choosing the right algorithm depends on whether your API must tolerate short client bursts (such as mobile apps syncing offline queues) or enforce strict uniform pacing (such as downstream payment gateways). As outlined in the Redis rate limiting architecture glossary, four core algorithms dominate production deployments:

  • Token Bucket: A bucket holds up to capacity tokens and refills at a steady refill_rate per second. Each request consumes one token. Because unused tokens accumulate up to the capacity ceiling, legitimate clients can burst smoothly after idle periods while sustained averages stay capped.
  • Leaky Bucket: Requests enter a fixed-size FIFO queue and drain at a constant rate. This smooths downstream traffic into a flat line, making it ideal for protecting fragile legacy upstreams, though bursty clients face added queuing latency.
  • Sliding Window Log: Stores a timestamp per request inside a Redis Sorted Set (ZSET) and prunes entries older than the window. Accuracy is exact, but memory grows linearly with request volume—storing 10,000 timestamps per user across 100,000 users consumes hundreds of megabytes of RAM.
  • Sliding Window Counter: Blends the previous fixed window's count with the current window's count weighted by elapsed overlap time. It achieves near-exact accuracy using only two integer keys per tenant.
Algorithm Redis Data Structure Memory Per Key Burst Handling Best Production Fit
Fixed Window Counter String (INCR + EXPIRE) ~64 bytes Poor (2x edge spikes) Coarse IP flood protection
Sliding Window Log Sorted Set (ZSET) High (O(N) requests) Strict (zero boundary spike) Low-volume high-value endpoints (OTP, password reset)
Sliding Window Counter Two String/Hash counters ~128 bytes Smooth approximation High-volume SaaS API quotas
Token Bucket (Lua) Hash (tokens, ts) ~120 bytes Controlled bursts up to capacity General-purpose REST/GraphQL APIs & webhooks

3. Atomic Redis Lua Scripting & Cluster Key Tagging

Redis executes Lua scripts inside its single-threaded event loop, guaranteeing that all reads, math, and writes within a script complete atomically without interleaving commands from other clients. According to the official Redis Lua scripting documentation, using EVALSHA avoids transmitting the script body on every request, reducing network overhead to a 40-byte SHA-1 hash.

Two production rules prevent subtle failures in clustered Redis deployments:

  • Explicit Key Passing: Every Redis key accessed by the script must be passed via the KEYS array rather than concatenated dynamically inside Lua. In Redis Cluster, keys must hash to the same slot—use hash tags such as rl:{tenant_42}:api when a single script touches multiple keys for one tenant.
  • Server-Side or Synchronized Clocks: Calling redis.call('TIME') inside Lua (supported safely in Redis 5.0+ effects replication) eliminates clock skew between PHP/Go app servers, ensuring token refill math remains consistent across dozens of containers.

The Lua script below implements a production-ready Token Bucket that returns four values in a single round-trip: whether the request is allowed (1 or 0), remaining tokens, exact retry-after seconds, and reset timestamp.

-- token_bucket.lua
-- KEYS[1] = rate limit hash key (e.g., "rl:{tenant_42}:orders")
-- ARGV[1] = capacity (max burst tokens, e.g., 100)
-- ARGV[2] = refill_rate (tokens per second, e.g., 10)
-- ARGV[3] = requested_tokens (usually 1; higher for expensive endpoints)

local key = KEYS[1]
local capacity = tonumber(ARGV[1])
local refill_rate = tonumber(ARGV[2])
local requested = tonumber(ARGV[3])

-- Use Redis server time to avoid app-node clock drift
local now_parts = redis.call('TIME')
local now = tonumber(now_parts[1]) + (tonumber(now_parts[2]) / 1000000)

local state = redis.call('HMGET', key, 'tokens', 'last_refill')
local tokens = tonumber(state[1])
local last_refill = tonumber(state[2])

if tokens == nil or last_refill == nil then
tokens = capacity
last_refill = now
else
local elapsed = math.max(0, now - last_refill)
tokens = math.min(capacity, tokens + (elapsed * refill_rate))
last_refill = now
end

local allowed = 0
local retry_after = 0

if tokens >= requested then
tokens = tokens - requested
allowed = 1
else
local deficit = requested - tokens
retry_after = math.ceil(deficit / refill_rate)
end

-- Expire idle buckets automatically after full-refill period + 60s buffer
local ttl = math.ceil(capacity / refill_rate) + 60
redis.call('HSET', key, 'tokens', string.format('%.4f', tokens), 'last_refill', string.format('%.6f', last_refill))
redis.call('EXPIRE', key, ttl)

local reset_seconds = math.ceil((capacity - tokens) / refill_rate)

return { allowed, math.floor(tokens), retry_after, reset_seconds }

4. Production PHP 8.3 Middleware & HTTP 429 Semantics

Returning a bare 429 status code without backoff guidance forces well-behaved SDKs into blind retry loops. Under RFC 6585, an HTTP 429 Too Many Requests response should include a Retry-After header alongside standard quota headers (X-RateLimit-Limit, X-RateLimit-Remaining, and X-RateLimit-Reset) so clients pause until tokens replenish.

Crucially, your middleware must handle Redis restarts cleanly. Because Redis stores loaded Lua scripts in a volatile cache, a failover or restart clears registered SHA-1 digests and returns a NOSCRIPT error on EVALSHA. A resilient client catches NOSCRIPT, falls back to EVAL (which reloads the script into Redis automatically), and applies a fail-open circuit breaker so a brief Redis blip never takes down your entire API. Pairing this with defense-in-depth PHP application security hardening protects authentication and billing routes from automated abuse.

<?php

declare(strict_types=1);

namespace App\Http\Middleware;

use Redis;
use RedisException;

final class RedisTokenBucketLimiter
{
private readonly string $scriptSha;

public function __construct(
    private readonly Redis $redis,
    private readonly string $luaScript,
    private readonly bool $failOpen = true
) {
    $this->scriptSha = sha1($this->luaScript);
}

/**
 * Evaluates a Token Bucket quota for a tenant/route key.
 *
 * @return array{allowed: bool, remaining: int, retry_after: int, reset: int}
 */
public function consume(
    string $bucketKey,
    int $capacity,
    float $refillPerSecond,
    int $cost = 1
): array {
    $args = [$bucketKey, (string) $capacity, (string) $refillPerSecond, (string) $cost];

    try {
        $result = $this->redis->evalSha($this->scriptSha, $args, 1);

        if ($result === false) {
            $lastError = (string) $this->redis->getLastError();
            if (str_contains($lastError, 'NOSCRIPT')) {
                $this->redis->clearLastError();
                $result = $this->redis->eval($this->luaScript, $args, 1);
            }
        }

        if (!is_array($result) || count($result) < 4) {
            return $this->fallbackDecision($capacity);
        }

        retur
n [
'allowed' => ((int) $result[0]) === 1,
'remaining' => (int) $result[1],
'retry_after' => (int) $result[2],
'reset' => (int) $result[3],
];
} catch (RedisException) {
return $this->fallbackDecision($capacity);
}
}

/**
 * @return array{allowed: bool, remaining: int, retry_after: int, reset: int}
 */
private function fallbackDecision(int $capacity): array
{
    return [
        'allowed' => $this->failOpen,
        'remaining' => $this->failOpen ? $capacity : 0,
        'retry_after' => $this->failOpen ? 0 : 5,
        'reset' => 5,
    ];
}

}

5. Layering Edge Pre-Filtering in Nginx Before Redis

Even with sub-millisecond Redis checks, forwarding 50,000 malicious requests per second from a single IP through PHP-FPM wastes worker processes and network sockets. Placing an Nginx limit_req_zone pre-filter in front of your upstream drops volumetric floods directly in Nginx's shared memory slab before a PHP worker ever wakes up—a key layer in any high-performance Nginx and PHP-FPM hosting stack.

# /etc/nginx/conf.d/rate_limit.conf
# 10m zone holds ~160,000 IPv4 states in shared memory
limit_req_zone $binary_remote_addr zone=edge_ip_flood:10m rate=50r/s;
limit_req_status 429;

server {
    listen 443 ssl;
server_name api.example.com;

location /v1/ {
    # Allow short bursts of 100 requests without delaying normal clients
    limit_req zone=edge_ip_flood burst=100 nodelay;

    proxy_pass http://app_backend;
    prox
y_set_header X-Real-IP $remote_addr;
}
}

Set the Nginx edge ceiling 5x to 10x higher than your per-tenant Redis quota so corporate NATs and shared office IPs never hit false positives at the edge, while leaving fine-grained plan enforcement (Free vs. Pro vs. Enterprise API keys) to your Redis Lua limiter.


6. Developer FAQs on Distributed API Rate Limiting

1. Should API rate limiting fail open or fail closed if Redis becomes unreachable?

For general product APIs, fail open ($failOpen = true) while emitting an alert to Prometheus so a brief Redis failover does not cause a total outage for paying customers. For high-risk security endpoints such as login, OTP verification, or password resets, fail closed or fall back to a strict local Nginx IP zone.

2. How do I charge expensive GraphQL or bulk-export endpoints more than simple GET requests?

Pass a weighted cost argument as ARGV[3] in the Token Bucket Lua script. A lightweight GET /v1/health request consumes 1 token, whereas a heavy POST /v1/reports/export consumes 25 tokens from the same tenant bucket.

3. Why use EVALSHA instead of Redis Functions in Redis 7+?

Both execute atomically on the server. EVALSHA works identically across Redis 5, 6, 7, Valkey, and managed cloud clusters without requiring separate cluster-wide function deployment steps during CI/CD rollouts. If your infrastructure already manages server-side libraries, Redis 7+ Functions provide cleaner versioning.

4. How can I prevent rate-limit keys from exhausting Redis maxmemory?

Always set an automatic EXPIRE TTL inside the Lua script equal to the time required to refill an empty bucket plus a short buffer, and run your rate-limiting Redis instance with maxmemory-policy allkeys-lru rather than noeviction so stale idle buckets are evicted cleanly under memory pressure.


7. Summary & Production Rollout Checklist

Reliable API rate limiting protects both backend latency and unit economics without punishing legitimate traffic bursts. Start with coarse IP flood protection in Nginx, move tenant and API-key quotas into an atomic Redis Token Bucket Lua script using EVALSHA, and standardize 429 + Retry-After headers across every public route.

  1. Shadow Mode First: Deploy the Redis Lua limiter in log-only mode for 7 days to measure p99 Redis latency and identify legitimate tenants whose burst patterns exceed initial estimates.
  2. Enforce Edge + Tenant Layers: Enable Nginx limit_req_zone for volumetric IP protection and activate Redis Token Bucket enforcement per API key with weighted endpoint costs.
  3. Verify Failover Behavior: Simulate a Redis restart in staging to confirm NOSCRIPT automatic recovery and verify your fail-open circuit breaker keeps core APIs online.

Related Architectural & Engineering Guides

Team CodeBodh

CodeBodh Team creates high quality scripts, SaaS applications and developer tools to help you build faster.

Comments (0)

Security check against automated spam
3 × 2 = ?