Implement a Delayed Task Scheduler for Unpaid Order Cancellation
Last updated: November 29, 2026
Quick Overview
Orders that stay unpaid for a set time must be auto-cancelled. Implement an in-process scheduler that runs callbacks after a delay, supports cancellation when payment arrives, and uses one worker thread that sleeps until the next deadline.
Amazon
November 29, 20260
0
0 solved
Orders that stay unpaid for a set time must be auto-cancelled. Implement an in-process scheduler that runs callbacks after a delay, supports cancellation when payment arrives, and uses one worker thread that sleeps until the next deadline.
Checkout flows schedule timeouts for payment authorization holds and pending orders, and cancelling them is far more common than firing them. The interviewer wants a heap ordered by deadline, a condition variable that wakes early for sooner tasks, and lazy cancellation.
What the Interviewer Expects
- Uses a min-heap keyed by run time with a tie-breaking sequence
- Wakes the worker when a new task is earlier than the current head
- Implements cancel in O(1) with lazy deletion
- Runs callbacks outside the lock and isolates their exceptions
- Injects a clock and discusses monotonic time
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 persist scheduled cancellations so a host restart does not lose them?
- How would you scale to millions of timers, for example with a hierarchical timing wheel?
- How would you run callbacks on a thread pool without reordering guarantees breaking?
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
schedule(delay, fn)returns a task id;cancel(id)returns whether it prevented the run.- Tasks run no earlier than their deadline, in deadline order.
- A failing callback must not kill the work...
High-Level Design
The heap stores (run_at, seq, id); a dict maps live ids to callbacks. Cancel just pops the dict entry, and the worker discards heap heads whose id is gone. The worker loop waits on the condition wit...