KatInterview

Token-Bucket Rate Limiter in Node.js/Express: Build & Review

System DesignModel answer
MediumModel answerSystem Designrate-limitingnode.jsexpress

Last updated

Implement a file-configured Express middleware using the token-bucket algorithm, then explain its design trade-offs as you would in a peer code review.

Token-Bucket Rate Limiter in Node.js/Express

You are building a small Express service that enforces a rate limit on incoming requests using the token-bucket algorithm. The bucket's parameters come from a configuration file, not hard-coded values.

What you need to build

  1. Configuration loading — read a file (JSON or similar) that specifies at minimum:

    • capacity: the maximum number of tokens the bucket can hold
    • refillRate: how many tokens are restored per second
  2. Express application — expose at least one endpoint (e.g. GET /ping) whose responses are governed by the rate limiter.

  3. Rate-limiter middleware — implement the token-bucket logic. When a request arrives:

    • If at least one token is available, consume it and let the request through (200 OK).
    • If the bucket is empty, reject the request (429 Too Many Requests) with a response body indicating when the caller may retry.
  4. Startup validation — if the configuration file is missing or contains invalid values (negative capacity, zero refill rate, etc.), the process should exit with a clear error before binding to any port.

Scope for this exercise

Keep the initial implementation simple and explicit:

  • One in-memory bucket, shared across all callers of one endpoint, within a single Node.js process.
  • The bucket starts full.
  • Each request costs exactly one token.
  • No external state store and no multi-process coordination.

Code-review discussion

After writing the code, explain it as you would during a peer review. Cover:

  • Why you chose the clock source you did.
  • How the middleware separates concerns from the route handler.
  • What breaks first if the service is scaled horizontally or if per-user buckets are introduced.
  • How you would test the limiter without depending on real wall-clock time.

Clarifying questions worth raising

Before or while coding, think through:

  • Should the bucket be per-endpoint, per-user, per API key, or per IP address? How does that change the data structure?
  • When a request is denied, does it consume a token?
  • What information should the 429 response carry to help the caller back off gracefully?

Hints

Hint 1

Track only two pieces of state per bucket: the current token count and the timestamp of the last refill check. On each request, compute how many tokens have accumulated since that timestamp, add them (capped at capacity), then attempt to consume one. This lazy refill approach avoids any background timer.

Hint 2

Use process.hrtime.bigint() or Date.now() rather than new Date() for measuring elapsed time. A monotonic high-resolution source is immune to system clock adjustments that could cause negative elapsed-time calculations and therefore incorrect refills.

Hint 3

To make the limiter testable without sleeping, inject the clock as a dependency — a function that returns the current time. In tests, replace it with a manually advanced counter. This lets you simulate exhaustion, a full refill cycle, and a long idle period in milliseconds rather than real seconds.