The Ordering Layer — Or, "It Went Through" Is Not the Same as "It Went Through in Order"

本文为原文前 6,000 字符的节选翻译,完整内容请查看原文。

The Ordering Layer — Or, “It Went Through” Is Not the Same as “It Went Through in Order”

Yesterday’s piece ended with a promise: replay does not only repeat events, it reorders them. That sentence deserves its own article, because most teams have a guard against duplication and no guard at all against inversion. Duplication is the failure you can name. Reordering is the failure that leaves no trace except a state that should be impossible. Nobody gets an alert when a shipment goes out before the payment clears — they get a support ticket three weeks later asking why the invoice and the tracking number disagree.

昨天的文章以一个承诺结尾:重放不仅会重复事件,还会重新排序。这句话值得单独写一篇文章,因为大多数团队都有防止重复的机制,却完全没有防止顺序颠倒的措施。重复是你可以明确指出的故障,而乱序则是那种除了留下一个本不该存在的状态外,不留任何痕迹的故障。当发货发生在付款确认之前时,没人会收到警报——他们只会在三周后收到一张支持工单,询问为什么发票和追踪号码不一致。

Every invariant is an ordering claim. Read your business rules as sentences about sequence and most of them turn out to be ordering constraints wearing a different costume. “No shipment before payment.” “No access before approval.” “No disclosure before the notice.” “No deletion before the backup is verified.” “No charge after cancellation.” Each one says: event A must be observed before event B, or the state is wrong. We write these as ifs in application code — if payment.captured then ship() — and then we put a queue between the two halves. The queue preserves order within a partition, and partitions are chosen by a key that has nothing to do with the invariant. Two messages about the same order can land on different partitions, and then the only ordering guarantee left is the one the consumer accidentally implements.

每一个不变性(invariant)都是一种顺序声明。将你的业务规则读作关于序列的句子,你会发现其中大多数都是披着不同外衣的顺序约束。“先付款后发货。”“先批准后访问。”“先通知后披露。”“先验证备份后删除。”“取消后不得收费。”每一条都在说:事件 A 必须在事件 B 之前被观察到,否则状态就是错误的。我们在应用代码中将其写为 if 语句——如果 payment.captured 则 ship()——然后我们在两半之间放置一个队列。队列在分区内保持顺序,而分区是由一个与不变性毫无关系的键来选择的。关于同一订单的两条消息可能会落在不同的分区上,此时剩下的唯一顺序保证就是消费者偶然实现的那些。

Sequence numbers measure the wrong stream. The standard reassurance is “messages carry a sequence number.” Ask what the number is scoped to. In most systems it is scoped to the producer, the partition, or the topic — not to the entity the business cares about. A sequence number on a topic tells you the order in which the broker received messages from one producer. It says nothing about the order in which two different producers’ messages about the same customer were applied, and nothing about what happened when one producer restarted and its counter reset. The number you actually need is per entity: for this order, for this account, for this document. And almost nobody emits it, because emitting it requires deciding which entity owns the invariant — a decision usually deferred until the first incident.

序列号衡量的是错误的流。标准的安慰是“消息带有序列号”。问问自己这个数字的作用域是什么。在大多数系统中,它的作用域是生产者、分区或主题,而不是业务所关心的实体。主题上的序列号告诉你代理从一个生产者接收消息的顺序。它无法说明两个不同生产者的关于同一客户的消息是如何应用的,也无法说明当一个生产者重启且计数器重置时发生了什么。你真正需要的是针对每个实体的编号:针对这个订单、这个账户、这个文档。几乎没有人发出这种编号,因为发出它需要决定哪个实体拥有该不变性——这个决定通常会被推迟到第一次事故发生时才做。

Timestamps are a story about clocks. The fallback is the timestamp. It is worse than the sequence number, for a reason that is easy to state and hard to remember: you are comparing clocks you do not own. Two services on two hosts write created_at. One has NTP drift of forty milliseconds. One had its clock stepped backward during the incident because someone fixed the time sync. Now the record that says which event happened first is sorted by which machine was more wrong. Worse is the case where the timestamp is generated by the client. A mobile app that retries after twelve hours offline will happily present a request that is twelve hours old, with a timestamp to match, to a server that has already moved past that state. The server has two choices: reject it and lose work the user believes was saved, or apply it and move the state backward. This is not a hypothetical. It is the ordinary behavior of any offline-first client, any long retry window, and any backfill script run against historical data. Ordering failures arrive with the most innocent inputs.

