Token-Bucket Rate Limiter in Node.js/Express: Build & Review
System DesignModel answerLast 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
-
Configuration loading — read a file (JSON or similar) that specifies at minimum:
capacity: the maximum number of tokens the bucket can holdrefillRate: how many tokens are restored per second
-
Express application — expose at least one endpoint (e.g.
GET /ping) whose responses are governed by the rate limiter. -
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.
- If at least one token is available, consume it and let the request through (
-
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
429response 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The token-bucket algorithm maintains a counter of available tokens and a record of when it was last updated. Rather than refilling on a timer, each incoming request triggers a lazy refill: calculate how many tokens have accumulated since the last check, add them up to the configured capacity, then either consume one token or reject the request.
This lazy approach requires no background process and fits naturally into Express middleware.
Configuration and Startup Validation
Load and validate configuration before the server starts. Fail fast with a descriptive error so a misconfigured deploy is immediately obvious.
// config.js
const fs = require('fs');
function loadConfig(filePath) {
let raw;
try {
raw = JSON.parse(fs.readFileSync(filePath, 'utf8'));
} catch (err) {
throw new Error(`Cannot read config file at ${filePath}: ${err.message}`);
}
const { capacity, refillRate } = raw;
if (typeof capacity !== 'number' || capacity <= 0) {
throw new Error('Config: "capacity" must be a positive number.');
}
if (typeof refillRate !== 'number' || refillRate <= 0) {
throw new Error('Config: "refillRate" must be a positive number (tokens/sec).');
}
return { capacity, refillRate };
}
module.exports = { loadConfig };
Token-Bucket Core
The limiter is a plain class that accepts an injectable clock function — the key decision for testability.
// tokenBucket.js
class TokenBucket {
constructor({ capacity, refillRate, now = () => Date.now() }) {
this.capacity = capacity;
this.refillRate = refillRate; // tokens per millisecond internally
this.tokens = capacity; // start full
this.lastRefill = now();
this.now = now;
}
// Returns true and consumes a token, or returns false if empty.
consume() {
const currentTime = this.now();
const elapsed = currentTime - this.lastRefill; // ms
const newTokens = (elapsed / 1000) * this.refillRate; // tokens per second
this.tokens = Math.min(this.capacity, this.tokens + newTokens);
this.lastRefill = currentTime;
if (this.tokens >= 1) {
this.tokens -= 1;
return true;
}
return false;
}
// Seconds until at least one token is available.
retryAfterSeconds() {
const deficit = 1 - this.tokens;
return deficit / this.refillRate;
}
}
module.exports = { TokenBucket };
Express Middleware and Route
The middleware owns the rate-limiting decision; the route handler only handles the happy path. Separation of concerns keeps both easy to test independently.
// app.js
const express = require('express');
const { loadConfig } = require('./config');
const { TokenBucket } = require('./tokenBucket');
function createApp(configPath) {
const config = loadConfig(configPath); // throws and exits if invalid
const bucket = new TokenBucket(config);
const app = express();
function rateLimitMiddleware(req, res, next) {
if (bucket.consume()) {
return next();
}
const retryAfter = Math.ceil(bucket.retryAfterSeconds());
res.setHeader('Retry-After', retryAfter);
res.status(429).json({
error: 'Too Many Requests',
retryAfterSeconds: retryAfter,
});
}
app.get('/ping', rateLimitMiddleware, (req, res) => {
res.json({ message: 'pong' });
});
return app;
}
module.exports = { createApp };
// server.js
const { createApp } = require('./app');
try {
const app = createApp('./config.json');
app.listen(3000, () => console.log('Listening on :3000'));
} catch (err) {
console.error(err.message);
process.exit(1);
}
Clock Choice
Date.now() is used here for clarity, but process.hrtime.bigint() is a better default in production. System clock corrections (NTP jumps, DST changes) can make Date.now() move backward or jump forward, producing negative elapsed times or an accidental token windfall. hrtime is monotonic and avoids both failure modes. The injectable now parameter makes swapping easy.
Testing Without Real Time
Because now is injected, tests control time completely:
// tokenBucket.test.js
const { TokenBucket } = require('./tokenBucket');
test('exhausts bucket and refills after one second', () => {
let fakeTime = 0;
const bucket = new TokenBucket({
capacity: 2,
refillRate: 1, // 1 token/sec
now: () => fakeTime,
});
expect(bucket.consume()).toBe(true); // 1 token left
expect(bucket.consume()).toBe(true); // 0 tokens left
expect(bucket.consume()).toBe(false); // empty
fakeTime += 1000; // advance 1 second
expect(bucket.consume()).toBe(true); // refilled 1 token
});
Useful test scenarios: exhaustion, partial refill, idle period longer than capacity / refillRate (tokens must not exceed capacity), and a denied request not consuming tokens.
Code-Review Trade-off Discussion
What breaks first with horizontal scaling: Each process holds its own bucket in memory. Two instances behind a load balancer effectively double the real rate limit. The fix is a shared atomic store (Redis with a Lua script, or a distributed counter). Lua scripts on Redis execute atomically, making the check-and-decrement safe without locks.
Per-user buckets: Change the single bucket instance to a Map keyed by user ID, API key, or hashed IP. Now memory is unbounded — introduce a TTL eviction policy or use Redis with key expiry. The middleware grows by one lookup and one conditional creation.
Denied requests: They do not consume a token in this implementation. That is the right default — penalizing callers who are already being told to back off can prevent them from ever recovering, especially under retry loops.
Common mistakes to flag in a review:
- Using
new Date()arithmetic instead of a monotonic source. - Forgetting to cap tokens at capacity, allowing unlimited accumulation during idle periods.
- Placing rate-limit logic inside the route handler instead of middleware, making it hard to reuse.
- Not returning a
Retry-Afterheader, which forces clients to guess their backoff interval.