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
capacitytokens. No external cache or cross-process synchronization is used in this baseline version. - Lazy refill and burst cap: Unused tokens replenish continuously at
refillPerSecondtokens per elapsed second measured on a monotonic clock, capped atcapacityso quiet periods never build up extra burst allowance abovecapacity. - Per-request accounting: Every permitted request deducts
1token and returns HTTP200. When fewer than1token is present, the request is rejected with HTTP429,0tokens are deducted, and the response reports how many whole seconds (rounded up) the client must wait before1full 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
ConfigErrorbefore 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 stringtextinto{"capacity": int, "refillPerSecond": float, "port": int}.- Required keys:
"capacity"(whole number>= 1) and"refillPerSecond"(finite number> 0). - Optional key:
"port"(whole number in1..65535, defaulting to3000). - Reject non-object JSON roots, booleans, strings,
NaN,Infinity, fractional values on integer fields (whole-valued floats such as4.0are accepted and converted toint), and any unknown key by raisingConfigError.
- Required keys:
load_config(path: str) -> Dict[str, Any]: read the UTF-8 file atpathand pass its contents toparse_config, converting anyOSErrororUnicodeDecodeErrorintoConfigError.TokenBucket(capacity: int, refill_per_second: float, clock: Callable[[], float] = time.monotonic):- Raise
ValueErrorifcapacity < 1,refill_per_second <= 0, either argument is abool, orrefill_per_secondis non-finite. try_remove() -> Tuple[bool, float]: advance token balance usingclock(). If at least1.0token is available, subtract1.0and return(True, 0.0); otherwise subtract nothing and return(False, wait_seconds)wherewait_secondsis the exact time needed to reach1.0token.available() -> float: advance token balance usingclock()and return the current fractional balance without removing tokens.
- Raise
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})wherewhole_tokens_leftis 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}).
- If
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 like4.0are accepted in JSON and normalized toint)."refillPerSecond"must be a finiteintorfloatstrictly greater than0."port", when present, must be an integer in1..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(), andhandle_request()must each run inO(1)time andO(1)space per call.
Step-by-step walkthrough
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) andrefillPerSecond(how many tokens trickle in each second):- Short bursts allowed: Because the bucket starts full at
capacity, up tocapacityrequests can succeed immediately back to back. - Long-run rate bounded: Over any interval of
Tseconds, at mostcapacity + refillPerSecond × Trequests can pass. For example, withcapacity = 10andrefillPerSecond = 2, at most10 + 2 × 60 = 130requests 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 atcapacity, and each allowed request spends1token. - Denied requests: Spend
0tokens and return HTTP429 Too Many Requestswith aRetry-Afterheader 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.- Short bursts allowed: Because the bucket starts full at
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:- Event-loop lag under-counts tokens: If CPU work delays a timer tick, adding a fixed amount per tick falls behind real elapsed time.
- Wasted idle CPU: Timers wake up continuously even when zero traffic hits the server.
- 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:
tokensandlastRefill: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
nowfrom 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.Implement the `TokenBucket` class
Inject
clockas a constructor parameter (defaulting totime.monotonic) so unit tests can advance time deterministically withoutsleep(). Notice two defensive details:- Reject
bool,NaN,Infinity,capacity < 1, andrefill_per_second <= 0in__init__. - Only update
tokensandlast_refillwhenelapsed > 0. If a fake test clock ever steps backward, leavinglast_refilluntouched 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- Reject
Validate startup configuration and fail fast
Bad configuration in a rate limiter causes silent production outages: for instance, in JavaScript a typo like
"refilPerSecond": 2leavesconfig.refillPerSecondasundefined, turningtokens + elapsed * undefinedintoNaNand silently returning429on 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"(default3000). capacitymust be a whole number>= 1,refillPerSeconda finite number> 0, andporta whole number in1..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)- Top-level JSON must be an object containing only
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): Use429rather than503 Service Unavailablebecause the server itself is healthy — only the rate quota is exhausted. HTTP'sRetry-Afterheader requires a non-negative integer number of seconds, so we round up (math.ceil) to make sure a well-behaved client never retries100 mstoo early and hits a second429.
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- Allowed (
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 };Walk through Sample 2 and code-review points
Trace Example 2 (
capacity = 2,refillPerSecond = 0.5tokens/second, plus an idle recovery check att = 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:
- Separation of concerns & testability:
config.jsvalidates inputs at startup,TokenBucketcontains pure math with an injected clock (microsecond unit tests, zerosleep), andrateLimitMiddlewarehandles HTTP headers/statuses. - Single-thread atomicity: Because Node.js runs JavaScript on a single event loop thread and
tryRemove()has noawaitinside it, two concurrent HTTP requests never interleave mid-calculation. - Changing scope to per-user/API-key: Replace the single
TokenBucketwith aMap<key, TokenBucket>plus idle eviction oncenow - lastRefill >= capacity / refillPerSecond(when an idle bucket is full again anyway) and an LRU cap against random-key floods. - Scaling across multiple instances: Separate processes hold separate memory, multiplying a client's burst by
Nservers unless bucket state moves to an atomic shared store (such as a Redis Lua script).
- Separation of concerns & testability:
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):
- Initial burst (
t = 0.0 s): Bucket starts full (tokens = 2.0,lastRefill = 0.0). Call 1 spends1.0token (1whole token left ->200 OK), and Call 2 att = 0.0 sspends the second token (0whole tokens left ->200 OK). - Partial recharge (
t = 0.5 s): Call 3 adds0.5 * 0.5 = 0.25token (tokens = 0.25,lastRefill = 0.5), which is below1.0. It leavestokens = 0.25untouched, computeswait = (1.0 - 0.25) / 0.5 = 1.5 s, and returns429withRetry-After: 2(ceil(1.5)). - Full token restored (
t = 2.0 s): Call 4 adds(2.0 - 0.5) * 0.5 = 0.75token (tokens = 0.25 + 0.75 = 1.0), spends1.0(0left), and returns200 OK.
Complexity
- Time per request —
O(1): Each call totry_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 orcapacity. Startup configuration parsing runs once inO(C)time whereCis the byte length of the JSON file. - Space —
O(1)per bucket: EachTokenBucketstores just two changing floats (tokensandlast_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
capacityimmediate 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 yieldscapacitytokens rather than thousands. - Slow fractional rates (e.g.,
refillPerSecond = 0.25, one token every4 s): Exact wait times like2.5 sround up viamath.ceiltoRetry-After: 3so clients never retry0.5 searly into another429. - Backward clock steps in tests: If a mocked clock ever reports
now < last_refill, theelapsed > 0check skips updating bothtokensandlast_refillso tokens are neither erased nor double-counted later. - Floating-point rounding boundaries: Adding
0.1ten times in IEEE-754 binary float produces0.9999999999999999, which safely errs on the conservative side by asking for1 sretry; 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 raiseConfigErrorbeforelisten().
Common mistakes
- Using wall-clock time (
Date.now()/time.time()): An NTP clock rollback makeselapsednegative (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 thanrefillPerSecondto dig a deeper negative hole and starve forever unless explicitly intended as a penalty. - Returning
503or roundingRetry-Afterdown:503misleads load balancers and alerts into thinking the backend is unhealthy, whileMath.floor(wait)tells callers to retry before1full token exists. - Loose config parsing (
parseInt("10ms")or ignoring unknown keys): Silently runs with unintended limits orNaNbalances 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 allows2 * capacityrequests right across a window boundary. - Sliding-window log: Stores the exact timestamp of every accepted request and evicts entries older than
Wseconds, giving exact window enforcement at the cost ofO(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 deducts1token synchronously with zeroawaitpoints 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 asynchronousawaitbetween reading and writing the token count (such asGETting the balance from Redis and laterSETting it, allowing two requests to both read1token 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 tocapacity, making it indistinguishable from a brand-new user's bucket! You can safely delete entries idle longer thancapacity / refillPerSecond(via a periodic cleanup sweep usingsetInterval(...).unref()in Node.js, orEXPIRETTLs in Redis) with zero impact on accuracy. To defend against an attacker spraying millions of unique keys inside that5 swindow, authenticate before creating per-user buckets and cap theMapat a fixed maximum entry count with LRU eviction (evicting the least recently used key when full, leveraging JavaScriptMap's insertion-order iteration).
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?
- When multiple server replicas sit behind a load balancer, how do you stop callers from getting a separate full quota on each replica?
- If you switch from a global bucket to one bucket per user, how do you keep idle accounts from exhausting server RAM?
Similar questions
- Securing an MCP Server with Auth0 RS256 Tokens
- Fixing a Blocking Express Login Endpoint Safely
- Refactor Session Deduplication for Time and Memory
- Three-Part Behavioral Screen: AI Workflows, Peer Leadership, and Cross-Team Delivery
- Order-Preserving Array Deduplication
- Multi-Tenant Time-Series Metrics Platform
More Okta interview questions
- Three-Part Behavioral Screen: AI Workflows, Peer Leadership, and Cross-Team Delivery Medium
- Cross-Domain OIDC Sign-On and Delegated Tool Authorization Medium
- Fixing a Blocking Express Login Endpoint Safely Medium Pro
- Securing an MCP Server with Auth0 RS256 Tokens Medium Pro
- Order-Preserving Array Deduplication Medium Pro
- Real-Time Messaging and Critical Alert Platform Medium Pro
- Cross-Domain OIDC Single Sign-On and Third-Party API Delegation Medium Pro
- Multi-Tenant Time-Series Metrics Platform Medium Pro
- Refactor Session Deduplication for Time and Memory Medium Pro
- Filter Valid IPv4 Addresses Medium Pro