KatInterview

Building a Throttling Service for a Multi-Node API Fleet

System DesignModel answer
HardModel answerSystem Designrate-limitingtoken-bucketsliding-window

Last updated

Design a throttling layer that caps per-key request rates with burst tolerance, first on one machine, then across many app servers, covering consistency, clock drift, failures, and observability.

Problem

Your company exposes a public API served by hundreds of stateless application instances. You need a throttling component that keeps each caller's traffic under a configured requests-per-second ceiling, while optionally permitting short bursts above the steady rate.

Design it end to end. Your answer should cover:

  1. Requirements and scale. State your assumptions: what a "caller" is (user, API key, IP, tenant plus endpoint), the number of keys, total QPS, latency budget, and how much overshoot is tolerable.
  2. Two algorithms. Compare a token-bucket approach with a sliding-window approach. For each, describe the per-key state, time and space complexity, and how you guarantee correctness when many threads hit the same key at once. Sketch an implementation of both.
  3. Going distributed. Extend the design to many instances sharing the same limits. Discuss:
    • centralized store (for example Redis) versus sharded or local counters,
    • clock skew between machines,
    • atomicity of the check-and-update step,
    • idempotency when clients retry,
    • failure modes such as node loss and partial updates,
    • how to keep enforcement consistent and fair.
  4. Interface and configuration. Define the API your services call, the response a rejected client sees, and an example rule configuration.
  5. Operations. Describe the metrics and alerts you would use to detect saturation and misbehavior.

State the trade-offs behind each decision rather than only the final choice.

Hints

Hint 1

Start by deciding whether the limiter should fail open or fail closed when its backing store is unreachable, and whether that answer differs by rule.

Hint 2

The refill, compare, and deduct steps must be a single atomic read-modify-write per key; think about striped locks locally and server-side scripts in a shared store.

Hint 3

Never compare timestamps produced by different machines. Use a monotonic clock locally, and the store's own clock for shared state.

Hint 4

Per-request calls to a central store become the bottleneck for hot keys. Consider letting instances borrow batches of capacity and spend them locally.