▶ Cinematic fable · Watch on YouTube ▶ 影片版寓言 · 在 YouTube 观看

朔方关外的风雪一年刮八个月,斥候堂的灯一夜也不许灭。

堂里有一条铁规矩:凡出关的斥候,临上马前必留一支铁箭,报清归期——近的翻一道梁,四十滴铜漏便回;远的入瀚海探营,要走三天三夜。到点不见人回来,堂上就要敲响救命钟,派轻骑出关接应。

起初几十年,管箭架的老吏用的一直是最稳妥的笨法子:按归期先后,把铁箭从左到右排成一线。 最左边永远是最早到点的那一支,守堂人只要盯着排头看,一分神都不会出差错。

后来边事吃紧,每日出关的斥候从百十骑涨到了上万骑。二十个书办围着三丈长的箭架,从早到晚汗流浃背:每出一骑,要顺着几千支箭比对时刻,把新箭塞进正中间,后面的箭全往右挪;更要命的是每归来一骑,又要从几千支箭里把那一支抽出来,再把空当合拢。关门口排起了长队,斥候在风雪里冻得直跺脚,不是等马,是在等书办排箭。

新调来的掌堂官裴疏站在廊下看了一整天,傍晚只问了校尉沈烈一句话:”昨日出关一万骑,救命钟响了几回?”

沈烈愣了愣:”三回。”

“其余九千九百九十七骑呢?”

“都在到点前平安入关,自己把箭抽走了。”

裴疏点点头:”你们二十个人从早忙到晚,手心磨出血泡,是在给九千九百九十七声根本不会响的钟排队。”

第二天,裴疏让人撤了长架,抬进一只圆木盘。木盘沿口凿了六十个深槽,铜漏每滴一滴水,盘心的铜针就往前拨一格。每支铁箭尾上系一根朱砂红绒线,线头直接挂在门口各自的鞍钩上。

规矩改成了三句话:

  • 出关报十七滴后归?从铜针眼下往前数十七格,把箭直接丢进槽里——槽里哪怕已有几十支箭,也不许比先后,随手放进去就行。
  • 第九滴人就平安回来了?进门一拽自己鞍钩上的红绒线,铁箭直接从槽里提出来,左右邻箭纹丝不动。
  • 铜针拨到哪一格,哪一格里还剩着没被抽走的箭,一并敲钟发兵。

一夜之间,十九个书办回去歇了。只留一个小厮守在盘边,一只手就管下了全关的近哨。

真正的难关在入秋之后。

大军开拔前,去瀚海深处的远哨多了起来——动辄两个时辰、一天、三天,折算成铜漏,是几十万滴水。木匠算了算,若按一滴一格凿一只三十万格的大木盘,把整座斥候堂拆了也放不下。

沈烈想了个折中的主意:盘还是那只六十格的盘,只在远哨的铁箭杆上用白粉写一行字——“转满三千圈再响”。

不到两天,那个小厮就累趴在了盘边。因为铜漏每一滴水落下,铜针拨进下一格,小厮都得把槽里八百支远哨铁箭抱出来,一支一支擦掉”三千”,改写成”两千九百九十九”,再塞回去。水滴不等他擦完粉笔字就落下了下一滴,铜针卡在半途,连翻山梁的近哨都误了钟点。

裴疏走进堂里,拿袖口擦净一支箭杆上的白粉,说了一句点醒全堂的话:

“三天后才该响的钟,今天干吗要跟眼皮底下的近哨挤在一个盘里数水滴?离得远的事,本来就用不着细尺子量。”

她让木匠在同一根立轴上套了大、中、小三重木盘:

  • 内盘(滴盘) 六十格,铜漏一滴拨一格,转一圈是一刻;
  • 中盘(刻盘) 六十格,内盘转满一圈,中盘才拨一格;
  • 外盘(辰盘) 七十二格,中盘转满一圈,外盘才拨一格,足足装得下三天三夜。

