Defending an API with Layered Rate Limiting

Medium · System Design · Software Engineer · Technical Screen

Prompt

During an active denial-of-service incident against a production HTTP API, your team has just analyzed recent access logs and compiled the client addresses generating the largest request counts. Design a rate-limiting architecture that shields the API and keeps legitimate callers working reliably throughout the flood.

Keep two operational realities in mind as you scope the design: high request volume from an address does not by itself prove malicious intent, and thousands of legitimate end users may sit behind a single shared egress IP. Because exact traffic figures and numeric quotas are left open, state the clarifying questions and assumptions you need around bottlenecked routes, caller authentication, bursty client workloads, perimeter capabilities, and degraded-mode behavior.

Scope & Expectations

  • Clarify which backend resources and endpoints are under stress, whether callers authenticate, and whether short traffic spikes occur during normal usage.
  • Define where limits are enforced across the network perimeter and application tiers, and how client identities are chosen without disconnecting shared-IP users.
  • Specify the rate-limiting algorithm, how differing endpoint costs and bursts are handled, and how state is coordinated across multiple servers.
  • Explain how the system behaves if shared rate-limit storage slows down or fails, and how rules are rolled out safely during a live incident.

Step-by-step walkthrough

  1. Clarify the incident, traffic patterns, and requirements

    Before converting a list of top-talking client addresses from access logs into block rules, we have to watch out for two classic traps: heavy traffic from an address is not automatic proof of malicious behavior, and thousands of real users can share one public IP. Under NAT (Network Address Translation)—a networking setup where many devices inside a company office, university, mobile carrier, or CI/CD provider share a single public IP address—blocking a top IP can instantly disconnect your biggest enterprise customer.

    Clarifying questions and the assumptions we make for this design:

    • Where is the backend actually hurting? The database behind POST /v1/search (a slow, heavy query) is pinned at 100% connection capacity, and API server CPU is elevated. Fast reads like GET /v1/items/{id} are healthy on their own, while POST /v1/login shows a spike in failed password attempts.
    • Do legitimate callers carry credentials? About 90% of normal traffic carries an API key or session token. Only login, signup, password-reset, and a handful of public catalog endpoints allow anonymous requests.
    • Do normal workloads arrive in spikes? Yes. Customer CI pipelines and analytics dashboards routinely fire bursts of 50–200 requests when a job starts, then sit idle for minutes.
    • Which controls belong at the network perimeter versus the application tier? Requests first pass through a CDN/WAF (Content Delivery Network / Web Application Firewall)—a globally distributed proxy layer sitting in front of our servers that sees network details like IP addresses and URL paths, but cannot look up authenticated customer accounts. Behind it sits our load balancer and API gateway fleet, which authenticates tokens and knows which account owns each request.
    • What distinguishes benign top talkers from hostile ones in the logs? Inspecting status codes and auth headers shows two completely different groups: 4 IPs belong to paying enterprise NATs and a CI runner pool (99% valid API keys, normal endpoint mix, 200 OK), while the other 46 IPs are unauthenticated or send bogus API keys, hammer POST /v1/search and POST /v1/login, and receive mostly 401 Unauthorized or 404 Not Found. That behavioral signature—not raw count—identifies abuse.

    Functional requirements:

    • Rate-limit requests by client identity while allowing short legitimate bursts and charging higher weights for expensive endpoints.
    • Block or challenge clearly abusive network sources at the edge with automatic expiration.
    • Cap total concurrent load on shared bottlenecks (like the search database) by priority tier, even when no individual IP exceeds its per-IP limit.
    • Return clear HTTP status codes and retry headers so well-behaved clients back off cleanly.

    Non-functional requirements:

    • Add less than 2 ms of p99 latency on the normal path and survive 10x–20x traffic spikes without the limiter itself becoming a bottleneck.
    • Protect legitimate customers: historical accounts in good standing should see no drop in success rate or spike in latency during the attack.
    • Degrade safely if the shared rate-limit store slows down or crashes (neither turning protection completely off nor taking the whole API down).
    • Support shadow mode—running a new rule on live traffic to log what would have been blocked without actually rejecting requests—before turning enforcement on.
  2. Back-of-the-envelope numbers: why per-IP limits alone fail

    Because concrete traffic volumes and quota numbers are left open, we state realistic baseline figures and trace what happens mathematically during the incident.

    Normal baseline
      Normal peak traffic          4,000 req/s (~90% authenticated, ~10% anonymous)
      Origin fleet capacity        8,000 req/s for the normal endpoint mix across 30 API gateway nodes
      Expensive endpoint           POST /v1/search uses ~20x the DB CPU of GET /v1/items/{id}
                                   and holds a DB connection for ~1.0 s on average.
                                   Max safe DB concurrency = 400 searches in flight.
    
    Attack traffic (from the log analysis)
      Total attack volume          80,000 req/s spread across ~3,000 source IPs
      Top 50 abusive IPs           40,000 req/s  (~800 req/s per IP)
      Long tail (~2,950 bot IPs)   40,000 req/s  (~14 req/s per IP)
    
    Legitimate enterprise NAT
      1,500 employees behind 1 IP  1,500 users x 0.1 req/s = 150 req/s from a single IP address
    

    By Little's law—a queueing rule stating that the average number of requests in flight equals the arrival rate multiplied by the average request duration—400 searches/s taking 1 second each holds 400 x 1 = 400 concurrent database connections. If the database slows down under stress so each search takes 2 seconds, just 200 searches/s will fill all 400 connections.

    Now test what happens if we only apply a naive 20 req/s per-IP limit everywhere:

    1. Enterprise NAT (150 req/s from 1 IP):
       130 req/s (87% of a paying customer's traffic!) is falsely rejected with HTTP 429.
    
    2. Attack traffic after 20 req/s per-IP cap:
       Top 50 IPs:        50 IPs x 20 req/s =  1,000 req/s gets through
       2,950 tail IPs:    all send ~14 req/s (< 20), so 40,000 req/s ALL gets through!
       Total reaching API = 41,000 attack + 4,000 normal = 45,000 req/s vs. 8,000 capacity -> API still crashes.
    

    Two design pillars fall straight out of this math:

    1. Key authenticated traffic by account, not by IP, so 1,500 employees behind one NAT each draw from their organization's authenticated quota rather than colliding on a tiny anonymous IP cap.
    2. Pair per-client rate limits with global, priority-weighted resource budgets, because thousands of low-rate bot IPs can stay below any reasonable per-IP limit and still overwhelm the database together.

    Sizing the shared counter store (Redis):

    • After the CDN edge drops the top abusive IPs, up to ~45,000 req/s reaches the 30 API gateways (~1,500 req/s per node).
    • Storing 1,000,000 active buckets at ~150 bytes per Redis hash uses only ~150 MB of RAM—easily fitting in memory on a small sharded Redis cluster with < 1 ms same-zone latency.
    • With a local deny cache on each gateway node (caching blocked keys in process memory until enough time passes for tokens to refill), hot attacking keys stop hitting Redis after their first rejection.
  3. API design: policies, gateway check, and client HTTP responses

    Policy definitions (stored in versioned config and pushed to gateways and edge nodes):

    policy anon-ip-search
      match          POST /v1/search (unauthenticated)
      key            client IP (IPv4 /32, IPv6 /64 prefix)
      bucket         rate = 2 units/s, burst = 10 units, cost = 1 unit per search
      mode           enforce          (can be set to "shadow" during rollout)
      on_store_down  local bucket: rate = 2 / N_nodes, burst = 1
    
    policy login-ip
      match          POST /v1/login, POST /v1/signup, POST /v1/password-reset
      key            client IP (IPv4 /32, IPv6 /64 prefix)
      bucket         rate = 0.1 units/s (6 attempts/min), burst = 5 units, cost = 1 unit
      mode           enforce
      on_store_down  local bucket: rate = 0.1 / N_nodes, burst = 1
    
    policy account-default
      match          any authenticated request
      key            account_id (or api_key_id)
      bucket         rate = 100 units/s, burst = 1,000 units (scaled by billing plan)
      endpoint_costs GET /v1/items/{id} = 1, GET /v1/items = 2, POST /v1/search = 20, POST /v1/export = 50
      concurrency    POST /v1/search <= 5 in-flight requests per account
      on_store_down  local bucket: rate = 2 * 100 / N_nodes, burst = max(50, 1000 / N_nodes)
    
    policy search-global-budget
      match          POST /v1/search
      key            global per priority class
      concurrency    max 300 in-flight searches total; anonymous class capped at 30 in-flight
    

    Here /32 and /64 are CIDR (Classless Inter-Domain Routing) prefixes—a slash notation specifying how many leading bits of an IP address identify the network group (/32 is a single IPv4 address; /64 is the standard block of 2^64 IPv6 addresses assigned to one home or cloud server).

    Internal gateway decision interface:

    check(keys = ["account:acct_81"], endpoint = "POST /v1/search", cost = 20)
      -> {
           allowed: false,
           limited_by: "account:acct_81",
           remaining_units: 3,
           retry_after_ms: 170
         }
    

    Every matching policy is checked, and the most restrictive result wins. Notice how retry_after_ms is exact: the caller needs 20 units, has 3 units left, and refills at 100 units/s, so (20 - 3) / 100 = 0.17 s = 170 ms.

    HTTP responses returned to clients:

    HTTP/1.1 429 Too Many Requests          (client exceeded its own per-account or per-IP limit)
    Retry-After: 1
    RateLimit-Limit: 1000
    RateLimit-Remaining: 3
    RateLimit-Reset: 1
    
    HTTP/1.1 503 Service Unavailable        (global priority load shedding; backend DB is full,
    Retry-After: 5                           not this specific client's fault)
    
    HTTP/1.1 403 Forbidden                  (matched an active edge block-list rule; minimal body)
    

    Keep 429, 503, and 403 responses tiny, static, and cheap: never touch the database to render an error, and log denied attack traffic via sampling (recording, say, 1 in 100 blocked requests) so logging I/O does not collapse under 80,000 blocks/s.

  4. Data model: soft bucket state and expiring block lists

    policies          policy_id PK, version, route_match, auth_state, key_type,
                      rate_per_s, burst, endpoint_costs_json, max_concurrency,
                      priority_class, mode (enforce | shadow), fallback_policy
    
    bucket_state      Redis hash key: rl:{policy_id}:{identity_key}
                      fields: { tokens: float, ts_ms: int }
                      TTL = ceil(burst / rate_per_s * 1000) + 1000 ms
    
    block_list        entry_id PK, target_type (cidr | asn | api_key | tls_fingerprint),
                      target_value, reason, created_by, created_at, expires_at
    
    allow_list        entry_id PK, cidr_or_account, owner_note, custom_rate, custom_burst
    
    decision_log      sampled event stream -> analytics store:
                      timestamp, policy_id, identity_key, endpoint, cost, allowed, mode
    

    Two deliberate data-modeling choices keep operations safe:

    1. Bucket counters are soft state. Soft state is temporary operational data that does not need disk-backed durability because losing it only resets active buckets back to full once—a tiny one-time blip rather than data corruption. Keeping buckets in in-memory Redis with automatic TTL expiration means idle keys vanish on their own.
    2. Every block-list entry requires an expires_at timestamp. Cloud providers, home ISPs, and mobile carriers constantly reassign IP addresses. A permanent IP ban inevitably punishes an innocent customer weeks later; expiring blocks (for example, 1 hour, automatically renewed only if abuse continues) prevent collateral damage.
  5. High-level architecture: three independent layers of defense

    No single component has both the raw throughput to absorb 80,000 req/s and the business context to know each customer's billing tier and live database health. We split enforcement across three layers that do not share a single point of failure:

      Incoming traffic (80,000 attack req/s + 4,000 legitimate req/s)
            |
            v
      +-------------------------------------------------------------------+
      | Layer 1: CDN / WAF Edge (hundreds of global PoPs)                 |
      | - Absorbs volumetric floods before TLS/TCP hits our origin        |
      | - Enforces expiring IP/CIDR/ASN block lists (~39k req/s dropped)  |
      | - Coarse local per-IP caps & browser challenges on anon routes    |
      +-------------------------------------------------------------------+
            |  (~45,000 req/s survives to origin)
            v
      +-------------------------------------------------------------------+
      | Layer 2: API Gateway Fleet (30 stateless nodes behind L7 LB)      |
      | - Negative-caches bad API keys; authenticates valid tokens        |
      | - Local deny cache (drops known-empty keys in 0 network hops)     |
      | - Checks per-account (cost-weighted) & anon per-IP token buckets  |----> [ Sharded Redis ]
      | - Falls back to local in-memory buckets if Redis > 5 ms or down   |<---- (Atomic Lua check)
      +-------------------------------------------------------------------+
            |  (authenticated within quota + small trickle of anon)
            v
      +-------------------------------------------------------------------+
      | Layer 3: Backend Services (Search, Auth, Items)                   |
      | - Per-endpoint in-flight concurrency semaphores (300 total cap)   |
      | - Priority shedding: P0 paid (60%), P1 free (30%), P2 anon (<=30) |
      +-------------------------------------------------------------------+
            |  (<= 300 concurrent queries; DB stays healthy)
            v
      [ Primary Database ]
    
      Control Plane (out of band, never on the hot request path):
      [ Policy Service ] ---> pushes versioned configs; gateways cache last-known-good copy
      [ Log Analyzer ]   ---> flags high-error unauthenticated talkers for expiring edge blocks
    

    Trace how the three layers cooperate during the 80,000 req/s attack:

    1. Layer 1 (Edge) blocks the 46 confirmed-abusive top IPs (~39,000 req/s dropped right at the CDN perimeter) while letting the 4 enterprise NAT IPs pass untouched.
    2. Layer 2 (Gateway) authenticates the enterprise NAT's 1,500 users into their individual accounts (account-default), caches invalid API keys in memory so bogus tokens never hit the user database, and rate-limits login and anonymous search per IP.
    3. Layer 3 (Service) sees the remaining long-tail botnet IPs (~14 req/s each, all unauthenticated P2 priority) trying to flood POST /v1/search. As soon as P2 hits its hard cap of 30 concurrent searches, every extra anonymous search is shed immediately with 503 Retry-After: 5, leaving 270+ database slots wide open for P0 and P1 customers.
  6. Deep dive 1: choosing client identity (NATs, IPv6, and credential floods)

    Counting by the wrong key punishes legitimate users or gives attackers infinite free identities. Each request is keyed by the most specific verified identity available:

    Priority   Identity key                        Used when                          Solves
    1 (best)   account_id / api_key_id             Valid auth credential present      Enterprise/carrier NATs
    2          session_id                          Logged-in web/mobile cookie        Shared Wi-Fi browsers
    3          IPv4 /32 or IPv6 /64 prefix         Anonymous traffic & failed auth    Basic unauth floods
    4          IPv4 /24, IPv6 /48, or ASN          Aggregate ceiling across subnets   Botnet IP rotation in 1 ISP
    5 (signal) TLS fingerprint + HTTP headers      Combined with IP/ASN on challenges Headless script detection
    

    Here an ASN (Autonomous System Number) is the globally unique ID of an entire network operator (such as a specific cloud host or ISP), and a TLS fingerprint (like JA3/JA4) is a hash of the cipher suites and extensions a client sends during the HTTPS handshake, which often distinguishes a Python attack script from real Chrome or Safari browsers.

    Four critical rules prevent identity bypasses:

    • Never apply tight per-IP limits to valid authenticated requests. Keep only an emergency per-IP safety ceiling (say, 5,000 req/s) at the edge; inside the gateway, authenticated requests draw purely from their account_id bucket so 1,500 office workers behind one NAT never step on one another.
    • Always mask IPv6 to at least /64 (never /128). Home routers and cloud VMs are routinely allocated an entire /64 block containing 2^64 IPv6 addresses. Counting single /128 addresses lets one attacker VM use a fresh IP on every single request.
    • Treat invalid credentials as anonymous failed-auth attempts. If an attacker sprays random Authorization: Bearer ... strings, looking each one up in Postgres would DoS the auth database. Verify stateless JWT signatures at the gateway, keep a short-TTL negative cache (caching "this API key does not exist" in memory for 60 seconds) or Bloom filter of valid key prefixes, and charge every failed auth against a strict per-IP bucket.
    • Protect account creation. If POST /v1/signup is free and unlimited, an attacker will mint 10,000 accounts to get 10,000 fresh account-default buckets. Rate-limit signups per IP /24 and ASN, require email/phone or payment verification before unlocking higher tiers, and start unverified accounts in P2.
  7. Deep dive 2: token buckets, endpoint costs, and priority concurrency caps

    A token bucket models quota as a bucket that holds at most burst tokens and refills continuously at rate tokens per second. When a request of cost c arrives, we lazily compute how many tokens accumulated since the last check; if at least c tokens are in the bucket, we deduct c and allow the request.

    Mini-trace: burst = 10, rate = 2 tokens/s
      t = 0.0 s : bucket starts full at 10.0 tokens.
                  CI job fires a burst of 8 requests (cost 1 each) -> 8 deducted, 2.0 left (ALL ALLOWED).
      t = 0.5 s : 0.5 s x 2/s = +1.0 refilled -> 3.0 tokens.
                  Request of cost 5 arrives -> 3.0 < 5 -> DENIED (needs 2.0 more; retry_after = 2.0 / 2 = 1.0 s).
      t = 1.5 s : 1.0 s x 2/s = +2.0 refilled -> 5.0 tokens.
                  Retry of cost 5 arrives -> 5.0 >= 5 -> 0.0 left (ALLOWED).
    

    Clean in-memory implementation used for gateway local/fallback buckets:

    import math
    import time
    
    
    class TokenBucket:
        def __init__(self, rate_per_s: float, burst: float):
            self.rate = rate_per_s
            self.burst = burst
            self.tokens = float(burst)
            # Monotonic clock never jumps backward when NTP adjusts system time
            self.updated_at = time.monotonic()
    
        def check(self, cost: float = 1.0) -> tuple[bool, int]:
            """Return (allowed, retry_after_ms)."""
            if cost > self.burst:
                return False, 60_000
    
            now = time.monotonic()
            elapsed = now - self.updated_at
            self.tokens = min(self.burst, self.tokens + elapsed * self.rate)
            self.updated_at = now
    
            if self.tokens >= cost:
                self.tokens -= cost
                return True, 0
    
            missing = cost - self.tokens
            retry_after_ms = math.ceil((missing / self.rate) * 1000)
            return False, retry_after_ms
    

    Why token bucket beats simpler window counters here:

    • A fixed-window counter (e.g., "max 100 requests per clock minute") suffers from boundary doubling: a client can send 100 requests at 12:00:59 and another 100 at 12:01:00—200 requests in 2 seconds.
    • A sliding-window log stores one timestamp per request in a sorted set, which blows up Redis memory when an attacker sends thousands of requests per second.
    • A sliding-window counter (blending the previous and current fixed windows) uses O(1) memory and prevents boundary spikes, making it a solid runner-up, though token buckets express rate + burst + endpoint cost more directly.

    Combining cost-weighted buckets with priority concurrency caps:

    1. Cost units prevent cheap-to-expensive gaming. Rather than maintaining dozens of separate per-endpoint buckets per user, one account-default bucket measured in cost units (GET item = 1, POST search = 20, POST export = 50) charges users proportionally to actual database work.
    2. Concurrency caps stop slow-query pileups. Rate limits measure arrivals per second, not work currently stuck in flight. By pairing token buckets with in-flight concurrency caps and four priority tiers (P0 paid guaranteed 60% of the 300 search slots, P1 free 30%, P2 anonymous hard-capped at 10% = 30 slots, P3 suspicious opportunistic only), an anonymous botnet of 100,000 IPs can never occupy more than 30 of our 300 database connections.
  8. Deep dive 3: distributed state — exact Redis Lua vs. approximate local counters

    With 30 gateway nodes, how do they agree on a client's remaining tokens?

    Approach                        Accuracy                  Trade-off
    1. Central Redis + Lua script   Exact across region       ~0.5-1 ms network hop; Redis is on the path
    2. Local memory, rate / N       Approximate               0 hops; sticky HTTP/2 client on 1 node gets 1/30 quota!
    3. Local memory, full rate      Approximate               0 hops; attacker spraying 30 nodes gets 30x quota!
    4. Token leasing from Redis     Exact ceiling, low load   Gateway checks out batches (e.g. 20 units) at once;
                                                              ~20x fewer Redis calls for chatty accounts
    

    If two gateway nodes read tokens = 20 from Redis, both subtract 20 in application code, and both write 0 back, both requests slip through (a classic read-modify-write race). Instead, we run the entire check-and-deduct inside a single atomic Redis Lua script—Redis executes a Lua script start-to-finish without interleaving any other command:

    -- KEYS[1] = rl:{policy_id}:{key}
    -- ARGV[1] = rate_per_s, ARGV[2] = burst, ARGV[3] = cost
    local rate = tonumber(ARGV[1])
    local burst = tonumber(ARGV[2])
    local cost = tonumber(ARGV[3])
    
    -- Use Redis server clock so clock skew across 30 gateway VMs cannot corrupt refill math
    local t = redis.call('TIME')
    local now_ms = tonumber(t[1]) * 1000 + math.floor(tonumber(t[2]) / 1000)
    
    local state = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
    local tokens = tonumber(state[1]) or burst
    local last_ms = tonumber(state[2]) or now_ms
    
    -- Clamp elapsed >= 0 in case NTP steps the server wall clock slightly backward
    local elapsed_s = math.max(0, now_ms - last_ms) / 1000.0
    tokens = math.min(burst, tokens + elapsed_s * rate)
    
    if tokens >= cost then
      tokens = tokens - cost
      redis.call('HSET', KEYS[1], 'tokens', tokens, 'ts', now_ms)
      -- Key expires only after the bucket would have completely refilled to burst anyway
      local ttl_ms = math.ceil((burst / rate) * 1000) + 1000
      redis.call('PEXPIRE', KEYS[1], ttl_ms)
      return { 1, tostring(tokens), 0 }
    end
    
    -- Denied: do NOT write to Redis! Skipping HSET/PEXPIRE avoids write/replication
    -- amplification during an attack, and leaving (tokens, last_ms) intact preserves exact refill.
    local retry_ms = math.ceil(((cost - tokens) / rate) * 1000)
    return { 0, tostring(tokens), retry_ms }
    

    Protecting Redis itself with a local deny cache: When Redis returns { 0, tokens, retry_ms }, the gateway caches (tokens, now_ms, rate) in process memory for a few seconds. Subsequent requests on that node for the same key whose cost cannot possibly have refilled yet are rejected in nanoseconds right inside the gateway—turning an 800 req/s flood from one IP into ~2 Redis reads/s per node.

    Where we use approximate local limits vs. globally exact counters:

    • Approximate local counters at the CDN edge (per-IP flood rules), inside the gateway's local deny cache, for service-level in-flight concurrency caps (300 / K backend pods), and during Redis fallback. When an attacker sends 800 req/s against a 20 req/s edge limit, being off by 2x–5x across PoPs still blocks >95% of the flood with zero cross-network hops.
    • Globally exact Redis counters for customer account-default quotas (where HTTP/2 connection reuse would starve sticky clients under rate / N local splitting) and low-rate security endpoints like POST /v1/login (6 attempts/min, where a 30x local multiplier across 30 gateways would let an attacker test 180 passwords/min).
  9. Failure behavior and safe incident rollout

    What happens if the shared Redis cluster slows down (> 5 ms) or goes offline in the middle of the attack?

    • Failing open (allowing everything when Redis errors) drops our shields right when an attacker stresses the limiter.
    • Failing closed (rejecting everything when Redis errors) turns a Redis blip into a 100% API outage.

    Instead, each gateway wraps Redis calls in a circuit breaker—a guard that trips open after repeated timeouts (> 5 ms), stops waiting on dead Redis connections for 10 seconds, and switches cleanly to in-memory fallback buckets tailored by endpoint risk:

    Failure scenario                         Fallback behavior
    Redis slow (> 5 ms) or unreachable       Circuit breaker trips to in-memory TokenBuckets:
      - Authenticated accounts               rate = 2 * plan_rate / N_nodes,
                                             burst = max(max_endpoint_cost, plan_burst / N_nodes).
                                             Why: sticky HTTP/2 clients on 1 node can still run 20-unit
                                             searches; Layer 3's 300-search cap still protects the DB!
      - Login / signup / anon search         Strict rate = policy_rate / N_nodes,
                                             burst = max(endpoint_cost, ceil(policy_burst / N_nodes)).
                                             Why: even if an attacker sprays all 30 nodes, total allowed
                                             rate <= policy_rate, while burst >= 1 avoids locking out
                                             a real user's single login attempt!
    Policy config service down               Gateways keep enforcing their cached last-known-good config.
    Bad rule pushed by an operator           One-click rollback; all edge/gateway rules carry an owner & TTL.
    

    On the client side, our SDKs honor Retry-After and apply exponential backoff with jitter—doubling wait times between retries (1s, 2s, 4s...) plus a small random offset so thousands of throttled clients do not retry in synchronized waves.

    Incident rollout and how we prove legitimate traffic is protected:

    1. Minutes 0–15 (Contain): Cap anonymous P2 concurrency on POST /v1/search to 30 slots and push a 1-hour expiring edge block list for the 46 confirmed unauthenticated attack IPs (after verifying the 4 enterprise NAT IPs are excluded).
    2. Minutes 15–60 (Verify in shadow mode): Replay the past hour of production logs offline against the new per-account and per-IP token bucket policies, then enable them in shadow mode for 15–30 minutes to confirm zero false-positive spikes on known customers.
    3. Hour 1+ (Enforce & monitor): Flip policies to enforce and track our north-star health dashboard: P95 latency and non-4xx success rate for a cohort of established customer accounts compared with the same hour last week, alongside 429/503 rates by cohort, database connection utilization, local-deny-cache hit rate, and Redis p99 latency.

Intuition & how it works

Think of protecting an API under a volumetric request flood like managing entry to a busy hospital or airport terminal with three checkpoints. Out on the curb (the network edge), security guards turn away obvious troublemakers before they even enter the building; at the badge gates (the API gateway), registered members swipe their ID cards and spend points from their personal allowance based on whether they want a quick hallway check or a 20-minute scan; and right outside the MRI room (the database), an occupancy counter reserves most of the scanners for badge-holding patients so a crowd of walk-ins can never clog every machine.

A naive "block or cap every busy IP at 20 requests/s" rule fails in both directions at once. First, under NAT (Network Address Translation)—where hundreds or thousands of employees inside one company office share a single public IP address—one paying enterprise customer legitimately sends 150 requests/s from one IP and gets 87% of its traffic falsely blocked. Second, a distributed botnet of 3,000 IPs sending just 14 requests/s per IP stays comfortably below 20 requests/s on every single IP, yet still floods your 8,000 requests/s backend with 42,000 requests/s and crashes the database.

Walk through four requests arriving during an 80,000 requests/s attack to see how our three layers work together:

  1. Known-bad flood IP (800 req/s, unauthenticated, 99% errors): Blocked immediately at the CDN/WAF (Content Delivery Network / Web Application Firewall) edge proxy before opening a connection to our servers, using an expiring 1-hour block entry.
  2. Enterprise NAT employee (150 req/s shared IP, valid key acct_42, POST /v1/search): Passes the edge, authenticates at the gateway as acct_42 (ignoring tight per-IP caps), deducts 20 cost units from acct_42's token bucket (a quota bucket holding up to 1,000 burst units and refilling at 100 units/s) via an atomic Redis script, enters the high-priority P0 search pool, and succeeds in 120 ms.
  3. Long-tail bot IP (14 req/s, unauthenticated, POST /v1/search): Slips past the per-IP rate cap, but hits the search service's priority concurrency budget, which hard-caps anonymous P2 callers to at most 30 of the 300 total in-flight database queries; because 30 anonymous searches are already running, it is shed immediately with 503 Service Unavailable and Retry-After: 5, leaving 270 slots safe for paying customers.
  4. Over-quota caller (acct_99 with 3 units left requesting a 20-unit search): Denied once by Redis (retry_after_ms = 170), cached in the gateway's in-memory local deny cache, and rejected locally with 429 Too Many Requests for the next 170 ms without touching Redis again.

Key trade-offs

  • Edge enforcement vs. API gateway enforcement vs. service shedding. Dropping floods at the CDN/WAF edge is cheap and absorbs massive volume before TLS handshakes hit your origin, but the edge only sees network-level signals (IPs, paths, headers) rather than customer accounts. The API gateway knows authenticated accounts and billing tiers, but every request reaching it has already consumed a connection. Service-level concurrency caps protect the database regardless of who is calling. Combining all three closes the blind spots of each individual layer.
  • Account identity vs. IP identity. Keying limits by account_id or API key is fair and NAT-safe, but requires authentication first. Keying by IP works for anonymous endpoints, yet punishes shared NATs and can be bypassed by rotating IPs; grouping IPv6 by /64 CIDR prefixes (address blocks of 2^64 hosts assigned to a single customer) and monitoring ASNs (Autonomous System Numbers)—unique IDs identifying whole ISPs or cloud networks—narrows rotation abuse at a higher risk of collateral friction.
  • Token bucket vs. fixed/sliding windows. A token bucket stores just two numbers (tokens and last_updated_ms), naturally permits legitimate CI/dashboard bursts up to burst, and supports variable endpoint costs. Fixed-window counters can allow 2x the rate across a clock boundary, while exact sliding-window logs store one timestamp per request and blow up memory under attack.
  • Request-rate limits vs. in-flight concurrency limits. Rate limits cap how fast requests arrive, whereas concurrency limits cap how many slow requests sit in progress simultaneously. When database queries slow from 1 s to 2 s under load, the same arrival rate holds twice as many connections—making concurrency caps and priority load shedding essential for expensive endpoints.
  • Exact central Redis counters vs. approximate local counters. A sharded Redis cluster running a single atomic Lua script (code Redis runs indivisibly with no race conditions between read and write) enforces exact quotas across 30 gateway nodes at the cost of < 1 ms latency and an external dependency. Pure local in-memory counters (rate / N per node) cost zero network hops, but starve clients pinned to one gateway over HTTP/2 keep-alive connections; pairing central Redis with token leasing (checking out small batches of tokens per node) and a local deny cache gets accuracy without overloading Redis.
  • Fail open vs. fail closed vs. tailored local fallback. Failing open disables protection right when an attack stresses Redis, while failing closed turns a Redis outage into a total API outage. Using a circuit breaker (a fast-fail switch triggered when Redis timeouts exceed 5 ms) to fall back to in-memory token buckets—slightly generous per node for authenticated customers, strict rate / N with burst >= 1 for login and anonymous search—keeps both legitimate users working and brute-force attacks contained.

Common mistakes

  • Auto-banning the busiest IPs from logs without checking auth and error ratios, which routinely disconnects a major customer's corporate NAT, mobile carrier gateway, or CI runner pool.
  • Applying low per-IP rate limits to authenticated API requests, penalizing large organizations that route hundreds of employees through one egress IP.
  • Keying IPv6 rate limits by single /128 addresses instead of /64 prefixes, allowing a single cloud VM to rotate through 2^64 free addresses and never hit a limit.
  • Relying solely on per-IP rate limits, which a distributed botnet of thousands of quiet IPs effortlessly stays beneath while saturating backend databases.
  • Charging 1 token for every endpoint, letting an attacker spend their quota exclusively on POST /v1/search (which costs 20x as much database CPU as a cached GET).
  • Checking and updating Redis in two separate network calls (GET then SET), creating a race condition where concurrent attack requests all read the same token count and pass together.
  • Writing to Redis on every denied request and skipping a local deny cache, which shifts the denial-of-service flood onto Redis write replication instead of shedding it in gateway memory.
  • Dividing fallback burst naively by N nodes (5 / 30 = 0.16 < 1), which leaves local buckets permanently below cost = 1 and locks out 100% of logins during a Redis failover.
  • Creating permanent IP block rules, forgetting that cloud and mobile IP addresses are reassigned and will later belong to innocent users.
  • Deploying brand-new rate limits straight to enforce mode without shadow mode or log replay, discovering threshold mistakes via customer outage tickets.

Follow-up questions

  • How does your design accommodate shared corporate NAT gateways, low-rate botnets, resource-heavy routes, and rapid IP rotation, and where do per-node approximate limits beat a globally synchronized counter? Accommodate shared NATs by keying authenticated requests on account_id or API key rather than source IP, applying strict IP caps only to anonymous routes while allow-listing verified partner egress blocks at higher ceilings. Stop low-rate distributed botnets via service-level in-flight concurrency budgets and priority tiers (for instance, capping all anonymous P2 searches combined at 10% of database capacity so paying P0/P1 accounts retain 90%), handle resource-heavy routes by charging proportional token weights (search = 20, export = 50) alongside per-account concurrency limits, and blunt IP rotation by grouping IPv6 at /64, enforcing /24 or /48 subnet and ASN ceilings, negative-caching invalid tokens, and throttling signups. Per-node approximate limits win at the CDN perimeter (where floods exceed thresholds by 40x and cross-network hops cost too much), for rapidly changing in-flight concurrency counts, inside each gateway's local deny cache, and during Redis failovers; a globally synchronized counter justifies its sub-millisecond Redis hop for contracted customer quotas and sensitive low-rate routes like POST /v1/login, where a 30x multi-node drift would permit credential stuffing.
  • How do you prevent an attacker spraying millions of fabricated API tokens from overwhelming your authentication store while bypassing anonymous IP caps? Querying the primary database on every unrecognized API key turns authentication itself into a denial-of-service vector. Prevent that by verifying stateless signed tokens (such as HMAC/JWT) or checking key prefixes and checksums locally first, storing "token not found" outcomes in a bounded 60-second in-memory negative cache, and charging every failed auth check against the caller's anonymous IP and /24 or /64 subnet buckets before returning 401.
  • During an active traffic flood, how do you choose concrete quota numbers and roll them out without accidentally throttling paying customers? Analyze several weeks of baseline request logs to compute each active customer's p99 1-second and 1-minute cost-unit rates, propose initial thresholds at 2x–3x normal peak usage, and replay the past hour of incident logs offline against those candidate rules to measure both flood drop rate and customer false-positive rate. Enable the rules in shadow mode (logging decisions without rejecting requests) for 15–30 minutes while monitoring established customer cohorts before flipping to enforce.

Follow-up questions

Similar questions

More Render interview questions

All 3 Render questions →