{"id":10552,"date":"2026-11-24T11:16:11","date_gmt":"2026-11-24T11:16:11","guid":{"rendered":"https:\/\/cybersecurityinfocus.com\/?p=10552"},"modified":"2026-11-24T11:16:11","modified_gmt":"2026-11-24T11:16:11","slug":"designing-a-distributed-api-rate-limiter-token-bucket-redis-and-multi-region-scaling","status":"publish","type":"post","link":"https:\/\/cybersecurityinfocus.com\/?p=10552","title":{"rendered":"Designing a Distributed API Rate Limiter: Token Bucket, Redis and Multi-Region Scaling"},"content":{"rendered":"<p>A token bucket permits bursts up to its capacity and refills continuously; 100 tokens per minute is a sustained rate, not a strict rolling-window maximum. The gateway enforces the Redis decision.<\/p>\n<p class=\"wp-block-paragraph\"><strong>System Design Daily \u00b7 Intermediate\u2013Advanced<\/strong><\/p>\n<h2 class=\"wp-block-heading\">A flash sale that almost takes down checkout<\/h2>\n<p class=\"wp-block-paragraph\">In this fictional but realistic scenario, Ananya runs an online shop\u2019s checkout API. A flash sale brings thousands of customers and aggressive retrying clients. Ravi, the SRE, sees database saturation. They introduce a distributed rate limiter that protects checkout while giving legitimate customers a fair chance. The goal is to reject excess work early, not to guarantee that every admitted request succeeds.<\/p>\n<h2 class=\"wp-block-heading\">Meet the participants: who does what?<\/h2>\n<div class=\"wp-block-columns is-layout-flex wp-container-core-columns-is-layout-7387b849 wp-block-columns-is-layout-flex\">\n<div class=\"wp-block-column is-layout-flow wp-block-column-is-layout-flow\">\n<h3 class=\"wp-block-heading\"> Client<\/h3>\n<p class=\"wp-block-paragraph\">Sends authenticated requests and respects retry guidance.<\/p>\n<\/div>\n<div class=\"wp-block-column is-layout-flow wp-block-column-is-layout-flow\">\n<h3 class=\"wp-block-heading\"> API gateway<\/h3>\n<p class=\"wp-block-paragraph\">Identifies the caller, selects a policy and enforces the decision.<\/p>\n<\/div>\n<div class=\"wp-block-column is-layout-flow wp-block-column-is-layout-flow\">\n<h3 class=\"wp-block-heading\"> Token bucket<\/h3>\n<p class=\"wp-block-paragraph\">Tracks available request credits and refills over time.<\/p>\n<\/div>\n<\/div>\n<div class=\"wp-block-columns is-layout-flex wp-container-core-columns-is-layout-7387b849 wp-block-columns-is-layout-flex\">\n<div class=\"wp-block-column is-layout-flow wp-block-column-is-layout-flow\">\n<h3 class=\"wp-block-heading\"> Redis<\/h3>\n<p class=\"wp-block-paragraph\">Atomically updates bucket state on the owning shard.<\/p>\n<\/div>\n<div class=\"wp-block-column is-layout-flow wp-block-column-is-layout-flow\">\n<h3 class=\"wp-block-heading\"> Backend<\/h3>\n<p class=\"wp-block-paragraph\">Processes admitted requests; still needs concurrency limits.<\/p>\n<\/div>\n<div class=\"wp-block-column is-layout-flow wp-block-column-is-layout-flow\">\n<h3 class=\"wp-block-heading\"> Ravi, SRE<\/h3>\n<p class=\"wp-block-paragraph\">Monitors denials, latency, store errors and saturation.<\/p>\n<\/div>\n<\/div>\n<h2 class=\"wp-block-heading\">Requirements and capacity<\/h2>\n<p class=\"wp-block-paragraph\">Support per-user and per-tenant policies, configurable burst capacity, low-latency decisions, HTTP 429 responses and explicit failure behavior. Assume 50,000 incoming requests per second at peak, 1 million active identities and 200 bytes of raw state per identity: about 200 MB before Redis object overhead, replicas and allocator overhead. At 50,000 decisions\/s, a 2 ms average decision latency implies about 100 concurrent in-flight decisions by Little\u2019s Law. Benchmark real scripts, network latency and hot keys before selecting shard counts. These are illustrative assumptions.<\/p>\n<h2 class=\"wp-block-heading\">Choose the algorithm<\/h2>\n<p>AlgorithmStrengthTrade-offFixed windowSimple countersBoundary burstsSliding logExact rolling countMemory proportional to requestsSliding counterCompact approximate rolling limitApproximation errorToken bucketControlled bursts and sustained rateNot a strict rolling-window capLeaky bucketSmooth outputQueueing delay or rejection<\/p>\n<h2 class=\"wp-block-heading\">Architecture and request flow<\/h2>\n<p>Client \u2192 Gateway \u2192 Rate-limit service \u2192 Redis shard<br \/>\n              \u2191           \u2193<br \/>\n              \u2514\u2500\u2500\u2500\u2500 allow \/ deny decision<br \/>\n              \u251c\u2500\u2500 allow \u2192 Backend \u2192 Response<br \/>\n              \u2514\u2500\u2500 deny  \u2192 HTTP 429 + Retry-After<\/p>\n<p class=\"wp-block-paragraph\">The gateway, not Redis, forwards or rejects requests. A policy service distributes versioned limits; the decision service uses a stable key such as tenant:user:route-class. Authenticate before using a trusted identity, and apply a separate coarse pre-authentication limit. Never trust arbitrary forwarded IP headers.<\/p>\n<h2 class=\"wp-block-heading\">Token bucket: the mathematics<\/h2>\n<p class=\"wp-block-paragraph\">For capacity B, refill rate r tokens\/second, elapsed time \u0394t and request cost c, compute available = min(B, previous + r \u00d7 \u0394t). Admit if available \u2265 c and subtract c. Otherwise reject and calculate ceil((c \u2212 available)\/r) seconds until enough credits exist. With B=100 and r=100\/60, a full bucket permits 100 immediate requests and then approximately 1.67 requests per second. This is not a guarantee of at most 100 requests in every rolling minute.<\/p>\n<h2 class=\"wp-block-heading\">Atomic Redis implementation<\/h2>\n<p class=\"wp-block-paragraph\">A Lua script prevents two gateways from reading the same remaining balance and both spending it. The following example assumes positive capacity, refill rate and cost, validated by the caller, and cost no greater than capacity. Use the Redis server clock, clamp backward time, and expire idle buckets only after enough time to refill.<\/p>\n<p>&#8212; KEYS[1]: bucket key; ARGV: capacity, rate\/sec, cost<br \/>\nlocal cap = tonumber(ARGV[1])<br \/>\nlocal rate = tonumber(ARGV[2])<br \/>\nlocal cost = tonumber(ARGV[3])<br \/>\nlocal t = redis.call(&#8216;TIME&#8217;)<br \/>\nlocal now = tonumber(t[1]) + tonumber(t[2])\/1000000<br \/>\nlocal s = redis.call(&#8216;HMGET&#8217;, KEYS[1], &#8216;tokens&#8217;, &#8216;ts&#8217;)<br \/>\nlocal tokens = tonumber(s[1]) or cap<br \/>\nlocal last = tonumber(s[2]) or now<br \/>\nnow = math.max(now, last)<br \/>\ntokens = math.min(cap, tokens + (now-last)*rate)<br \/>\nlocal allowed = 0<br \/>\nlocal wait = 0<br \/>\nif tokens &gt;= cost then<br \/>\n  tokens = tokens-cost<br \/>\n  allowed = 1<br \/>\nelse<br \/>\n  wait = math.ceil((cost-tokens)\/rate)<br \/>\nend<br \/>\nredis.call(&#8216;HSET&#8217;, KEYS[1], &#8216;tokens&#8217;, tostring(tokens), &#8216;ts&#8217;, tostring(now))<br \/>\nredis.call(&#8216;EXPIRE&#8217;, KEYS[1], math.max(1, math.ceil(cap\/rate)+1))<br \/>\nreturn {allowed, wait}<\/p>\n<p class=\"wp-block-paragraph\">This is a teaching implementation, not a benchmarked production library. Test clock jumps, fractional arithmetic, policy changes and Redis failover. For strict financial quotas use an appropriately durable accounting system rather than assuming asynchronous Redis replication is lossless.<\/p>\n<h2 class=\"wp-block-heading\">API contract and client behavior<\/h2>\n<p>HTTP\/1.1 429 Too Many Requests<br \/>\nRetry-After: 3<br \/>\nContent-Type: application\/json<\/p>\n<p>{&#8220;error&#8221;:&#8221;rate_limit_exceeded&#8221;,&#8221;retry_after_seconds&#8221;:3}<\/p>\n<p class=\"wp-block-paragraph\">Retry-After is guidance, not a reservation. Clients should back off with jitter. A rate limiter does not replace checkout idempotency; an admitted retry can still duplicate an order unless the business operation protects against it.<\/p>\n<h2 class=\"wp-block-heading\">Scaling across regions<\/h2>\n<div class=\"wp-block-columns is-layout-flex wp-container-core-columns-is-layout-7387b849 wp-block-columns-is-layout-flex\">\n<div class=\"wp-block-column is-layout-flow wp-block-column-is-layout-flow\">\n<h3 class=\"wp-block-heading\"> Central authority<\/h3>\n<p class=\"wp-block-paragraph\">Route each identity to its owning region for tighter global enforcement, at the cost of cross-region latency and availability.<\/p>\n<\/div>\n<div class=\"wp-block-column is-layout-flow wp-block-column-is-layout-flow\">\n<h3 class=\"wp-block-heading\"> Regional budgets<\/h3>\n<p class=\"wp-block-paragraph\">Allocate portions of a global budget to regions. Fast local decisions, but unused credits can be stranded.<\/p>\n<\/div>\n<div class=\"wp-block-column is-layout-flow wp-block-column-is-layout-flow\">\n<h3 class=\"wp-block-heading\"> Approximate global limit<\/h3>\n<p class=\"wp-block-paragraph\">Use local buckets with periodic coordination. Accept and quantify possible overshoot during partitions.<\/p>\n<\/div>\n<\/div>\n<p class=\"wp-block-paragraph\">Shard by stable identity; a single extremely hot tenant may need hierarchical budgets or local credit leases. Do not assume Redis Cluster makes a single hot key parallel. Multi-key atomic scripts require keys in the same cluster slot. Avoid silently granting every region the entire global quota.<\/p>\n<h2 class=\"wp-block-heading\">Failure recovery and operational decisions<\/h2>\n<p>FailureResponseRedis timeoutChoose fail-open for low-risk reads or fail-closed for sensitive operations; use bounded local emergency budgets where appropriate.Primary failoverExpect possible lost recent updates with asynchronous replication; measure overshoot.Retry stormReturn 429 with guidance; clients back off with jitter.Hot keyUse hierarchical quotas or allocated local credits.Backend saturation despite limitsAdd concurrency limits, load shedding and circuit breakers.<\/p>\n<h2 class=\"wp-block-heading\">Security, monitoring and cost<\/h2>\n<p class=\"wp-block-paragraph\">Protect Redis with private networking, authentication and TLS where supported. Avoid storing raw personal identifiers in keys or logs. Bound key cardinality to prevent memory exhaustion. Measure decision p95\/p99 latency, allow\/deny rates, store errors, evictions, hot keys, backend saturation and policy versions. Avoid high-cardinality per-user metric labels. Costs include memory, replication, cross-region traffic and decision-service CPU.<\/p>\n<h2 class=\"wp-block-heading\">Test the design<\/h2>\n<p class=\"wp-block-paragraph\">Run concurrent requests against a single identity and verify token conservation; test refill boundaries, expiration, different request costs, clock regression, failover and regional partitions. Load-test realistic identity distributions rather than only uniform random traffic. Verify that denial responses do not reach checkout.<\/p>\n<h2 class=\"wp-block-heading\">Frequently asked questions<\/h2>\n<h3 class=\"wp-block-heading\">Does a token bucket enforce an exact rolling-minute limit?<\/h3>\n<p class=\"wp-block-paragraph\">No. It permits bursts up to capacity plus credits refilled over the interval. Use a sliding log if exact rolling-window enforcement is required.<\/p>\n<h3 class=\"wp-block-heading\">Why not use an in-memory counter?<\/h3>\n<p class=\"wp-block-paragraph\">It is useful for local protection, but independent replicas multiply the effective quota unless they coordinate or receive allocated budgets.<\/p>\n<h3 class=\"wp-block-heading\">Should every Redis failure reject requests?<\/h3>\n<p class=\"wp-block-paragraph\">No universal policy fits every endpoint. Choose based on abuse risk, availability requirements and downstream capacity.<\/p>\n<h2 class=\"wp-block-heading\">Interview challenge and knowledge check<\/h2>\n<p class=\"wp-block-paragraph\">Design a 100,000 request\/s limiter across three regions with a strict global quota. Explain the latency and partition trade-offs. Quick check: why is Lua useful? It makes the read-refill-consume update atomic on the owning Redis server. Why does rate limiting not prevent duplicate orders? It controls admission, not business idempotency.<\/p>\n<h2 class=\"wp-block-heading\">Key takeaways<\/h2>\n<p class=\"wp-block-paragraph\">Choose the algorithm from the actual quota semantics. Keep decisions atomic, make failure behavior explicit, and distinguish local protection from global enforcement. Monitor both the limiter and the backend.<\/p>\n<h2 class=\"wp-block-heading\">References and related reading<\/h2>\n<p class=\"wp-block-paragraph\"><a href=\"https:\/\/redis.io\/docs\/latest\/develop\/programmability\/eval-intro\/\" target=\"_blank\" rel=\"noopener\">Redis scripting<\/a> \u00b7 <a href=\"https:\/\/www.rfc-editor.org\/rfc\/rfc6585#section-4\" target=\"_blank\" rel=\"noopener\">RFC 6585: HTTP 429<\/a> \u00b7 <a href=\"https:\/\/blog.cloudflare.com\/counting-things-a-lot-of-different-things\/\" target=\"_blank\" rel=\"noopener\">Cloudflare rate limiting engineering<\/a> \u00b7 <a href=\"https:\/\/www.envoyproxy.io\/docs\/envoy\/latest\/intro\/arch_overview\/other_features\/global_rate_limiting\" target=\"_blank\" rel=\"noopener\">Envoy global rate limiting<\/a> \u00b7 <a href=\"https:\/\/programesecure.com\/production-ready-rest-api-design-guide\/\">Production-ready REST API design<\/a><\/p>","protected":false},"excerpt":{"rendered":"<p>A token bucket permits bursts up to its capacity and refills continuously; 100 tokens per minute is a sustained rate, not a strict rolling-window maximum. The gateway enforces the Redis decision. System Design Daily \u00b7 Intermediate\u2013Advanced A flash sale that almost takes down checkout In this fictional but realistic scenario, Ananya runs an online shop\u2019s [&hellip;]<\/p>\n","protected":false},"author":0,"featured_media":10553,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2],"tags":[],"class_list":["post-10552","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-news"],"_links":{"self":[{"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=\/wp\/v2\/posts\/10552"}],"collection":[{"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"replies":[{"embeddable":true,"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=10552"}],"version-history":[{"count":0,"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=\/wp\/v2\/posts\/10552\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=\/wp\/v2\/media\/10553"}],"wp:attachment":[{"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=10552"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=10552"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=10552"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}