>_ SEEDOFWHALE / INDEX

技术笔记目录

按主题找文章。点标题看正文,技术索引可直达原文或视频。

AIGC标识 [译] 幂等键的取值决定消费端如何去重

授权转载与 AI 辅助翻译(非官方)
原作者及版权:© Gunnar Morling;首发:2025-11-25
英文原文:On Idempotency Keys
授权:英文原文及本简体中文译文均按 CC BY-SA 4.0 分享。编辑改动:增加中文翻译、译注和分类导航;保留完整英文正文,调整排版,外嵌演示以链接呈现。未暗示原作者认可本译文。

分类:Java 后端与交易 · 幂等、重试、消息去重、CDC
博客首页目录 · 一手技术资料总索引

中文译文

在分布式系统中,人们普遍认为,消息无法保证只投递一次。不过,只处理一次是可以做到的。给每条消息加一个唯一的幂等键,消费者就能识别并忽略重复消息,也就是以前接收过并已经成功处理的消息。

具体怎么做?消费者收到消息后,拿这条消息的幂等键和已处理消息的键对照。如果见过这个键,就可以忽略这条重复消息。否则就处理消息,例如把消息本身,或者由它派生出的视图,写入某个数据库。

此外,消费者还要保存消息的幂等键。关键是,这两件事必须是原子的,通常会放在一个数据库事务里。要么消息成功处理、幂等键也持久化,要么事务回滚,一项修改都不生效。这样,上次处理失败的消息在重新投递时会再处理;成功处理之后收到的重复消息则会跳过。

UUID

什么样的幂等键比较合适?一种选择是 UUIDv4。随机标识符能唯一标记每条消息,但为了可靠地判重,消费者必须保存过去收到的所有 UUID。消息量大时,这可能不现实。如果业务允许偶尔重复处理超过期限才重投的消息,一个务实做法是隔一段时间丢弃已收到的 UUID。遗憾的是,在这种情况下,生产者和消费者都不会知道这次处理是重复的。

可以在幂等键里加一个时间戳,例如使用 UUIDv7,前 48 位是时间戳,其余位包括随机位和格式保留位,或改用 ULID。这样消费者能识别适用期限之外的键。它无法判断消息是不是重复的,但可以告诉生产者:这条消息无法处理。后续该怎么办,由生产者决定。例如在支付流程中,系统可以先请用户查一下银行账户,确认款项是否已经付过。只有没付过时,才用相同载荷和一个新的 UUID 发送一条新消息。

单调递增序列

如果能用单调递增的序列值作为幂等键,上面的麻烦都可以省掉。消费者无需保留处理过的所有键,也无需留出一部分历史;只需记住最近处理过的那个键。收到相同或更小的值时,就可以判定为重复并忽略。对于分区消息源(比如有多个分区的 Kafka 主题),或多个彼此独立的生产者(如多个各用一套序列的 REST API 客户端),要按分区或来源分别保存最近的值。

从消费者的角度看,单调递增键是很大的改进;但它会增加生产者的复杂度。生产者如果是单线程、每次只产出一条消息,数据库序列乃至一个内存计数器就够了。序列可以有空洞,所以可让持久化计数器每次向前跳一大步,再从内存副本逐个发号,以减少磁盘 I/O。从消费者角度看,Kafka 分区的 offset 就属于这一类,可以作为该分区消息的单调递增幂等键。

当生产者同时处理多条请求时,情况就复杂了。比如一个 REST 服务有多个处理线程,甚至扩展到多台集群节点。要保持单调性,取号和用这个号发消息必须原子完成,中间不能插入其他线程的操作。不然线程 A 取到 100,线程 B 取到 101 并先发送,接着 A 才发出 100。消费者就会把 A 的消息误丢为重复。

在多数情况下,要做到这种原子性会遇到明显瓶颈:不管部署多少工作线程或实例,生产者的所有请求实际上都被串行化了。如果真要走这条路,仅用数据库序列产生幂等键还不够;还得采用 Postgres 咨询锁一类的机制,保证消息发出次序与键的顺序一致。

从事务日志生成幂等键

有没有办法兼顾消费者的空间效率和多线程生产者的性能?有,至少在生产者可以把发消息做成独立于入站请求的异步活动时。这意味着调用方会收到“发送意图已经持久化”的确认,但不会立即拿到活动结果。如果业务能接受这种语义,问题就能退化成前面的单线程情形:生产者线程先把消息写进队列,再由一个单线程工作进程按顺序发出。《The Synchrony Budget》也讨论了这一点:如果不马上需要结果,把活动改成异步通常有益。

一种具体做法是采用 Outbox 模式的变体,利用生产者数据库的事务日志。数据库已在日志里为事务排好顺序,我们不必自己给入站请求排序。生产者把发消息的意图持久化到日志里(例如向特定表插一行),跟读日志的进程就能按消息在日志中的位置分配幂等键。

