Configurable Token-Bucket API Rate Limiter and Code Review

Medium · Software Engineering Fundamentals · Backend Engineer · Onsite

Problem Statement

Implement the core configuration validator, lazy token-bucket limiter, and HTTP response mapper for a rate-limited web endpoint, and be ready to review the design choices and scaling trade-offs as you would with a teammate in a backend code review.

For the initial single-node service, enforce the following behavior:

  • Endpoint-scoped in-memory quota: A single process maintains one in-memory bucket guarding one endpoint, initialized completely full at capacity tokens. No external cache or cross-process synchronization is used in this baseline version.
  • Lazy refill and burst cap: Unused tokens replenish continuously at refillPerSecond tokens per elapsed second measured on a monotonic clock, capped at capacity so quiet periods never build up extra burst allowance above capacity.
  • Per-request accounting: Every permitted request deducts 1 token and returns HTTP 200. When fewer than 1 token is present, the request is rejected with HTTP 429, 0 tokens are deducted, and the response reports how many whole seconds (rounded up) the client must wait before 1 full token becomes available.
  • Fail-fast startup validation: Settings are loaded from a UTF-8 JSON file on startup. Missing files, malformed JSON, unexpected properties, invalid types, or out-of-range numbers must raise ConfigError before the server starts listening.
  • Architectural review: Consider how your design changes if quotas are tracked per caller (user ID, API key, or IP) or if multiple application replicas run behind a load balancer.

Implement the following Python components matching starter.py:

  • ConfigError(ValueError): exception class raised whenever configuration loading or validation fails.
  • parse_config(text: str) -> Dict[str, Any]: parse JSON string text into {"capacity": int, "refillPerSecond": float, "port": int}.
    • Required keys: "capacity" (whole number >= 1) and "refillPerSecond" (finite number > 0).
    • Optional key: "port" (whole number in 1..65535, defaulting to 3000).
    • Reject non-object JSON roots, booleans, strings, NaN, Infinity, fractional values on integer fields (whole-valued floats such as 4.0 are accepted and converted to int), and any unknown key by raising ConfigError.
  • load_config(path: str) -> Dict[str, Any]: read the UTF-8 file at path and pass its contents to parse_config, converting any OSError or UnicodeDecodeError into ConfigError.
  • TokenBucket(capacity: int, refill_per_second: float, clock: Callable[[], float] = time.monotonic):
    • Raise ValueError if capacity < 1, refill_per_second <= 0, either argument is a bool, or refill_per_second is non-finite.
    • try_remove() -> Tuple[bool, float]: advance token balance using clock(). If at least 1.0 token is available, subtract 1.0 and return (True, 0.0); otherwise subtract nothing and return (False, wait_seconds) where wait_seconds is the exact time needed to reach 1.0 token.
    • available() -> float: advance token balance using clock() and return the current fractional balance without removing tokens.
  • handle_request(bucket: TokenBucket) -> Tuple[int, Dict[str, str], Dict[str, Any]]:
    • If bucket.try_remove() allows the call, return (200, {}, {"message": "ok", "remainingTokens": whole_tokens_left}) where whole_tokens_left is the floor of the remaining token balance.
    • Otherwise compute retry_seconds = max(1, math.ceil(wait_seconds)) and return (429, {"Retry-After": str(retry_seconds)}, {"error": "rate_limited", "retryAfterSeconds": retry_seconds}).

Examples

Example 1

Input:
  parse_config('{"capacity": 4, "refillPerSecond": 0.5}')
  parse_config('{"capacity": 0, "refillPerSecond": 0.5}')

Output:
  {"capacity": 4, "refillPerSecond": 0.5, "port": 3000}
  raises ConfigError

Walk-through: Omitting "port" fills in the default 3000. Passing "capacity": 0 violates the >= 1 rule and aborts startup with ConfigError.

Example 2

Input:
  bucket = TokenBucket(capacity=2, refill_per_second=0.5, clock=fake_clock)
  t = 0.0 -> handle_request(bucket)
  t = 0.0 -> handle_request(bucket)
  t = 0.5 -> handle_request(bucket)
  t = 2.0 -> handle_request(bucket)

Output:
  (200, {}, {"message": "ok", "remainingTokens": 1})
  (200, {}, {"message": "ok", "remainingTokens": 0})
  (429, {"Retry-After": "2"}, {"error": "rate_limited", "retryAfterSeconds": 2})
  (200, {}, {"message": "ok", "remainingTokens": 0})

