Migration steps:
Step 0: Preparation
- Design the snapshot format and the versioning scheme.
- Implement upcasters for event versions (if needed, we might not need upcasters if we can handle multiple versions in the aggregate, but typically we want to upcast to the latest version when reading).
- Implement the snapshot storage (could be in the same event store or a separate store, but often snapshots are stored as events in a separate stream or as a separate type of record).
Step 1: Start writing snapshots for new events
- Modify the write path to take a snapshot periodically (e.g., every 100 events) or based on business rules.
- We will also write the snapshot as an event in the event stream? Or in a separate snapshot store? Common practice is to store snapshots as separate artifacts but linked by aggregate ID and version (or event number). However, some systems store snapshots as events (with a special type) in the same stream. We need to decide.
Let's assume we store snapshots in a separate store (like a key-value store) for faster access, and we also store a pointer to the snapshot in the event stream (e.g., by writing a special event that indicates a snapshot was taken). Alternatively, we can store the snapshot in the event stream as a special event type, but then replaying the stream would include the snapshot event and we would have to handle it.
Option A (separate store):
- We have a snapshot store (e.g., a table with columns: aggregate_id, aggregate_type, version, snapshot_data, created_at).
- We do not write a snapshot event to the event stream, but we update the snapshot store when we take a snapshot.
Option B (in the event stream):
- We write a special event (e.g., `SnapshotTaken`) that contains the snapshot data. Then when replaying, we would see this event and know that we can use the snapshot data from that event.
However, note that in event sourcing, we typically want to keep the event stream as the source of truth. Storing snapshots in a separate store introduces a new source of truth and must be kept in sync. But it is common to store snapshots separately for performance and to avoid bloating the event stream.
We'll go with Option A (separate store) for performance and clarity, but we must ensure that the snapshot store is updated transactionally with the event store? Not necessarily, because we take snapshots asynchronously. But we must ensure that if we take a snapshot, we have already written the event that triggered the snapshot. So the snapshot store entry must be written after the event is stored, and we must be able to tolerate the snapshot store being out of date (i.e., we can always rebuild from events).
Alternatively, we can store the snapshot in the same event store as a special event, but then we are storing potentially large data in the event stream and we might not want to replay that event every time (we would skip it when we have a snapshot). This is a design choice.
Let's choose Option B (snapshot as an event) for simplicity and because it keeps the snapshot in the same immutable log. Then we can do:
- When we take a snapshot, we write a `Snapshot` event that contains the serialized state of the aggregate. Then, when rebuilding, we look for the latest `Snapshot` event and then replay events after that.
But note: if we store the snapshot as an event, then the event stream becomes a mix of domain events and snapshot events. We have to filter out the snapshot events when projecting to read models? Not necessarily, because the projection should ignore events of type `Snapshot`? Or we can have a separate stream for snapshots?
Alternatively, we can store snapshots in a separate stream per aggregate? But then we have two streams per aggregate: one for events and one for snapshots? That complicates.
Let me reconsider:
Common practice (as in Martin Fowler's article) is to store snapshots as separate objects (not in the event stream). The event stream remains the only source of truth, and snapshots are just a cache. So we store:
- Event stream: sequence of domain events.
- Snapshot store: keyed by aggregate ID, with the latest snapshot (or periodic snapshots) and the version (or event number) at which the snapshot was taken.
Then when loading an aggregate:
- Check the snapshot store for a snapshot for that aggregate.
- If found, load the snapshot and then replay events from the version after the snapshot's version (from the event stream).
- If not found, replay all events.
This is the approach we'll take.
Step 2: Versioning events
- We will add a version field to each event. The version will be an integer that starts at 1 and increments when the event schema changes.
- We will have a registry of event upcasters: a function that can take an event of version X and convert it to version Y (where Y is the latest version). We will upcast events on the fly when reading, or we can pre-upcast during backfill? We'll do on the fly for simplicity and to avoid rewriting the event store.
However, note: if we change the event schema, we might want to rewrite the old events to the new version to avoid having to upcast every time we read. But that would require rewriting the event store, which is a big operation. So we'll do on-the-fly upcasting.
Steps for reading an event stream:
- Read the events from the event store (by aggregate stream).
- For each event, check its version. If it's not the latest, use the appropriate upcaster to convert it to the latest version (or to the version that the current aggregate code expects). We might have a chain of upcasters (from version 1 to 2, then 2 to 3, etc.) or we can have direct upcasters from any version to the latest? We'll do a chain for simplicity of upcaster implementation.
We can have a map:
upcasters: Map<currentVersion, Function<Event, Event>> that takes an event of currentVersion and returns the event in currentVersion+1.
Then to upcast from version 1 to 3, we apply the upcaster for 1->2 and then 2->3.
Step 3: Backfill simulations
- We will take a backup of the production event store (or a subset) and run the new code (with snapshotting and versioning) against it in a test environment.
- We will simulate the process of building snapshots for all aggregates (or a sample) and then verify that we can load aggregates correctly.
Steps for backfill simulation:
a. For each aggregate stream (or a sample of streams):
i. Replay all events (with upcasting if needed) to build the current state.
ii. Take a snapshot of the current state (using the latest event schema version).
iii. Store the snapshot in the snapshot store, along with the version (or event number) of the last event that was applied.
b. Then, test loading the aggregate by:
i. Loading the snapshot (if exists) and then replaying events from after the snapshot's version (with upcasting) and verify the state matches the one we built in step a.
We must also test that the upcasters work correctly for all historical events.
Step 4: Production migration plan
a. **Deploy new code with versioning and upcasters, but without writing snapshots** (or with snapshots disabled by feature flag). We will start by just reading with upcasters and writing events with the new version number for new events.
b. **Backfill snapshots in production**:
- We will run a background job that iterates over all aggregate streams (or a prioritized subset) and builds snapshots for them. We must be careful to not overload the event store. We can rate limit and do it over time.
- The job will:
For each aggregate stream (that doesn't have a snapshot or has an old snapshot):
Replay all events (with upcasting) to get the current state.
Write a snapshot (with the current version and event number) to the snapshot store.
c. **Enable snapshot reading**:
- Once we have snapshots for a significant portion of aggregates, we can enable the code to read from snapshots. We can do this by feature flag: first for a small percentage of aggregates (by ID) and then gradually.
d. **Enable snapshot writing**:
- After we are confident in reading from snapshots, we enable writing snapshots for new events (i.e., when a new event is written, we check if we need to take a snapshot based on the number of events since last snapshot).
e. **Monitor and adjust**:
- Monitor the performance and correctness.
Step 5: Handling schema changes in the future:
- When we change an event schema, we will increment the version and write new events with the new version.
- We will write an upcaster from the old version to the new version.
- We do not need to backfill old events because we have upcasters. But note: if we change the aggregate state structure, we might need to change the snapshot format as well. So we must version the snapshots too.
Snapshot versioning:
- The snapshot should contain the version of the aggregate state (or the version of the last event applied). But note: the snapshot is taken after applying an event of a certain version. So the snapshot's state is in terms of the aggregate's current state (which might be represented differently in different versions).
How to handle snapshot versioning?
Option 1: The snapshot stores the state in the latest version's format. Then when we load a snapshot, we are loading the state in the latest format. But then if we change the state structure (for the aggregate) we must convert the snapshot? That would require upcasting the snapshot. But we don't have an upcaster for snapshots.
Option 2: The snapshot stores the state in the version at which it was taken. Then when we load a snapshot, we must upcast the state from that version to the current version? But the state is not an event, it's the aggregate's state. We would need state upcasters? That's more complex.
Alternatively, we can avoid changing the aggregate state structure in a way that breaks old snapshots? Or we can store the snapshot in a format that is independent of the aggregate state (like a binary blob) and we have a way to convert that blob to the current state? That's what we do with events.
Actually, the snapshot is just a serialized form of the aggregate's state. If we change the aggregate's state class (adding/removing fields) then we cannot deserialize an old snapshot into the new class. So we need to version the snapshot format and have upcasters for snapshots too.
Alternatively, we can store the snapshot in a format that is forward-compatible (like Protobuf) and then we can read old snapshots into the new class? But if we remove a field, then the old snapshot has that field and the new class doesn't, that's okay. But if we add a field, then the old snapshot doesn't have it, so we need a default.
So using a format that supports forward and backward compatibility (like Protobuf, Avro, or JSON with optional fields) can help. But we still might need to handle data migrations.
Let's assume we use a versioned serialization format (like Protobuf with a version number in the snapshot). Then:
- The snapshot will have a version number (the aggregate's state version at the time of snapshot).
- When loading a snapshot, we check the version and if it's not the latest, we apply state upcasters (similar to event upcasters) to convert the state to the latest version.
But note: the state upcaster must be able to convert from state version X to state version X+1. We can store the state in a format that we can upcast (like a map or a generic structure) and then convert to the current state class? Or we can have a separate state representation that is versioned and we upcast that.
Alternatively, we can avoid storing the state in a versioned way by storing the snapshot as a serialized form of the aggregate's current state class at that time, and then when we change the state class, we break old snapshots. Then we would have to rebuild snapshots for all aggregates after a state class change? That's not acceptable.
So we need to version the snapshot format and have upcasters for the state.
How about this:
The snapshot store entry:
aggregate_id, aggregate_type, state_version, state_data (binary), last_event_version (the version of the last event applied), last_event_number.
Then when loading:
- Read the snapshot.
- If the state_version is less than the current state version, run the state upcasters (from state_version to current) to convert the state_data to the current state representation.
- Then apply events from last_event_number+1 (with event upcasters if the events are in old versions) to get to the current state.
But note: the state upcaster must know how to convert the state from version X to X+1, and we must have a chain of state upcasters.
Alternatively, we can avoid state upcasters by ensuring that the state representation is always backward and forward compatible? That might be hard.
Given the complexity, maybe we should avoid changing the aggregate state structure in an incompatible way? Or we can store the state as a map (or a JSON object) and then have a way to convert that map to the current state class. Then we only need to change the conversion logic when the state class changes.
Let's simplify:
We store the snapshot as a binary blob that is the serialized form of the aggregate's state at that time, using a serialization framework that supports schema evolution (like Protobuf). Then we can read the old snapshot into the new state class as long as the fields are compatible.
But if we change the state class in an incompatible way (like removing a field that is required) then we break.
So we must design the state class to be evolvable (use optional fields, etc.) and use a serialization framework that supports that.
Alternatively, we can store the snapshot as a set of events? That would be the same as the event stream. Then we don't need a separate snapshot store? But that defeats the purpose of snapshots for performance.
Given the complexity, I think we should:
- Use a serialization format for snapshots that supports schema evolution (like Protobuf or Avro) and register the schema for the state for each version.
- When we change the state class, we also change the snapshot schema and we write an upcaster for the state (from old state schema to new state schema). The upcaster would be applied when loading a snapshot.
However, note: the state upcaster might need to know about the events that were applied? Not necessarily, because the state at the snapshot is the result of applying all events up to a certain point. The state upcaster only converts the state representation, not the business logic.
But what if the state change between versions requires knowledge of the events? For example, if we split a field into two, then we need to compute the two new fields from the old one? That's a data transformation. We can do that in the state upcaster.
So we will have:
- Event upcasters: to convert events from version X to X+1.
- State upcasters: to convert the state from version X to X+1.
Then the process of loading an aggregate with a snapshot:
Let current_state_version = latest state version.
If we have a snapshot:
state = deserialize(snapshot.state_data) // this gives state in version = snapshot.state_version
current_state = apply_state_upcasters(state, from snapshot.state_version to current_state_version)
last_event_number = snapshot.last_event_number
Else:
current_state = new empty state
last_event_number = -1
Then, read events from the event store with event_number > last_event_number.
For each event (which might be in an old event version):
event = upcast_event(event) // to the latest event version (or to the version that the current aggregate code expects? We want to upcast to the latest event version so that we have a consistent event stream for the aggregate to handle? But the aggregate's event handling code is written for the latest event version? Actually, the aggregate's `apply` method should handle all event versions? Or we upcast events to the latest version and then the aggregate only has to handle the latest version.
We will upcast events to the latest version so that the aggregate's `apply` method only has to handle the latest version of each event type.
Then we apply the event to the current_state.
This way, we only have to write the aggregate's `apply` method for the latest event version.
Step 6: Implementation outline
We will have:
- Event:
String type;
int version;
Object payload; // in the latest version's schema? No, the payload is in the version of the event.
But note: when we upcast an event, we change the version and the payload? Yes, the upcaster converts the payload from the old schema to the new schema.
So the event store stores events with their original version and payload.
When reading, we upcast.
Steps for reading an aggregate:
1. Check snapshot store for a snapshot for the aggregate.
2. If found:
- Deserialize the snapshot's state_data (which is in the snapshot's state_version) to a state object (of that version).
- Apply state upcasters to convert the state to the current state version.
- Let last_event_number = snapshot.last_event_number.
3. Else:
- Create a new state (empty) in the current state version.
- last_event_number = -1.
4. Read events from the event store for the aggregate stream with event_number > last_event_number, ordered by event_number.
5. For each event:
- Upcast the event to the latest event version (by applying a chain of upcasters from the event's version to the latest version).
- Apply the event to the current state (by calling the aggregate's `apply` method with the upcasted event).
6. The current state is now the aggregate's state in the latest version.
Steps for writing an event:
- When a command is handled, we produce one or more events (in the latest event version).
- We write the event to the event store with:
aggregate_id, event_number (incremental for the stream), type, version (latest), payload (in latest version's schema), timestamp, etc.
- Then, we check if we need to take a snapshot (e.g., if the number of events since the last snapshot exceeds a threshold). We do this by checking the current event number and the last snapshot's event number (if exists).
Snapshot writing:
- We write the snapshot to the snapshot store with:
aggregate_id, state_version (the current state version), state_data (serialized current state in current state version), last_event_version (the version of the last event applied, which is the latest event version we wrote), last_event_number (the event number of the last event applied).
Note: the state_version and last_event_version might be different? The state_version is the version of the state class, and the last_event_version is the version of the last event. They are not necessarily the same. The state_version is the version of the state after applying all events up to the snapshot. The state_version might be higher than the last_event_version if we have state upcasters? Actually, the state_version is the version of the state class we are using now. The last_event_version is the version of the event that we just applied. They are independent.
But when we take a snapshot, we are storing the state in the current state version (which is the latest state version). So the state_version in the snapshot is the current state version. And the last_event_version is the version of the last event we applied (which might be old, but we upcasted it to the latest event version when applying? Wait, we upcast events to the latest event version before applying. So the event that we apply is in the latest event version. Therefore, the last_event_version in the snapshot should be the latest event version? Not necessarily, because the last event we applied might have been upcasted from an old version. But we store the event's original version in the event store. However, when we take a snapshot, we are storing the state after applying the event (which is now in the latest event version's effect). But the event's original version is not stored in the snapshot? We store the last_event_number and the last_event_version (which is the version of the event as stored in the event store? or the upcasted version?).
Let's clarify:
We store in the snapshot:
- last_event_number: the event number of the last event we applied (from the event store).
- last_event_version: the version of that event as stored in the event store? Or the upcasted version?
We need the last_event_number to know from which event to start replaying. We don't need the last_event_version for replaying because we will upcast every event from the event store anyway. But we might store the last_event_version for debugging? Or to know what version the state was built from? Actually, the state_version is the version of the state class, and that is independent.
So we can store:
snapshot:
aggregate_id
state_version
state_data
last_event_number
Then when replaying, we start from last_event_number+1.
But note: if we upcast events, we are changing the event's version and payload. Then the state we build is in the current state version. So the snapshot's state_version is the current state version at the time of snapshot.
However, if we change the state version in the future (by changing the state class), then we will have to upcast the snapshot's state when we load it. So we store the state_version to know which state upcaster to apply.
So the snapshot store entry should have:
aggregate_id (string)
aggregate_type (string) // maybe redundant, but for safety
state_version (int)
state_data (binary)
last_event_number (long)
Then when loading:
state = deserialize(snapshot.state_data) // this gives an object of state_version
if state_version < current_state_version:
state = apply_state_upcasters(state, from state_version to current_state_version)
Then replay events from last_event_number+1.
But note: the state upcasters must know how to convert the state from version X to X+1. We will have a chain of state upcasters, just like event upcasters.
Step 7: Testing the migration
We will write tests that:
a. Given a stream of events (in various versions) and an initial state, we can apply the events (with upcasting) and get the correct current state.
b. Given a snapshot (in an old state version) and then a set of events (in old event versions), we can load the snapshot, upcast the state, then upcast the events and apply them, and get the correct current state.
c. We can take a snapshot at a certain point and then later load it and continue.
We will also simulate the backfill:
- For a given stream of events (with versions), we run the backfill process to create a snapshot and then verify that we can load the aggregate from the snapshot and the remaining events.
Step 8: Deployment plan summary
1. Implement event upcasters and state upcasters in the codebase.
2. Implement snapshot store (table or separate store) and the logic to read/write snapshots.
3. Change the read path to use snapshots if available (with state upcasting if needed) and then replay events with event upcasting.
4. Change the write path to write events with the latest version and optionally write snapshots (but initially without writing snapshots, just reading).
5. Deploy the new code with snapshot reading enabled (but without writing snapshots) and with upcasters. This should be backwards compatible because we are only reading and we can read old events (with upcasters) and we are not writing snapshots yet.
6. Run the backfill job in production to populate snapshots for existing aggregates. This job must be idempotent and can be run in the background without affecting the live system (except for read load on the event store).
7. Once the backfill is complete for a significant portion, enable snapshot writing for new events (by feature flag, gradually).
8. Monitor and then gradually increase the snapshot writing.
Step 9: Rollback plan
If something goes wrong, we can:
- Disable snapshot reading (go back to replaying all events) by feature flag.
- Disable snapshot writing.
Since the event store is the source of truth and we are not deleting any events, we can always rebuild the state by replaying all events (without snapshots). So the rollback is simply to stop using snapshots.
However, note that we are writing snapshots in a separate store. If we stop using snapshots, we can just ignore the snapshot store.
Step 10: Considerations
- The event store must be able to handle the read load from the backfill job.
- The snapshot store must be durable and consistent. We might want to store the snapshot in the same transaction as the event? But that would be expensive. We can do it asynchronously and risk having a snapshot that is not taken (if we crash after writing the event but before the snapshot). But then we can always rebuild from events, so it's acceptable.
- We must handle the case where the snapshot is taken but then the event that triggered the snapshot is not stored? That should not happen because we take the snapshot after the event is stored. But if we do it asynchronously, we might take a snapshot for an event that is not yet durable? We must ensure that the event is durably stored before taking the snapshot.
- We must handle concurrent updates to the same aggregate: we should not take a snapshot while the aggregate is being updated? Actually, we take a snapshot after we have written the event and updated the in-memory state. But if multiple updates happen, we might take multiple snapshots? We should only take a snapshot if the number of events since the last snapshot exceeds a threshold. We must check the last snapshot's event number and compare to the current event number. But note: the current event number might have been incremented by another process? We are in a single process for one aggregate? In an event-sourced system, we typically handle one command at a time for a given aggregate (by using optimistic locking). So we are safe.
- However, if we are doing backfill in the background, we are reading the event store and writing snapshots. We must be careful not to take a snapshot for an aggregate that is being updated in real-time? Because then we might write a snapshot that is based on a state that is not the latest? But we are reading the event store up to the current event number (at the time we start reading the stream). If new events come in while we are building the snapshot, then our snapshot will be behind. But that's okay because we will write the snapshot with the event number we processed up to. Then when loading, we will replay the events after that event number. So it's safe.
- But if we are taking a snapshot for an aggregate that is being updated, we might be building the state from a stale view of the event stream? Actually, we are reading the event store sequentially, so we will get all events up to the point we read. If new events are added after we read the last event, then we won't include them in the snapshot. That's acceptable because we will replay from the snapshot's last_event_number+1, which will include the new events.
So the backfill job can run concurrently with the live system.
Step 11: Code structure
We will have:
AggregateRoot:
- state: in the current state version.
- apply(event: Event): applies an event (in the latest event version) to the state.
Event:
- type: String
- version: Int
- payload: Any (or a specific type for each event version? We can have a base Event interface and then specific event classes for each version? But then we have multiple classes for the same event type? That's complex.
Alternatively, we can have:
Event {
String type;
int version;
JsonNode payload; // or a generic object, but then we lose type safety.
Then we upcast the payload to the latest version's schema (which might be a different class).
But we want type safety in the aggregate's apply method. So we can have:
For each event type (e.g., `UserCreated`), we have a set of versions:
UserCreatedV1, UserCreatedV2, etc.
And we have upcasters that convert from V1 to V2, etc.
Then the aggregate's `apply` method for `UserCreated` only handles the latest version (say V2). But then we must upcast every `UserCreated` event to V2 before applying.
How do we know which upcaster to apply? We have a registry:
upcasterRegistry.getUpcaster(event.type, event.version, targetVersion)
The targetVersion is the latest version for that event type? Or we upcast to the version that the aggregate expects? We want to upcast to the version that the aggregate's `apply` method expects. So the aggregate's `apply` method for `UserCreated` expects a `UserCreatedV2`. So we upcast to V2.
But what if we have multiple event types and each has its own versioning? We can have:
EventType {
String name;
int currentVersion;
}
And for each event type, we have a chain of upcasters for that type.
Then when we read an event, we:
eventType = EventType.forName(event.type)
currentVersion = eventType.currentVersion
upcasters = upcasterRegistry.getUpcasters(event.type, event.version, currentVersion)
Then apply each upcaster in sequence.
Then we have an event of the current version for that type.
Then we call the aggregate's `apply` method with that event.
How does the aggregate's `apply` method know which event class to expect? We can have:
aggregate.apply(event: Event) and then inside, we check the event.type and version? But we want to avoid that.
Alternatively, we can have a dispatcher that calls the appropriate `apply` method for the event type and version? But we only have one `apply` method per event type (for the latest version). So we can have:
aggregate.apply(event: Event) {
switch (event.type) {
case "UserCreated":
applyUserCreated(event as UserCreatedV2) // we know it's V2 because we upcasted.
...
}
}
But then we are casting. We can have a map of event type to a function that takes the event (in the latest version) and applies it.
Alternatively, we can have the aggregate implement an interface for each event type? That might be too heavy.
Let's do:
interface EventHandler<T extends Event> {
void handle(T event);
}
Then the aggregate has a map:
Map<Class<? extends Event>, EventHandler<?>> handlers;
But then we need to register the handler for UserCreatedV2.
Given the complexity, maybe we can avoid having multiple event classes for the same event type? We can have one event class per event type and use a version field in the event and then have a single apply method that handles all versions? That would require the aggregate to handle multiple versions, which we wanted to avoid.
Alternatively, we can have the upcaster convert the event to a canonical form (the latest version) and then the aggregate only handles the canonical form. Then we don't need multiple event classes, we just have one class per event type (the latest version). The upcaster will convert the old version's payload to the new version's payload and then we create an instance of the latest event class.
So:
Event (base class) {
String type;
int version;
// no payload in the base class.
}
UserCreated (latest version) extends Event {
String userId;
String name;
// ...
}
Then the upcaster for UserCreated from V1 to V2:
Input: event of type UserCreatedV1 (which has fields: userId, name, maybe a different structure)
Output: event of type UserCreatedV2 (with the same fields but maybe in a different structure? Or with additional fields?).
The upcaster will create a new UserCreatedV2 event and set the fields appropriately.
Then the aggregate has:
void apply(UserCreated event) { ... }
So we need a way to map from the base Event (with type and version) to the specific event class (the latest version). We can have:
EventFactory:
Event createEvent(String type, int version, Object payload) // returns an instance of the latest event class for that type.
But the upcaster already does that? The upcaster takes an Event (which is of a specific version) and returns an Event of the latest version (which is an instance of the latest event class for that type).
So the upcaster for UserCreated from V1 to V2:
Event upcast(Event oldEvent) {
UserCreatedV1 old = (UserCreatedV1) oldEvent;
UserCreatedV2 newEvent = new UserCreatedV2();
newEvent.userId = old.userId;
newEvent.name = old.name;
// maybe set a new field that was added in V2 to a default?
return newEvent;
}
Then when we read an event:
event = readFromEventStore() // this gives us an event with type, version, and payload (in the old version's schema).
upcasters = getUpcasters(event.type, event.version)
for each upcaster in upcasters:
event = upcaster.upcast(event)
Then event is of the latest version's class.
Then we call aggregate.apply(event) which will call the correct method because event is of the latest class.
But note: the aggregate's apply method is overloaded? We have one apply method per event type? Or one apply method that takes Event and then uses instanceof? We can have:
aggregate.apply(Event event) {
if (event instanceof UserCreated) {
applyUserCreated((UserCreated) event);
} else if ...
}
Or we can have a map of event class to a consumer.
Given the complexity, I think we should have a single apply method that takes the base Event and then uses a visitor pattern or a map of event class to handler.
Alternatively, we can have the aggregate implement a method for each event type (by having an interface per event type) and then we register the aggregate as a handler for each event type? That might be too heavy.
Let's keep it simple:
The aggregate has a method:
void apply(Event event) {
// we switch on event.type and then cast to the latest event class for that type.
switch (event.type) {
case "UserCreated":
UserCreated userCreated = (UserCreated) event;
// handle userCreated
break;
...
}
}
But then we are casting, which is safe because we upcasted to the latest version.
However, note: we might have multiple event types and we don't want the aggregate to have a huge switch. We can have a map:
Map<String, Consumer<Event>> eventHandlers;
Then in the aggregate's constructor, we register:
eventHandlers.put("UserCreated", e -> {
UserCreated userCreated = (UserCreated) e;
// handle
});
Then:
void apply(Event event) {
Consumer<Event> handler = eventHandlers.get(event.type);
if (handler == null) {
throw new IllegalArgumentException("No handler for event type: " + event.type);
}
handler.accept(event);
}
This way, we avoid a big switch and we can register handlers dynamically.
Step 12: Summary of the plan
- We will implement event upcasters and state upcasters.
- We will change the read path to use snapshots (if available) and then replay events with upcasting.
- We will change the write path to write events with the latest version and optionally write snapshots (after a certain number of events).
- We will backfill snapshots for existing aggregates in production.
- We will gradually enable snapshot reading and writing.
This plan allows us to:
- Avoid replaying all events for every aggregate load (by using snapshots).
- Handle schema changes in events (via upcasters).
- Handle schema changes in the aggregate state (via state upcasters).
- Test the migration with backfill simulations.
The main complexity is in the upcasters and state upcasters, and in ensuring that the snapshot store is consistent and available.
We must also consider:
- How to handle the initial backfill: we are going to read all event streams and build snapshots. This might be a heavy operation. We should do it in batches and with rate limiting.
- How to handle new events that arrive while we are backfilling? We are reading the event store at a point in time. If new events come in after we read the stream, then our snapshot will not include them, but that's okay because we store the last_event_number and then when we load the aggregate, we will replay from that event number. However, if we write a snapshot for an aggregate that has new events after we read, then when we load the aggregate we might miss those events until we take a new snapshot? No, because we store the last_event_number in the snapshot. If new events come in after we wrote the snapshot, then when we load the aggregate, we will load the snapshot (which is at event number N) and then replay events from N+1, which includes the new events. So it's safe.
Therefore, the backfill job can run while the system is live.
Step 13: Implementation details for upcasters
We will have:
interface EventUpcaster {
Event upcast(Event oldEvent);
}
And for state:
interface StateUpcaster<S> {
S upcast(S oldState);
}
But note: the state upcaster must know the current state version and the target state version? We can have:
StateUpcaster fromVersionXToVersionY.
Then we have a chain of state upcasters.
We can have a registry:
EventUpcasterRegistry {
Map<String, List<EventUpcaster>> upcastersByEventType; // for each event type, a list of upcasters from version 1 to 2, 2 to 3, etc.
}
Then to upcast an event:
List<EventUpcaster> upcasters = upcasterRegistry.getUpcasters(event.type, event.version, targetVersion);
for (EventUpcaster upcaster : upcasters) {
event = upcaster.upcast(event);
}
Similarly for state:
StateUpcasterRegistry {
Map<Integer, List<StateUpcaster>> upcastersByStateVersion; // from version 1 to 2, 2 to 3, etc.
}
Then to upcast state:
List<StateUpcaster> upcasters = stateUpcasterRegistry.getUpcasters(stateVersion, currentStateVersion);
for (StateUpcaster upcaster : upcasters) {
state = upcaster.upcast(state);
}
But note: the state upcasters are independent of the event type? They are for the aggregate's state. So we have one chain of state upcasters for the entire aggregate state.
Step 14: Snapshot store implementation
We can use a key-value store (like Redis, or a database table) with key=aggregate_id and value=snapshot (state_version, state_data, last_event_number).
We must handle concurrent writes to the same aggregate's snapshot? We can use optimistic locking by storing the last_event_number and then when writing a new snapshot, we check that the last_event_number we are writing is still the current last event number? But if we are writing a snapshot after processing an event, we know the last_event_number is the event we just wrote. However, if two processes try to write a snapshot for the same aggregate (maybe because of concurrent commands? but we process one command at a time for an aggregate) then we should not have two snapshots written at the same time. But the backfill job and the live process might both write? We can have:
- The live process writes a snapshot after every N events. It writes the snapshot with the current event number (which is the event number of the last event applied).
- The backfill job writes a snapshot for an aggregate that might be updated by the live process. Then the backfill job might write a snapshot with an old event number (because it read the event store before the live process wrote new events). Then the live process might later write a snapshot with a newer event number.
We can allow multiple snapshots for the same aggregate, but we only need the latest one. So we can store the snapshot with the last_event_number and when reading, we read the snapshot with the highest last_event_number for that aggregate.
So the snapshot store should allow multiple snapshots per aggregate? Or we can overwrite the old snapshot with a new one that has a higher last_event_number? We can do:
When writing a snapshot for aggregate X with last_event_number = N, we write it and then when reading, we read the snapshot with the maximum last_event_number for that aggregate.
But if we have two snapshots for the same aggregate with different last_event_numbers, we want the one with the highest last_event_number.
So we can store:
Table: snapshots
aggregate_id (PK? no, because multiple per aggregate)
snapshot_id (auto increment, or timestamp)
aggregate_id (indexed)
state_version
state_data
last_event_number
Then when reading, we query for the aggregate_id and order by last_event_number desc limit 1.
But note: we might have a snapshot that is taken by the backfill job with a lower last_event_number than a snapshot taken by the live process. Then we want the live process's snapshot (with higher last_event_number). So the above query works.
Alternatively, we can store only the latest snapshot per aggregate by having aggregate_id as the primary key and then we update the row when we take a new snapshot (with a higher last_event_number). But then if the backfill job writes a snapshot with a lower last_event_number after the live process has written a higher one, we would overwrite the live process's snapshot? That would be bad.
So we must not overwrite if the new snapshot has a lower last_event_number? Or we can do:
When writing a snapshot, we check the current last_event_number for that aggregate in the snapshot store. If the new snapshot's last_event_number is greater than the current one, then we update. Otherwise, we skip.
But note: the backfill job might read an old view of the event store and then try to write a snapshot with an old last_event_number. We don't want to overwrite a newer snapshot. So we should only write a snapshot if the last_event_number is greater than the current one in the store? Or we can store multiple and then read the max.
Storing multiple and reading the max is safe because we can have multiple snapshots and we always take the latest. But it might waste storage. We can have a background job to clean old snapshots.
Alternatively, we can use a compare-and-set operation: when writing a snapshot, we set the snapshot only if the last_event_number is greater than the current one (or if there is no snapshot). Then we don't overwrite with an older snapshot.
We'll go with the compare-and-set approach.
Steps for writing a snapshot:
currentSnapshot = readSnapshot(aggregate_id)
if currentSnapshot == null or snapshot.last_event_number > currentSnapshot.last_event_number:
writeSnapshot(aggregate_id, state_version, state_data, last_event_number)
This way, we only keep the snapshot with the highest last_event_number.
Then when reading, we just read the snapshot for that aggregate (which is the one with the highest last_event_number) and then we replay events from last_event_number+1.
But what if the snapshot's last_event_number is not the latest? That can happen if we took a snapshot and then new events came in. Then when we read, we will replay the new events. So it's safe.
Step 15: Conclusion
This is a complex but feasible plan. We must be careful with the upcasters and state upcasters to ensure they are correct. We must test thoroughly with historical data.
The backfill simulation is critical: we must simulate the entire process of building snapshots and then loading aggregates from snapshots and events to ensure correctness.
We must also monitor the performance of the read path after enabling snapshots to ensure that we are getting the expected improvement.
Finally, we must have a rollback plan in case of issues.
Let me know if you have any questions or need more details on a specific part.
I'll outline a comprehensive event sourcing migration path that incorporates snapshotting, versioned events, and backfill simulations. This approach ensures a smooth transition while maintaining data integrity and system availability.