Rate Limiter

A deceptively small problem, worked through the TOGAF ADM — where shared distributed state becomes the Phase D crux.

Rate limiter, the ADM way, in 30 seconds

  • A (Vision): protect services and enforce fair usage; principles — enforce at the edge, one true limit across all servers, stay up even if the limiter's store fails.
  • B (Business): capabilities — decide allow/deny per client and tell the client the limit status.
  • C (Data/App): per-key counters (user/API-key); enforcement lives in the gateway; counters in a shared store.
  • D (Technology): the crux — token bucket, a shared counter store, atomic updates, 429 + Retry-After, fail-open.
  • E–H: ship a central-store limiter, then shard it; govern with per-tier limit policies.
  • Lesson: the 'one true limit' principle in Phase A is exactly what makes local counters wrong in Phase D.

A bouncer with a clicker counter

Picture a bouncer at a club door holding a handheld clicker. The rule is simple: let in up to 100 people an hour, then stop. One bouncer, one clicker — easy. Now the club gets so busy it opens fifty doors, each with its own bouncer and its own clicker. If each bouncer independently counts to 100, the club just let in 5,000 people an hour, not 100. The rule quietly broke the moment you added doors, and nobody noticed. That is the entire rate-limiter problem: not the counting, but making fifty counters agree on one count.

A rate limiter caps how many requests a client may make in a window — to protect your services from overload, stop one noisy tenant from starving the rest, and blunt brute-force abuse. On a single server it's a few lines of code. The interview is never about that. It's about the fifty-doors version: fifty servers that must enforce one shared limit, make the allow/deny decision in a fraction of a millisecond, and keep working even when the thing holding the count has a bad day.

What makes it hard — the problem before the solution

  • The limit is global, the servers are many. Fifty servers each counting locally multiply the real limit by fifty — the single most common mistake.
  • The check is on the hot path. Every request pays for it, so the allow/deny decision must be a sub-millisecond lookup, not a heavy query.
  • Concurrency is sneaky. Two requests arriving at the same instant can both see 'one token left' and both get in unless the check-and-spend is atomic.
  • The limiter itself can fail. If the thing holding the counters goes down, you must decide: block everything, or let everything through?

Why the ADM suits a 'small' problem

A rate limiter on one server is trivial; the interview is about fifty servers sharing one limit. If Phase A states the principle one true limit across all servers, then the Phase D rejection of local counters — the classic mistake — is a direct consequence, not a lucky catch.

Phase D holds the shared-state design; Phase A sets the principle that demands it.

Phase A — Architecture Vision

  • Vision: cap requests per client per time window to protect services, enforce fairness, and blunt abuse.
  • Stakeholders: downstream services (want protection), paying tenants (want fair shares), the business (wants uptime and abuse defense).
  • Principles: enforce at the edge (reject early); one true limit across all servers (no per-instance drift); degrade safely (a limiter outage must not become a total outage).

Phase B — Business Architecture

  • Value stream: request arrives → check the client's allowance → allow it through, or reject with 429.
  • Decide allow/deny — the core enforcement decision, per client key.
  • Report status — tell well-behaved clients their limit, remaining quota, and when it resets, so they back off instead of hammering.

Phase C — Information Systems Architecture (Data & Application)

Data architecture

  • Counter per key — the key is user ID, API key, or IP, depending on what we're limiting.
  • Small, hot, short-lived state — counts that refill/reset constantly; a perfect fit for an in-memory store.
  • Optional tiers — different limits for free vs paid, or per endpoint.

Application architecture

  • Enforcement at the API gateway (see API gateway) so rejected traffic never loads the services.
  • A shared counter store all gateway instances read and write — the heart of Phase D.
  • A clear response contract — 429 with rate-limit headers.

Phase D — Technology Architecture (the core)

D1 — Pick the algorithm

  • Decision — token bucket: tokens refill at a steady rate up to a capacity; each request spends one; empty = reject.
  • Why: it allows short, controlled bursts (realistic traffic) while capping the sustained rate, and it's easy to explain.
  • Full algorithm comparison lives on the Rate limiting concept page.
Token-bucket refill: lazily add tokens based on elapsed time (python)
def refill(bucket, rate, capacity, now):
    # Don't run a background timer per key; compute tokens lazily on each request.
    elapsed = now - bucket.last_refill          # seconds since we last touched it
    bucket.tokens = min(                        # add 'rate' tokens/sec, capped at capacity
        capacity,
        bucket.tokens + elapsed * rate          # the burst allowance lives here
    )
    bucket.last_refill = now
    return bucket