Walk-through: The bucket begins with 2.0 tokens, so the first two calls at t = 0.0 spend 1.0 token each, leaving 1 and 0 whole tokens. At t = 0.5, 0.5 * 0.5 = 0.25 tokens have accrued, which is below 1.0; no tokens are deducted, and the missing 0.75 token takes 0.75 / 0.5 = 1.5 seconds, rounding up to 2 seconds in Retry-After. By t = 2.0, another 1.5 * 0.5 = 0.75 token arrives (0.25 + 0.75 = 1.0), allowing the fourth call to succeed.

Example 3

Input:
  bucket = TokenBucket(capacity=4, refill_per_second=2.0, clock=fake_clock)
  t = 0.0  -> four calls to bucket.try_remove()
  t = 0.75 -> handle_request(bucket), then bucket.available()
  t = 30.0 -> bucket.available()

Output:
  four times (True, 0.0)
  (200, {}, {"message": "ok", "remainingTokens": 0}), then 0.5
  4.0

Walk-through: Draining all 4 tokens at t = 0.0 leaves 0.0. Waiting 0.75 seconds at 2.0 tokens/second adds 1.5 tokens; handle_request spends 1.0 token and reports floor(0.5) = 0 whole tokens remaining while available() still reflects the 0.5 fractional token. After 29.25 more idle seconds, the balance caps at capacity = 4.0.

Constraints

  • "capacity" must be an integer >= 1 (whole-number floats like 4.0 are accepted in JSON and normalized to int).
  • "refillPerSecond" must be a finite int or float strictly greater than 0.
  • "port", when present, must be an integer in 1..65535; only "capacity", "refillPerSecond", and "port" are permitted in the JSON object.
  • If clock() ever returns a timestamp earlier than the previous refill timestamp, neither deduct tokens nor move the recorded refill timestamp backward.
  • TokenBucket.try_remove(), TokenBucket.available(), and handle_request() must each run in O(1) time and O(1) space per call.

