Rate Limiting an API Under Active Abuse
System DesignModel answerLast updated
Design a layered rate limiter that blunts a traffic flood while keeping legitimate clients and anonymous users productive.
Context
Your API is being hammered. Traffic logs have already been analyzed and some client addresses stand out as extreme volumes — but volume alone is not proof of abuse, and a single address can front thousands of real users behind a NAT or corporate proxy. You now have to design the protective layer: rate limiting that absorbs the flood without locking out legitimate customers.
The Task
Describe a rate-limiting design for this API. Your answer should cover:
- Where enforcement happens. Which tier (CDN/edge, API gateway, per-service) enforces what, and why.
- What identity to limit on. Address, account, API key, session, endpoint, or some combination — and how you handle unauthenticated traffic and shared egress addresses.
- The algorithm. How burstiness is handled, not just average rate, and how you'd choose the parameters.
- Where state lives in a distributed deployment. How multiple gateway nodes share counters without becoming a bottleneck or a single point of failure.
- Failure behavior. What the system does when the limiter's shared store is slow or unreachable, or when the edge is bypassed.
- Client-facing behavior. Status codes, headers, retry guidance, and how you tell a throttled client apart from a blocked one.
- Observability. Which metrics prove the attack is being hindered and which prove you aren't hurting real users.
Constraints & Assumptions
- No traffic scale, limit values, or request mix are given — state your assumptions and justify numbers.
- Some endpoints are far more expensive than others (e.g., a search query vs. a health check).
- Clients may or may not authenticate; anonymous traffic must still be handled.
- Bursts are sometimes legitimate (batch jobs, app cold start, retries with backoff).
What a Good Answer Demonstrates
Layered limits rather than one magic number, keys that reflect real client identity, burst-tolerant algorithms, an honest discussion of distributed-counter trade-offs, explicit and safe degradation behavior, and monitoring that separates attack mitigation from collateral damage to legitimate users.
Hints
Hint 1
Limits belong at several tiers with different granularities — edge, gateway, per-endpoint — not one global number.
Hint 2
Token bucket (or GCRA/leaky bucket) tolerates bursts; a fixed-window counter does not, and sliding windows cost more memory.
Hint 3
Limiting purely by IP punishes NAT'd users; combine keys (account + endpoint + coarse IP) and weight by endpoint cost.
Hint 4
Decide up front whether your limiter fails open or closed on store outages — and how you keep a local fallback.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Framing
I'd start by stating assumptions: say the API serves a mix of authenticated and anonymous traffic across a CDN/edge, an API gateway, and backend services. Peak normal load is, say, 50k rps; the flood is 10–20× that concentrated on a few endpoints. I don't treat "top source IPs" as a hit list — they're a signal, and I limit on richer identity.
Enforcement point: layered
Limits go at multiple tiers, each doing what it's best at:
- Edge / CDN — coarse, cheap filtering: per-IP connection and request ceilings, geo/ASN blocks if warranted, and challenge pages (JS/captcha) for suspicious anonymous traffic. This sheds the bulk of the flood before it reaches origin.
- API gateway — authenticated per-key/account limits, weighted by endpoint cost, with headers and 429s.
- Service level — per-endpoint concurrency limits and expensive-query guards (e.g., max page size, query timeouts), because the gateway can't see cost.
Each layer's limit is slightly above the layer below, so the flood is stopped as early as possible without double-counting legitimate bursts.
Identity keys
No single key is right. I combine:
- Authenticated traffic: account / API key count. Optionally sub-limit per endpoint and per source IP within an account, so a stolen key or misbehaving integration is contained.
- Anonymous traffic: IP, but coarse and generous — a single IP may represent many users behind NAT, so anonymous IP limits are high and paired with challenge capability rather than outright blocks. Client-generated device/session cookies help separate users sharing an egress address.
- Endpoint dimension: cost-weighted. A search call may cost 1 unit per 10 records; a health check costs ~0. Token bucket capacity (the counter) is per key; cost is per request.
I never permanently block an IP from the logs alone; volume ≠ abuse. I quarantine/challenge first.
Algorithm
Token bucket (or equivalently GCRA) per key. It allows a burst up to bucket capacity while enforcing a long-run rate — matching real clients that idle then burst. A fixed-window counter lets 2× the limit through the window boundary and smooths nothing; a sliding log is accurate but stores every timestamp. Token bucket needs only (tokens, last_refill) — two numbers.
Parameter choice: choose rate ≈ p99 of normal per-key traffic and capacity ≈ a few seconds' worth, then tune from data. Different costs per endpoint mean a single bucket per account with weighted debits, plus separate concurrency limits for heavy endpoints.
Distributed state
Counters must be shared across gateway nodes. Options and trade-offs:
- Central Redis with atomic Lua/
INCR: simple, accurate, but a latency hop and potential hotspot. Shard by key hash; keep the operation O(1). - Local token bucket per node + periodic sync: approximate. Each node allows
limit/Nlocally, so a client spread across N nodes gets roughly the right aggregate. Cheap and resilient; some overshoot. - Consistent hashing a key to one node's in-memory limiter: no network hop per request, but rebalancing shifts state. Good for hot keys.
I'd run Redis-backed buckets for precision at the gateway, plus a cheap local cache of recent decisions and a local fallback, so a Redis hiccup doesn't take down the API.
Failure behavior
Critical decision: fail open or closed?
- The limiter is a shield, not core logic — so a limiter outage fails open for already-authenticated normal traffic, but closed/queued for anything above a local, per-node reflex threshold (e.g., very high per-IP rate). This keeps the flood out even if shared state is gone.
- Under attack, have a "panic/attack mode": tighten limits, require challenges, and enable per-IP connection caps at the edge; escalate to a WAF/scrubbing tier if needed.
- If the edge is bypassed, services still enforce per-endpoint concurrency as a backstop.
Client-facing behavior
Return 429 Too Many Requests with Retry-After, and RateLimit-Limit, RateLimit-Remaining, RateLimit-Reset so clients back off correctly. Well-behaved clients should retry with jittered backoff; the point is to make limiter responses cheap (don't hit backends to say "no"). Distinguish throttling (429, retry later) from a block/challenge (403 + challenge) in the response and error code.
Observability
Two dashboards, deliberately separate:
- Attack mitigation: reject ratio, edge-filtered rps, backend load drop, time-to-shed.
- Legitimate impact: 429 rate broken out by authenticated vs. anonymous, by status code, and by NAT'd or high-fanout customers; support tickets; p99 latency for those who succeed.
If 429s spike among paying accounts while backend load stays high, the limits are misaimed. If backend load drops but 429s among real users rise, you've cut too deep. Alert on both, and review limits from real traffic histograms rather than guessing.
Common mistakes
One global limit number; IP-only identity (punishes NAT); fixed windows (bursts and boundary doubles); a limiter that fails closed and takes down the whole API on a Redis blip; 429s without Retry-After/headers; and no measurement of collateral damage to legitimate traffic.