一骑远哨报”五个时辰零二十三刻十四滴后归”,他的铁箭根本不进内盘,只丢进外盘往前数第五格。接下来的五个时辰里,内盘飞快地转上几百圈、铜漏滴下一万八千滴水,连碰都不会碰这支箭一下。倘若他在第三个时辰平安归关——十有八九都是如此——进门一拽红绒线,箭直接从外盘提走,自始至终没花过半点搬运功夫。

只有当五个时辰真到了、外盘的铜针咔哒一声拨进第五格,而那支箭居然还在槽里时,小厮才把这一格里仅剩的几支箭捧出来,看一眼剩下的零头,往里降一盘,放进中盘的第二十三格;二十三刻后还没人抽走,再降进内盘的第十四格;十四滴水落尽,铜钟轰然敲响。

那年腊月大雪封山,夜里全关只派出了四骑探路,最早的一骑也要五个时辰后才到点。半夜裴疏巡堂,却见小厮冻得眼圈通红,还守在铜漏边,”咔哒、咔哒”地一格一格空拨内盘——一宿要空拨一万八千下。

裴疏笑着递给他一块巴掌大的小木牌:”傻孩子,别记箭,只记哪几个槽里有箭。就算一万骑齐出,三只盘加起来总共也才一百九十二个槽,牌子上最多不过一百九十二行字。”

小厮低头一看:今夜整块牌子上只有四行字,排头那一行写着”外盘第五格”。他吹灭油灯,裹上羊皮袄睡了整整五个时辰,等铜漏积满五壶水,起身直接把指针拨到外盘第五格——一分不差。

——到这儿你大概已经认出来了:这就是分层时间轮(Hierarchical Timing Wheel)。三丈长的排序箭架是按到期时间维护的最小堆(min-heap);六十格木盘配红绒线是单层时间轮上的 O(1) 插入与双向链表 O(1) 撤单;在箭杆上写”转满三千圈”是带圈数计数的哈希时间轮(hashed wheel with rounds);内、中、外三重木盘的逐级下放是级联降盘(cascade);而腊月夜里那块只记”非空槽位”的掌心小牌,正是 Kafka Purgatory 用 DelayQueue 驱动时间轮的巧思。

这是什么

George Varghese 与 Tony Lauck 在 1987 年 SOSP 论文《Hashed and Hierarchical Timing Wheels》里提出时间轮,最初就是为了解决网络协议栈里的定时器瓶颈。在 TCP 重传、RPC 超时、心跳检测这类场景里,一台机器往往同时挂着几十万到上百万个定时器,但它们有一个极偏斜的共同特征:99.9% 的定时器在到期前就会因为收到 ACK 或响应而被提前取消,真正到点触发的不到千分之一。

如果用传统的二叉最小堆(min-heap)或红黑树管定时器,每次新建连接插入是 $O(\log N)$,每次收到正常数据包取消定时器也是 $O(\log N)$。当 $N = 10^6$、每秒收发几十万包时,CPU 大把的缓存行和指令周期都浪费在给永远不会触发的超时重排堆序上。

时间轮利用了超时管理的一个天然性质:超时的精度是有限的(比如 1 毫秒一跳,没人需要纳秒级精度的 30 秒超时)。于是它把时间切成固定步长(tick)的环形数组,每个槽位挂一条双向链表:

  • 插入 $O(1)$:到期还剩 $\Delta t$ 个 tick,直接算 (current + Δt) mod M,插进对应槽位的链表头,槽内完全不排序;
  • 取消 $O(1)$:请求对象自己持有链表节点指针(那根”红绒线”),收到响应时直接修改前后指针摘除节点,和总定时器数量 $N$ 完全无关;
  • 分层级联(Hierarchical Cascade):为了同时覆盖”1 毫秒精度”与”几天跨度”而不建几亿个空槽,用多层不同粒度的轮盘叠起来(如 20×1ms、20×20ms、20×400ms……)。远期任务只放在高层粗粒度轮里,内层快轮怎么转都不碰它;只有高层指针走到那一格时,才把槽里幸存的定时器取出,按剩余时间重插(cascade)进下一层细轮。每个定时器最多被级联搬运 $L$ 次(轮的层数,通常 3~4 层),均摊仍是 $O(1)$。