Step-by-step walkthrough

  1. Clarify the contract and rate-limiter guarantees

    A token bucket is a rate-limiting model controlled by two numbers — capacity (maximum tokens the bucket can hold) and refillPerSecond (how many tokens trickle in each second):

    • Short bursts allowed: Because the bucket starts full at capacity, up to capacity requests can succeed immediately back to back.
    • Long-run rate bounded: Over any interval of T seconds, at most capacity + refillPerSecond × T requests can pass. For example, with capacity = 10 and refillPerSecond = 2, at most 10 + 2 × 60 = 130 requests can succeed in any 60-second window.

    Pin down the open assumptions before coding:

    • Bucket scope: One in-memory bucket shared across the endpoint in a single Node.js process (we will review per-user and multi-server scaling afterward).
    • Token rules: Bucket starts full (capacity), idle accumulation caps at capacity, and each allowed request spends 1 token.
    • Denied requests: Spend 0 tokens and return HTTP 429 Too Many Requests with a Retry-After header telling the caller how many whole seconds to wait.
    • Invalid configuration: Fail fast at startup before opening the listening port.

    Because the automated sandbox runs Python, we implement the testable core (parse_config, load_config, TokenBucket, handle_request) in Python and present the matching 3-file Node.js Express application right alongside it.

  2. Key idea: lazy refill from elapsed monotonic time

    A beginner's first instinct is to start a background timer (setInterval(() => tokens++, 1000 / rate)). That timer design has three serious flaws:

    1. Event-loop lag under-counts tokens: If CPU work delays a timer tick, adding a fixed amount per tick falls behind real elapsed time.
    2. Wasted idle CPU: Timers wake up continuously even when zero traffic hits the server.
    3. Poor per-user scaling: Ten thousand users would need ten thousand timers.

    Instead, use lazy refill (recomputing earned tokens on demand only when a request arrives) by storing just two numbers: tokens and lastRefill:

    Request arrives at time `now`:
      1. elapsed      = now - lastRefill
      2. earned       = elapsed * refillPerSecond
      3. tokens       = min(capacity, tokens + earned)   <-- cap at capacity
      4. lastRefill   = now
      5. if tokens >= 1:
             tokens  -= 1       --> ALLOW (200 OK)
         else:
             wait     = (1 - tokens) / refillPerSecond   --> DENY (429 Too Many Requests)
    

    Always read now from a monotonic clock (performance.now() in Node.js, time.monotonic() in Python) — a clock guaranteed never to jump backward or forward when the operating system syncs wall-clock time via NTP.

  3. Implement the `TokenBucket` class

    Inject clock as a constructor parameter (defaulting to time.monotonic) so unit tests can advance time deterministically without sleep(). Notice two defensive details:

    • Reject bool, NaN, Infinity, capacity < 1, and refill_per_second <= 0 in __init__.
    • Only update tokens and last_refill when elapsed > 0. If a fake test clock ever steps backward, leaving last_refill untouched prevents neither losing tokens nor double-counting that interval later.
    from typing import Any, Callable, Dict, Tuple
    import math
    import time
    
    
    def _is_finite_number(value: Any) -> bool:
        # In Python, bool subclasses int (isinstance(True, int) is True), so reject bool first.
        if isinstance(value, bool) or not isinstance(value, (int, float)):
            return False
        # Reject NaN, Infinity, and -Infinity, which Python's json.loads accepts by default.
        return math.isfinite(value)
    
    
    class TokenBucket:
        """Single in-memory token bucket starting full and refilling lazily from a monotonic clock."""
    
        def __init__(self, capacity: int, refill_per_second: float,
                     clock: Callable[[], float] = time.monotonic) -> None:
            if isinstance(capacity, bool) or capacity < 1:
                raise ValueError("capacity must be an integer >= 1")
            if not _is_finite_number(refill_per_second) or refill_per_second <= 0:
                raise ValueError("refill_per_second must be a finite number > 0")
    
            self.capacity = capacity
            self.refill_per_second = float(refill_per_second)
            self.clock = clock
            # Bucket state: current fractional token balance (0.0 .. capacity) and last accounting timestamp.
            self.tokens = float(capacity)
            self.last_refill = clock()
    
        def _refill(self) -> None:
            """Credit tokens earned since self.last_refill, capped at self.capacity."""
            now = self.clock()
            elapsed = now - self.last_refill
            # Guard elapsed > 0: if a fake clock steps backward, neither deduct tokens nor move last_refill,
            # ensuring the same time interval is never double-counted when the clock advances again.
            if elapsed > 0:
                earned_tokens = elapsed * self.refill_per_second
                self.tokens = min(float(self.capacity), self.tokens + earned_tokens)
                self.last_refill = now
    
        def try_remove(self) -> Tuple[bool, float]:
            """Attempt to spend 1 token; return (True, 0.0) or (False, seconds_until_1_token)."""
            self._refill()
            if self.tokens >= 1.0:
                self.tokens -= 1.0
                return True, 0.0
    
            # Denied requests consume zero tokens; compute exact wait until balance reaches 1.0.
            missing_tokens = 1.0 - self.tokens
            wait_seconds = missing_tokens / self.refill_per_second
            return False, wait_seconds
    
        def available(self) -> float:
            """Return the up-to-date fractional token balance without consuming any tokens."""
            self._refill()
            return self.tokens
    
  4. Validate startup configuration and fail fast

    Bad configuration in a rate limiter causes silent production outages: for instance, in JavaScript a typo like "refilPerSecond": 2 leaves config.refillPerSecond as undefined, turning tokens + elapsed * undefined into NaN and silently returning 429 on every request forever! Validating strictly at startup catches mistakes before the server ever binds its port:

    • Top-level JSON must be an object containing only "capacity", "refillPerSecond", and optional "port" (default 3000).
    • capacity must be a whole number >= 1, refillPerSecond a finite number > 0, and port a whole number in 1..65535.
    import json
    
    
    class ConfigError(ValueError):
        """Raised when configuration is missing, malformed, or out of range so startup aborts."""
    
    
    ALLOWED_KEYS = ("capacity", "refillPerSecond", "port")
    DEFAULT_PORT = 3000
    
    
    def _is_whole_number(value: Any) -> bool:
        # Accept JSON numbers with zero fractional part (such as 3 or 3.0) to match JS Number.isInteger.
        return _is_finite_number(value) and value == int(value)
    
    
    def parse_config(text: str) -> Dict[str, Any]:
        """Parse and validate JSON configuration text, raising ConfigError on any invalid field."""
        try:
            data = json.loads(text)
        except json.JSONDecodeError as exc:
            raise ConfigError(f"config is not valid JSON: {exc}") from exc
    
        # Reject JSON arrays, strings, numbers, or null at the top level.
        if not isinstance(data, dict):
            raise ConfigError("config must be a JSON object")
    
        # Reject unknown keys so typos like "refilPerSecond" fail loudly instead of being ignored.
        for key in data:
            if key not in ALLOWED_KEYS:
                raise ConfigError(f"unknown config key: {key}")
    
        capacity = data.get("capacity")
        if not _is_whole_number(capacity) or capacity < 1:
            raise ConfigError("capacity must be an integer >= 1")
    
        refill_per_second = data.get("refillPerSecond")
        if not _is_finite_number(refill_per_second) or refill_per_second <= 0:
            raise ConfigError("refillPerSecond must be a finite number > 0")
    
        port = data.get("port", DEFAULT_PORT)
        if not _is_whole_number(port) or port < 1 or port > 65535:
            raise ConfigError("port must be an integer in 1..65535")
    
        return {
            "capacity": int(capacity),
            "refillPerSecond": float(refill_per_second),
            "port": int(port),
        }
    
    
    def load_config(path: str) -> Dict[str, Any]:
        """Read configuration from disk and validate it, wrapping file errors in ConfigError."""
        try:
            with open(path, encoding="utf-8") as config_file:
                text = config_file.read()
        except (OSError, UnicodeDecodeError) as exc:
            raise ConfigError(f"cannot read config {path}: {exc}") from exc
        return parse_config(text)
    
  5. Map bucket decisions to HTTP 200 and 429 responses

    • Allowed (200 OK): Return {"message": "ok", "remainingTokens": math.floor(bucket.tokens)} so callers can see how many whole tokens remain right now.
    • Denied (429 Too Many Requests): Use 429 rather than 503 Service Unavailable because the server itself is healthy — only the rate quota is exhausted. HTTP's Retry-After header requires a non-negative integer number of seconds, so we round up (math.ceil) to make sure a well-behaved client never retries 100 ms too early and hits a second 429.
    def handle_request(bucket: TokenBucket) -> Tuple[int, Dict[str, str], Dict[str, Any]]:
        """Map one bucket decision to an HTTP (status_code, headers, json_body) response."""
        allowed, wait_seconds = bucket.try_remove()
        if allowed:
            whole_tokens_left = math.floor(bucket.tokens)
            return 200, {}, {"message": "ok", "remainingTokens": whole_tokens_left}
    
        # HTTP Retry-After uses whole seconds: round UP so callers do not retry slightly too early.
        retry_seconds = max(1, math.ceil(wait_seconds))
        headers = {"Retry-After": str(retry_seconds)}
        body = {"error": "rate_limited", "retryAfterSeconds": retry_seconds}
        return 429, headers, body
    
  6. Full Node.js Express implementation

    Split the Node.js application into three focused modules (config.js, tokenBucket.js, server.js) so each piece can be unit-tested independently without starting a real TCP socket:

    // config.js — synchronous startup config loader and validator
    const fs = require('fs');
    
    const ALLOWED_KEYS = new Set(['capacity', 'refillPerSecond', 'port']);
    
    function parseConfig(text) {
      let data;
      try {
        data = JSON.parse(text);
      } catch (err) {
        throw new Error(`config is not valid JSON: ${err.message}`);
      }
      if (data === null || typeof data !== 'object' || Array.isArray(data)) {
        throw new Error('config must be a JSON object');
      }
      for (const key of Object.keys(data)) {
        if (!ALLOWED_KEYS.has(key)) {
          throw new Error(`unknown config key: ${key}`);
        }
      }
      const { capacity, refillPerSecond, port = 3000 } = data;
      if (!Number.isInteger(capacity) || capacity < 1) {
        throw new Error('capacity must be an integer >= 1');
      }
      if (typeof refillPerSecond !== 'number' || !Number.isFinite(refillPerSecond) || refillPerSecond <= 0) {
        throw new Error('refillPerSecond must be a finite number > 0');
      }
      if (!Number.isInteger(port) || port < 1 || port > 65535) {
        throw new Error('port must be an integer in 1..65535');
      }
      return { capacity, refillPerSecond, port };
    }
    
    function loadConfig(path) {
      const text = fs.readFileSync(path, 'utf8');
      return parseConfig(text);
    }
    
    module.exports = { parseConfig, loadConfig };
    
    // tokenBucket.js — pure in-memory token bucket with injectable monotonic clock
    function monotonicSeconds() {
      return performance.now() / 1000;
    }
    
    class TokenBucket {
      constructor(capacity, refillPerSecond, clock = monotonicSeconds) {
        if (!Number.isInteger(capacity) || capacity < 1 || !Number.isFinite(refillPerSecond) || refillPerSecond <= 0) {
          throw new RangeError('capacity must be >= 1 and refillPerSecond > 0');
        }
        this.capacity = capacity;
        this.refillPerSecond = refillPerSecond;
        this.clock = clock;
        this.tokens = capacity;
        this.lastRefill = clock();
      }
    
      _refill() {
        const now = this.clock();
        const elapsed = now - this.lastRefill;
        if (elapsed > 0) {
          this.tokens = Math.min(this.capacity, this.tokens + elapsed * this.refillPerSecond);
          this.lastRefill = now;
        }
      }
    
      tryRemove() {
        this._refill();
        if (this.tokens >= 1) {
          this.tokens -= 1;
          return { allowed: true, remainingTokens: Math.floor(this.tokens), retryAfterSeconds: 0 };
        }
        return {
          allowed: false,
          remainingTokens: 0,
          retryAfterSeconds: (1 - this.tokens) / this.refillPerSecond,
        };
      }
    }
    
    module.exports = { TokenBucket };
    
    // server.js — Express middleware, route wiring, and fail-fast entrypoint
    const express = require('express');
    const { loadConfig } = require('./config');
    const { TokenBucket } = require('./tokenBucket');
    
    function rateLimitMiddleware(bucket) {
      return (req, res, next) => {
        const decision = bucket.tryRemove();
        if (decision.allowed) {
          res.locals.remainingTokens = decision.remainingTokens;
          next();
          return;
        }
        const retrySeconds = Math.max(1, Math.ceil(decision.retryAfterSeconds));
        res.set('Retry-After', String(retrySeconds));
        res.status(429).json({ error: 'rate_limited', retryAfterSeconds: retrySeconds });
      };
    }
    
    function createApp(bucket) {
      const app = express();
      app.get('/api/resource', rateLimitMiddleware(bucket), (req, res) => {
        res.status(200).json({ message: 'ok', remainingTokens: res.locals.remainingTokens });
      });
      return app;
    }
    
    function main() {
      let config;
      try {
        config = loadConfig(process.argv[2] || 'config.json');
      } catch (err) {
        console.error(`startup failed: ${err.message}`);
        process.exit(1);
      }
      const bucket = new TokenBucket(config.capacity, config.refillPerSecond);
      createApp(bucket).listen(config.port);
    }
    
    if (require.main === module) {
      main();
    }
    
    module.exports = { createApp, rateLimitMiddleware };
    
  7. Walk through Sample 2 and code-review points

    Trace Example 2 (capacity = 2, refillPerSecond = 0.5 tokens/second, plus an idle recovery check at t = 30.00 s):

    Time (s)  Balance after refill       Decision  Balance after  HTTP response
    --------  -------------------------  --------  -------------  ---------------------------------
      0.00    2.00 (starts full)         ALLOW     1.00           200 {"remainingTokens": 1}
      0.00    1.00 + 0.00 = 1.00         ALLOW     0.00           200 {"remainingTokens": 0}
      0.50    0.00 + 0.50*0.5 = 0.25     DENY      0.25           429 Retry-After: 2 (wait = 1.50s)
      2.00    0.25 + 1.50*0.5 = 1.00     ALLOW     0.00           200 {"remainingTokens": 0}
     30.00    min(2.00, 0.00 + 28*0.5)   ALLOW     1.00           200 {"remainingTokens": 1}
    

    When reviewing this architecture with a teammate, highlight four design trade-offs:

    1. Separation of concerns & testability: config.js validates inputs at startup, TokenBucket contains pure math with an injected clock (microsecond unit tests, zero sleep), and rateLimitMiddleware handles HTTP headers/statuses.
    2. Single-thread atomicity: Because Node.js runs JavaScript on a single event loop thread and tryRemove() has no await inside it, two concurrent HTTP requests never interleave mid-calculation.
    3. Changing scope to per-user/API-key: Replace the single TokenBucket with a Map<key, TokenBucket> plus idle eviction once now - lastRefill >= capacity / refillPerSecond (when an idle bucket is full again anyway) and an LRU cap against random-key floods.
    4. Scaling across multiple instances: Separate processes hold separate memory, multiplying a client's burst by N servers unless bucket state moves to an atomic shared store (such as a Redis Lua script).
  8. Complete solution

    from typing import Any, Callable, Dict, Tuple
    import json
    import math
    import time
    
    
    class ConfigError(ValueError):
        """Raised when configuration is missing, malformed, or out of range so startup aborts."""
    
    
    ALLOWED_KEYS = ("capacity", "refillPerSecond", "port")
    DEFAULT_PORT = 3000
    
    
    def _is_finite_number(value: Any) -> bool:
        # In Python, bool subclasses int (isinstance(True, int) is True), so reject bool first.
        if isinstance(value, bool) or not isinstance(value, (int, float)):
            return False
        # Reject NaN, Infinity, and -Infinity, which Python's json.loads accepts by default.
        return math.isfinite(value)
    
    
    def _is_whole_number(value: Any) -> bool:
        # Accept JSON numbers with zero fractional part (such as 3 or 3.0) to match JS Number.isInteger.
        return _is_finite_number(value) and value == int(value)
    
    
    def parse_config(text: str) -> Dict[str, Any]:
        """Parse and validate JSON configuration text, raising ConfigError on any invalid field."""
        try:
            data = json.loads(text)
        except json.JSONDecodeError as exc:
            raise ConfigError(f"config is not valid JSON: {exc}") from exc
    
        # Reject JSON arrays, strings, numbers, or null at the top level.
        if not isinstance(data, dict):
            raise ConfigError("config must be a JSON object")
    
        # Reject unknown keys so typos like "refilPerSecond" fail loudly instead of being ignored.
        for key in data:
            if key not in ALLOWED_KEYS:
                raise ConfigError(f"unknown config key: {key}")
    
        capacity = data.get("capacity")
        if not _is_whole_number(capacity) or capacity < 1:
            raise ConfigError("capacity must be an integer >= 1")
    
        refill_per_second = data.get("refillPerSecond")
        if not _is_finite_number(refill_per_second) or refill_per_second <= 0:
            raise ConfigError("refillPerSecond must be a finite number > 0")
    
        port = data.get("port", DEFAULT_PORT)
        if not _is_whole_number(port) or port < 1 or port > 65535:
            raise ConfigError("port must be an integer in 1..65535")
    
        return {
            "capacity": int(capacity),
            "refillPerSecond": float(refill_per_second),
            "port": int(port),
        }
    
    
    def load_config(path: str) -> Dict[str, Any]:
        """Read configuration from disk and validate it, wrapping file errors in ConfigError."""
        try:
            with open(path, encoding="utf-8") as config_file:
                text = config_file.read()
        except (OSError, UnicodeDecodeError) as exc:
            raise ConfigError(f"cannot read config {path}: {exc}") from exc
        return parse_config(text)
    
    
    class TokenBucket:
        """Single in-memory token bucket starting full and refilling lazily from a monotonic clock."""
    
        def __init__(self, capacity: int, refill_per_second: float,
                     clock: Callable[[], float] = time.monotonic) -> None:
            if isinstance(capacity, bool) or capacity < 1:
                raise ValueError("capacity must be an integer >= 1")
            if not _is_finite_number(refill_per_second) or refill_per_second <= 0:
                raise ValueError("refill_per_second must be a finite number > 0")
    
            self.capacity = capacity
            self.refill_per_second = float(refill_per_second)
            self.clock = clock
            # Bucket state: current fractional token balance (0.0 .. capacity) and last accounting timestamp.
            self.tokens = float(capacity)
            self.last_refill = clock()
    
        def _refill(self) -> None:
            """Credit tokens earned since self.last_refill, capped at self.capacity."""
            now = self.clock()
            elapsed = now - self.last_refill
            # Guard elapsed > 0: if a fake clock steps backward, neither deduct tokens nor move last_refill,
            # ensuring the same time interval is never double-counted when the clock advances again.
            if elapsed > 0:
                earned_tokens = elapsed * self.refill_per_second
                self.tokens = min(float(self.capacity), self.tokens + earned_tokens)
                self.last_refill = now
    
        def try_remove(self) -> Tuple[bool, float]:
            """Attempt to spend 1 token; return (True, 0.0) or (False, seconds_until_1_token)."""
            self._refill()
            if self.tokens >= 1.0:
                self.tokens -= 1.0
                return True, 0.0
    
            # Denied requests consume zero tokens; compute exact wait until balance reaches 1.0.
            missing_tokens = 1.0 - self.tokens
            wait_seconds = missing_tokens / self.refill_per_second
            return False, wait_seconds
    
        def available(self) -> float:
            """Return the up-to-date fractional token balance without consuming any tokens."""
            self._refill()
            return self.tokens
    
    
    def handle_request(bucket: TokenBucket) -> Tuple[int, Dict[str, str], Dict[str, Any]]:
        """Map one bucket decision to an HTTP (status_code, headers, json_body) response."""
        allowed, wait_seconds = bucket.try_remove()
        if allowed:
            whole_tokens_left = math.floor(bucket.tokens)
            return 200, {}, {"message": "ok", "remainingTokens": whole_tokens_left}
    
        # HTTP Retry-After uses whole seconds: round UP so callers do not retry slightly too early.
        retry_seconds = max(1, math.ceil(wait_seconds))
        headers = {"Retry-After": str(retry_seconds)}
        body = {"error": "rate_limited", "retryAfterSeconds": retry_seconds}
        return 429, headers, body
    
    
    if __name__ == "__main__":
        demo_bucket = TokenBucket(capacity=3, refill_per_second=2)
        for _ in range(5):
            print(handle_request(demo_bucket))
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine an arcade game card that holds at most capacity credits and automatically earns refillPerSecond new credits every second until the card is full. Each API call swipes the card for 1 credit: if at least 1 credit is available, the call goes through (200 OK); if less than 1 credit is on the card, the swipe is declined (429 Too Many Requests) without deducting anything, and the screen tells you how many seconds to wait until 1 full credit has recharged. Rather than running a background timer to drip credits into the card, we use lazy refill (computing the newly earned credits on the spot from now - lastRefill only when a request actually arrives), reading time from a monotonic clock (a timer that counts steadily forward since boot and never jumps when the system wall clock is adjusted).