时间戳是关于时钟的故事。备选方案是时间戳。它比序列号更糟糕,原因很简单却难以记住:你在比较你不拥有的时钟。两台主机上的两个服务写入 created_at。一个有 40 毫秒的 NTP 漂移。另一个在事故期间因为有人修复了时间同步,时钟被向后调整了。现在,记录哪个事件先发生的依据,变成了哪台机器的错误更严重。更糟糕的情况是时间戳由客户端生成。一个在离线 12 小时后重试的移动应用,会愉快地向一个已经越过该状态的服务器提交一个 12 小时前的请求,并附带相应的时间戳。服务器有两个选择:拒绝它并丢失用户认为已保存的工作,或者应用它并将状态向后移动。这不是假设,这是任何离线优先客户端、任何长重试窗口以及任何针对历史数据运行的回填脚本的常规行为。乱序故障往往伴随着最无辜的输入而来。

Where inversion actually shows up. Four patterns cover most of it, and all four look fine in a diagram. The compensating action overtakes the original. A refund is issued, then the charge retry lands. The customer is charged after being refunded, and the ledger now shows a payment that the business believes was reversed. Reconciliation finds it a month later, if at all. The grant arrives before the check. A permission is provisioned from one queue and a revocation is processed from another. For a window measured in seconds, the user has access they should not have. Nothing failed; both messages were delivered exactly once. The delete outruns the write. A support agent deletes an account; a retry of an earlier write recreates a row in a table that was supposed to be empty. The deletion receipt is true at the moment it is issued and false an hour later. The customer’s request was honored and then quietly undone. The notification precedes the change. An email announces a plan change that has not been applied yet, and a second email announces the rollback. To the recipient, both are true statements about a system that flickered. To the auditor, the record shows a promise made before the state existed to support it. None of these requires a bug in any single service. They require only two paths with independent ordering and an invariant that spans both.

顺序颠倒实际上出现在哪里?四种模式涵盖了大部分情况,且这四种在图表中看起来都没问题。补偿操作超过了原始操作。退款已发出,然后收费重试到达。客户在退款后被扣款,账本现在显示了一笔业务认为已经撤销的付款。对账可能在一个月后发现它,如果能发现的话。授权在检查之前到达。权限从一个队列配置,撤销从另一个队列处理。在几秒钟的时间窗口内,用户拥有了他们本不该拥有的访问权限。没有任何环节失败;两条消息都恰好被投递了一次。删除操作超过了写入操作。支持人员删除了一个账户;早期写入的重试在应该为空的表中重新创建了一行。删除回执在发出时是真的,一小时后就变成了假的。客户的请求被执行了,然后又悄悄撤销了。通知先于变更。一封电子邮件宣布了一个尚未应用的计划变更,第二封邮件宣布了回滚。对于接收者来说,这两者都是关于一个闪烁系统的真实陈述。对于审计员来说,记录显示了一个在支持它的状态存在之前就做出的承诺。这些情况都不需要任何单一服务出现 Bug。它们只需要两条具有独立顺序的路径,以及一个跨越两者的不变性。

The only thing that saves you is a decision about where order is enforced. There are two honest architectures, and one dishonest default. The first is to make the invariant local: put both events in the same partition, keyed by the entity, and process them serially. This works, and it costs you throughput and a key design you must not change later. The second is to make the consumer tolerant of any order: every handler checks the current state and refuses to move backward. This works, and it costs you a state machine per entity plus the discipline to write the check in every handler, forever. The dishonest default is to assume the queue gives you order and to write handlers that apply whatever arrives. That is the architecture most systems actually have, and it is indistinguishable from the first two until the day two paths race. The question to ask is not “is our queue ordered.” It is: for each invariant, which component is responsible for refusing an out-of-order event, and what does it do when it sees one? If the answer is “nothing, it cannot happen,” that is a claim about your topology, not a guarantee in your code.

唯一能拯救你的是关于在哪里强制执行顺序的决定。有两种诚实的架构,以及一种不诚实的默认做法。第一种是使不变性本地化:将两个事件放在同一个分区中,以实体为键,并串行处理它们。这行得通,但代价是吞吐量和必须在后续设计中保持不变的键设计。第二种是使消费者能够容忍任何顺序:每个处理器检查当前状态并拒绝向后移动。这行得通,但代价是每个实体都需要一个状态机,并且需要纪律性地在每个处理器中编写检查逻辑,永远如此。不诚实的默认做法是假设队列能保证顺序,并编写处理任何到达数据的处理器。这是大多数系统实际采用的架构,在两条路径发生竞争之前,它与前两种架构无法区分。要问的问题不是“我们的队列是否有序”,而是:对于每一个不变性,哪个组件负责拒绝乱序事件,以及当它看到乱序事件时会做什么?如果答案是“什么都不做,这不可能发生”,那只是对你拓扑结构的一种声明,而不是代码中的保证。

This is an evidence problem before it is an engineering problem. Here is the part that matters for anyone keeping records: an append-only ledger that stores events in arrival order is not a causal record. It is a log of what this system heard, in the…

这在成为工程问题之前,首先是一个证据问题。对于任何保存记录的人来说,重要的一点是:一个按到达顺序存储事件的仅追加账本,并不是因果记录。它只是该系统所听到的内容的日志,在……