Build a Distributed Token Bucket
Distributed Token Bucket — a complete walkthrough of distributed rate limiting, covering local bucket, remote sync, refill scheduler, and testing.
Project goal
Implement distributed rate limiting that solves enforcing a global rate limit across multiple instances without a centralized bottleneck, with each component independently testable.
Final features
- Local bucket
- Remote sync
- Refill scheduler
- Bias compensation
- Fallback limiter
Architecture
The system is organized around local bucket, remote sync, refill scheduler, and bias compensation ties them together. Data flows as a local token count that refills over time and periodically syncs against a shared counter, with bias to avoid over-granting.
Prerequisites
- Node.js 20 LTS or later
- Familiarity with distributed rate limiting fundamentals
- A local environment to run the test suite
Dependencies
- redis ^4.7.0 — Shared counter
- fastify ^5.0.0 — Limit check API
Directory structure
token_bucket_distributed/
├── src/index.ts
├── src/local-bucket.ts
├── src/remote-sync.ts
├── tests/token_bucket_distributed.test.ts
└── package.json
Phases
1. Local bucket
Build the local bucket that anchors distributed rate limiting and defines the core data shape.
// Local bucket: distributed rate limiting core
export function localbucket(input: LocalbucketInput): LocalbucketResult {
// Build the local bucket that anchors distributed rate limiting and defines the core data shape.
return processLocalbucket(input);
}
Expected behavior: After this phase the local bucket works in isolation and is covered by a unit test.
2. Remote sync
Add the remote sync so distributed rate limiting can enforcing a global rate correctly.
// Remote sync — handles distributed rate limiting Add the remote sync so
export class Remotesync {
constructor(private opts: RemotesyncOptions) {}
async run(ctx: Context): Promise<RemotesyncOutput> {
return this.execute(ctx);
}
}
Expected behavior: After this phase the remote sync works in isolation and is covered by a unit test.
3. Refill scheduler
Wire the refill scheduler to handle clock skew between instances without losing data.
// Refill scheduler: distributed rate limiting stage
export const refillscheduler = (next: Next) => async (req: Request) => {
const out = await transform(req);
return next(out);
};
Expected behavior: After this phase the refill scheduler works in isolation and is covered by a unit test.
4. Bias compensation
Integrate the bias compensation to make distributed rate limiting observable and testable end to end.
// Bias compensation for distributed rate limiting
export async function biascompensation(stream: AsyncIterable<Chunk>): Promise<Aggregate> {
let acc = init();
for await (const c of stream) acc = merge(acc, c);
return acc;
}
Expected behavior: After this phase the bias compensation works in isolation and is covered by a unit test.
5. Fallback limiter
Finalize the fallback limiter so the distributed rate limiting system degrades gracefully under overload.
// Fallback limiter: distributed rate limiting finalization
export function fallbacklimiter(state: State): Result {
validate(state);
return finalize(state);
}
Expected behavior: After this phase the fallback limiter works in isolation and is covered by a unit test.
Testing
Each phase has a focused test: local bucket, remote sync, refill scheduler are exercised in isolation, then an integration test drives the full distributed rate limiting pipeline and asserts the clock skew between instances case is handled.
Troubleshooting
Clock skew between instances that lets each refill slightly faster than the global rate and overshoots the limit
Reproduce with a minimal fixture, then add a guard test so the distributed rate limiting system rejects the condition loudly.
Performance regresses under load
Profile with the sampling analyzer, locate the hot path, and add a targeted benchmark to lock the regression.
Deployment
Run two instances behind a load balancer, share state in Redis, and set resource limits so overload surfaces as backpressure rather than failure.
Known limitations
- Single-region; multi-region replication is out of scope.
- The local bucket is in-process and not horizontally shared by default.
- No auth layer; assume deployment behind an edge that enforces identity.
Project overview
This project builds a distributed rate limiting system whose reason for existing is enforcing a global rate limit across multiple instances without a centralized bottleneck. The temptation in distributed rate limiting is to bolt the interesting part onto a working prototype and discover the hard cases in production; this build inverts that order and treats clock skew between instances that lets each refill slightly faster than the global rate and overshoots the limit as the first thing designed, not the last.
You will implement Local bucket, Remote sync, Refill scheduler, Bias compensation, and Fallback limiter, each as a module with one responsibility and a test that proves it in isolation. The distributed rate limiting pipeline is then the wiring that composes them, and the integration test is where the composition is shown to survive clock skew between instances that lets each refill slightly faster than the global rate and overshoots the limit.
The walkthrough is written for a developer who has used a distributed rate limiting system but has not had to make one honest. It favors explicit data shapes over clever abstractions, and it names the failure each design choice prevents rather than presenting the choice as a style preference.
Each phase ends with something observable — a local bucket that returns the right shape, a remote sync that rejects bad input, an integration test that goes green — so you can stop at any point and still have a distributed rate limiting system that works for the cases covered so far.
What you will build
The finished distributed rate limiting system exposes five capabilities, each with a focused test:
- Local bucket
- Remote sync
- Refill scheduler
- Bias compensation
- Fallback limiter
Local bucket is the foundation that every later stage assumes; Remote sync is where distributed rate limiting correctness lives; Refill scheduler handles clock skew between instances that lets each refill slightly faster than the global rate and overshoots the limit; Bias compensation makes the system observable; and Fallback limiter is the graceful-degradation layer that keeps overload from becoming corruption.
The build keeps the distributed rate limiting logic in ordinary modules you can read in one sitting, and pulls in dependencies only for the parts that are genuinely tedious to hand-roll. That keeps the diff between the tutorial and a real codebase small, and keeps the failure modes visible in code rather than hidden behind a framework.
Architecture and data model
The system is organized around Local bucket, Remote sync, and Refill scheduler, with Bias compensation tying them together. Data flows as a local token count that refills over time and periodically syncs against a shared counter, with bias to avoid over-granting.
Each component is a module with a pure interface where practical: the same input produces the same output, and side effects are pushed to the edges. That discipline is what makes the phases independently testable, because a test for Refill scheduler does not need to stand up Local bucket and Remote sync to exercise the interesting branch.
The data model is deliberately explicit. A local token count that refills over time and periodically syncs against a shared counter, with bias to avoid over-granting Keeping the shape written down — in a schema, a type, or a fixture — means a change to the shape is a visible diff rather than a silent runtime shift, and it means the integration test can assert against a concrete shape instead of guessing.
Configuration and code are kept apart: the configuration says what distributed rate limiting should do, the modules say how. A reviewer can change a threshold or a policy without reading the implementation, which keeps the risky changes small and lets the diff stand as the review.
The failure path through Refill scheduler is designed before the happy path is finished, because clock skew between instances that lets each refill slightly faster than the global rate and overshoots the limit is the case that distinguishes a distributed rate limiting system from a demo. Every component declares what it does when its inputs are wrong, and the integration test asserts each of those declarations.
Prerequisites and dependencies
Have these ready before you install anything, so the distributed rate limiting setup is not blocked by a missing tool:
- Node.js 20 LTS or later
- Familiarity with distributed rate limiting fundamentals
- A local environment to run the test suite
The runtime dependencies are chosen to keep the distributed rate limiting datapath legible:
redis(^4.7.0) — Shared counterfastify(^5.0.0) — Limit check API
# setup for token-bucket-distributed
pnpm init
pnpm add redis fastify
pnpm add -D typescript tsx vitest
Versions are pinned to a major range so the distributed rate limiting install is reproducible; commit the lockfile. The local bucket reads its operational parameters from the environment and validates them at startup, so a missing value fails the boot rather than the first distributed rate limiting request.
Directory structure
Keep each distributed rate limiting component in its own file so it can be tested without starting the others:
token_bucket_distributed/
├── src/index.ts
├── src/local-bucket.ts
├── src/remote-sync.ts
├── tests/token_bucket_distributed.test.ts
└── package.json
Phase 1: Local bucket
Build the local bucket that anchors distributed rate limiting and defines the core data shape.
// Local bucket: distributed rate limiting core
export function localbucket(input: LocalbucketInput): LocalbucketResult {
// Build the local bucket that anchors distributed rate limiting and defines the core data shape.
return processLocalbucket(input);
}
After this phase the local bucket works in isolation and is covered by a unit test. The local bucket defines the data shape that every later stage assumes, so getting it right first means the later phases compile against a stable contract.
Treat the local bucket as the single source of truth for the distributed rate limiting data shape. Validate inputs at the boundary and reject early, so a malformed value never reaches Remote sync or Refill scheduler where its effect would be harder to localize.
Phase 2: Remote sync
Add the remote sync so distributed rate limiting can enforcing a global rate correctly.
// Remote sync — handles distributed rate limiting Add the remote sync so
export class Remotesync {
constructor(private opts: RemotesyncOptions) {}
async run(ctx: Context): Promise<RemotesyncOutput> {
return this.execute(ctx);
}
}
After this phase the remote sync works in isolation and is covered by a unit test. This is where distributed rate limiting correctness lives: the remote sync is what makes enforcing a global rate limit across multiple instances without a centralized bottleneck true, and its test is the proof.
Keep the remote sync pure where you can. A function that takes an input and returns an output is trivial to test and impossible to mock wrong; a class with hidden state is the opposite. Push side effects to the caller and keep the remote sync about the transformation.
Phase 3: Refill scheduler
Wire the refill scheduler to handle clock skew between instances without losing data.
// Refill scheduler: distributed rate limiting stage
export const refillscheduler = (next: Next) => async (req: Request) => {
const out = await transform(req);
return next(out);
};
After this phase the refill scheduler works in isolation and is covered by a unit test. The refill scheduler is the difference between a distributed rate limiting system that works on the happy path and one that survives clock skew between instances that lets each refill slightly faster than the global rate and overshoots the limit.
Design the failure before the success. Decide what refill scheduler does when clock skew between instances that lets each refill slightly faster than the global rate and overshoots the limit: reject, retry, shed, or degrade — and write that test first. A distributed rate limiting system whose failure behavior is unspecified will pick one at random under pressure, and it is usually the wrong one.
Phase 4: Bias compensation
Integrate the bias compensation to make distributed rate limiting observable and testable end to end.
// Bias compensation for distributed rate limiting
export async function biascompensation(stream: AsyncIterable<Chunk>): Promise<Aggregate> {
let acc = init();
for await (const c of stream) acc = merge(acc, c);
return acc;
}
After this phase the bias compensation works in isolation and is covered by a unit test. Observability is not a finishing touch; it is how you know the distributed rate limiting system is doing what it claims in production.
Emit one structured event per meaningful action, with enough context to localize a failure without a second round-trip. The bias compensation is what turns “something is slow” into “the remote sync is slow for inputs matching this shape,” which is the difference between an alert and an investigation.
Phase 5: Fallback limiter
Finalize the fallback limiter so the distributed rate limiting system degrades gracefully under overload.
// Fallback limiter: distributed rate limiting finalization
export function fallbacklimiter(state: State): Result {
validate(state);
return finalize(state);
}
After this phase the fallback limiter works in isolation and is covered by a unit test. The fallback limiter is what keeps overload from becoming corruption: when the distributed rate limiting system is asked for more than it can do, it degrades in a defined way instead of failing in an undefined one.
Pick a degradation strategy for fallback limiter — shed, queue, or backpressure — and make it explicit in code and in a test. Leaving the behavior to chance is how a distributed rate limiting traffic spike becomes a data loss incident.
Testing
Each phase has a focused test: local bucket, remote sync, and refill scheduler are exercised in isolation, then an integration test drives the full distributed rate limiting pipeline and asserts the clock skew between instances case is handled.
Start with unit tests that pin each component’s contract: the local bucket returns the documented shape, the remote sync transforms correctly, and the refill scheduler fails in the documented way. These tests are fast and they localize regressions to the component that broke.
Then add an integration test that composes the components and drives a realistic distributed rate limiting scenario end to end. Assert the happy path first, then deliberately trigger clock skew between instances that lets each refill slightly faster than the global rate and overshoots the limit and assert the system degrades rather than corrupts. Because the components are pure where practical, the integration test stays deterministic rather than flaky.
A distributed rate limiting suite must also prove the negative: bad input is rejected at the boundary, overload is shed rather than queued indefinitely, and a partial failure does not leave the system in an inconsistent state. These are the tests that catch the regressions a happy-path suite never would.
The entire distributed rate limiting suite runs with no external service; every dependency is either in-process or stubbed, so every case is reproducible in CI. That is what lets the refill scheduler failure-mode assertions live as tests rather than as a manual checklist that drifts out of date.
# run the distributed rate limiting test suite
pnpm vitest run
Deployment and operations
Run at least two distributed rate limiting instances behind a load balancer and share state in Redis. Set resource limits so distributed rate limiting overload surfaces as backpressure rather than failure.
Run at least two stateless instances behind a load balancer, and move any shared state into a shared store so the distributed rate limiting behavior is global rather than per instance. Size limits so the system sheds load before it runs out of memory, because a distributed rate limiting system that OOMs under load fails in a way that is hard to reason about.
Drain on deploy: stop accepting new work, let in-flight distributed rate limiting operations finish, then exit. Because the system holds no state that cannot be reconstructed, a rollout is a matter of cycling instances one at a time while watching the error rate.
When a dependency is unavailable, decide explicitly whether the distributed rate limiting system fails closed or degrades. Leaving that choice to chance is how a dependency outage becomes a silent data loss, so make the choice visible in code and in a test.
Security considerations
Validate all distributed rate limiting inputs at the boundary, reject oversized payloads before buffering them, and keep secrets in the environment rather than the repository.
The distributed rate limiting system is a choke point, so it is the right place to reject malformed input before it reaches remote sync or refill scheduler. Validate the shape and the size at the edge, and let the inner components assume what they receive is well-formed.
Never log secrets or full payloads; log enough to localize a failure without recording data that should not be on disk. Treat any external call as untrusted and validate its response before using it, because a distributed rate limiting system that trusts its inputs blindly is one malformed response away from corruption.
Keep dependencies pinned and run an audit in CI. A transitive dependency with a known vulnerability is still a vulnerability in your distributed rate limiting system, and the lockfile is what makes the audit meaningful.
Observability
Emit one structured event per distributed rate limiting operation with the inputs’ shape, the outcome, and a correlation id. Track error rate and latency per component and alert on a step change rather than a single spike.
The correlation id is the thread that ties a user-visible symptom to the distributed rate limiting decision and to the component log entry for the same operation. Without it, an investigation starts from a timestamp and a guess.
Watch the refill scheduler failure rate separately from the overall error rate. A jump in refill scheduler failures usually means clock skew between instances that lets each refill slightly faster than the global rate and overshoots the limit, not a bug in remote sync, and the two have different owners and different fixes.
Chart the share of distributed rate limiting operations that shed, queue, or succeed. A change in the mix points at the cause faster than an aggregate latency can, because each class has a different root.
Troubleshooting
Clock skew between instances that lets each refill slightly faster than the global rate and overshoots the limit. Reproduce with a minimal fixture, then add a guard test so the distributed rate limiting system rejects the condition loudly.
Performance regresses under distributed rate limiting load. Profile with the sampling analyzer, locate the hot path in remote sync, and add a targeted benchmark to lock the regression.
Keep the distributed rate limiting dashboards separate from dependency dashboards. When an operation fails, the correlation id lets you decide in seconds whether the fault is local bucket, remote sync, or refill scheduler, instead of guessing from a timeout.
Limitations and next steps
- Single-region; multi-region replication is out of scope.
- The local bucket is in-process and not horizontally shared by default.
- No auth layer; assume deployment behind an edge that enforces identity.
The distributed rate limiting system is single-region by design; extending to multi-region means making local bucket shareable across regions, which is a real change to the consistency model rather than a config flag. The refill scheduler is in-process, which is correct for one instance but must move to a shared store before scaling out.
There is no authentication or authorization layer; the system assumes it is deployed behind an edge that enforces identity. Adding one is straightforward but out of scope for this build, and doing it here would distract from the distributed rate limiting correctness that is the point.
The natural next step, once the distributed rate limiting pipeline is trusted in production, is to add a short-TTL cache for idempotent reads and a richer bias compensation that exports histograms rather than counters. Both are additive and neither changes the contracts this build establishes.