A naive timer-based implementation (setInterval) fails because CPU spikes delay timer callbacks and under-count elapsed time, idle buckets burn CPU ticks when nobody calls the service, and scaling to thousands of per-user buckets would spawn thousands of timers. Simply counting requests per calendar minute (a fixed window) also falls short because a caller can send capacity requests at 00:59.9 and another capacity requests at 01:00.1, doubling the intended burst limit.

Walk through Example 2 with capacity = 2 and refillPerSecond = 0.5 tokens/second (1 token every 2 seconds):

  1. Initial burst (t = 0.0 s): Bucket starts full (tokens = 2.0, lastRefill = 0.0). Call 1 spends 1.0 token (1 whole token left -> 200 OK), and Call 2 at t = 0.0 s spends the second token (0 whole tokens left -> 200 OK).
  2. Partial recharge (t = 0.5 s): Call 3 adds 0.5 * 0.5 = 0.25 token (tokens = 0.25, lastRefill = 0.5), which is below 1.0. It leaves tokens = 0.25 untouched, computes wait = (1.0 - 0.25) / 0.5 = 1.5 s, and returns 429 with Retry-After: 2 (ceil(1.5)).
  3. Full token restored (t = 2.0 s): Call 4 adds (2.0 - 0.5) * 0.5 = 0.75 token (tokens = 0.25 + 0.75 = 1.0), spends 1.0 (0 left), and returns 200 OK.

