Make a Time and Randomness Dependent Token Cache Deterministically Testable
Last updated: November 29, 2026
Quick Overview
A cache refreshes an auth token shortly before it expires, with random jitter, and its tests are flaky because they call sleep and depend on real randomness. Refactor it for testability and write unit tests that are fast and deterministic.
OpenAI
November 29, 20260
0
0 solved
A cache refreshes an auth token shortly before it expires, with random jitter, and its tests are flaky because they call sleep and depend on real randomness. Refactor it for testability and write unit tests that are fast and deterministic.
OpenAI services and SDKs are full of code that depends on wall-clock time and jitter (token refresh, retries, rate limits). Interviewers use this to see whether a candidate writes tests that pin down behavior instead of sleeping and hoping, and whether they can reason about the bounds of randomized logic.
What the Interviewer Expects
- Identifies the hidden dependencies: the clock and the random source
- Injects a clock and a seeded RNG instead of patching globals
- Tests the boundaries of the refresh window, not one lucky value
- Keeps tests free of real sleeps
- Explains why jitter exists in the first place
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 test this if the clock could not be injected?
- How do you test concurrent callers that all see an expired token at once?
- What property-based test would you write for the refresh window?
- How would you find which test in a large suite is flaky?
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
get() returns a cached token and fetches a new one once now >= refresh_at, where refresh_at falls uniformly between ttl - 2*margin and ttl - margin after the fetch. Tests must run in millise...
High-Level Design
Flakiness comes from two hidden inputs: time.time() and random.uniform. Make both constructor parameters. Production passes time.monotonic and random.Random(); tests pass a FakeClock they ca...