为什么重要

因为几乎所有高并发基础设施的底层都在转这只轮子,而且各自演化出了两记极其精彩的工程变招:

第一记变招在 Apache Kafka 的 DelayedOperationPurgatory(以及 Netty 的 HashedWheelTimer 对比)。Netty 用的是单层 rounds 圈数法,槽位冲突多时每跳仍要遍历扣减圈数;而 Kafka 面对成千上万个 acks=all 生产请求和长轮询拉取请求时,采用了标准分层时间轮 + DelayQueue:如果像故事里的小厮那样每 1 毫秒由后台线程空拨一格,空闲集群也会白烧 CPU。Kafka 的做法是不把百万个定时任务放进最小堆,而是只把”非空槽位(Bucket)”放进 DelayQueue(最小堆)。无论挂了多少百万个请求,三四层轮盘加起来总共只有几十到一两百个槽位!堆的大小被死死锁在常数级,工作线程平时直接 poll() 阻塞休眠到下一个非空槽位到期,一举兼得了百万级任务 $O(1)$ 插删与零空转休眠。

第二记变招在 Linux 内核定时器(timer_list)。Linux 从 1997 年起用了近二十年的经典级联时间轮(tvec_base),直到 2016 年(Linux 4.8,Thomas Gleixner 重构)发现了一个微妙的尾延迟毛刺:当高层轮盘每隔几秒咔哒拨动一格时,如果那一格恰好攒了几万个还没取消的定时器,瞬间集中级联重插会锁住轮盘,给软中断制造一次毫秒级抖动。内核团队看穿了本质——网络重传和套接字超时根本不在乎”30 秒整”还是”31.5 秒”触发,而高精度需求早有独立的红黑树 hrtimer 负责。于是新版内核干脆取消了级联搬运(no cascade):高层轮用几何级数放宽刻度,换取约 6%~12.5% 的到期容差(slack),让远期定时器直接在高层槽位原地触发,永远不下放。

这就是系统设计里最迷人的一课:动手选数据结构之前,先问哪件事发生一万次、哪件事只发生三次。 为千分之三的触发去拖累千分之九百九十七的撤单,再精巧的排序也是白费力气。

隐喻对应表

  • 出关留铁箭、到点敲救命钟 —— 超时定时器(TCP 重传、RPC 超时、心跳检测)
  • 一万骑里九千九百九十七骑提前平安归关 —— 绝大多数定时器在到期前被正常 ACK/响应提前取消
  • 三丈长按先后排队的箭架 —— 最小堆(min-heap)或有序队列,插入与取消均需 $O(\log N)$ 重排
  • 圆木盘上的六十个深槽与铜漏水滴 —— 时间轮的环形槽位数组(buckets)与固定时间步长(tick)
  • 箭入槽不比先后,随手丢入 —— 双向链表头插法,$O(1)$ 插入
  • 系在门口鞍钩上的朱砂红绒线 —— 任务对象直接持有的链表节点引用,支持 $O(1)$ 原地摘除取消
  • 在箭杆上写”转满三千圈再响” —— 单层带 rounds 计数的哈希时间轮,长跨度下每跳需遍历未到期节点
  • “离得远的事用不着细尺子量” —— 远期超时无需在当下维护细粒度精度,按剩余时间分层存放
  • 同轴套叠的内盘(滴)、中盘(刻)、外盘(辰) —— 多级不同刻度(tickMs 与 wheelSize)的分层时间轮
  • 外盘到点后把剩余箭捧出、放入中盘 —— 级联降盘(cascade / reinsert),将高层到期桶拆解下放至低层细轮
  • 大雪夜空拨一万八千下指针 —— 空槽轮询(empty-tick spinning)导致的空闲 CPU 唤醒浪费
  • 只记”哪几个槽里有箭”的掌心小牌 —— Kafka 以 DelayQueue(最小堆)仅管理非空槽位(桶数量恒定),兼顾 $O(1)$ 增删与阻塞休眠