Complexity

  • Time per request — O(1): Each call to try_remove() reads the monotonic clock once and performs a fixed handful of floating-point arithmetic operations (elapsed, min, subtraction or division), regardless of request volume or capacity. Startup configuration parsing runs once in O(C) time where C is the byte length of the JSON file.
  • Space — O(1) per bucket: Each TokenBucket stores just two changing floats (tokens and last_refill) plus its configuration constants, keeping zero per-request timestamp history and zero background timers.

Edge cases

  • Initial burst & server restarts: Starting full intentionally allows capacity immediate requests; however, because state is in-memory, restarting the process resets the bucket to full.
  • Long idle periods: min(capacity, tokens + earned) caps accumulation so an hour of silence yields capacity tokens rather than thousands.
  • Slow fractional rates (e.g., refillPerSecond = 0.25, one token every 4 s): Exact wait times like 2.5 s round up via math.ceil to Retry-After: 3 so clients never retry 0.5 s early into another 429.
  • Backward clock steps in tests: If a mocked clock ever reports now < last_refill, the elapsed > 0 check skips updating both tokens and last_refill so tokens are neither erased nor double-counted later.
  • Floating-point rounding boundaries: Adding 0.1 ten times in IEEE-754 binary float produces 0.9999999999999999, which safely errs on the conservative side by asking for 1 s retry; systems needing exact decimal boundaries can count integer micro-tokens instead.
  • Malformed startup configs: Booleans (true), strings ("10"), 0, negatives, NaN, Infinity, overflow (1e400), invalid ports (0, 70000), and misspelled keys (refilPerSecond) all raise ConfigError before listen().

