Rate-Limiter-Algorithms
Four rate-limiting algorithms — Token Bucket, Fixed Window Counter, Sliding Window Log, Sliding Window Counter — implemented in C++20, with tests that prove (not just claim) each one's actual behavioral tradeoffs, including a well-known algorithmic weakness deliberately reproduced and confirmed rather than glossed over.
Why this matters across industries
Rate limiting is a general-purpose control problem, not a finance-specific one: API gateways throttling client traffic (tech infrastructure), exchange/order-entry throughput controls (finance), and command-rate limiting on industrial control interfaces (a write-flood-style protection, the same category of rule this account's IEC104-ICS-IDS/ICS-Modbus-IDS projects implement for SCADA protocols) all reduce to picking the right algorithm for the right tradeoff. The point of this project is that the tradeoffs in the table below are proven by test, not asserted — the same rigor a consulting engagement or a production infra decision needs before picking one.
The four algorithms, and why more than one exists
| Algorithm |
Memory |
Exact? |
Known weakness |
| Token Bucket |
O(1) |
Yes |
Allows a burst up to capacity all at once |
| Fixed Window Counter |
O(1) |
Yes, per window |
Boundary burst: up to 2× the limit can pass in a short span straddling a window edge |
| Sliding Window Log |
O(limit) |
Yes, always |
Memory scales with the limit (stores every request timestamp) |
| Sliding Window Counter |
O(1) |
Approximate |
Assumes uniform request distribution within the previous window |
This project exists specifically to make that table verifiable rather than asserted: tests/test_fixed_window.cpp reproduces the boundary-burst problem and proves it (5 requests accepted at t=999ms, 5 more at t=1001ms — 10 requests within ~3ms under a "5/second" limit), and tests/test_sliding_window_log.cpp runs the identical scenario through Sliding Window Log to prove it doesn't have that problem.
Design
Every limiter takes a Clock& (see include/ratelimit/clock.hpp) instead of calling std::chrono::steady_clock::now() directly. Tests use a TestClock that only advances when told to — so timing-dependent tests (refill rates, window boundaries, decay of a sliding counter's previous-window influence) are exact and instant, never a flaky sleep()-and-hope.
All four are thread-safe (mutex-guarded); tests/test_concurrency.cpp runs 8 real OS threads against a shared limiter instance and asserts the exact expected grant count — not "roughly right," exactly capacity grants out of many more attempts, every time.
Verified correctness
- Token Bucket: burst-to-capacity then reject, refill rate checked against a hand-computed value, capacity is a hard ceiling even after a very long idle period, variable per-request cost.
- Fixed Window Counter: exact limit enforcement within one window, full reset at the boundary, and the boundary-burst problem reproduced explicitly as a documented property of the algorithm, not hidden.
- Sliding Window Log: exact limit enforcement in the trailing window at any instant, correct behavior across the exact scenario that breaks Fixed Window.
- Sliding Window Counter: the estimate formula (
current + previous × overlap_fraction) checked against hand-computed values at several points, including the previous window's influence decaying to ~0 near the end of the current window and being discarded entirely after a multi-window gap.
- Concurrency: 8 threads × 50 attempts against a 100-capacity limiter — exactly 100 granted, every run, for all three lock-protected limiters tested.
64 assertions across 19 Catch2 test cases, all passing, plus the same suite run clean under AddressSanitizer + UndefinedBehaviorSanitizer.
Benchmarks
Measured on this repo's own dev machine (shared 4-core Xeon E5-2683 v3 @ 2.5GHz VM):
| Limiter |
Latency/call |
Throughput |
| Token Bucket |
12.2 ns |
81.6M/s |
| Fixed Window Counter |
12.4 ns |
81.0M/s |
| Sliding Window Log (near capacity) |
18.8 ns |
53.2M/s |
| Sliding Window Counter |
28.9 ns |
34.5M/s |
Worth noting honestly: Sliding Window Counter is the slowest here despite being O(1) memory — its window-alignment arithmetic (integer division on chrono::durations every call) costs more than Sliding Window Log's simple deque operations at this scale. "O(1)" isn't automatically "fastest in practice." Reproduce with cmake --build build --target rl_bench && ./build/rl_bench.
Try it
cmake -B build -G Ninja -DCMAKE_BUILD_TYPE=Release
cmake --build build
./build/rate-limiter-demo
Or with Docker:
docker build -t rate-limiter-algorithms .
docker run --rm rate-limiter-algorithms
Honest scope — what this is not
- Single-process only. These are in-memory limiters for one process; a real distributed rate limiter needs a shared store (Redis, etc.) and network round-trips change the performance/consistency tradeoffs significantly. Not attempted here.
- ThreadSanitizer could not be verified in this project's development sandbox — it fails with
FATAL: ThreadSanitizer: unexpected memory mapping even on a completely empty int main(){} program in that environment, confirming it's a sandbox limitation, not a bug here. CI attempts it on a normal GitHub-hosted runner instead (see .github/workflows/ci.yml); check the Actions tab for the current result rather than assuming either way.
- No distributed rate limiting, no per-key/per-user sharding, no persistence — this is the algorithmic core, not a production rate-limiting service.
License
MIT — see LICENSE.