用 Debezium 一类基于日志的变更数据捕获(CDC)工具,就能实现这个做法:捕获 Outbox 表的 INSERT 事件,从日志取出待发送消息,并在发出之前,根据日志偏移赋予幂等键。具体实现随数据库而异。

举例说,Postgres 的预写日志(WAL)保证提交事件的日志序列号(LSN)是单调递增的:后提交事务的提交事件 LSN 更大;同一事务内的事件 LSN 也保证单调递增。因此,二元组 { Commit LSN, Event LSN } 很适合当幂等键。为了不向外暴露生产者在用 Postgres,可以把两者编码成一个 128 位数值。这个方案不必部署 Kafka 或 Kafka Connect;用 Debezium 的嵌入式引擎,在生产者服务内部的回调里分配键即可,不需要额外基础设施。Postgres 甚至可以不建专门的 Outbox 表:用 pg_logical_emit_message()就能往事务日志写任意内容,正好适合这里的用途。

讨论

究竟该用哪种幂等键?没有万能答案,要看具体场景。不少业务用 UUID、过一段时间清理就够了,前提是能接受少量超期重投的消息偶尔被处理第二次。

消息越多,以单调序列为核心的方案就越有吸引力:不管总共处理了多少消息,都能用很小的空间检测和过滤重复。基于事务日志的方案可以高效地实现这一点,不过也增加了运维复杂度:数据库要支持逻辑复制,还要运行 CDC 连接器等。很多组织本来就为了分析、搜索索引、缓存失效等维护着 CDC 流水线;这时新增的复杂度很小。如果没有,就按自己的消息规模,权衡运维开销和常量空间去重带来的收益。

译注:只保存最高水位的前提不只是“发号递增”,还包括消费端不会在一条从未成功处理的低序号消息之前提交更高水位。本文的消息消费去重也不同于 HTTP 接口的请求幂等。


English Original

On Idempotency Keys

In distributed systems, there’s a common understanding that it is not possible to guarantee exactly-once delivery of messages. What is possible though is exactly-once processing. By adding a unique idempotency key to each message, you can enable consumers to recognize and ignore duplicate messages, i.e. messages which they have received and successfully processed before.

Now, how does this work exactly? When receiving a message, a consumer takes the message’s idempotency key and compares it to the keys of the messages which it already has processed. If it has seen the key before, the incoming message is a duplicate and can be ignored. Otherwise, the consumer goes on to process the message, for instance by storing the message itself, or a view derived from it, in some kind of database.

In addition, it stores the idempotency key of the message. Critically, these two things must happen atomically, typically by wrapping them in a database transaction. Either the message gets processed and its idempotency key gets persisted. Or, the transaction gets rolled back and no changes are applied at all. That way, it is ensured that the consumer will process a message again upon redelivery, if it failed to do so before. It also is ensured that duplicates received after successfully processing the message are skipped over.

UUIDs

So let’s discuss what makes for a good idempotency key then. One possible option would be to use a UUIDv4. These random identifiers solve the requirement of uniquely identifying each message. However, they require the consumer to store the UUIDs of all the previous messages it ever has received in order to reliably identify a duplicate. Depending on the message volume, this may not be practical. Pragmatically, you might get away with discarding received UUIDs after some time period, if it is acceptable to occasionally receive and process a duplicate after that period. Unfortunately, neither the producer of the message nor the consumer will have any indication of the duplicated processing in that case.

We can somewhat improve this situation by adding a timestamp to the idempotency key, for instance by using a UUIDv7 which contains both a timestamp part (first 48 bits) and a random part (remaining bits), or an ULID. That way, the consumer can detect when it receives a message with an idempotency key which is "too old". While it can’t decide whether the message is a duplicate or not, it can flag to the producer that it can’t handle that message. It is then upon the producer to decide how to proceed. For instance, if the message is part of a payment flow, the system might suggest to the user to first check in their banking account whether this payment has already been executed or not. Only if that’s not the case, a new message with the same payload and a fresh UUID would be sent.

Monotonically Increasing Sequences

All these intricacies can be avoided when it is possible to use a monotonically increasing sequence value as the idempotency key. In that case, the consumer does not need to store all the keys it ever has processed (or a reasonably sized subset thereof). It only needs to store a single value, the one of the latest message which it has processed. If it receives a message with the same or a lower idempotency key, that message must be a duplicate and can be ignored. When receiving messages from a partitioned source, such as a Kafka topic with multiple partitions, or from multiple independent producers (e.g., different clients of a REST API, each using their own separate sequence), then the latest key value per partition must be stored.

