Preparing your design workspace

Loading the problem and your saved attempt…

Design a Timing-Wheel Timer

Design a timer service on a timing wheel that holds a very large number of pending timers and starts or cancels each one at constant cost, then stretch it to day-long delays and to calls from worker threads.

Design a timer service built on a timing wheel. A timing wheel is a circular array of slots: each tick maps to one slot that holds the timers due then, and a pointer moves forward one slot per tick, so the service only looks at the slot it has reached instead of searching every pending timer.

For this exercise, assume timers are used inside one long-running server process, for request timeouts and retry delays. As many as 1,000,000 timers can be pending at once, and most of them are canceled before they are due. Time is counted in ticks of 10 ms, and the process's event loop reports the ticks.

The service has three operations. 1. Start. A caller gives a delay in whole ticks, from 1 to 6,000 (up to 60 seconds), and an action to run. Any other delay is rejected. The caller gets back something it can later use to cancel this timer. 2. Cancel.

If the timer is still pending, its action will never run, and the caller is told the cancel worked. If the timer already fired or was already canceled, nothing changes, and the caller is told so. 3. Advance. The event loop reports how many ticks have passed since its last report; after a stall, this can be many.

The service processes every one of those ticks in order and skips none. A timer started with delay d fires while the d-th tick after its start is processed: its action runs once, on the event-loop thread. Timers due on the same tick may fire in any order.

Actions are short. An action may start and cancel timers, including a timer due on the same tick that has not fired yet; that timer must then not fire. A timer started from inside an action never fires on the tick being processed.

If an action throws an error, the error is logged, its timer counts as fired, and the other timers on that tick still fire.

Start and cancel must take constant time however many timers are pending, and processing a tick must never look through all pending timers. In the core design, every call comes from the event-loop thread.

The service does not need repeating timers, timers that outlive a restart, wall-clock alarms or timers shared between machines.

Every number and rule above is set for this exercise. Clarify the requirements, then design the objects, interfaces and interactions of the timer service.