Outside Shuofang Pass the snow blows eight months of the year, and the lamps in the Scout Hall never go out.

The hall keeps one iron rule: every scout who rides through the gate leaves an iron arrow behind and names a return mark — forty drips of the bronze water-clock to check the near ridge, two hours down the gorge, three days and nights into the salt desert. If the mark arrives and the rider has not, the hall strikes the rescue bell and sends fast cavalry out the gate.

For decades the old clerks kept the arrows by the safest, plainest method anyone knew: line every arrow up along a thirty-foot cedar rack in strict order of who is due back first. The leftmost arrow is always the next deadline; watch the head of the rack and you can never miss an alarm.

Then the northern frontier grew tense, and daily patrols swelled from a hundred riders to ten thousand. Twenty clerks stood drenched in sweat from dawn till midnight around that cedar rack. Every departing scout meant walking thousands of arrows to compare deadlines, wedging the new arrow into the middle, and shifting everything to its right; worse, every returning scout meant hunting down one arrow mid-rack, pulling it free, and closing the gap. Riders stood stamping their boots in the snow outside the gate — waiting not for fresh horses, but for clerks to finish sorting arrows.

Pei Shu, newly appointed keeper of the hall, watched from the gallery for one full day. At dusk she asked Captain Shen Lie a single question: “Ten thousand riders went out yesterday. How many times did the rescue bell ring?”

Shen Lie blinked. “Three.”

“And the other nine thousand nine hundred and ninety-seven?”

“Came home before their mark and pulled their arrows.”

Pei Shu nodded. “Twenty men with blisters bleeding on their palms from dawn till dark — all to keep a neat queue of nine thousand nine hundred and ninety-seven bells that will never ring.”

Next morning she had the long rack carried out and a round cedar wheel brought in. Sixty deep slots were cut around its rim. Each drip of the water-clock nudged a bronze hand forward by one slot. And tied to the tail of every iron arrow was a cord of vermillion silk, its loop hung directly on that rider’s saddle-hook beside the gate.

Three short rules replaced the old ones:

  • Riding out for seventeen drips? Count seventeen slots ahead of the bronze hand and drop the arrow straight in — even if thirty arrows are already lying in that slot, do not sort them. Just let it fall.
  • Back safe on the ninth drip? Reach up by the gate and tug your vermillion cord. Your arrow lifts clean out of its slot without disturbing a single neighbour.
  • Wherever the bronze hand lands, any arrow still lying in that slot is genuinely overdue — strike the bell for all of them at once.

Overnight, nineteen clerks went home to sleep. One boy tended the entire near-pass patrol with one hand.

The real wall arrived in autumn.

Ahead of the main army’s march, long-range scouts began riding deep into the desert — two hours out, a full day, three days and nights. Measured in water-drips, three days was hundreds of thousands of beats. The carpenter did the sums: a single wheel with three hundred thousand slots would not fit inside the hall if you tore the walls down.

Shen Lie proposed a clever compromise: keep the sixty-slot wheel, and chalk a line onto each desert arrow — “ring after three thousand laps.”

Within two days the boy collapsed beside the wheel. On every single drip of the water-clock, as the bronze hand clicked into the next slot, he had to haul out eight hundred desert arrows, rub out 3,000, chalk 2,999, and cram them back in before the next drop fell. The water did not wait for his chalk; the bronze hand jammed halfway round, and even short-range ridge scouts began missing their rescue bells.

Pei Shu walked in, wiped the chalk off an arrow shaft with her sleeve, and said the sentence that untangled the hall:

“Why is a bell due three days from now crowding into the same ring to count water-drips beside a scout on the near ridge? What is far off does not yet need a fine ruler.”

She had the carpenter mount three concentric wooden wheels on the same central spindle:

  • The Inner Wheel (Drips) — sixty slots; one water-drip advances one slot, one full turn is a quarter-hour.
  • The Middle Wheel (Quarters) — sixty slots; one full turn of the Inner Wheel advances the Middle Wheel by one slot.
  • The Outer Wheel (Hours) — seventy-two slots; one full turn of the Middle Wheel advances the Outer Wheel by one slot, spanning three full days.

