Zum Hauptinhalt springen

A Million Timers, One Tick: The Hashed Timer Wheel

· 11 Minuten Lesezeit
Clustron Team
Engineering für verteilte Systeme

A cache that honours time-to-live is, underneath, a timer service running at a scale most timer code never sees. Every key written with a TTL is a timer that must fire at its own deadline; on a busy node that is millions of live timers at once, and they churn — keys are written, overwritten with a new TTL, and deleted before they ever expire, so timers are set and cancelled constantly. The expiry mechanism is not a background detail. It is a data-structure problem, and the wrong choice shows up as CPU burned on bookkeeping instead of serving requests.

The instinctive design is a structure sorted by deadline: a binary heap or a balanced tree that always has the soonest-expiring timer at its root, so a sweep thread can peek the minimum and fire everything due. This is correct and it is genuinely good when there are hundreds or thousands of timers. It falls apart at millions because every operation that is not "fire the minimum" costs O(log n): setting a timer is a logarithmic insert, and — the killer — cancelling one is a logarithmic delete, because the overwritten or deleted key has to find and remove its pending timer. Under heavy TTL churn the set-and-cancel traffic dwarfs the actual firings, so the system spends its time re-balancing a tree for timers that never even reach their deadline.

The structure built for exactly this load is the hashed timer wheel, and its whole appeal is that it replaces the logarithm with a constant. This post is about how it does that, how a hierarchy of wheels handles timeouts spanning milliseconds to hours, and what the tick interval costs.

A ring of buckets and a moving hand​

Picture a circular array of N buckets, each holding an unordered list of timers, with a hand that advances one bucket on every tick — a fixed interval, say one millisecond. The bucket a timer belongs in is pure arithmetic: a timer due in d ticks from now goes into bucket (current + d) mod N. Scheduling is therefore an array index and a list append — O(1), no comparison, no reshuffle. Cancelling is removing the timer's node from the doubly-linked list it sits in, which, if the timer holds a pointer to its own node, is also O(1) with no search. The two operations that dominate TTL churn both became constant-time.

Firing is where the wheel earns its name. On each tick the hand moves to the next bucket and fires only the timers in that one bucket — it never looks at the other N−1 buckets, so the cost of a tick is proportional to the timers actually due now, not to the total number pending. A million timers spread across the wheel cost nothing to hold; the sweep only ever touches the handful landing in the current bucket. Compare that to the heap, which is cheap to fire but expensive to maintain; the wheel inverts the trade and maintenance is the thing TTL workloads do most.

The one wrinkle is a timer whose delay exceeds one full revolution of the wheel. If the wheel has N buckets ticking every millisecond, it only directly represents the next N milliseconds. A longer timer is handled by recording how many full revolutions remain: it still lands in bucket (current + d) mod N, but carries a rotation count, and when the hand reaches its bucket the timer only fires if its rotation count is zero — otherwise the count is decremented and it waits for the hand to come round again. It works, but a bucket can accumulate many not-yet-due timers that the hand must skip over tick after tick, which is the single-wheel design's weakness and the reason real systems go hierarchical.

01234567nowfire now (2 timers)bucket 4: due in 2 ticks · bucket 7: due in 5 · bucket 1: rotation=1, skip oncebucket = (current + d) mod Nschedule: O(1) array indexcancel: O(1) unlink own nodesorted heap: O(log n) insert + delete

Hierarchy: one wheel per timescale​

A single wheel fine enough to tick every millisecond cannot also cheaply represent a timeout an hour away — it would need millions of buckets or pile long timers into rotation-counted buckets the hand wastes time skipping. The fix is the same one a clock uses: multiple wheels at different granularities, like the second, minute and hour hands. A millisecond wheel covers the next second; a second wheel covers the next minute; a minute wheel covers the next hour. A timer is placed in the coarsest wheel that can hold it, and when a coarse wheel's bucket is reached, its timers are not fired — they are cascaded down into the finer wheel, re-bucketed now that their deadline is close enough to resolve precisely.

This keeps every operation O(1) in the common case while covering a huge range of delays with a small, fixed number of buckets per wheel. The cascade is the only non-constant moment, and it is rare and bounded: it happens once per coarse tick and touches only the timers in one coarse bucket, amortizing to near-constant per timer. This hierarchical hashed wheel is the scheme in the classic Varghese–Lauck design, and it is what sits under Linux kernel timers, Netty's HashedWheelTimer, and the TTL machinery of large caches.

// Schedule: drop into the right wheel, O(1) — no comparison, no reshuffle.
int ticks = delayMillis / tickMillis;
if (ticks < WHEEL_SIZE) { // fits the fine wheel
int slot = (fine.cursor + ticks) & (WHEEL_SIZE - 1); // power-of-two mask = mod
fine.bucket[slot].AddLast(timer); // append to an unordered list
} else {
coarse.Schedule(timer, delayMillis); // a coarser wheel; cascades down later
}

// Cancel: the key held a pointer to its node, so removal is a pure unlink. O(1).
timer.node.Unlink();

// Tick: advance one slot and fire only what landed here — never scan the rest.
var due = fine.bucket[fine.cursor];
fine.cursor = (fine.cursor + 1) & (WHEEL_SIZE - 1);
foreach (var t in due) Fire(t); // cost ∝ timers due now, not timers pending

The tick interval is the dial​

The one tuning knob is the tick duration, and it sets a direct trade. A short tick — a millisecond — gives fine resolution: a timer fires within about a millisecond of its true deadline, which matters for request timeouts where distinguishing a dead peer from a slow one and firing hedged requests on time depends on tight timing. But a short tick means the hand wakes more often, and a wheel that ticks when no timers are due is spending CPU to look at empty buckets. A long tick — a second — costs almost no idle CPU but rounds every deadline to the nearest second, which is fine for key TTL expiry where nobody cares whether a cached value dies at 30.0 or 30.9 seconds, and wrong for a tight network timeout.

Good implementations avoid the idle-tick waste by not ticking blindly: when the wheel is empty or the next timer is far off, the thread sleeps until the next deadline rather than waking every tick, so resolution stays fine without paying for empty sweeps. That combination — fine granularity, slept-through idleness — is why one wheel can serve both millisecond request timeouts and multi-hour TTLs on the same node without the sorted structure's per-operation tax, and why it composes cleanly with the bounded queues and timeout-driven control paths around it.

Wrap-up​

A TTL cache is a timer service at a scale where the data structure is the design. A deadline-sorted heap or tree is correct but pays O(log n) on every set and cancel, and TTL churn is almost entirely sets and cancels, so the maintenance cost swamps the firings. The hashed timer wheel turns scheduling and cancelling into constant-time array indexing and list unlinking, and firing into walking one bucket per tick instead of searching the whole set — exactly inverting the heap's trade toward the operations the workload actually does. A hierarchy of wheels at clock-like granularities covers milliseconds to hours with a small fixed bucket count, cascading coarse timers down to fine ones only as their deadlines approach. The tick interval is the single dial, trading timing resolution against idle CPU, and sleeping through empty stretches removes most of the cost of a fine one. A million live timers, and each tick touches only the few that are actually due.