HomeBlogAPI Rate Limiting and Throttling: A...

Engineering Guide · 9 min read · November 23, 2026

API Rate Limiting and Throttling: A Production Implementation Guide

In-memory rate limiters fail behind load balancers, and unthrottled background workers routinely trip partner 429 circuit breakers. Learn how to build an atomic Redis Lua token bucket for inbound traffic, throttle outbound worker queues cleanly, and fail open safely.

Author
Smit Desai
Published
November 23, 2026
Read time
9 min read
Topic
APIs & Integrations
Services
Custom Web · Mobile Apps · All Services

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.

API Rate Limiting and Throttling Architecture


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 hardcoding sleep() inside individual worker threads.
  • Honor upstream Retry-After globally: When one worker receives 429 with Retry-After: 12, write a short cooldown_until timestamp 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_id or api_key_id, plus endpoint cost tier (a heavy /exports route should consume 10 tokens while GET /users/:id consumes 1).
  • Public routes (login, password reset, webhooks): Key by normalized client IP—and normalize IPv6 addresses to their /64 subnet so callers cannot rotate /128 suffixes.
  • Proxy trust boundary: Only read X-Forwarded-For from 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.

Written by Smit Desai · Principal Full-Stack & FDSE

8+ years shipping production systems · 171 case studies · 300+ WordPress servers managed for Finland partners.

Next Steps and Recommended Resources

Next Steps · Recommended Resources

Pillar 1 · Custom Web & SaaS

Custom Web Application Development

Production Laravel, Next.js, API, and multi-tenant SaaS systems engineered end to end at $55/day (8–9 hrs) or $1,999/mo.

Comparison · Buyer Guide

SmitDev vs Software Agencies

See side-by-side economics, senior code ownership, and onboarding speed vs traditional dev shops and marketplaces.

01 — Frequently asked questions

apis & integrations

What is the difference between API rate limiting and throttling?

Rate limiting enforces a hard quota cap by rejecting excess requests immediately (typically with HTTP 429), whereas throttling smooths traffic flow by queuing, delaying, or shaping request concurrency so downstream services remain stable.

Why do distributed rate limiters require a Redis Lua script instead of GET followed by SET?

Running GET and SET as separate network round-trips creates a check-then-act race condition under concurrent requests. A Lua script executes atomically inside Redis's single-threaded event loop, keeping token math exact.

What should happen to inbound API rate limiting if Redis temporarily times out?

Configure a strict short timeout (such as 50ms) and fail open on Redis errors while emitting a high-priority alert. Blocking every legitimate customer request because the rate-limiter cache hiccupped turns a cache issue into a full outage.

How should you handle IPv6 addresses in unauthenticated rate limiters?

Normalize IPv6 addresses to a /64 prefix rather than the full /128 address. Residential ISPs assign entire /64 blocks to a single subscriber, so limiting per /128 lets a single script rotate addresses trivially.

03 — Have an engineering need?

hire the right expertise

Let's talk tech.

Deciding between an embedded forward deployed engineer or a senior full stack developer? Share your technical context and timeline.

Solitaire Corporate Park, Makarba, Ahmedabad, Gujarat 380015, India · IST (UTC+5:30) · --:-- IST · Mon–Fri 09:00–18:00 IST · US & EU overlap daily

No newsletter, no CRM. Just a reply.