Unit Testing an Order Throttle With an Injected Clock
Last updated: November 29, 2026
Quick Overview
Implement a token bucket that limits order messages sent to an exchange, and write deterministic unit tests for burst, refill, long idle periods, and a clock that jumps backwards. Explain why the clock must be injectable.
DRW
November 29, 20260
0
0 solved
Implement a token bucket that limits order messages sent to an exchange, and write deterministic unit tests for burst, refill, long idle periods, and a clock that jumps backwards. Explain why the clock must be injectable.
Exchanges such as CME enforce message rate limits, and breaching them can mean rejected orders or penalties, so DRW needs throttles that are correct and well tested. The interviewer focuses on testability: time dependent code that sleeps in tests is slow and flaky, and they want to see you design around that.
What the Interviewer Expects
- Implements token bucket with rate and burst
- Injects a clock function instead of calling time directly
- Writes tests for burst, refill, cap after idle, and time going backwards
- Uses a monotonic clock in production
- Mentions floating point edge cases at exact refill boundaries
Key Topics to Cover
How to Approach This
- Apply SOLID principles. Single Responsibility makes code testable, Open/Closed makes it extensible.
- Choose data structures based on access patterns, not familiarity.
- Prefer immutable data and message passing over shared mutable state for concurrency.
- Design APIs with RESTful conventions, versioning, meaningful errors, and pagination from day one.
Possible Follow-up Questions
- How would you throttle per session and globally at the same time?
- Should rejected sends be queued or dropped? What are the risks of each?
- How would you test this under real concurrency?
- How do you catch a regression where tokens accumulate beyond burst?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice System Design ProblemsSample Answer
Requirements
try_send() returns True if a message may go out now. Allow bursts up to burst, refill at rate per second, never exceed burst after idle. Tests must run instantly and the same way every time....
High-Level Design
Token bucket: tokens refill continuously as elapsed * rate, capped at burst. Time comes from an injected callable defaulting to time.monotonic, which never jumps with NTP. Tests pass a `FakeCloc...