Common mistakes

  • Using wall-clock time (Date.now() / time.time()): An NTP clock rollback makes elapsed negative (draining tokens), while a forward jump refills the bucket instantly.
  • Refilling with setInterval: Wastes CPU when idle and drifts downward whenever the Node.js event loop (the single thread that executes JavaScript callbacks one after another) is busy.
  • Forgetting min(capacity, ...): Allows unbounded token hoarding during quiet hours, defeating burst protection.
  • Deducting tokens on denied (429) requests: Causes an impatient caller retrying faster than refillPerSecond to dig a deeper negative hole and starve forever unless explicitly intended as a penalty.
  • Returning 503 or rounding Retry-After down: 503 misleads load balancers and alerts into thinking the backend is unhealthy, while Math.floor(wait) tells callers to retry before 1 full token exists.
  • Loose config parsing (parseInt("10ms") or ignoring unknown keys): Silently runs with unintended limits or NaN balances instead of failing deployment fast.

Alternative approaches

  • Fixed-window counter: Counts requests in each discrete clock window (e.g., 12:01:00–12:01:59) using one integer per key, which is tiny in memory (O(1)) but allows 2 * capacity requests right across a window boundary.
  • Sliding-window log: Stores the exact timestamp of every accepted request and evicts entries older than W seconds, giving exact window enforcement at the cost of O(capacity) memory per key.
  • Sliding-window counter: Approximates a sliding window using only two counters (previous and current fixed windows) weighted by overlap fraction, trading slight burst approximation for O(1) space.
  • Leaky bucket (as a FIFO queue): Places incoming requests into a bounded queue drained at a constant rate, smoothing traffic spikes into a steady trickle at the cost of extra queuing latency.
  • Generic Cell Rate Algorithm (GCRA): Tracks a single timestamp ("theoretical arrival time") per key that is mathematically equivalent to a token bucket while needing only one number in distributed stores like Redis.