Monotonically increasing idempotency keys are a great improvement from the perspective of the message consumer. On the flipside, they may make things more complicated for producers: creating monotonically increasing sequence values isn’t without its own challenges. It is trivial if producers are single-threaded, producing one message at a time. In that case, a database sequence, or even a simple in-memory counter, can be used for creating the idempotency keys. Gaps in the sequence are fine, hence it is possible to increment the persistent state of the sequence or counter in larger steps, and dispense the actual values from an in-memory copy. That way, disk IO can be reduced. From a consumer perspective, Kafka partition offsets fall into that bucket, as they can be considered a monotonically increasing idempotency key for the messages consumed from a given partition.

Things get more complicated when the producer is subject to multiple concurrent requests at once, for instance a REST service with multiple request workers, perhaps even scaled out to multiple compute nodes in a cluster. To ensure monotonicity, retrieval of the idempotency key and emitting a message with that key must happen atomically, uninterrupted by other worker threads. Otherwise, you may end up in a situation where thread A fetches sequence value 100, thread B fetches sequence value 101, B emits a message with idempotency key 101, and then A emits a message with idempotency key 100. A consumer would then, incorrectly, discard A’s message as a duplicate.

For most cases, ensuring this level of atomicity will impose a severe bottleneck, essentially serializing all requests of the producer system, regardless of how many worker threads or service instances you deploy. Note that if you really wanted to go down that route, solely using a database sequence for producing the idempotency key will not work. Instead, you’d have to use a mechanism such as Postgres advisory locks in order to guarantee monotonicity of idempotency keys in the outgoing messages.

Deriving Idempotency Keys From the Transaction Log

Now, is there a way for us to have this cake and eat it too? Can we get the space efficiency for consumers when using monotonically increasing idempotency keys, without hampering performance of multi-threaded producers? Turns out we can, at least when the emission of messages can be made an asynchronous activity in the producer system, happening independently from processing inbound requests. This means clients of the producer system receive confirmation that the intent to send a message or request was persisted, but they don’t get the result of the same right away. If a use case can be modeled with these semantics, the problem can be reduced to the single-threaded situation above: instead of emitting messages directly to the target system, each producer thread inserts them into a queue. This queue is processed by a single-threaded worker process which emits all the messages sequentially. As argued in The Synchrony Budget, making activities asynchronous can be generally advantageous, if we don’t require their outcome right away.

One specific way to do so would be a variation of the widely used outbox pattern, utilizing the transaction log of the producer service’s database. After all, it’s not necessary to sequence inbound requests ourselves as the database already is doing that for us when serializing the transactions in its log. When producers persist the intent to send a message in the transaction log—for instance by writing a record into a specific table—a process tailing the log can assign idempotency keys to these messages based on their position in the transaction log.

An implementation of this is straight-forward using tools for log-based Change Data Capture (CDC), such as Debezium: You retrieve the messages to be sent from the log by capturing the INSERT events from the outbox table, and assign an idempotency key before emitting them, derived from their log offset. The exact details are going to depend on the specific database.

For example, in Postgres it is ensured that the log sequence numbers (LSN) of commit events within its write-ahead log (WAL) are monotonically increasing: the commit event of a transaction committing after another transaction will have a higher LSN. Furthermore, it is guaranteed that within a given transaction, the LSNs of the events are also monotonically increasing. This makes the tuple of { Commit LSN, Event LSN } a great fit for an idempotency key. In order to not leak the fact that a producer is using a Postgres database, both values can be encoded into a single 128 bit number value. Note that you don’t need to deploy Kafka or Kafka Connect for this solution. Debezium’s embedded engine is a great fit for this use case, allowing you to assign idempotency keys from within a callback method in the producer service itself, not requiring any further infrastructure. When using Postgres to implement this pattern, you don’t even need a dedicated outbox table, as it lets you write arbitrary contents into the transaction log via pg_logical_emit_message(), which is perfect for the use case at hand.

Discussion

So, when to use which kind of idempotency key then? As always, there are no silver bullets, and the answer depends on your specific use case. For many scenarios, using UUIDs and dropping them after some time will probably be sufficient, provided you can tolerate that messages occasionally can be processed a second time when duplicates arrive after the retention period of processed keys.

The more messages you need to process overall, the more attractive a solution centered around monotonically increasing sequences becomes, as it allows for space-efficient duplicate detection and exclusion, no matter how many messages you have. The proposed log-based approach can be an efficient solution for doing so, but it also adds operational complexity: your database needs to support logical replication, you need to run a CDC connector, etc. However, many organizations already operate CDC pipelines for other purposes (analytics, search indexing, cache invalidation, etc.). If you’re in that category, the incremental complexity is minimal. If you’re not, you should weigh the operational overhead against the benefits (constant-space duplicate detection) for your specific scale.

posted @ 2026-12-04 13:04  西门咬狗  阅读(4)  评论(0)    收藏  举报