# rate=10, capacity=10 -> steady 10 req/sec, but up to 10 may burst at once.

Why token bucket, and why not the alternatives?

The honest competitors are the fixed window, the sliding window, and the leaky bucket. Each has a gap worth naming.

A fixed window ('100 per minute, reset on the minute') is the simplest, but it has an ugly edge: a client can fire 100 requests at 12:00:59 and another 100 at 12:01:00 — 200 requests in two seconds, double the intended rate, right at the boundary. The sliding window fixes that boundary burst but needs more bookkeeping per key. A leaky bucket smooths output to a perfectly constant rate but forbids bursts entirely, which punishes bursty-but-legitimate traffic (a page that loads ten assets at once).

Token bucket is the sweet spot: it caps the sustained rate like all of them, but its small reserve of tokens allows the short, realistic bursts real clients produce — without the fixed window's boundary doubling. And it's trivial to explain, which matters in an interview. That's why it's the default answer.

AlgorithmWhat it buysThe gap it can't fill
Fixed windowDead simple, one counter per window.Boundary burst: up to 2× the limit straddling the reset.
Sliding windowNo boundary burst.More state/compute per key to track the moving window.
Leaky bucketPerfectly smooth output rate.Forbids all bursts — hurts legitimate bursty traffic.
Token bucket (chosen)Caps sustained rate, allows controlled bursts, easy to explain.Burst size is a knob you must tune per use case.

D2 — The shared-state crux

All gateways share one counter store — otherwise each enforces its own limit.
  • The mistake: local in-memory counters. With 50 servers, a '100/min' limit becomes 100 × 50 = 5,000/min.
  • The fix: a shared in-memory store (e.g. Redis) holds the counters; every gateway reads/writes the same truth.
  • Atomicity: make check-and-decrement atomic (a small Lua script / atomic op) so two simultaneous requests can't both slip past the last token.
Atomic check-and-spend in the shared store (Redis Lua) (pseudocode)
-- Runs INSIDE the store as one indivisible step, so two concurrent
-- requests can never both see the same 'last token' and both pass.
local tokens = tonumber(redis.call('GET', KEYS[1]) or capacity)
if tokens >= 1 then
  redis.call('DECR', KEYS[1])        -- spend a token
  return 1                           -- allowed
else
  return 0                           -- 429: bucket empty
end
-- The whole script is atomic -> no read-then-write race between gateways.
The check against shared state (pseudo)
def allow(key):
    bucket = store.get(key)          # SHARED store, not local memory!
    refill(bucket, rate, capacity, now)
    if bucket.tokens >= 1:
        bucket.tokens -= 1           # must be atomic with the check
        store.set(key, bucket)
        return True                  # allowed
    return False                     # 429 Too Many Requests

Why not keep each server's counters in its own memory? It's faster (no network hop) and simpler to build — that's the trap. The gap local counters can't fill is the whole point of the system: there is no single truth. Fifty servers with private clickers enforce fifty separate limits, so your '100/min' becomes '100/min per server' and the global cap you promised silently doesn't exist. The shared store costs a network round trip per check, but it's the only way fifty doors agree on one count — which is exactly the one true limit principle from Phase A.

Where counters liveUpsideThe gap it can't fill
Local in-memory (per server)Zero network hop, dead simple.N servers = N independent limits; the real cap is silently ×N.
Shared store (chosen)One true count across the whole fleet.A network hop per check; the store becomes a dependency to make fast and resilient.
Local + periodic syncFast reads, roughly global.Approximate during the sync gap — fine for soft limits, wrong for hard ones.

D3 — The response contract

  • Over the limit → HTTP 429 Too Many Requests.
  • Include Retry-After and rate-limit headers (limit, remaining, reset) so good clients back off instead of retrying blindly.
  • This realizes the Phase B report status capability.
