Event Sourcing
Event Sourcing in Symfony 8: an event store, aggregates rebuilt from events, projections, snapshots, and event versioning. Including the operational problems: projector idempotence, projection rebuilds, and eventual consistency.
In this chapter
13.01 What is Event Sourcing?#
Traditional CRUD persistence has a blind spot: every change overwrites the previous state, and the history is lost for good. Event Sourcing (ES) stores the state of a system as a sequence of immutable events that led to it [1]. Every change to the domain state is recorded by a separate named event with its own data. The current state of an aggregate then comes from replaying these events from the beginning.
Fowler puts the principle as “Event Sourcing ensures that all changes to application state are stored as a sequence of events” [1]. Instead of one row in a table that keeps being overwritten, you get an append-only log of every event that has ever happened to the aggregate.
Fowler's 2005 formulation is broad. An audit log fits it, and so does stream processing. Fourteen years later, Verraes narrowed it down [3]. In his view, a system is event-sourced when the stored history of events is its only source of truth. He adds a condition that Fowler does not have: the same history must be used to enforce the rules for new events. That is what separates Event Sourcing from mere change logging – a log that nobody makes decisions from is an archive, not a source of truth.
Comparison with traditional CRUD persistence
In the CRUD approach, a table holds only the current state of an entity, and a changed value is gone. Event Sourcing writes every change as a new row in the event log, so nothing is overwritten or deleted.
13.02 Relationship to CQRS#
Event Sourcing and CQRS are two separate patterns [2]. They are not the same thing: CQRS can be used without Event Sourcing, and ES without CQRS. In domain-oriented applications, though, they usually appear together.
The reason is technical: Event Sourcing produces events as the basic artifact of persistence, and CQRS needs a way to update read models on every change on the write side. Events cover this propagation without additional infrastructure: the write side stores an event in the Event Store, and the read side reads it and updates the projection.
The symmetry between the two patterns does not hold, however. CQRS on top of classic ORM persistence is a common configuration with no special demands. Event Sourcing without CQRS is possible, but the write model then cannot be queried by anything other than reading a stream by ID. A query such as “list all users named Greg” cannot be built on top of an event stream, as Young already points out [2]. You end up building the read side anyway – and that brings you to CQRS by a detour.
13.03 When to use Event Sourcing#
Event Sourcing adds an audit log, replay, and temporal queries. You pay for them with higher complexity in both infrastructure and code, so it pays off only where the benefits outweigh the cost of implementation and operation.
Suitable use cases
- Audit log as a domain requirement – Financial systems, medical records, or any domain with a legal obligation to keep the complete history of changes. In ES, the audit log follows directly from the storage format and needs no separate implementation.
- Complex domain logic with rich state transitions – Aggregates go through many states, each transition has its own semantics and must be reconstructable. Typical examples: order systems, workflow engines, banking transactions.
- Temporal queries – The need to “replay” the state of the system to any point in the past (debugging, analysis, “what-if” scenarios). With ES, replaying events up to the given timestamp is enough.
- Event-driven integration – The system produces events consumed by other Bounded Contexts or external systems. In ES, an event is also the record of state, so it cannot get lost from the storage. Delivery to consumers, however, is handled only by a relay, see The Event Store as an outbox. In addition, only a selected subset of events is published to the outside, not the internal stream of the aggregate; see Internal and published events.
- CQRS with a heavy read load – ES lets you build any number of optimized read models from one event stream without having to change the write model.
Unsuitable use cases
- Simple CRUD applications – If the domain logic consists of basic Create/Read/Update/Delete operations without complex state transitions, ES brings only unnecessary complexity.
- Systems focused mainly on reporting – If the primary requirement is fast reading and aggregation of data (BI, analytics), classic data warehouse solutions or OLAP databases are a better fit.
- Prototypes and MVPs – Quick validation of a product idea does not need complex infrastructure. ES can be added to a mature system incrementally if the need arises; see Migrating from CRUD to DDD.
- Teams without ES experience – Implementing Event Sourcing without prior experience carries a high risk of errors in critical infrastructure (Event Store, serialization, versioning). The usual start is a smaller Bounded Context as an experiment.
A broker is not an Event Store
Kafka, RabbitMQ, and Redis Streams cannot take on the role of an Event Store, even though events appear in them in order as well. Dudycz gives two technical reasons [4]. Brokers do not support optimistic concurrency at the stream level, so they have nothing to protect an aggregate's invariant against a concurrent write with. A stream in them can be subscribed to, not read. Assembling an aggregate from it is therefore either unreliable or expensive. According to him, brokers are built to transport events, not to store them durably. Retention shows it too: data disappears after a configured period, and that is unacceptable for a source of truth.
The division of roles is therefore clear: the Event Store holds the history and enforces rules over it, and the broker delivers it to consumers. The rest of the chapter uses Symfony Messenger and RabbitMQ exclusively as transport, never as storage.
Ready-made libraries or your own store?
Once the decision for Event Sourcing is made, the choice of implementation remains. The PHP ecosystem offers several libraries that differ in weight and philosophy. The following overview describes the state as of September 2026 and ages faster than the rest of the chapter – check the current condition of a package on Packagist before choosing.
- EventSauce – a small core, clear documentation, no coupling to a framework. It ships a Doctrine message repository and an outbox in separate packages, so the code you write yourself is mostly around DI and Messenger.
- patchlevel/event-sourcing – the bundle declares support for Symfony 8, as does the Ecotone Symfony bundle. It brings ready-made subscriptions, snapshots, upcasting, and crypto-shredding. If you prefer a ready-made solution for Symfony, this is the first thing to look at today.
- Ecotone – not a library but a whole framework with ES, CQRS, and sagas. It has a distinct philosophy built on message-driven architecture; you accept it as a whole, not piece by piece. The stable 1.x line supports Symfony 8; the 2.0 line is still in beta.
- prooph – the 7.x line is maintained and in use, but the accompanying Symfony bundle has not moved since 2024 and stops at Symfony 7. You write the Symfony 8 integration yourself.
Broadway no longer belongs on this list. In August 2026, version 3.0.1 was released marked as
abandoned, and the repository was archived. It is out for new projects; in existing
codebases it remains a liability to remove.
A minimalist store of your own makes sense in three situations. When learning, if you want to see the principles without a layer of someone else's abstractions. When you need full control over the schema and serialization. And in a small domain with a handful of event types, where a library would be bigger than the problem. This book builds its own store for the first reason: the examples are meant to teach principles, not to replace a proven library in production.
13.04 Domain events as the foundation of Event Sourcing#
In Event Sourcing, domain events are the source of truth about the state of the system. In an application built on Doctrine ORM, they are only notifications about side effects. That is why the requirements on their shape are stricter.
The first two concern the class itself. An event is immutable once created – all properties are read-only and set by the constructor. And it must be serializable to a durable format (JSON, MessagePack…) and deserializable back without losing information.
The remaining three concern content and lifecycle:
- the event's schema evolves over time, so old data in the Event Store must stay readable, typically through upcasting (transforming old versions into the current one),
- the name expresses a fact in the past tense:
UserRegistered,OrderPlaced,PaymentFailed, - the data must be granular enough that the state can be reconstructed from the event without access to external sources.
The idempotence of the whole system rests on the split between create() and fromPayload(). If the constructor
generated eventId and occurredAt every time an instance is created, the same stored
event would get a new UUID and a new time after deserialization. The tracking table of processed events
would not recognize a duplicate delivery, and a projection rebuild would work with different times than the ones
valid at the time of writing. The event's identity is therefore created exactly once, in create(), and the payload carries it
along; the event_id and occurred_on columns in the table serve only as indexed metadata.
The event time is stored and parsed in UTC explicitly. The payload format carries no offset,
so otherwise deserialization on a server with a different default timezone would shift the times.
For eventType(), the format <bounded_context>.<noun>_<past_tense_verb> has proven itself,
for example ordering.order_placed or payment.payment_succeeded. It makes routing
events in Symfony Messenger easier, as well as filtering them in the Event Store.
Internal and published events
Events in the Event Store serve two different purposes, and mixing them is costly. An internal event is a unit of the aggregate's state. Its shape changes together with the domain model, and nobody outside the Bounded Context should know about it. A published (integration) event, on the other hand, is the public interface of the context – a contract that other teams build on.
Verraes formulates a rule for this: what is public is a small, selected subset of events; everything else stays private by default [7]. Without this split, the inner structure of the context becomes its API. Every renamed field in the aggregate is then a breaking change for consumers, and refactoring the internal model is no longer possible. Most of the pain addressed in the Event versioning section has its origin right here.
In practice this means two sets of classes. Internal events stay in Domain\Event, and only
the aggregate and its own projections read them. Published events live in a separate namespace
(typically Application\IntegrationEvent), have a stable eventType and their own versioning,
and an explicit mapper translates the internal event into the published one. The cost is one extra
layer; in return, you can change the domain model without coordinating with the surroundings.
13.05 Implementing the Event Store#
Each record in the Event Store carries one event with its context: which aggregate it belongs to, at which version of the stream, and when it happened. Records are never overwritten or deleted.
Structure of the Event Store table
The SQL in this chapter targets MySQL 8: AUTO_INCREMENT, INSERT IGNORE, NOW(6),
TRUNCATE TABLE, and ENGINE=InnoDB. The Symfony skeleton, however, defaults to
PostgreSQL, and local experiments often run on SQLite. On both, the examples need
translating: neither of those databases knows INSERT IGNORE, and SQLite does not know TRUNCATE.
The version column carries optimistic locking. Before writing a new event, the command handler
reads the latest version of the aggregate's stream. If another process has meanwhile written an event with the same
version, the database raises a unique index violation on uq_aggregate_version during the insert.
Concurrent writes are thus detected without pessimistic row locking.
There is a second variant as well. Next to the events table, Young also works with an aggregates table
that carries the current stream version in denormalized form
[2]. The conflict is then
checked up front, against the stored value, and the error message comes from application code.
The cost is one extra write on every commit and the need to keep both tables in one
transaction. The unique index needs no extra write, but it detects the conflict only
from an exception, which the code translates into a ConcurrencyException. That is exactly what
the following implementation does.
The :limit parameter in the loadAll() method has the explicit type ParameterType::INTEGER.
Without it, DBAL binds the value as a string, and MySQL rejects the expression LIMIT '500' as a
syntax error.
13.06 An aggregate with Event Sourcing#
An aggregate with state-based persistence changes its attributes directly. In Event Sourcing, every change of state goes through a domain event: the aggregate's method records the event, and only applying it changes the state.
The aggregate therefore contains two sets of methods:
- Mutating methods (the aggregate's public interface) – validate invariants, decide which event happens, and call an internal method that records the event (typically
recordEvent()). The name deliberately differs fromrecord()in the state-based AggregateRoot; here the method also applies the event to the state and increments the stream version. apply*()methods (protected, see the comment inapplyEvent()) – take a concrete event type and apply the change to the internal state. They are called both when a new event is recorded and during replay from the Event Store.
For testing, this means the given/when/then pattern: given are the historical events, when is the call of a method on the aggregate, and then are the newly emitted events. Details in the chapter Testing DDD.
In an event-sourced aggregate, the state is reconstructed by replay, and the inner properties stay
private – the apply* methods overwrite them repeatedly. That is why the getters at the end of the Order class below
replace public private(set) from the chapter Aggregate Design; this is
a deliberate deviation from the convention of the rest of the book.
PHP: events of the event-sourced aggregate
The events extend DomainEvent, so they carry eventId and occurredAt and can be translated
into a payload and back. They hold their own data in primitive fields – precisely because they travel
to the Event Store and back through the serializer. They are created by the named constructor create(),
so they get their identity and time exactly once:
1<?php2 3declare(strict_types=1);4 5namespace App\Ordering\EventSourced\Event;6 7use App\Ordering\EventSourced\OrderItem;8use App\SharedKernel\Domain\Event\DomainEvent;9use DateTimeImmutable;10use Symfony\Component\Uid\Uuid;11 12final class OrderPlaced extends DomainEvent13{14 private function __construct(15 string $eventId,16 DateTimeImmutable $occurredAt,17 public readonly string $orderId,18 public readonly string $customerId,19 ) {20 parent::__construct($eventId, $occurredAt);21 }22 23 public static function create(string $orderId, string $customerId): self24 {25 return new self(26 eventId: (string) Uuid::v7(),27 occurredAt: new DateTimeImmutable('now', new \DateTimeZone('UTC')),28 orderId: $orderId,29 customerId: $customerId,30 );31 }32 33 /** @param array<string, mixed> $payload */34 public static function fromPayload(array $payload): static35 {36 return new self(37 eventId: $payload['eventId'],38 occurredAt: new DateTimeImmutable($payload['occurredAt'], new \DateTimeZone('UTC')),39 orderId: $payload['orderId'],40 customerId: $payload['customerId'],41 );42 }43 44 public function eventType(): string { return 'ordering.order_placed'; }45 46 public function schemaVersion(): int { return 1; }47 48 /** @return array<string, mixed> */49 public function toPayload(): array50 {51 return [52 'eventId' => $this->eventId,53 'occurredAt' => $this->occurredAt->format('Y-m-d H:i:s.u'),54 'orderId' => $this->orderId,55 'customerId' => $this->customerId,56 ];57 }58}59 60final class OrderItemAdded extends DomainEvent61{62 private function __construct(63 string $eventId,64 DateTimeImmutable $occurredAt,65 public readonly string $orderId,66 public readonly OrderItem $item,67 ) {68 parent::__construct($eventId, $occurredAt);69 }70 71 public static function create(string $orderId, OrderItem $item): self72 {73 return new self(74 eventId: (string) Uuid::v7(),75 occurredAt: new DateTimeImmutable('now', new \DateTimeZone('UTC')),76 orderId: $orderId,77 item: $item,78 );79 }80 81 /** @param array<string, mixed> $payload */82 public static function fromPayload(array $payload): static83 {84 return new self(85 eventId: $payload['eventId'],86 occurredAt: new DateTimeImmutable($payload['occurredAt'], new \DateTimeZone('UTC')),87 orderId: $payload['orderId'],88 // A value object inside an event is reassembled by hand;89 // the serializer knows only the scalar payload.90 item: new OrderItem(91 $payload['item']['productId'],92 $payload['item']['quantity'],93 $payload['item']['unitPriceInCents'],94 ),95 );96 }97 98 public function eventType(): string { return 'ordering.order_item_added'; }99 100 public function schemaVersion(): int { return 1; }101 102 /** @return array<string, mixed> */103 public function toPayload(): array104 {105 return [106 'eventId' => $this->eventId,107 'occurredAt' => $this->occurredAt->format('Y-m-d H:i:s.u'),108 'orderId' => $this->orderId,109 'item' => [110 'productId' => $this->item->productId,111 'quantity' => $this->item->quantity,112 'unitPriceInCents' => $this->item->unitPriceInCents,113 ],114 ];115 }116}117 118final class OrderConfirmed extends DomainEvent119{120 private function __construct(121 string $eventId,122 DateTimeImmutable $occurredAt,123 public readonly string $orderId,124 ) {125 parent::__construct($eventId, $occurredAt);126 }127 128 public static function create(string $orderId): self129 {130 return new self(131 eventId: (string) Uuid::v7(),132 occurredAt: new DateTimeImmutable('now', new \DateTimeZone('UTC')),133 orderId: $orderId,134 );135 }136 137 /** @param array<string, mixed> $payload */138 public static function fromPayload(array $payload): static139 {140 return new self(141 eventId: $payload['eventId'],142 occurredAt: new DateTimeImmutable($payload['occurredAt'], new \DateTimeZone('UTC')),143 orderId: $payload['orderId'],144 );145 }146 147 public function eventType(): string { return 'ordering.order_confirmed'; }148 149 public function schemaVersion(): int { return 1; }150 151 /** @return array<string, mixed> */152 public function toPayload(): array153 {154 return [155 'eventId' => $this->eventId,156 'occurredAt' => $this->occurredAt->format('Y-m-d H:i:s.u'),157 'orderId' => $this->orderId,158 ];159 }160}161 162final class OrderShipped extends DomainEvent163{164 private function __construct(165 string $eventId,166 DateTimeImmutable $occurredAt,167 public readonly string $orderId,168 public readonly string $trackingNumber,169 ) {170 parent::__construct($eventId, $occurredAt);171 }172 173 public static function create(string $orderId, string $trackingNumber): self174 {175 return new self(176 eventId: (string) Uuid::v7(),177 occurredAt: new DateTimeImmutable('now', new \DateTimeZone('UTC')),178 orderId: $orderId,179 trackingNumber: $trackingNumber,180 );181 }182 183 /** @param array<string, mixed> $payload */184 public static function fromPayload(array $payload): static185 {186 return new self(187 eventId: $payload['eventId'],188 occurredAt: new DateTimeImmutable($payload['occurredAt'], new \DateTimeZone('UTC')),189 orderId: $payload['orderId'],190 trackingNumber: $payload['trackingNumber'],191 );192 }193 194 public function eventType(): string { return 'ordering.order_shipped'; }195 196 public function schemaVersion(): int { return 1; }197 198 /** @return array<string, mixed> */199 public function toPayload(): array200 {201 return [202 'eventId' => $this->eventId,203 'occurredAt' => $this->occurredAt->format('Y-m-d H:i:s.u'),204 'orderId' => $this->orderId,205 'trackingNumber' => $this->trackingNumber,206 ];207 }208}
The aggregate holds an item as an immutable record. It must be serializable, because it travels inside an event to the Event Store and back:
1<?php2 3declare(strict_types=1);4 5namespace App\Ordering\EventSourced;6 7final readonly class OrderItem8{9 public function __construct(10 public string $productId,11 public int $quantity,12 public int $unitPriceInCents,13 ) {}14}
The model has its own namespace App\Ordering\EventSourced, not App\Ordering\Domain\Model.
The reason is practical: the event-sourced Order is a different model of the same concept than the state-based
aggregate from the other chapters. Sharing both the name and the namespace would mean two incompatible classes
in one place.
The identifiers here are primitive strings, not value objects as in the rest of the book.
This is the chapter's second deliberate deviation: the event is serialized to the Event Store
and back, so the primitive shape keeps the example readable without a layer of conversion types.
For the same reason, OrderItem carries the price as an int in cents instead of Money,
and addItem() takes the whole item, not the trio of ProductId, quantity, and Money
as the canonical aggregate does.
In production, the value objects stay, and the serializer handles the conversion.
Loading the aggregate from the event stream (replay)
The repository of an event-sourced aggregate does not read an entity table. It loads the event stream from the Event Store
and passes it to the static factory method reconstituteFromEvents(). The resulting state of the aggregate
corresponds exactly to the history of its events.
13.07 Projections#
The Event Store is append-only and cannot answer ad hoc queries such as “all orders of customer X with a total value over CZK 1,000”. For queries like that, projections are built next to it: denormalized read models built from the event stream specifically for the shape of the application's queries.
Synchronous vs. asynchronous projections
- Synchronous projection – The projection is updated directly in the same transaction as the write of the event. It guarantees consistent data at the moment of the response to the command, but it increases write latency and introduces tight coupling between the write and read sides.
- Asynchronous projection – After being stored in the Event Store, events are put into a queue (Symfony Messenger plus a transport such as RabbitMQ or Redis). The projector is a consumer that processes messages independently. The read model is inconsistent for a short time window (eventual consistency), but the write side is faster and decoupled.
A projection as a position in the stream
An asynchronous projection is better described by the catch-up subscription model than as “a handler that receives messages”: the projection keeps a position (checkpoint) in the stream and reads on from it. Three operational properties follow. Restarting the projector breaks nothing; it continues from the stored position. A rebuild means setting the position to zero and letting the projection catch up with the history. And the difference between the last written event and the projection's position is the lag, the one number that really tells you about the health of the read side; it belongs in monitoring.
The Practical problems with projections section uses a checkpoint table for idempotence, that is, to answer the question “have I already processed this event?”. That is a derived role of the checkpoint. The primary one is the position. The table in the example holds no position; it serves only for deduplication. Sagas and Process Managers use the same model of a position in the stream too. On top of the event stream, though, they maintain a process in progress rather than a read model (chapter Sagas and Process Managers).
The read model has its own table. It is created by a migration like any other, except that it can be dropped at any time and rebuilt from the Event Store:
1CREATE TABLE order_summary (2 order_id VARCHAR(36) NOT NULL PRIMARY KEY,3 customer_id VARCHAR(36) NOT NULL,4 status VARCHAR(20) NOT NULL,5 item_count INT UNSIGNED NOT NULL DEFAULT 0,6 -- Money in cents; the column holds the total for the whole order.7 total_amount BIGINT NOT NULL DEFAULT 0,8 placed_at DATETIME NOT NULL,9 shipped_at DATETIME NULL,10 tracking_no VARCHAR(100) NULL,11 12 KEY idx_customer (customer_id, placed_at)13) ENGINE=InnoDB;
Asynchronous delivery of events to projectors through Symfony Messenger requires a configured
transport and routing in config/packages/messenger.yaml:
The list of classes in routing is the item people forget about with Event Sourcing. Event types
multiply quickly, and a missing line shows itself only by the projection going silent. Since Symfony 7.2,
routing can be attached directly to the event with the #[AsMessage('async_events')] attribute, and the YAML list dropped.
The configuration then cannot drift apart from the domain model, because it lives in the same class.
Projections can be rebuilt by replaying the whole Event Store from the beginning. When the domain requirements change, it is enough to create a new projection and replay the history. CRUD systems do not have this option – the historical data is no longer available in them.
Where the event types themselves come from is a question for the domain, not for infrastructure. The fastest way to uncover them is the workshop described in the chapter Event Storming and Domain Storytelling: the orange stickies with domain events are direct candidates for the content of the event stream.
13.08 The Event Store as an outbox#
The projectors from the previous section receive events from an asynchronous queue. In doing so, they silently assume that an event reliably reaches the message broker after it is written to the Event Store. Without additional infrastructure, that does not hold. Writing to the database and publishing to the broker are two independent operations; if the process crashes between them, the event is stored but never reaches the consumers. This dual-write problem, its variants, and the general solution with complete code are covered in the chapter Outbox Pattern. Here, only what is specific to Event Sourcing: no second table is needed.
The relay reads directly from event_store
The event_store table has the properties of an outbox table on its own. It is an append-only
log, and each record is created in the same transaction as the corresponding domain change. What gets
added is a relay worker that reads new rows by id and sends them to Messenger.
It stores the position of the last published row in a checkpoint table, so after a restart it
continues where it left off. The checkpoint alone is not enough, though. Because of the gap problem
described in the following callout, it has to be complemented by one of the mitigations: overlap
with deduplication, selection via FOR UPDATE SKIP LOCKED, or CDC.
The relay implementation is the same as for a regular outbox, whether it is a polling worker
under supervisord or the CDC variant; see
Relay process – two variants.
Delivery guarantees and their consequences
The outbox gives at-least-once delivery within one channel. Specifically:
- At-least-once: if the relay crashes between the dispatch and the checkpoint update, the same event is published again after the restart. Consumers must be idempotent – exactly as the following section shows for projectors.
- Ordering: the relay publishes in ascending order of
id. Within the stream of one aggregate, this matches the order of versions, so the projector seesOrderPlacedbeforeOrderShipped. Across aggregates, ordering is not guaranteed, and because of the gap problem described above, it is not a reliable global commit order. - Latency: between the commit of an event and its delivery to the projector there is a window corresponding to the relay's polling interval. In practice, 100 ms to 1 s; lower latency comes from an output transport that can push (e.g., PostgreSQL
LISTEN/NOTIFYor Debezium).
You do not have to write the push variant on PostgreSQL yourself. The Doctrine transport of Symfony Messenger
has used LISTEN/NOTIFY on PostgreSQL since Symfony 5.1; it is controlled by the use_notify option
in the transport configuration and is enabled by default. A worker consuming from the transport
then does not wait for the polling tick but is woken up by a notification from the database. That does not make
the relay over event_store any faster, though: where it reads the table directly and Messenger plays no part
in that role, you need your own implementation.
13.09 Practical problems with projections#
Simple projection examples leave out four operational problems: idempotence, error states, rebuilds, and eventual consistency from the user interface's point of view.
Projector idempotence
An asynchronous transport (RabbitMQ, Redis Streams, Amazon SQS) guarantees that a message is delivered at least once (at-least-once delivery). A message can therefore be delivered repeatedly – after a timeout, a worker restart, or a network outage. When a projector is not idempotent, repeated processing corrupts the data: duplicate rows, doubled amounts, inconsistent counts.
The projector below is a variant of OrderSummaryProjector from the previous section, not an addition
to it. If you copy both classes, you get two registered handlers for OrderPlaced,
and the second one ends with a UniqueConstraintViolationException. Only one of them belongs
in the application.
Idempotence can be achieved in two ways: an upsert (INSERT … ON DUPLICATE KEY UPDATE) instead of a plain INSERT, or a tracking table of already processed events. With a tracking table, the checkpoint record and the projection write must happen in one database transaction – the atomicity of both writes is the essence of idempotence. Otherwise, a worker crash between them would silently lose the event.
Error states and retry strategies
A projector can fail for many reasons: temporary unavailability of the database, an invalid payload in an old event without an upcaster, or a bug in the projection logic. Symfony Messenger offers two mechanisms for these:
- Retry transport – after a failure, the message automatically returns to the queue with exponential backoff (defaults: 3 retries with a multiplier of 2,
max_delay0, meaning no cap, and a jitter of 0.1 that spreads the retries out in time). - Failed transport (dead letter queue) – after the retry attempts are exhausted, the message moves to a separate queue, where it waits for manual intervention. The event is not lost, and the rest of the queue is not blocked.
Symfony Messenger commands serve to diagnose and reprocess failed messages:
bin/console messenger:failed:show– shows the messages in the dead letter queuebin/console messenger:failed:retry– tries to process the messages againbin/console messenger:failed:remove {id}– removes an invalid message
In day-to-day operation, a few options turn these commands into a triage tool.
messenger:failed:show --stats prints counts by message class, so a single faulty projection
is visible at first glance; --class-filter then limits the listing (and, since Symfony 7.3, the removal too)
to a single message type. Bulk cleanup after a fixed bug is handled by messenger:failed:remove --all.
For projectors with long-running batches, Symfony 7.2 added messenger:consume --keepalive, which
keeps telling the transport that the message is being worked on and prevents a premature redelivery.
At a high event throughput, --fetch-size (Symfony 8.1) reduces overhead by taking messages
from the transport in batches instead of one at a time.
Rebuilding projections
The ability to rebuild a projection from scratch is a practical defense in Event Sourcing against bugs in projection logic. In production, however, it is not a trivial task. A rebuild must run separately from the normal operation of the projector, the old data must be removed correctly, and once it finishes, the projection must match the current state of the Event Store.
The command does not find the projectors on its own. AutowireIterator collects services by tag,
and the table map comes from a parameter, so both have to be in the configuration:
1parameters:2 app.projection_tables:3 order_summary: 'order_summary'4 5services:6 App\Infrastructure\Ordering\Projection\OrderSummaryProjector:7 tags:8 # 'key' becomes the projection name that the command expects as its argument9 - { name: 'app.projection', key: 'order_summary' }
Eventual consistency and the user interface
An asynchronous projection creates a time window, typically milliseconds to a few seconds, in which the user has performed an action but the read model does not show it yet. After clicking “Confirm”, the listing still shows “Draft”. The architecture counts on this; it is not a bug. UI strategies are covered in the Eventual consistency in practice section of the CQRS chapter: optimistic updates, Post-Redirect-Get, polling, and synchronous projections for critical paths.
13.10 Snapshotting#
Aggregate event streams grow as the system ages. An aggregate with thousands of events has to load and replay all of those rows on every command. The performance problem shows up in production sooner than the team expects.
The snapshotting pattern keeps the current state of the aggregate at regular intervals – after every N events or on a schedule. On the next load, the repository looks up the latest snapshot and fetches from the Event Store only the events newer than that snapshot. Young calls this construct a Rolling Snapshot and stresses its nature [2]: it is a denormalization of the aggregate's state at a given moment, that is, a performance heuristic, not a source of truth. The event stream remains the source of truth, and a snapshot can be thrown away and rebuilt at any time.
When to create snapshots
- After replaying the aggregate starts to slow down measurably – the threshold depends on the domain and typically ranges from hundreds to thousands of events. The interval in the example below (50) is a tunable parameter, not a recommendation.
- Periodically (e.g., once a day) for aggregates with a high event frequency.
- On demand – as an optimization step after a data migration or import.
Snapshotting rests on two aggregate methods shown in the
PHP: the Order aggregate with Event Sourcing section: toSnapshot(): array
serializes the current state, and the static reconstituteFromSnapshot(array $state, int $version)
loads it back. Unlike reconstituteFromEvents(), it does not call apply*(): it sets the properties
directly from the snapshot and restores the stream version through restoreVersion() from the base class.
Without the restored version, optimistic locking would fail on the first save. Because the snapshot
copies the aggregate's internal state, its format must evolve together with the domain model.
13.11 Event versioning#
A stored event keeps its shape forever. The domain model, meanwhile, evolves: attributes are added, the data structure changes, fields are split or merged. The old event then has to be read by new code.
This backward readability is provided by event versioning. The most widespread pattern is upcasting: during deserialization, an older version of the payload is transformed into the current format, so the domain model works only with the newest version. The most thorough treatment of the topic is Young's book Versioning in an Event Sourced System [8], which is also the source of most of the terminology in use today – weak schema, copy and replace, double write.
How much work versioning takes is largely decided by the split described in the Internal and published events section. For an internal event, you are the only consumer, and an upcaster is enough. For a published one, you are changing a contract with other teams, and you cannot do without a transition period.
Why versioning is necessary
- The append-only principle – Events in the Event Store cannot be changed. If you change an event's schema, the old data stays in its original format forever.
- Replay and projections – When projections are rebuilt or an aggregate is replayed, all historical events are replayed, including those from the first versions of the system.
- System longevity – An event-sourced system can run for years. Over that time, the domain requirements change many times, and the event schemas have to evolve with them.
The Upcaster pattern
An upcaster transforms an event's payload from one version to the next. Upcasters are chained: if there is an event in version 1 and the current version is 3, the transformation v1 → v2 → v3 takes place. Upcasting happens on read (deserialization), not on write – the original data in the Event Store stays untouched.
A concrete example: splitting the fullName field
When the system launched, the UserRegistered event contained
the fullName field (the full name as one string). Later, a requirement arose to distinguish
first name and last name, so version 2 was created with two fields, firstName
and lastName. The Event Store, however, still contains thousands of v1 events with the fullName field.
UpcasterChain is integrated into EventSerializer. During deserialization,
event_type and schema_version are read from the stored record, and the payload goes through the chain of
upcasters. The fromPayload() method of the current event class then receives only the transformed data.
Changes that upcasting does not solve
Upcasting assumes that old data can be translated deterministically into the new format. Some changes lack this property:
- A semantic change of a field.
Order.shippingPriceoriginally included VAT; from v3 on, it does not. The old data cannot be translated correctly – the VAT rate at the time the order was placed is not stored in the event. An upcaster can only assume (e.g., a constant 21%). That is imprecise, and the reports then carry wrong numbers. - Event splitting. The original
OrderPlacedcontainedcustomerDatainline. In the new version, it is split intoOrderPlaced+CustomerSnapshotted(a separate event). The upcaster would have to create a second event from the first one, and that violates the principle “1 physical event in the Event Store = 1 logical fact”. - Event merging. Two events,
ItemAdded+ItemQuantityChanged, are merged into oneItemUpsertedin the new domain. One-way upcasting is not enough; a transformation over the whole stream is needed. - A semantic bug in the domain logic. The old data was valid according to the old model, but that model was wrong. A replay through the fixed code throws exceptions.
Four possible paths, from the most invasive to the least (the last one concerns published events):
Archiving streams and storage tiering
Aggregates with a long lifecycle (UserAccount, Subscription, LedgerAccount) accumulate
tens to hundreds of thousands of events over years of operation. The active Event Store table
grows, queries slow down, and snapshots have to be created more often.
The standard solution: storage tiering by the age of the stream.
- Hot tier (the primary database, whether MySQL or PostgreSQL) – events from the last 90 days, queries < 10 ms.
- Warm tier (a read replica or the same database on a slower disk) – events from 90 days to 2 years. Hydration reaches here only for forensic queries or a full projection replay.
- Cold tier (S3, Glacier, on-prem object storage) – events older than 2 years. Read-only; only audit reports and compliance need access to it.
Implementation: every night, a job runs that
moves event_store rows older than N days into an event_store_archive table
(or directly to S3 as Parquet). During hydration, the repository does not read the cold tier by default. If an aggregate needs history that reaches into the cold tier, the operator explicitly restores it
from a snapshot newer than the cold-tier boundary. For audit queries, there is a separate query
service that can read from all three tiers.
Frequently asked questions
What is Event Sourcing?
Event Sourcing is an approach to persisting state in which you do not store a current snapshot of the data but an append-only sequence of immutable events that led to the current state. The current state of an aggregate comes from replaying these events from the beginning. The system thus gains a complete audit trail and can reconstruct any past state after the fact. The principle is that the current state is derived from the history of events: the event log only grows with new records. See the What is Event Sourcing? section.
What is the relationship between Event Sourcing and CQRS?
Event Sourcing and CQRS are two separate patterns that are often combined. CQRS works with classic ORM persistence too, and ES can be introduced without a formal split into write and read models. The symmetry does not hold, however: the write model of an event-sourced system cannot be queried other than by ID, so you end up building the read side anyway. In practice, they fit together well. ES naturally leads to separating writes (the event store) from reads (projections into read models), and that is exactly the idea of CQRS. More in the Relationship to CQRS section.
What is an Event Store and what is it for?
An Event Store is a specialized append-only storage that persists the domain events of individual aggregates in chronological order. It typically provides queries on the event stream of a specific aggregate for its reconstruction, and a global query through which all projections read the events. The basic methods are append() and loading a stream (loadStream() in this chapter); more advanced solutions include optimistic locking on versions and publishing events to an event bus. Implementation-wise, there are three options. A specialized product (KurrentDB, which was called EventStoreDB until December 2024), a PHP library on top of a relational database (EventSauce, patchlevel/event-sourcing, prooph), or a minimalist layer of your own, like the one this chapter builds. A detailed walkthrough is in the Implementing the Event Store section.
What are projections in Event Sourcing?
A projection is a process that listens to events from the event store and builds read models from them – denormalized data structures intended for fast queries. A projection tends to be single-purpose: each read model usually has its own projection that keeps it up to date from the beginning or from the last processed offset. Projections can be rebuilt at any time by replaying events from the beginning, which is a safe way to fix errors in read models. A practical example is in the Projections section.
What is snapshotting for in Event Sourcing?
Snapshotting is a technique that periodically stores the serialized state of an aggregate so that its reconstruction does not have to replay the whole history of events from the beginning. On load, the latest snapshot is taken, and only the events that happened after it are applied. Snapshots solve the performance problem of long streams, typically for aggregates with thousands of events. For short streams, they are unnecessary and add operational complexity. A detailed discussion is in the Snapshotting section.
When does Event Sourcing pay off?
Event Sourcing pays off where the history of changes is valuable to the domain in itself (financial systems, warehouses, audited processes, regulated industries), or where you need to reconstruct the state at any point in the past. It is a poor fit for prototypes, MVPs, and plain CRUD applications. It is usually rolled out selectively in one Bounded Context, not across the whole application. Decision criteria are in the When to use Event Sourcing section.