# 事件溯源

**事件溯源**（Event sourcing）是一种持久化模式，其中对应用程序状态的所有更改都存储为不可变的、仅追加的事件序列，当前状态通过重放这些事件来派生，而非就地存储和更新。<sup>[1](https://martinfowler.com/eaaDev/EventSourcing.html)</sup> Martin Fowler如此定义，并指出还可以查询事件日志来重建过去的状态，以及响应追溯性更改自动调整状态。<sup>[1](https://martinfowler.com/eaaDev/EventSourcing.html)</sup>该模式将订单或客户等业务实体持久化为一系列状态变更事件，每当实体状态发生变化时就追加一个新事件。<sup>[2](https://microservices.io/patterns/data/event-sourcing.html)</sup>

| 关键事实 | 详情 |
|---|---|
| 核心机制 | 事件按时间顺序追加到仅追加存储中；日志成为主要的事实来源，状态通过重新处理事件来重建。<sup>[3](https://ibm-cloud-architecture.github.io/refarch-eda/patterns/event-sourcing/)</sup> |
| 状态重建 | 应用程序通过重放实体流中的事件来派生当前状态，这一过程称为再水合；使用快照时，可以加载快照并重放其后的事件。<sup>[4](https://learn.microsoft.com/en-us/azure/architecture/patterns/event-sourcing)</sup> |
| 不可变性 | 事件数据永不更新；撤销更改需要补偿事件，例如 `ReservationCanceled` 补偿先前的 `SeatsReserved`。<sup>[4](https://learn.microsoft.com/en-us/azure/architecture/patterns/event-sourcing)</sup> |
| 并发控制 | 在支持乐观并发控制的事件存储中，追加操作会验证调用方提供的预期序列号，不匹配则返回错误。<sup>[5](https://www.sciencedirect.com/science/article/pii/S0164121221000674)</sup> |
| 实际规模 | 所研究的事件存储规模从不足3 GB到250 GB不等，其中两个系统持有超过十亿个事件，一个系统报告每天增长400万个事件。<sup>[5](https://www.sciencedirect.com/science/article/pii/S0164121221000674)</sup> |
| 采用建议 | Microsoft建议仅在可审计性等收益足以证明其复杂性时才采用事件溯源；对于大多数系统和系统的大多数部分，传统数据管理已经足够。<sup>[4](https://learn.microsoft.com/en-us/azure/architecture/patterns/event-sourcing)</sup> |

## 工作原理

**写入事件。** 应用程序代码引发描述对对象所执行每个操作的事件，例如 `AddedItemToOrder` 或 `OrderCanceled`，每个事件记录在仅追加存储中，通常通过队列由事件处理器持久化。<sup>[4](https://learn.microsoft.com/en-us/azure/architecture/patterns/event-sourcing)</sup>事件是对过去所发生事情的记录：它们可以被创建或读取，但不能被重写，且只存储事件，同时更新内存中的状态。<sup>[6](https://www.confluent.io/learn/event-sourcing/)</sup>Akka的文档将同一思想表述为一种建模技术：数据存储不存储当前状态，而是保存增量，对业务状态和状态之间的转换进行建模。<sup>[7](https://doc.akka.io/libraries/guide/concepts/event-sourcing.html)</sup>事件携带时间戳、唯一ID和关联信息，提供对领域对象生命周期的完整可见性。<sup>[8](https://aws-samples.github.io/eda-on-aws/patterns/event-sourcing/)</sup>

**读取状态。** 当前状态可以通过在处理请求时按需重放实体流中的所有事件来派生，也可以通过加载快照并重放后续事件来派生。<sup>[4](https://learn.microsoft.com/en-us/azure/architecture/patterns/event-sourcing)</sup>由于读取和重放事件代价高昂，系统构建物化视图：针对查询优化的、事件存储的只读投影。<sup>[4](https://learn.microsoft.com/en-us/azure/architecture/patterns/event-sourcing)</sup>重放成本随流长度增长。<sup>[6](https://www.confluent.io/learn/event-sourcing/)</sup>实践者Andrii Boyko引用的EventStoreDB团队示例计算得出：一个聚合每天接收3个事件、涉及17种事件类型，一年累积3 × 17 × 365 = 18,615个事件，在没有快照的情况下回答余额查询必须全部重放。<sup>[9](https://andriiboyko.com/articles/event-sourcing-the-parts-that-are-genuinely-hard)</sup>快照通过定期存储当前状态来解决这个问题，重建时读取快照并仅应用自快照以来事件的增量。<sup>[8](https://aws-samples.github.io/eda-on-aws/patterns/event-sourcing/)</sup>

**并发与投递。** 事件存储按实体ID自然分区，简化了分片，乐观并发控制防止对同一流的冲突写入：存储拒绝预期序列号不匹配的事件。<sup>[4](https://learn.microsoft.com/en-us/azure/architecture/patterns/event-sourcing)</sup><sup> • </sup><sup>[5](https://www.sciencedirect.com/science/article/pii/S0164121221000674)</sup>[实现](https://www.edgepedia.org/zh/implementation)细节在此很重要。在[PostgreSQL](https://www.edgepedia.org/zh/postgresql)中，自动生成的全局序列号可能因序列递增发生在独立事务中而出现间隙或顺序混乱，因此按聚合的序列号同时用于排序和并发控制。<sup>[10](https://softwaremill.com/things-i-wish-i-knew-when-i-started-with-event-sourcing-part-3-storage/)</sup>EventStoreDB保证流序列号严格单调递增且无间隙，并通过准备位置和提交位置组成的复合位置保证全局排序。<sup>[10](https://softwaremill.com/things-i-wish-i-knew-when-i-started-with-event-sourcing-part-3-storage/)</sup>向消费者的投递通常是至少一次，因此事件处理器必须幂等，例如通过跟踪最后处理的事件序列号。<sup>[4](https://learn.microsoft.com/en-us/azure/architecture/patterns/event-sourcing)</sup>

**纠正错误。** 由于事件不可变，错误条目永远不会被编辑。补偿事件是逆转或纠正先前事件效果的新事件。<sup>[4](https://learn.microsoft.com/en-us/azure/architecture/patterns/event-sourcing)</sup>一份已报告的事件溯源错误恢复案例涉及：不再在命令处理器中更新实体的当前状态，而是在加载实体时从事件历史计算状态。<sup>[11](https://www.infoq.com/news/2019/07/mistakes-recovery-event-sourcing/)</sup>

## 与CQRS和事件驱动架构的关系

这三个概念相关但不相同。事件溯源关乎状态如何存储；命令查询职责分离（CQRS）关乎将读取与写入分离。事件溯源通常与[CQRS](https://www.edgepedia.org/zh/cqrs)结合以独立扩展读写，但CQRS可以独立于事件溯源实现；它可以使用领域事件生成投影，异步更新的投影是最终一致的。<sup>[4](https://learn.microsoft.com/en-us/azure/architecture/patterns/event-sourcing)</sup><sup> • </sup><sup>[12](https://debezium.io/blog/2020/02/10/event-sourcing-vs-cdc/)</sup>

事件存储也不同于消息代理。[Apache Kafka](https://www.edgepedia.org/zh/apache-kafka)等代理通常不提供按实体级别的流查询或乐观并发控制。虽然这使它们能有效分发事件——将事件广播到投影和外部消费者——但它们无法取代事件存储。<sup>[4](https://learn.microsoft.com/en-us/azure/architecture/patterns/event-sourcing)</sup>具体到Kafka，无法高效地为给定聚合挑选事件，保存事件时也没有内置并发控制，因此必须在应用层应用单写入者原则。<sup>[10](https://softwaremill.com/things-i-wish-i-knew-when-i-started-with-event-sourcing-part-3-storage/)</sup>[变更数据捕获](https://www.edgepedia.org/zh/change-data-capture)（CDC）是另一种不同的机制：事件溯源在应用边界以领域事件日志捕获状态，日志作为事实来源；而CDC在系统边界从数据库事务日志导出变更事件；两者都支持重放。<sup>[12](https://debezium.io/blog/2020/02/10/event-sourcing-vs-cdc/)</sup>

## 数据一览

2021年发表在《Journal of Systems and Software》上的一项实证研究考察了19个事件溯源系统，并借鉴了25位工程师的经验。<sup>[5](https://www.sciencedirect.com/science/article/pii/S0164121221000674)</sup>其规模数据最清晰地反映了生产规模：

- 事件存储大小从不足3 GB到250 GB不等，两个系统报告超过十亿个事件。<sup>[5](https://www.sciencedirect.com/science/article/pii/S0164121221000674)</sup>
- 十一个系统（超过半数）持有超过一百万个事件；名为HealthSys的系统报告每天增长400万个事件。<sup>[5](https://www.sciencedirect.com/science/article/pii/S0164121221000674)</sup>
- 报告的模式包含20到450种事件类型，没有系统超过500种。<sup>[5](https://www.sciencedirect.com/science/article/pii/S0164121221000674)</sup>

基准测试提供了性能背景。2026年IEEE COMSNETS的一项研究对基于Kafka的事件溯源架构（含CQRS、模式注册表版本管理、Zstandard压缩、死信队列处理和RocksDB状态缓存）与CRUD REST+SQL实现进行了基准测试，使用50,000个银行事件生成超过150,000次持久状态转换；事件溯源方案持续达到105.4事件/秒，是CRUD实现的2.69倍，同时保持一致的低延迟读取。<sup>[13](https://doi.org/10.1109/comsnets67989.2026.11418216)</sup>在存储引擎方面，ChronicleDB的作者报告称，在其基准测试中，他们专门构建的事件存储在事件存储工作负载的写入性能上超过[Cassandra](https://www.edgepedia.org/zh/cassandra) 200倍以上。<sup>[14](https://dl.acm.org/doi/fullHtml/10.1145/3342357)</sup>相反，SoftwareMill在PostgreSQL上对基于Akka的事件存储进行的只写基准测试表明，基于RDBMS的事件存储即使在中等硬件上也可能出奇地快。<sup>[15](https://softwaremill.com/reactive-event-sourcing-benchmarks-part-1-postgresql/)</sup>

## 与其他方案的比较

**对比CRUD。** CRUD持久化存储最新状态并覆盖它；事件溯源存储每一次状态变更。保存事件是单一操作，microservices.io目录将其列为优于多表更新的优势，因为持久化是原子的。<sup>[2](https://microservices.io/patterns/data/event-sourcing.html)</sup>按创建顺序不可变地存储状态变更，产生对系统所做事情的全面审计，并允许从日志重新派生状态。<sup>[16](https://www.oreilly.com/library/view/designing-event-driven-systems/9781492038252/ch07.html)</sup>然而Microsoft的指导很明确：事件溯源是一种复杂的模式，对于大多数系统和系统的大多数部分，传统数据管理已经足够；迁移到或迁离它的成本很高，因此应在可审计性和历史重建等收益足以证明复杂性时采用。<sup>[4](https://learn.microsoft.com/en-us/azure/architecture/patterns/event-sourcing)</sup>

**对比审计表。** Fowler将事件存储比作版本控制系统，所有提交的日志就是事件存储。<sup>[17](https://martinfowler.com/articles/201701-event-driven.html)</sup>[版本控制](https://www.edgepedia.org/zh/version-control)也是他常用的现实世界中事件溯源的例子，但需注意[Subversion](https://www.edgepedia.org/zh/subversion)使用完全重建（转储和恢复）而非事件重放。<sup>[1](https://martinfowler.com/eaaDev/EventSourcing.html)</sup>事件日志在特定意义上是仅追加的：新事件只在末尾添加，不过旧段可能在保留期过后被截断或按键压缩。<sup>[18](https://queue.acm.org/doi/10.1145/3317287.3321612)</sup>

**对比CDC。** 如上所述，CDC在系统边界从数据库事务日志读取变更，而事件溯源在应用边界写入领域事件；两者可以结合，通过CDC从发件箱导出领域事件。<sup>[12](https://debezium.io/blog/2020/02/10/event-sourcing-vs-cdc/)</sup>

## 实际挑战

**Schema演化。** 旧事件必须多年保持可读，而日志本身没有模式迁移，因此随着系统演化会积累许多模式版本。<sup>[19](https://www.confluent.io/blog/event-sourcing-outgrows-the-database/)</sup>Microsoft记录了主要策略：容错反序列化、带版本标识符的事件版本管理，以及链式向上转换函数，在反序列化期间将旧事件模式转换为当前模式，使应用程序代码只处理最新版本；就地迁移是破坏不可变性的最后手段。<sup>[4](https://learn.microsoft.com/en-us/azure/architecture/patterns/event-sourcing)</sup>该实证研究独立记录了五种策略：版本化事件、弱模式、向上转换、就地转换和复制并转换。<sup>[5](https://www.sciencedirect.com/science/article/pii/S0164121221000674)</sup>

**最终一致性。** 当物化视图通过重放事件异步生成时，事件写入、发布和消费者处理之间存在延迟，因此视图是最终一致的。<sup>[4](https://learn.microsoft.com/en-us/azure/architecture/patterns/event-sourcing)</sup>在基于CQRS的事件溯源中，视图异步更新，读者不一定能读到自己的写入。<sup>[19](https://www.confluent.io/blog/event-sourcing-outgrows-the-database/)</sup>投影还需要比预期更频繁地重建，原因包括程序缺陷、新的报告需求和模式变更；实践者建议使其幂等、版本化，并能在可行的时间范围内重建，因为需要一周的完全重建是个问题。<sup>[20](https://yaroslavkladko.dev/event-sourcing-in-practice)</sup>

**删除与GDPR。** 不可变事件与擦除权冲突。已记录的应对措施包括假名化、加密粉碎和重写。在加密粉碎中，个人可识别信息在事件存储中加密，密钥单独保存；收到擦除请求时删除密钥，使加密数据不可读，而无需重写事件。<sup>[21](https://patchlevel.dev/blog/mastering-sensitive-data-handling-and-gdpr-compliant-secure-data-removal-with-event-sourcing)</sup>Mathias Verraes指出，这使得删除极其廉价，因为只需删除密钥而非所有副本，不过加密粉碎和相关的“可遗忘载荷”模式都无法解决消费者存储加密数据的问题。<sup>[22](https://verraes.net/2019/05/eventsourcing-patterns-throw-away-the-key/)</sup>在需要重写的情况下，可以通过读取所有事件、应用更改（如删除流或编辑值）并写入清理后的新存储来重建整个事件存储。<sup>[21](https://patchlevel.dev/blog/mastering-sensitive-data-handling-and-gdpr-compliant-secure-data-removal-with-event-sourcing)</sup>在实证研究中，HealthSys和P-PaySys使用匿名化和移除，这需要重写事件；而IdentitySys将事件和个人信息分离到两个不同的存储中，并在个人数据被移除处提供默认值。<sup>[5](https://www.sciencedirect.com/science/article/pii/S0164121221000674)</sup>

**规模成本。** 事件流通常被视为实际上长期存在：存储可能随时间增长，旧事件版本可能需要保持可解析，实践者建议为每个聚合规划5到10年的事件历史。<sup>[20](https://yaroslavkladko.dev/event-sourcing-in-practice)</sup>AWS建议使用许多短生命周期、事件较少的流，而非长生命周期、事件众多的流，因为较短的流便于维护和版本管理，并减少对快照的需求。<sup>[8](https://aws-samples.github.io/eda-on-aws/patterns/event-sourcing/)</sup>

**出错时。** 该实证研究识别了五个实践者挑战：事件系统演化、陡峭的学习曲线、缺乏可用技术、重建投影和数据隐私。<sup>[5](https://www.sciencedirect.com/science/article/pii/S0164121221000674)</sup>过度应用事件溯源的已报告失败症状包括：不断与快照和重放性能作斗争、因程序缺陷每两周重建投影，以及团队成员害怕接触事件溯源模块。<sup>[20](https://yaroslavkladko.dev/event-sourcing-in-practice)</sup>

## 采用、工具与最新发展

使用事件溯源的企业应用比该模式的知名度所暗示的要少；Fowler指出他见过少数使用它的应用或应用部分。<sup>[1](https://martinfowler.com/eaaDev/EventSourcing.html)</sup>一个值得注意的大规模应用是《纽约时报》，它将报纸全部历史中（可追溯到1851年创刊）的所有修改记录、图片、文章和署名保存在一个Kafka主题中，同时服务将这些事件转换为网站视图。<sup>[19](https://www.confluent.io/blog/event-sourcing-outgrows-the-database/)</sup>

实践者报告了工具缺口。Oskar Dudycz写道，他看到事件溯源最初的简单性与生产中的使用之间存在鸿沟，并同意Alexey Zimarev的观点，即社区仍然需要事件溯源框架或库。<sup>[23](https://event-driven.io/en/practical-introduction-to-event-sourcing/)</sup>

**2023年后的发展。** 专用事件存储产品已经成熟。EventSourcingDB 1.1版（2025年9月）引入了动态一致性边界，让团队通过EventQL查询而非仅通过聚合来定义何时需要严格一致性，还引入了EventQL前置条件和动态生成的Ed25519事件签名，这使得密钥更改无需适配现有事件；1.2版（2025年11月）增加了更多前置条件，并在EventQL中暴露签名和哈希字段。<sup>[24](https://docs.eventsourcingdb.io/blog/2025/12/18/2025-in-review-a-year-of-events/)</sup><sup> • </sup><sup>[25](https://www.heise.de/en/news/EventSourcingDB-1-1-offers-more-flexible-consistency-control-and-signed-events-10630020.html)</sup>该产品以Docker镜像和Linux、macOS、Windows二进制文件形式提供，附带Go、JavaScript/[TypeScript](https://www.edgepedia.org/zh/typescript)、.NET、PHP、Python、Rust和JVM的SDK，每个实例最多25,000个事件免费。<sup>[25](https://www.heise.de/en/news/EventSourcingDB-1-1-offers-more-flexible-consistency-control-and-signed-events-10630020.html)</sup>截至2025年12月，它报告超过10,000次[Docker Hub](https://www.edgepedia.org/zh/docker-hub)拉取，并宣布EventSourcingDB Cloud（全托管选项）的私有测试版。<sup>[24](https://docs.eventsourcingdb.io/blog/2025/12/18/2025-in-review-a-year-of-events/)</sup>一个新的应用领域也已开辟：Akka认为事件溯源适合代理式AI系统，因为不可变事件允许可靠地重现任何代理在任何时间点的状态，且事件日志可以馈送微调和上下文工程。<sup>[26](https://akka.io/blog/event-sourcing-the-backbone-of-agentic-ai)</sup>学术兴趣也在同步增长；2024年的一篇论文指出事件溯源的许多方面仍未被科学研究探索，并提出了事件溯源数据库的性能评估基准。<sup>[27](https://science.lpnu.ua/sisn/all-volumes-and-issues/volume-15-2024/developing-performance-evaluation-benchmark-event)</sup>

**一个现存的争议：日志是审计追踪吗？** Ben Stopford和InfoQ的实践者小组在事件日志能否作为审计追踪的问题上存在分歧。Ben Stopford的O'Reilly著作指出，不可变、有序的事件日志提供了对系统所做事情的全面审计。<sup>[16](https://www.oreilly.com/library/view/designing-event-driven-systems/9781492038252/ch07.html)</sup>InfoQ的实践者小组则警告相反的情况：作为审计追踪，无法保证状态和历史匹配，因此事件历史不能盲目信任。<sup>[28](https://www.infoq.com/articles/panel-event-sourcing/)</sup>

## References

1. [Event Sourcing, Martin Fowler](https://martinfowler.com/eaaDev/EventSourcing.html)
2. [Pattern: Event sourcing, microservices.io](https://microservices.io/patterns/data/event-sourcing.html)
3. [Pattern: Event sourcing, IBM Event-Driven Architecture reference architecture](https://ibm-cloud-architecture.github.io/refarch-eda/patterns/event-sourcing/)
4. [Event Sourcing Pattern, Azure Architecture Center, Microsoft Learn](https://learn.microsoft.com/en-us/azure/architecture/patterns/event-sourcing)
5. [An empirical characterization of event sourced systems and their schema evolution, Journal of Systems and Software (2021)](https://www.sciencedirect.com/science/article/pii/S0164121221000674)
6. [Event Sourcing: An Introduction, Confluent](https://www.confluent.io/learn/event-sourcing/)
7. [Event Sourcing, Akka Guide](https://doc.akka.io/libraries/guide/concepts/event-sourcing.html)
8. [Event Sourcing, Event-driven Architecture on AWS](https://aws-samples.github.io/eda-on-aws/patterns/event-sourcing/)
9. [The Genuinely Hard Parts of Event Sourcing in Production, Andrii Boyko](https://andriiboyko.com/articles/event-sourcing-the-parts-that-are-genuinely-hard)
10. [Things I wish I knew when I started with Event Sourcing, part 3: storage, SoftwareMill](https://softwaremill.com/things-i-wish-i-knew-when-i-started-with-event-sourcing-part-3-storage/)
11. [Mistakes and Recoveries When Building an Event Sourcing System, InfoQ](https://www.infoq.com/news/2019/07/mistakes-recovery-event-sourcing/)
12. [Distributed Data for Microservices: Event Sourcing vs. Change Data Capture, Debezium](https://debezium.io/blog/2020/02/10/event-sourcing-vs-cdc/)
13. [Event Sourcing with Kafka Streams: A Comprehensive Benchmark Against CRUD for Financial Workloads, IEEE COMSNETS](https://doi.org/10.1109/comsnets67989.2026.11418216)
14. [ChronicleDB: A High-Performance Event Store, ACM](https://dl.acm.org/doi/fullHtml/10.1145/3342357)
15. [Reactive Event Sourcing benchmarks, part 1: PostgreSQL, SoftwareMill](https://softwaremill.com/reactive-event-sourcing-benchmarks-part-1-postgresql/)
16. [Event Sourcing, CQRS, and Other Stateful Patterns, Ben Stopford, Designing Event-Driven Systems, O'Reilly](https://www.oreilly.com/library/view/designing-event-driven-systems/9781492038252/ch07.html)
17. [What do you mean by Event-Driven?, Martin Fowler](https://martinfowler.com/articles/201701-event-driven.html)
18. [Online Event Processing, ACM Queue](https://queue.acm.org/doi/10.1145/3317287.3321612)
19. [Event Sourcing Outgrows the Database, Confluent blog](https://www.confluent.io/blog/event-sourcing-outgrows-the-database/)
20. [Event Sourcing in Practice: Lessons From Shipping It, Yaroslav Kladko](https://yaroslavkladko.dev/event-sourcing-in-practice)
21. [Mastering sensitive data handling and GDPR compliant secure data removal with event sourcing, patchlevel](https://patchlevel.dev/blog/mastering-sensitive-data-handling-and-gdpr-compliant-secure-data-removal-with-event-sourcing)
22. [Eventsourcing Patterns: Crypto-Shredding, Mathias Verraes](https://verraes.net/2019/05/eventsourcing-patterns-throw-away-the-key/)
23. [Practical Introduction to Event Sourcing, event-driven.io](https://event-driven.io/en/practical-introduction-to-event-sourcing/)
24. [2025 in Review: A Year of Events, EventSourcingDB](https://docs.eventsourcingdb.io/blog/2025/12/18/2025-in-review-a-year-of-events/)
25. [EventSourcingDB 1.1 offers more flexible consistency control and signed events, heise](https://www.heise.de/en/news/EventSourcingDB-1-1-offers-more-flexible-consistency-control-and-signed-events-10630020.html)
26. [Event Sourcing: The Backbone of Agentic AI, Akka](https://akka.io/blog/event-sourcing-the-backbone-of-agentic-ai)
27. [Developing a Performance Evaluation Benchmark for Event Sourcing Databases (2024)](https://science.lpnu.ua/sisn/all-volumes-and-issues/volume-15-2024/developing-performance-evaluation-benchmark-event)
28. [Virtual Panel: Succeeding with Event Sourcing, InfoQ](https://www.infoq.com/articles/panel-event-sourcing/)

---
*Initially written Oct 15, 2026*

Topic: 技术与人造世界 › 计算技术与数字系统 › 软件与编程 › Software engineering and development process › Software design and architecture › Titles 4 to Mo

Copyright 2026 Edgepedia

License: Edgepedia Community License 1.0, https://www.edgepedia.org/edgepedia/license

Source: https://www.edgepedia.org/zh/event-sourcing

English original: https://www.edgepedia.org/event-sourcing