Follow-up questions

  • Why does updating the bucket without locks avoid race conditions in a single-threaded Node.js process, and what code modification would break that safety? Node.js executes JavaScript callbacks on a single event-loop thread to completion without preemption, and tryRemove() reads the clock, computes the refill, and deducts 1 token synchronously with zero await points in between. Because no other request callback can run mid-function, two simultaneous HTTP arrivals execute strictly one after the other. That guarantee breaks immediately if you put an asynchronous await between reading and writing the token count (such as GETting the balance from Redis and later SETting it, allowing two requests to both read 1 token and both pass), or if you run multiple Node.js worker threads/processes without shared atomic state.
  • When multiple server replicas sit behind a load balancer, how do you stop callers from getting a separate full quota on each replica? Move bucket state out of per-process RAM into a shared, low-latency store like Redis and execute the read-refill-deduct logic atomically inside a single Redis Lua script (which Redis runs from start to finish without interleaving other commands), using Redis's own server clock (TIME) so clock skew across Node.js hosts cannot distort refills. Because this adds a ~1 ms network hop and an external dependency, you must also choose an explicit failure policy (fail-open to preserve availability vs fail-closed to protect downstream capacity) if Redis is unreachable. Simpler alternatives when approximate limits suffice include consistent-hash routing by API key at the load balancer or enforcing rate limits centrally at an API gateway.
  • If you switch from a global bucket to one bucket per user, how do you keep idle accounts from exhausting server RAM? Notice that any bucket untouched for at least fullRefillSeconds = capacity / refillPerSecond (for example, 10 / 2 = 5 s) has refilled completely to capacity, making it indistinguishable from a brand-new user's bucket! You can safely delete entries idle longer than capacity / refillPerSecond (via a periodic cleanup sweep using setInterval(...).unref() in Node.js, or EXPIRE TTLs in Redis) with zero impact on accuracy. To defend against an attacker spraying millions of unique keys inside that 5 s window, authenticate before creating per-user buckets and cap the Map at a fixed maximum entry count with LRU eviction (evicting the least recently used key when full, leveraging JavaScript Map's insertion-order iteration).

Follow-up questions

Similar questions

More Okta interview questions

All 11 Okta questions →