事务性发件箱模式
学习事务性发件箱模式如何可靠地衔接数据库事务与 Kafka 发布,避免在 Spring Boot 中出现双重写入不一致。
事务性发件箱模式 是 CoddyKit 上的免费 Advanced Spring Boot 4: Event-Driven Architecture (Kafka) 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Advanced Spring Boot 4: Event-Driven Architecture (Kafka) 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Advanced Spring Boot 4: Event-Driven Architecture (Kafka) 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
The Dual-Write Problem
A common bug: a service updates its database and publishes a Kafka event in two separate operations. If one succeeds and the other fails, the system becomes inconsistent.
The transactional outbox pattern eliminates this risk.
Core Idea
Instead of publishing directly, write the event into an outbox table within the same database transaction as your business change.
A separate process then reads the outbox and publishes to Kafka.
The Outbox Table
The outbox table stores serialized events plus metadata.
CREATE TABLE outbox (
id UUID PRIMARY KEY,
aggregate_type VARCHAR(255),
aggregate_id VARCHAR(255),
event_type VARCHAR(255),
payload JSONB,
created_at TIMESTAMP DEFAULT now(),
published BOOLEAN DEFAULT false
);Writing in One Transaction
Both the domain entity and the outbox row are saved inside one @Transactional method, so they commit or roll back together.
@Transactional
public void placeOrder(Order order) {
orderRepository.save(order);
outboxRepository.save(OutboxEvent.from(order));
}Atomicity Guarantee
Because both writes share the database transaction, there is no window where the order exists without its event recorded. This is the key correctness property.
The Relay Process
A background relay polls unpublished outbox rows and sends them to Kafka, marking them published on success.
@Scheduled(fixedDelay = 500)
public void relay() {
for (OutboxEvent e : outboxRepository.findUnpublished()) {
kafkaTemplate.send(e.getTopic(), e.getPayload());
e.markPublished();
}
}At-Least-Once Publishing
If the relay crashes after sending but before marking published, the event is sent again. Consumers must therefore be idempotent, often using the event id as a dedup key.
Change Data Capture Alternative
Instead of polling, tools like Debezium tail the database transaction log and stream outbox inserts to Kafka automatically — lower latency and no polling load.
Cleaning Up the Outbox
Periodically delete or archive published rows to keep the table small and queries fast.
DELETE FROM outbox WHERE published = true AND created_at < now() - INTERVAL '7 days';When to Use It
Use the outbox when you must keep a database state change and an event publication consistent. It is simpler and more portable than spanning a Kafka transaction across an external database.
Putting It Together
The outbox pattern turns two unreliable writes into one atomic database commit plus a reliable relay. Combine it with idempotent consumers for end-to-end consistency.
Quick Check
Test your understanding of the outbox pattern.
Recap
You learned the transactional outbox pattern.
- Avoids dual-write inconsistency by using one DB transaction.
- An outbox table stores pending events.
- A relay (polling or CDC) publishes to Kafka.
- Consumers must be idempotent due to at-least-once delivery.
常见问题解答
「事务性发件箱模式」课时是免费的吗?
是的 — 「事务性发件箱模式」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Advanced Spring Boot 4: Event-Driven Architecture (Kafka) 课程的其余内容,请升级到 CoddyKit PRO。 Advanced Spring Boot 4: Event-Driven Architecture (Kafka) 课程共包含 4 节课。
「事务性发件箱模式」这节课中我会学到什么?
学习事务性发件箱模式如何可靠地衔接数据库事务与 Kafka 发布,避免在 Spring Boot 中出现双重写入不一致。 你通过在浏览器中直接运行的动手代码来练习 Advanced Spring Boot 4: Event-Driven Architecture (Kafka),全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Advanced Spring Boot 4: Event-Driven Architecture (Kafka) 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Advanced Spring Boot 4: Event-Driven Architecture (Kafka) 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「事务性发件箱模式」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Advanced Spring Boot 4: Event-Driven Architecture (Kafka) 课中编写并运行代码吗?
能。每节 Advanced Spring Boot 4: Event-Driven Architecture (Kafka) 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 了解 Kafka 事务
- 实现事务性生产者
- 恰好一次处理语义
- 事务性发件箱模式