The 429 response contract with rate-limit headers (javascript)
function rateLimitMiddleware(req, res, next) {
  const key = req.apiKey || req.ip;         // what we limit on
  const decision = limiter.check(key);      // allow() against the SHARED store

  // Tell well-behaved clients where they stand so they self-throttle.
  res.set("X-RateLimit-Limit", decision.limit);
  res.set("X-RateLimit-Remaining", decision.remaining);
  res.set("X-RateLimit-Reset", decision.resetAt);

  if (!decision.allowed) {
    res.set("Retry-After", decision.retryAfterSeconds);
    return res.status(429).send("Too Many Requests");
  }
  return next();                            // under the limit: let it through
}

D4 — Failure handling (fail open vs closed)

  • Question: what if the shared counter store is unreachable?
  • Fail closed (reject everything) turns a limiter outage into a total outage — usually unacceptable.
  • Fail open (allow through) keeps the service up but temporarily drops protection.
  • Decision: fail open, treating the limiter as best-effort — realizing the Phase A degrade safely principle. Say this trade-off out loud; interviewers probe it.

D5 — Scale the limiter

  • At huge scale, shard the counter store by the limit key with consistent hashing so one node doesn't hold every counter.
  • Co-locate the store with the gateways to keep the per-request hop cheap.
  • Separately, pair per-client rate limiting with load shedding for system-wide overload — a different mechanism for a different problem.

Scaling & bottlenecks — what breaks first

A rate limiter is small, but it sits on every request, so its failures are loud. Here's the order things buckle under growth.

Breaks first as you scaleThe symptomThe fix
The shared counter storeEvery request's check queues on one hot store; latency spikes.Shard counters by key (consistent hashing); co-locate the store near the gateways.
A single hot keyOne huge tenant's counter concentrates on one node.Split that key's budget across shards, or give big tenants a dedicated limiter.
Clock/skew between nodesRefill math drifts if servers disagree on 'now'.Compute refill inside the store (one clock), or use the store's own time.
The store goes downThe check can't run at all.Fail open (best-effort) so a limiter outage isn't a product outage — decided in D4.

The irony worth stating out loud: the component whose job is to protect you from overload can itself become the bottleneck, because it touches every request. That's why the shared store is the thing you shard first and co-locate with the gateways — the per-request hop has to stay cheap or the limiter taxes everything it guards.

Phases E & F — Migration Planning

  • Ship a single-region central-store limiter first — simplest correct design.
  • Shard the store once counter traffic approaches a single node's limit.
  • Add tiers (free vs paid, per-endpoint) as a bounded enhancement.

Phases G & H — Governance & Change

  • Governance (G): limit policies per tier and endpoint; monitor 429 rates and the fail-open fallback firing.
  • Change (H): adjusting limits or adding a new tier is a config change within guardrails, not a redesign.

A rate limiter is a small component with an outsized role — and the ADM turns a 'simple' question into a defensible distributed-systems design.

Why it matters

  • It protects every downstream service from overload, abuse, and runaway clients.
  • It enforces fairness between tenants sharing infrastructure.
  • It's a frontline defense against brute-force and denial-of-service attacks.

If ignored

  • Local-only counters silently multiply the real limit by your server count.
  • Non-atomic updates let concurrent requests slip past the limit.
  • A limiter that fails closed turns its own outage into a full product outage.

Where it fits

  • Phase D holds the algorithm, the shared counter store, atomicity, and failure handling.
  • Phase A's 'one true limit' and 'degrade safely' principles drive those D decisions.
  • Sits at the edge/gateway, alongside load shedding for system-wide overload.

Related topics

Interview lens

Questions it unlocks

  • Design a rate limiter for a public API.
  • How do you enforce one limit across many servers?
  • How would TOGAF's ADM structure this?

60-second answer

I frame it as an ADM walk. Phase A's principles — enforce at the edge, one true limit across all servers, degrade safely — pre-decide the hard parts. Phase B names allow/deny and report-status. Phase C puts per-key counters in an in-memory store with enforcement at the gateway. Phase D is the crux: token bucket over a shared Redis with atomic check-and-decrement, because local counters multiply the limit by server count; 429 with Retry-After; and fail-open so a counter-store outage doesn't become a full outage. At scale I shard the store by key with consistent hashing. Every Phase D choice traces back to a Phase A principle, which is what makes it defensible.

Common traps

  • Local in-memory counters that multiply the real limit across servers.
  • Non-atomic check-and-decrement letting requests slip past under concurrency.
  • Never deciding fail-open vs fail-closed for a counter-store outage.

Search topics

↑↓ to move · Enter to open · Esc to close