Make a Flaky Token Expiry Test Deterministic With an Injected Clock

Last updated: November 29, 2026

Quick Overview

A test for an access token cache passes locally but fails intermittently in CI because it sleeps and reads the real clock. Explain why it is flaky and refactor the cache so the test controls time.

Microsoft
Software Engineering Fundamentals
Software Engineer
Microsoft
November 29, 2026
Software Engineer
Onsite
Software Engineering Fundamentals
Medium

0

0

0 solved


A test for an access token cache passes locally but fails intermittently in CI because it sleeps and reads the real clock. Explain why it is flaky and refactor the cache so the test controls time.

Flaky tests waste enormous engineering time in large Microsoft CI systems, and identity code (Microsoft Entra tokens) is full of expiry logic. The interviewer checks that the candidate can diagnose the source of non-determinism and apply dependency injection to make time a controlled input.

What the Interviewer Expects
  • Identifies the real clock and sleep as the source of flakiness
  • Injects a clock dependency with a production default
  • Writes a fake clock and tests exact boundaries
  • Uses a monotonic clock for durations in production
  • Names other common sources of flakiness
Key Topics to Cover
flaky tests
dependency injection
test doubles
monotonic clocks
token caching
How to Approach This
  1. Apply SOLID principles. Single Responsibility makes code testable, Open/Closed makes it extensible.
  2. Choose data structures based on access patterns, not familiarity.
  3. Prefer immutable data and message passing over shared mutable state for concurrency.
  4. Design APIs with RESTful conventions, versioning, meaningful errors, and pagination from day one.
Possible Follow-up Questions
  • How would you find flaky tests across a repository with thousands of tests?
  • Why should production code use a monotonic clock instead of wall-clock time here?
  • How would you test concurrent refreshes from many threads?
  • When should a flaky test be quarantined versus fixed immediately?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice System Design Problems
Sample Answer
Requirements
  • The cache returns a cached token until 60 seconds before expiry (a skew buffer), then fetches a new one.
  • The original test fetched a token with a 2 second lifetime, called time.sleep(1.5), and a...
High-Level Design

Make time an input. The cache takes a clock callable that defaults to time.monotonic in production. Tests pass a FakeClock they can advance by exact amounts, so they can test right at the bo...


Submit Your Answer
Markdown supported