When a desert scout named “five hours, twenty-three quarters, and fourteen drips,” his arrow never touched the Inner Wheel. It dropped straight into slot five of the Outer Wheel. For the next five hours the Inner Wheel spun hundreds of times — eighteen thousand drips of water — without touching that arrow once. And when, as happened nine times out of ten, the scout rode home safe in the third hour, one tug on his vermillion cord lifted the arrow straight out of the Outer Wheel: zero laps counted, zero sorting paid.

Only when five full hours elapsed, the Outer Wheel’s hand clicked into slot five, and an arrow was still lying there, did the boy lift out the handful of surviving arrows in that slot, read what remained on each, and drop them down one wheel into slot twenty-three of the Middle Wheel; twenty-three quarters later, if still unclaimed, down into slot fourteen of the Inner Wheel; fourteen drips later — the bronze bell tolled.

In the twelfth month a blizzard sealed the pass. All night only four scouts rode out, the earliest due back in five hours. Walking the hall at midnight, Pei Shu found the boy red-eyed and shivering by the brazier, still nudging the inner bronze hand click, click, click across empty slot after empty slot — eighteen thousand empty clicks before dawn.

She handed him a wooden slate no bigger than her palm. “Don’t list the arrows,” she told him. “List only which slots aren’t empty. Even if ten thousand riders go out together, all three wheels hold only a hundred and ninety-two slots in total. Your slate will never carry more than a hundred and ninety-two lines.”

The boy looked down. Tonight the whole slate held four lines, and the top line read Outer Wheel, slot five. He blew out the lamp, pulled his sheepskin coat over his shoulders, slept five straight hours, and woke when five measures of water filled the basin — stepping the pointer straight to Outer Wheel slot five, not a breath late.

— By now you’ve probably recognised it: this is the Hierarchical Timing Wheel. The thirty-foot sorted arrow rack is a deadline-ordered min-heap; the sixty-slot wheel with vermillion cords is a single timing wheel giving $O(1)$ insertion and $O(1)$ cancellation via doubly-linked list nodes; chalking “three thousand laps” on an arrow is a hashed timing wheel with rounds; the concentric inner, middle, and outer rings dropping survivors inward is hierarchical cascading; and that palm-sized winter slate tracking only non-empty slots is the exact trick Apache Kafka’s Purgatory uses when it drives a hierarchical timing wheel with a DelayQueue.

What it is

George Varghese and Tony Lauck introduced timing wheels in their 1987 SOSP paper “Hashed and Hierarchical Timing Wheels” to break a bottleneck in network protocol stacks. In TCP retransmission, RPC deadlines, and heartbeat monitoring, a single host routinely holds hundreds of thousands or millions of active timers — yet those timers share a wildly skewed property: 99.9% of them are cancelled early when an ACK or reply arrives, and fewer than one in a thousand ever expire.

Manage those timers in a classic binary min-heap or red-black tree and every arm costs $O(\log N)$ while every early cancellation also costs $O(\log N)$. At $N = 10^6$ timers and hundreds of thousands of packets per second, CPU cache lines and cycles vanish into re-heapifying deadlines that will never fire.

A timing wheel exploits one natural fact about timeouts: timeout resolution is bounded (say 1 ms per tick — nobody needs nanosecond precision on a 30-second socket timeout). Divide time into a circular array of fixed-width ticks, each bucket holding an unsorted doubly-linked list:

  • $O(1)$ insert: a timer due in $\Delta t$ ticks lands directly in bucket (current + Δt) mod M, prepended to the list with zero sorting.
  • $O(1)$ cancel: the request object holds a direct pointer to its list node (the vermillion cord); when the ACK arrives, unlinking two pointers removes it in constant time regardless of $N$.
  • Hierarchical cascade: to span both 1 ms precision and multi-day horizons without allocating hundreds of millions of empty buckets, stack multiple wheels of coarser granularity (e.g. 20 × 1ms, 20 × 20ms, 20 × 400ms…). Distant timers sit untouched in outer wheels while the inner wheel spins; only when an outer hand steps onto a bucket are its surviving timers extracted and reinserted (cascaded) into the next finer wheel. Each timer cascades at most $L$ times (typically 3–4 levels), keeping amortized cost $O(1)$.

