Unrestricted resource consumption sits near the top of the OWASP API Security Top 10 for a simple reason: it takes very little traffic to topple an unguarded endpoint. A runaway client retry loop, an unindexed search endpoint hit by a scraper, or a background worker firing 300 concurrent requests at a third-party webhook can exhaust your database connection pool in seconds.
Yet many production rate limiters are barely functional. Developers drop in an in-memory counter that breaks as soon as traffic scales across four containers, or they enforce naive fixed windows that allow double bursts at minute boundaries.
Here is how to implement distributed inbound rate limiting and outbound client throttling that actually hold up under production load.

Rate Limiting vs. Throttling vs. Load Shedding
Engineers often use these terms interchangeably, which leads to conflicting implementation choices:
- Rate limiting (Inbound protection): Rejects requests above a quota (
HTTP 429 Too Many Requests) to protect compute, database connections, and tenant fairness. - Throttling (Outbound & queue shaping): Deliberately paces or delays requests—especially from your own background workers toward third-party APIs—so you stay within upstream quotas without dropping work.
- Load shedding (Origin survival): Drops low-priority traffic (
HTTP 503) based on real-time server saturation (event-loop lag or queue depth) regardless of whether any single caller hit their quota.
Choosing a Rate-Limiting Algorithm
Selecting the right algorithm balances burst tolerance, Redis memory overhead, and implementation complexity.
| Algorithm | Burst Behavior | Memory per Key | Race-Free in Redis | Best Use Case |
|---|---|---|---|---|
| Fixed Window Counter | Allows 2x spike across boundary | 1 integer | Yes (INCR) |
Coarse abuse caps |
| Sliding Window Log | Smooth, exact | High (sorted set of timestamps) | Yes (Lua) | Low-volume sensitive endpoints |
| Sliding Window Counter | Smooth approximation | 2 integers | Yes (Lua) | General REST API quotas |
| Token Bucket | Controlled burst + steady refill | 2 numbers (tokens, timestamp) | Yes (Lua) | Production APIs & webhooks |
| Leaky Bucket | Strictly constant drain rate | Queue/timestamp | Yes (Lua) | Outbound partner throttling |
For almost every production REST API, Token Bucket gives the cleanest user experience: legitimate UI bursts (loading five dashboard widgets simultaneously) succeed immediately, while sustained scraping drains the bucket and gets throttled.
Atomic Distributed Token Bucket in Redis Lua
Never read a counter in Node.js or PHP, compute tokens in application memory, and write the new value back. Under concurrent requests, parallel workers read the same stale token count and allow excess traffic through.
Execute the refill and decrement atomically inside a single Redis Lua script:
-- KEYS[1] = bucket key (e.g. "rl:api:tenant_42")
-- ARGV[1] = capacity (max burst tokens)
-- ARGV[2] = refill_rate_per_ms
-- ARGV[3] = now_ms
-- ARGV[4] = requested_tokens (usually 1)
local capacity = tonumber(ARGV[1])
local refill_rate = tonumber(ARGV[2])
local now_ms = tonumber(ARGV[3])
local cost = tonumber(ARGV[4])
local data = redis.call("HMGET", KEYS[1], "tokens", "last_ms")
local tokens = tonumber(data[1])
local last_ms = tonumber(data[2])
if tokens == nil then
tokens = capacity
last_ms = now_ms
else
local elapsed = math.max(0, now_ms - last_ms)
tokens = math.min(capacity, tokens + (elapsed * refill_rate))
last_ms = now_ms
end
local allowed = 0
local retry_after_ms = 0
if tokens >= cost then
tokens = tokens - cost
allowed = 1
else
retry_after_ms = math.ceil((cost - tokens) / refill_rate)
end
redis.call("HMSET", KEYS[1], "tokens", tokens, "last_ms", last_ms)
redis.call("PEXPIRE", KEYS[1], math.ceil((capacity / refill_rate) * 2))
return { allowed, math.floor(tokens), retry_after_ms }
Standard Response Headers
Attach explicit quota headers on both allowed and rejected responses, and document them in your OpenAPI Specification:
res.setHeader('RateLimit-Limit', String(capacity));
res.setHeader('RateLimit-Remaining', String(remaining));
if (!allowed) {
const retrySeconds = Math.max(1, Math.ceil(retryAfterMs / 1000));
res.setHeader('Retry-After', String(retrySeconds));
return res.status(429).json({
error: 'rate_limit_exceeded',
retry_after_seconds: retrySeconds,
});
}
For framework-level API caching and route-group throttling strategies in PHP stacks, compare this with our guide on building high-performance REST APIs in Laravel.
Outbound Throttling Against Partner APIs
Inbound rate limiting is only half the problem. When your platform drains a Redis queue to push updates into HubSpot, Shopify, or a payment gateway, worker concurrency quickly exceeds partner limits.
Guardrails for Background Workers
- Share a distributed limiter across workers: Key outbound token buckets by
(provider, tenant_id)in Redis rather than hardcodingsleep()inside individual worker threads. - Honor upstream
Retry-Afterglobally: When one worker receives429withRetry-After: 12, write a shortcooldown_untiltimestamp in Redis so sibling workers stop hitting that tenant's endpoint immediately. - Add full jitter to exponential backoff: Use
delay = random(0, min(cap, base * 2 ** attempt))so 100 delayed jobs do not wake up on the exact same millisecond (the thundering herd problem). See our queue scaling guide for full worker topology patterns.
Keying Dimensions, Spoofing Hazards, and Fail-Open Strategy
Choose the Right Bucket Key
- Authenticated routes: Key by
tenant_idorapi_key_id, plus endpoint cost tier (a heavy/exportsroute should consume 10 tokens whileGET /users/:idconsumes 1). - Public routes (login, password reset, webhooks): Key by normalized client IP—and normalize IPv6 addresses to their
/64subnet so callers cannot rotate/128suffixes. - Proxy trust boundary: Only read
X-Forwarded-Forfrom trusted reverse proxies (Cloudflare, AWS ALB, Nginx); otherwise any caller can spoof the header and bypass your limiter entirely.
Fail Open on Cache Timeouts
Set a tight socket timeout (30–50ms) on rate-limiter Redis commands. If Redis fails or times out, log a critical metric and allow the request through rather than taking down your entire API.
Hardening Production APIs with SmitDev
At SmitDev, rate limiting and origin protection are part of our daily production baseline—from architecting multi-tenant SaaS APIs to managing 300+ WordPress sites at server level for a Finnish partner, where layered edge and origin throttling keeps burst traffic from exhausting PHP-FPM and database pools.
Whether you need targeted hourly developer support to fix a throttling bottleneck, a dedicated engineer at $55/day for 8–9 hours of focused work, or $1,999/month dedicated delivery across your backend stack, we ship practical, measurable reliability fixes.
Need help hardening your APIs before traffic scales? Talk to Smit about your architecture.