In brief
Event sourcing records every change as an immutable event and rebuilds the current state from their sequence. CQRS separates the write model (commands) from the read model (queries). Both patterns pay off in selected parts of a system: where the history of changes has business or audit value (ledgers, payments, orders) and reads and writes have different requirements. In simple areas, such as a user profile or reference data, they add complexity without benefit.
What event sourcing is
Event sourcing is a pattern in which the source of truth is not the current state of a record but an ordered sequence of events that changed it. Instead of updating a `balance` column on an account, the system appends events: "deposit of 500 PLN," "outgoing transfer of 120 PLN," "fee of 5 PLN." The balance is the result of replaying those events.
Each entity, e.g. an account or an order, has its own event stream. Events are neither changed nor deleted. An error is corrected with a new compensating event, e.g. "refund of fee of 5 PLN," and the original entry stays in the history.
A well-designed event describes business intent, not only the outcome. "The customer reserved two seats" says more than "the number of free seats changed to 42." From the first you can build any report in the future; the second is just a change log of a column.
Replaying a long stream on every request would be expensive, so snapshots are used: after a set number of events, the entity's state is saved and only the events after the snapshot are replayed. A snapshot is an optimization, not the source of truth, and can be rebuilt from scratch at any time.
What CQRS is and how it combines with event sourcing
CQRS (Command Query Responsibility Segregation) is the separation of the model that accepts commands and changes data from the model that answers queries. A command describes a business task ("block the card"), not a data operation ("set status to 3"). A query changes nothing and returns data in a form convenient for a screen or a report.
CQRS can be used without event sourcing, e.g. with one database and separate models in code, or with a read replica. The two patterns do complement each other well, though:
- the event store is the write model and the only source of truth,
- projections, that is, materialized views built from events, are the read model,
- a new report is a new projection built by replaying the history, with no changes on the write side.
An example from a brokerage: order and trade events go into an event store. One projection feeds the customer screen with the current portfolio, a second feeds a data warehouse for regulatory reporting, a third feeds a fraud detection module. Each has a schema tailored to its own queries.
When it is worth it and when it is not
Event sourcing and CQRS should be applied selectively, in those parts of a system where their benefits are real. Microsoft's pattern documentation explicitly recommends sticking with traditional data management in most systems and in most parts of them.
| Worth it | Probably not |
|---|---|
| Ledgers, payments, settlements, where history is required | Simple CRUD with no need for audit or state replay |
| Processes where the "why" matters, not only the "what" | Reference and lookup data that rarely changes |
| Many different views of the same data | Prototypes and short-lived systems |
| High write contention on the same entities | Screens that must immediately show the saved state |
| Integration with many systems reacting to changes | A team with no experience in event-driven architecture |
A good split within one banking system: the account transaction ledger on event sourcing, the customer profile and product configuration on ordinary tables. The same common sense applies to splitting into modules, which we cover in the article on the modular monolith.
Design pitfalls
Most of the trouble comes not from the patterns themselves but from the consequences of immutability and asynchrony.
Eventual consistency
Projections are updated after the event is written, so for a short time the read model shows the old state. The interface has to account for this: after an order is placed, show "accepted for processing" rather than an empty list. If the business requires immediate read consistency, that area is not suited to CQRS with a separate read store.
Event versioning
Events live for years, and their schema changes. Approaches: tolerant deserialization (ignoring unknown fields, default values), a version number in the event, and functions that upgrade old events to the new schema on read (upcasting). Rewriting events in the store is a last resort, because it destroys the audit trail.
Idempotency and ordering
Consumers usually receive events "at least once," so every projection must handle a duplicate safely, e.g. by remembering the number of the last processed event. The event store should reject an append to a stream that has changed since it was read (optimistic concurrency control).
An event store is not a broker
Apache Kafka is excellent at distributing events to projections and other systems, but on its own it does not provide reading the stream of a single entity or concurrency control on append. The event store is usually a specialized database or a table in a relational database with the right constraints, and Kafka is sometimes the distribution layer. We describe the first decisions when working with Kafka in the article Apache Kafka in the enterprise.
Personal data
An immutable event store conflicts with the obligation to erase personal data. This is solved at the design stage: personal data is kept outside the events and referenced by an identifier, or encrypted with a key assigned to the person, and the key is deleted (crypto-shredding). More on this in the article on privacy by design.
How to test an event-based system
Business logic in event sourcing is tested with a given-when-then scheme: given these past events, when this command arrives, these new events are produced. Such tests need neither a database nor a queue and are fast.
Dane: RachunekOtwarty(limit=0), Wpłata(500)
Kiedy: ZlećPrzelew(kwota=600)
Wtedy: PrzelewOdrzucony(powód="brak środków")Beyond that you need integration tests of projections (is the view correct after replaying the history), idempotency tests (a duplicate does not change the result), and event schema migration tests. This is more work than with CRUD, so it is worth settling the test plan before choosing the pattern.
B2Bnetwork engineers design event-driven integrations and test payment systems at banks and financial institutions. The scope of services is described in the What we do section.
Questions and answers
Does CQRS require event sourcing?
No. CQRS only means separating the write model from the read model. It can be used with one database and two models in code, or with a database replica for reads. Event sourcing often goes hand in hand with CQRS, because views for reading are easy to build from events, but each pattern can work on its own.
Does event sourcing replace an audit log?
Largely yes, because every change is recorded as an event with a time and context. You do need to make sure events contain the information an auditor needs, e.g. who initiated the command. A data access log, that is, who read what, is still kept separately, because reads do not generate events.
How do you fix a wrong event if events are never changed?
You append a compensating event that reverses or corrects the effect of the wrong one, e.g. a "fee correction." The original entry stays in the history, so both the error and the fix are visible. If a bug in the code generated many bad events, you apply a bulk correction or a transformation on read, and treat rewriting the store as a last resort.
Does event sourcing improve performance?
Writes can be faster, because they consist of appending an event without locking and updating a row. Reads depend on the projection: a well-chosen view responds quickly, but building it and replaying the history cost time and resources. Overall performance has to be measured with a test on realistic data, not assumed up front.