Why it matters

Nearly every high-concurrency runtime turns this wheel under the hood, and two production evolutions show how deep the engineering goes:

The first is Apache Kafka’s DelayedOperationPurgatory (contrasted with Netty’s HashedWheelTimer). Netty uses a single wheel with rounds counters, which still walks colliding long-horizon timers on ticks; Kafka, managing hundreds of thousands of acks=all produce requests and long-polling fetch requests, pairs a Hierarchical Timing Wheel with a DelayQueue. Ticking a background thread every 1 ms across empty buckets wastes CPU when a broker is quiet. Instead of putting millions of individual timers into a min-heap, Kafka puts only non-empty buckets into a DelayQueue. Even under a million pending requests, three or four wheels contain only a few dozen to a couple hundred buckets in total! The heap stays tiny and bounded by bucket count, worker threads block cleanly inside poll() until the next occupied bucket expires, and individual timers still arm and cancel in $O(1)$.

The second is the Linux kernel timer wheel (timer_list). Linux ran the classic cascading hierarchical wheel (tvec_base) from 1997 until 2016, when Thomas Gleixner’s Linux 4.8 redesign addressed a subtle tail-latency spike: whenever an outer wheel clicked forward every few seconds, cascading thousands of uncancelled timers all at once locked the wheel and injected millisecond-scale softirq jitter. Kernel engineers recognised a deeper domain truth — general timeouts (retransmits, socket keepalives) protect against failure and never care whether “30 seconds” fires at 30.0s or 31.8s, whereas true microsecond deadlines already belong in the separate red-black-tree hrtimer subsystem. So modern Linux eliminated cascading altogether: outer levels widen geometrically and accept ~6%–12.5% timer slack, firing expired timers directly from their outer bucket without ever moving them inward.

It is one of systems engineering’s cleanest lessons: before choosing a data structure, ask which operation happens ten thousand times and which happens three. Paying $O(\log N)$ on nine thousand nine hundred and ninety-seven cancellations just to keep three expirations neatly sorted is solving the wrong half of the problem.

Metaphor mapping

  • Leaving an iron arrow at the pass and striking the rescue bell if overdue — arming a timeout timer (TCP retransmit, RPC deadline, heartbeat)
  • 9,997 of 10,000 riders returning safe and pulling their arrows early — ~99.9% of production timers cancelled by normal ACKs/replies before expiry
  • The thirty-foot cedar rack sorted strictly by deadline — a min-heap or balanced tree paying $O(\log N)$ re-ordering on every insert and cancel
  • The sixty-slot wooden wheel and bronze water-clock drip — circular bucket array and fixed tick duration
  • Dropping an arrow into a slot without sorting against neighbours — unsorted doubly-linked bucket insertion in $O(1)$
  • The vermillion silk cord hung on each rider’s gate hook — direct list-node pointer held by the request for $O(1)$ unlink on cancellation
  • Chalking “ring after 3,000 laps” on long-range arrows — a single hashed wheel with rounds, forced to scan unexpired timers on every lap
  • “What is far off does not yet need a fine ruler” — coarse-to-fine time resolution across wheel levels
  • Concentric Inner (drip), Middle (quarter), and Outer (hour) wheels — multi-level Hierarchical Timing Wheel (tickMs scaling by wheelSize per level)
  • Lifting surviving arrows from an Outer slot and dropping them into the Middle wheel — cascading (demoting) timers inward as their horizon approaches
  • Clicking the hand eighteen thousand times across empty slots on a snowy night — idle CPU burn from empty-tick polling
  • The palm-sized slate listing only non-empty slots — Kafka Purgatory’s DelayQueue over buckets (bounded heap size + zero idle spinning + $O(1)$ per-timer ops)
Daily Fables每日寓言 2026-11-14