Run Delayed Callbacks With a Single Condition-Variable Timer Thread

Last updated: November 29, 2026

Quick Overview

Build a scheduler where callers register callbacks to run after a delay; one background thread must fire them in deadline order, wake early when an earlier task arrives, and support cancellation and shutdown.

Google
Software Engineering Fundamentals
Software Engineer
Google
November 29, 2026
Software Engineer
Onsite
Software Engineering Fundamentals
Hard

0

0

0 solved


Build a scheduler where callers register callbacks to run after a delay; one background thread must fire them in deadline order, wake early when an earlier task arrives, and support cancellation and shutdown.

Retry timers, lease renewals, and deadline enforcement in Google RPC stacks all rest on a timer facility like this. The onsite question checks heap-based ordering, timed condition waits, handling of a newly inserted earlier deadline, and keeping the timer thread alive when a callback throws.

What the Interviewer Expects
  • Keeps tasks in a min-heap keyed by absolute deadline
  • Uses a timed wait on a condition variable, not polling or sleep
  • Notifies the worker on insert so an earlier deadline preempts the current wait
  • Implements cancellation lazily with tombstones
  • Runs callbacks outside the lock and isolates their exceptions
  • Uses a monotonic clock
Key Topics to Cover
min-heap
timed wait
condition variable
cancellation
timer thread
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 a hierarchical timing wheel change complexity for millions of timers?
  • How would you run callbacks on a separate pool so a slow one does not delay others?
  • How do you add periodic tasks without drift?
  • How would you test this deterministically without sleeping?
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
  • schedule(delay, fn) returns an id; fn runs no earlier than delay seconds later.
  • Callbacks fire in deadline order.
  • cancel(id) prevents a pending callback from running.
  • stop() terminat...
High-Level Design

Heap of (run_at, seq, fn); seq breaks ties and avoids comparing functions. The worker loops: if the heap is empty, wait indefinitely; if the head is due, pop it; otherwise wait(run_at - now). Ev...


Submit Your Answer
Markdown supported