Dealing with Events and Their Evolution
As software systems grow and adapt to new requirements, managing the evolution of data structures becomes critical. In this chapter, we will explore strategies to handle event versioning in event-sourced systems. By the end of this chapter, you will know how to do the following:
- Implement basic event versioning techniques
- Apply strategies such as upcasting and weak schemas for managing evolving events
- Leverage advanced approaches such as content negotiation and copy-replace for more complex scenarios
While we aim to introduce you to practical solutions, it’s important to acknowledge that event versioning is a vast and nuanced topic. Due to space constraints and the focused scope of this book, we cannot go too deep into all aspects of this subject. However, the strategies and examples provided here will equip you with a solid foundation to start managing event evolution effectively. For those who wish to explore this topic further, we recommend additional resources such as Gregory Young’s comprehensive work on versioning, Versioning in an Event Sourced System .
Let’s dive into how to navigate the challenges of event versioning and ensure your systems remain robust and adaptable over time.
The complete code for this chapter can be found in the 03-monolith_with_cqrs_and_event_sourcing branch in the book’s GitHub repository here: https://github.com/PacktPublishing/Domain-driven-Refactoring/tree/03-monolith_with_cqrs_and_event_sourcing .
CQRS, event sourcing, and the event streaming misconception
Modern software systems often face challenges such as scalability, flexibility, and traceability, especially in domains with complex business logic. As you learned in the previous chapters, two architectural patterns, Command Query Responsibility Segregation and Event Sourcing ( CQRS+ES ), have emerged as powerful tools to address these challenges.
CQRS is an architectural pattern that separates the responsibilities of commands (which represent write operations) and queries (which represent read operations). This separation allows the system to handle these operations independently, optimizing each one for its specific purpose. Unlike traditional CRUD systems, where reading and writing often share the same data model, CQRS employs distinct models for each function. Thus, commands in CQRS act as transporters of data for the aggregate, which ensures data consistency and enforces business logic during state changes. The query model, on the other hand, is tailored for efficient data retrieval and presentation. This division not only improves scalability by allowing each model to evolve and scale independently but also enhances maintainability by clearly defining the responsibilities of each operation. Additionally, CQRS enables better alignment with DDD principles, as it allows for more expressive models that reflect the unique requirements of reading and writing in a given domain.
The key concepts of CQRS include the following:
-
Commands : Represent actions that change the system’s state, such as
CreateSalesOrderin our ERP example -
Queries : Represent requests for retrieving data without modifying it, such as
GetSalesOrders - Write model : Handles commands and enforces business rules
- Read model : Optimizes for querying and returning data efficiently
The primary reason for choosing CQRS is scalability. Since the read and write models are separate, they can be scaled independently to meet specific demands. For example, in a system with significantly more read operations than write operations, the read model can be scaled horizontally without affecting the write model. This separation also simplifies the code base by isolating the logic for reading and writing, making the system easier to maintain and understand. Additionally, the read model can be optimized and tailored to specific query patterns, improving performance and user experience by delivering precisely the needed data in the most efficient way.
While CQRS focuses on separating the responsibilities of commands and queries to improve scalability and maintainability, the second pattern, ES, complements it by storing the state of an application as a sequence of events. Together, they create a powerful synergy: CQRS defines how the system interacts with data, and ES defines how the data is stored and evolves over time.
ES is a pattern that captures state changes as a sequence of immutable events. Unlike traditional approaches that store the current state of an entity in a database, ES maintains a complete history of all events that have led to the current state. This means that the system doesn’t just know what the current state is, it also knows how it got there. This approach provides a richer and more detailed understanding of the system’s behavior over time.
An event is an immutable record raised by an aggregate when it processes a command and persists in a specialized database called an event store . The event store serves as the single source of truth, containing all the events that have occurred in the system. When the state of an aggregate is needed, the system replays these stored events to rebuild the aggregate’s current state. This approach ensures consistency and allows the system to process new commands based on the reconstructed state.
One of the key benefits of ES is its ability to provide full traceability of business processes. By maintaining a complete history of all changes, it supports auditing, debugging, and compliance requirements. For example, if an issue arises, developers or auditors can trace back through the event history to understand exactly what happened and why. This level of transparency is invaluable in systems where accountability and accuracy are critical.
A common mistake is to conflate ES with event streaming, but these are distinct patterns with different purposes. Understanding their key features and the differences between the two is crucial.
Key features of event streaming are as follows:
- You subscribe to a stream of events, but you cannot directly read all the events as you would in an event store
- Event streaming does not inherently provide guarantees for optimistic concurrency checks or strong consistency
- The primary focus of event streaming is to move data from one part of the system to another, enabling real-time communication between components
- While event streaming systems offer durable storage for fault tolerance and resilience, they are not designed to act as a source of truth for your application
Key features of ES are as follows:
- In ES, events represent the immutable history of changes that define the current state of the aggregate
-
When a new command is processed in an event-sourcing system, the workflow typically looks like this:
- The repository reads all events for the aggregate from the event store.
- These events are applied sequentially to rebuild the aggregate’s current state.
- The aggregate evaluates the command, executes the business logic, and raises a new event.
- The repository appends this new event to the event store.
- An event store supports strong consistency and optimistic concurrency, and often guarantees global ordering of events, making it suitable as the source of truth for your application
The purpose of an event store is to provide a consistent and reliable mechanism for storing and replaying events to rebuild the application state. In contrast, the purpose of event streaming is to facilitate the movement of data across systems, enabling real-time processing but without the guarantees required to act as the authoritative source of truth.
As with any software application, systems built with CQRS and ES evolve over time. New business requirements often necessitate changes to the structure and meaning of events. Managing these changes effectively is a critical part of system design. This process, often referred to as negotiation, involves ensuring that updates to events maintain backward compatibility and minimize disruptions for existing consumers. As you’ll learn in this chapter, there are several strategies for managing event evolution, all of which begin with event versioning . By versioning events, the system can support both old and new formats, allowing for a smooth transition during updates and ensuring continued functionality across all components.
The lifespan of events: why evolution matters
Event-sourced systems , being an append-only model, are subject to versioning issues, and you must handle them effectively to ensure the system’s long-term viability. Events, once written to the event store, are immutable and represent a historical record of what has occurred in the system. This immutability is a core strength of event sourcing, providing a complete audit trail and the ability to reconstruct the state from past events. However, the immutability of events also introduces challenges when the structure or meaning of events needs to evolve, as older events must coexist with newer ones in the same system. Since aggregates rely on replaying historical events to reconstruct the state, they must remain compatible with all previous event versions.
In traditional systems, managing changes to a database schema is often straightforward. You apply a schema update script, and as long as you add columns or make non-breaking changes, the system continues to operate smoothly. Modern systems, however, rarely follow this monolithic update approach. Instead, changes are deployed incrementally, often with multiple versions of the same software running concurrently in production. If you modify the structure of an event, not all event handlers across the system are updated at the same time. Moreover, projections and event handlers must always be able to process events written years ago, even if the logic or structure has changed.
These factors make event evolution critical. Without careful planning and strategies such as versioning, upcasting, and schema compatibility, systems risk inconsistencies and failures. Properly managing the lifespan of events ensures that your system remains flexible, scalable, and capable of supporting both historical and future requirements without breaking existing functionality.
In the context of event-sourced systems, modifying an existing event can lead to two distinct scenarios: versioning or creating a new event. When you add or remove a property from an existing event while preserving its core meaning and purpose, you are creating a new version of the same event. This approach maintains continuity with the original event, allowing older and newer versions to coexist while ensuring backward compatibility. However, if you rewrite the event entirely, changing its meaning, structure, or purpose, you are effectively creating a new event. This new event represents a fundamentally different concept or domain activity and is treated as distinct from the original event, with no implicit compatibility between the two. Properly distinguishing between these cases is crucial to maintaining the integrity and evolution of an event-sourced system.
Adopting CQRS+ES: overcoming technical and cultural challenges
While CQRS+ES is a powerful architectural pattern, it’s important to recognize that it’s not a silver bullet or a universal solution. Much like owning a hammer doesn’t turn every problem into a nail, CQRS+ES is most effective when applied to the right scenarios. As with any tool, its adoption should be thoughtful and context-driven.
In practice, it is perfectly valid, and often advisable, to apply CQRS+ES selectively within a system. For example, it is particularly effective in core business modules where capturing the complete history of changes, ensuring strong consistency, and enabling complex business logic are critical. ES shines in these areas by allowing the system to rehydrate the current state of an aggregate from a sequence of events, providing a detailed audit trail and enabling powerful features such as temporal queries and event replay.
However, not all parts of a system require this level of complexity. For supportive modules, where the primary goal is to manage data rather than enforce intricate business rules, a traditional CRUD approach is often more appropriate. In such cases, modules can be treated as “data bags,” simple repositories for storing and retrieving information, which support the core domain. This works because we are not concerned with the history of changes or the exact sequence of events leading to the current state. Instead, we prioritize simplicity, efficiency, and ease of implementation.
As discussed in the Architectural quanta callout in Chapter 6 , Transitioning from Chaos , introducing modules helps create pragmatic, maintainable systems by aligning code structure with bounded contexts and business responsibilities. By applying CQRS+ES where it provides the most value and using CRUD elsewhere, you can strike a balance between the benefits of event-driven architectures and the simplicity of traditional data management. Ultimately, the goal is to tailor the architecture to the needs of your system rather than forcing every part of it into a single paradigm. Remember what you learned in the Problem and solution space section in Chapter 2 , Handling Complexity, the Problem, and Solution Space : you do not have to start from the solution, but you must listen to the problem, and then propose the solution. Possibly a solution that can grow with the features of your system.
While these technical considerations are crucial when searching for a solution, they are not the only factors to address. Socio-technical challenges often prove to be even more significant. Broadly speaking, we can categorize these challenges into three main scenarios:
- A winning team doesn’t change. This principle holds true not only in sports but also in our environment.
- The team could improve their game with better training or players but believes their current strategy is enough to win.
- The team believes they need a new playbook to win but they lack the skills and experience to execute it effectively.
The first scenario is straightforward: if you have a strong team that consistently wins, there’s no need to fix what is not broken. Similarly, if your traditional layered architecture is performing well for both your team and your customers, adopting new approaches purely for the sake of innovation isn’t practical or necessary.
In the second scenario, the team recognizes issues with their current setup but lacks the motivation to propose an alternative solution. In our experience, this reluctance often stems not from the team itself but from the company culture. This is how we’ve always done it, why change the strategy? is the mindset typically driving management in such cases. Also, this mindset becomes self-reinforcing. When a company prioritizes maintaining the status quo, its employees often adopt the same outlook. It is important to remember that our goal is to deliver effective business solutions, not to indulge in learning new frameworks for personal satisfaction. As you have learned, an architect must make critical decisions at the start of a project when the least information is available. While introducing accidental complexity may not seem significant initially, your role goes beyond technical choices, you must also act as a motivator, fostering a culture of learning and growth within the team and the company.
The third scenario is more challenging. The team acknowledges the need for change and is willing to explore new approaches but lacks the experience or confidence to execute them effectively. This can lead to hesitation, missteps, or an overreliance on external tools without fully understanding their implications. In such cases, the architect’s role extends beyond proposing the right solution; you must also guide the team in acquiring the necessary skills and provide a clear, incremental path forward. Mentorship, prototyping, and safe spaces to experiment become critical enablers for long-term success.
Regardless of which scenario your team is in, the guiding principle we have followed in this book is start simple – grow big . This approach is especially important during a refactor phase, where it is crucial to begin with supporting and generic domain components. If you make mistakes here, the consequences are minimal; you won’t face significant setbacks or financial loss. The functionalities you deal with during this phase are often straightforward, giving you the opportunity to learn more about the domain you are working in. The approach also allows your team time to explore and experiment with new frameworks and patterns. A pragmatic approach ensures that new concepts are introduced gradually, allowing the team and company to adapt before they are integrated into the system.
That said, if you choose to implement CQRS+ES, be prepared to handle event versioning; it’s not optional but inevitable, as change is a constant, and events are immutable by design.
Event versioning strategies
Now that you understand how events can evolve over time, let’s explore how to manage this evolution effectively. There are several strategies to handle event versioning, each with its own advantages and drawbacks. Before diving into specific solutions, let’s review some fundamental principles that are crucial when working with events:
- Immutability : Events are immutable records of occurrences in the past. Once an event is published, it cannot be altered or removed without compromising the integrity of your system’s history. Instead of modifying an event, you should publish a compensating or corrective event to address any required changes.
- Event handlers : After an event is in production, any changes to its structure or meaning must be managed with caution. If you modify an event or its corresponding handlers, you must consider the impact on historical data. During an event replay, old events will retain their original structure, potentially causing compatibility issues with updated handlers.
So, where to start? First, it’s important to note that commands are not subject to versioning. This is because commands represent actions that trigger changes immediately and are not typically stored in the event store for rebuilding the aggregate state. Instead, our focus must be on versioning events, since they form the persistent history that defines how the state is reconstructed.
Let’s begin with the most straightforward technique.
Simple event versioning
As an example, let’s consider the SalesOrderCreated event:
public sealed class SalesOrderCreated(SalesOrderId aggregateId, Guid commitId, SalesOrderNumber salesOrderNumber,
OrderDate orderDate, CustomerId customerId, CustomerName customerName,
IEnumerable<SalesOrderRowDto> rows) : DomainEvent(aggregateId, commitId)
{
public readonly SalesOrderId SalesOrderId = aggregateId;
public readonly SalesOrderNumber SalesOrderNumber = salesOrderNumber;
public readonly OrderDate OrderDate = orderDate;
public readonly CustomerId CustomerId = customerId;
public readonly CustomerName CustomerName = customerName;
public readonly IEnumerable<SalesOrderRowDto> Rows = rows;
}
Let’s say that the preceding code is the first version you put into production. After some time, new requirements emerge, and you need to add a Boolean property called IsReseller , indicating whether the order was made by a regular customer or a reseller. The simplest way to address this, without encountering the problems discussed earlier, is to create a new version of the event called SalesOrderCreated_V2 :
public sealed class SalesOrderCreated_V2(SalesOrderId aggregateId, Guid commitId, SalesOrderNumber salesOrderNumber,
OrderDate orderDate, CustomerId customerId, CustomerName customerName,
IEnumerable<SalesOrderRowDto> rows, bool isReseller) : DomainEvent(aggregateId, commitId)
{
public readonly SalesOrderId SalesOrderId = aggregateId;
public readonly SalesOrderNumber SalesOrderNumber = salesOrderNumber;
public readonly OrderDate OrderDate = orderDate;
public readonly CustomerId CustomerId = customerId;
public readonly CustomerName CustomerName = customerName;
public readonly IEnumerable<SalesOrderRowDto> Rows = rows;
public readonly bool IsReseller = isReseller;
}
Regardless, this requires a bit of work on your end. For the reasons explained in the The lifespan of events: why evolution matters section earlier in the chapter, our aggregate must always be able to load older versions of an event. So, we must retain the older Apply methods and create a new one. Therefore, the code in our aggregate must change by implementing a new Apply method for the new version and the old one should handle default values (if needed).
Let’s look at the relevant code in the SalesOrder aggregate:
private SalesOrder(SalesOrderId salesOrderId, Guid correlationId, SalesOrderNumber salesOrderNumber, OrderDate orderDate,
CustomerId customerId, CustomerName customerName, IEnumerable<SalesOrderRowDto> rows)
{
RaiseEvent(new SalesOrderCreated(salesOrderId, correlationId, salesOrderNumber, orderDate, customerId, customerName, rows));
}
private void Apply(SalesOrderCreated @event)
{
Id = @event.SalesOrderId;
_salesOrderNumber = @event.SalesOrderNumber;
_orderDate = @event.OrderDate;
_customerId = @event.CustomerId;
_customerName = @event.CustomerName;
_rows = @event.Rows.MapToDomainRows();
}
With the new event, you add a new Apply method and change the RaiseEvent call using the new event version:
private SalesOrder(SalesOrderId salesOrderId, Guid correlationId, SalesOrderNumber salesOrderNumber, OrderDate orderDate,
CustomerId customerId, CustomerName customerName, IEnumerable<SalesOrderRowDto> rows, bool isReseller)
{
RaiseEvent(new SalesOrderCreated_V2(salesOrderId, correlationId, salesOrderNumber, orderDate, customerId, customerName, rows, isReseller));
}
private void Apply(SalesOrderCreated @event)
{
Id = @event.SalesOrderId;
_salesOrderNumber = @event.SalesOrderNumber;
_orderDate = @event.OrderDate;
_customerId = @event.CustomerId;
_customerName = @event.CustomerName;
_rows = @event.Rows.MapToDomainRows();
_isReseller = false; // Default value that we choose
}
private void Apply(SalesOrderCreated_V2 @event)
{
Id = @event.SalesOrderId;
_salesOrderNumber = @event.SalesOrderNumber;
_orderDate = @event.OrderDate;
_customerId = @event.CustomerId;
_customerName = @event.CustomerName;
_rows = @event.Rows.MapToDomainRows();
_isReseller = @event.IsReseller;
}
The same goes for the event handlers in your read model. You should retain the old handler with default values for new properties and implement a new handler for the new event, like what was done in the aggregate.
This approach is straightforward to implement, but it comes with significant drawbacks that shouldn’t be overlooked. The main issue lies in the growing number of event versions. Imagine reaching version 19, or even having multiple events, each with several versions. This can quickly lead to a proliferation of Apply methods in your aggregate. Over time, the code becomes increasingly bloated, making it harder to maintain, understand, and reason about. The readability of your aggregate suffers, and managing changes across these numerous methods becomes a daunting task, ultimately jeopardizing the scalability and maintainability of the solution. As a rule of thumb, remember what Greg Young wrote on versioning in his book, Versioning in an Event Sourced System ( https://leanpub.com/esversioning/read ):
“A new version of an event must be convertible from the old version of the event. If not, it is not a new version of the event but rather a new event.”
This implies that new events should be convertible to the older versions, and vice versa.
If you are struggling with how to convert your old event to its new version, maybe it is an entirely new event. That said, what other solutions do we have?
How to manage event evolution outside the aggregate
We can approach the problem by handling event evolution over time while keeping aggregates manageable and avoiding unnecessary complexity. This means managing changes to event structures and versions in a way that keeps the code base clean and maintainable. To achieve this, we can move the problem outside the event by using upcasting, weak schema, content negotiation, or copy-replace.
Upcasting
Upcasting is a technique for handling event versioning in a way that avoids proliferating multiple versions of event handlers. Instead of maintaining multiple versions of an event, you can create a converter (or “upcaster”) that transforms older versions of an event into the most recent version. This transformation typically occurs as the event is read from the event stream, applying any necessary default values or adjustments to match the latest schema.
A possible implementation, again using SalesOrderCreated with the added IsReseller property, could be as follows:
public class EventUpcaster
{
public DomainEvent Upcast(DomainEvent oldEvent)
{
return oldEvent switch
{
SalesOrderCreated v1 => new SalesOrderCreated_V2
{
Id = v1.Id,
SalesOrderNumber = v1.SalesOrderNumber,
OrderDate = v1.OrderDate,
CustomerId = v1.CustomerId,
CustomerName = v1.CustomerName,
Rows = v1.Rows,
IsReseller = false // Default value for new field
},
_ => throw new NotSupportedException($"Unknown event type: {oldEvent.EventType}, version: {oldEvent.Version}")
};
}
}
public class EventProcessor
{
private readonly EventUpcaster _upcaster = new();
public void ProcessEvent(IEvent evt)
{
// Upcast the event to the latest version if necessary
var upcastedEvent = evt.Version < 2 ? _upcaster.Upcast(evt) : evt;
// Handle the latest version of the event
Handle((SalesOrderCreated_V2)upcastedEvent);
}
private void Handle(SalesOrderCreated_V2 evt)
{
Console.WriteLine($"Processing SalesOrderCreated_V2: {evt.Id}");
//process the event...
}
}
// Example usage
class Program
{
static void Main()
{
var oldEvent = new SalesOrderCreated
{
Id = Guid.NewGuid(),
SalesOrderNumber = "2025.12",
OrderDate = DateTime.UtcNow,
CustomerId = Guid.NewGuid(),
CustomerName = "Jane Doe",
Rows = new List<string> { "Item1", "Item2" }
};
var processor = new EventProcessor();
processor.ProcessEvent(oldEvent);
}
}
Upcasters must correctly transform old events to maintain the integrity of the data. It is crucial to rigorously test them as they form a critical part of the event-handling pipeline.
With this approach, you only need one event handler for the latest version of the event, simplifying your event processing logic. However, upcasting introduces some challenges, particularly in distributed or multi-node systems.
If two versions of the application or two separate services are running concurrently, one may not yet be updated to handle the latest event version.
A workaround is to implement a double publish mechanism where all versions of the event are saved in the event store. Each node reads only the versions it can handle. However, this approach introduces potential complexities such as additional storage and maintenance overhead for multiple event versions.
For example, if the latest version of the event has not been written to the event store at the time of reading, the consuming node must wait or reprocess events later. This means that if the latest version of the event is not yet written in the event store while the service tries to read it, it can look ahead in the stream and read the events again. As you can imagine this process can become complex very fast.
Weak schema
In an event-sourced application, weak schema refers to a flexible, loosely defined structure for the event payloads. Instead of enforcing a rigid, strongly typed schema (as is typical in relational databases), a weak schema approach allows for variability in the structure and fields of events over time. In practice, this often means storing data in formats such as JSON, where the exact structure of fields is not fully predefined or tightly validated. Weak schemas are particularly useful because, as events evolve, older versions of events can still be read and processed, even as new fields are introduced or removed. This approach also allows for the easy introduction of new event versions without breaking existing consumers.
Let’s look at this event in JSON format:
{
"id" = 10,
"salesOrderNumber" = "2025.12",
"orderDate" = "2025-01-09",
"customerId" = 12345,
"customerName" = "John Doe",
"rows" = [{row-1}, {row-2}, ..., {row-n}]
"isReseller" = false;
}
The preceding code easily maps to both SalesOrderCreated and SalesOrderCreated_V2 events. The isReseller property is simply ignored during deserialization for version 1 of the event and this does not disrupt existing consumers. This approach would also simplify the code in our aggregate because we do not need more than one Apply method for each event.
As a best practice tip, you should always include a version identifier in the event metadata to distinguish between different schemas. Doing so allows consumers to better handle missing fields gracefully and ignore unexpected ones.
But what are the cons of this kind of implementation? The first and most obvious one is that weak schema delays validation until runtime, increasing the risk of invalid or malformed events being saved in the event store. Secondly, consumers must handle multiple event versions, deal with missing or unknown fields, and implement fallbacks for default values or error-handling mechanisms. Thirdly, without a strongly enforced schema, the structure of events in the system becomes harder to understand leading to confusion, double efforts, and errors when a developer misinterprets the event or adds duplicate fields.
Content negotiation
Content negotiation is a strategy where, instead of managing versioning within the event store, version control is handled at the producer-consumer communication layer. Producers and consumers negotiate both the format and version of events, similar to how HTTP content negotiation works using headers such as Accept and Content-Type . This approach enables dynamic, flexible schema evolution.
The flow of this approach goes through the following sequence:
-
Version metadata : Each event includes metadata that specifies its version (e.g.,
SalesOrderCreated:v1orSalesOrderCreated:v2). - Consumer declaration : Consumers declare which event versions they can process, either at subscription time or during the event processing phase.
- Producer negotiation : Producers adapt the events they emit to match the versions supported by each consumer.
- Middleware transformation : Middleware or an adaptation layer dynamically converts events to a format and version acceptable to the consumer if the exact match isn’t available.
This sequence, in practice, allows older consumers to continue processing events in a version they understand, while newer consumers can take advantage of updated schemas. By requesting explicitly the versions they support, the risk of misinterpretation or failure due to unsupported schemas is reduced.
Producers can evolve event schemas without requiring immediate updates from all consumers. Middleware can handle version transformations on the fly. Middleware can act as a bridge, converting older event versions into newer ones (or vice versa) as needed.
One way to implement this kind of version-aware communication is by using a transport mechanism that supports extensibility and version tagging. Atom feeds offer this capability: they were originally designed for syndicating structured data with built-in support for version metadata, schema links, and content type negotiation. By leveraging these features, Atom feeds can serve as a practical foundation for content negotiation in event-driven architectures.
By adapting the versioning and extensibility features of Atom feeds to an event-sourced architecture, you can support schema evolution more effectively. One added advantage is that, since the list of events is immutable, it can be safely cached across multiple nodes to reduce read latency and improve scalability.
Here is an example Atom feed that illustrates how multiple versions of an event can be published and negotiated using content - type metadata:
<feed xmlns="http://www.w3.org/2005/Atom">
<title>SalesOrder events</title>
<updated>2025-01-09T12:00:00Z</updated>
<entry>
<id>urn:uuid:1234-5678-91011</id>
<title>SalesOrderCreated</title>
<updated>2025-01-09T12:01:00Z</updated>
<content type="application/vnd.brewup.event.salesorder+json;version=1">
{
"id" = 10,
"salesOrderNumber" = "2025.12",
"orderDate" = "2025-01-09",
"customerId" = 12345,
"customerName" = "John Doe",
"rows" = [{row-1}, {row-2}, ..., {row-n}]
}
</content>
<link rel="schema" href="https://schemas.brewup.com/salesorder/v1.json"/>
</entry>
<entry>
<id>urn:uuid:1234-5678-91012</id>
<title>SalesOrderCreated</title>
<updated>2025-01-09T12:05:00Z</updated>
<content type="application/vnd.brewup.event.salesorder+json;version=2">
{
"id" = 10,
"salesOrderNumber" = "2025.12",
"orderDate" = "2025-01-09",
"customerId" = 12345,
"customerName" = "John Doe",
"rows" = [{row-1}, {row-2}, ..., {row-n}]
"isReseller" = false;
}
</content>
<link rel="schema" href="https://schemas.brewup.com/salesorder/v2.json"/>
</entry>
</feed>
To optimize further, consider that, usually, an event does not evolve into a new version frequently. So, asking for a specific version of the event every time could be a waste of calls. The consumer could instead register the content types they support beforehand, and the publisher consequently can directly expose the correct versions and formats for that specific consumer, reducing the requests per message.
Copy-replace
Copy-replace is a versioning strategy where you create a new event stream by selectively copying events from an existing one, often transforming, merging, or omitting events in the process. This approach was defined by Greg Young as the nuclear option of versioning , which, for all intents and purposes, it is, and is typically used when other strategies fall short.
For example, look at Figure 11 .1 .
Figure 11 .1 – An event is omitted, and one has changed
But is copy-replace really the definitive solution? Of course not; there are many aspects, as per the other solutions described, that you must keep in mind if you want to go down this road.
Problems especially arise when you use this solution with a live system. If you need, at some point, to do a full replay and both the events and the streams have new IDs, what will happen to our consumers? A simple solution could be to save the old ID together with the new one. But what if you created a brand-new event? Also, what if the data in the copied events has changed and is not the same anymore?
The answers to these questions could be to simply take down the entire system, perform a copy-replace, and then bring the system back up again. But what if you have 90 gigabytes of events? Are you sure you can take the system offline for 8 or more hours?
A less invasive alternative, if your event store supports it (EventStoreDB does), is that you can use the truncate before property. This function allows you to delete all the events before a specific one in the stream. This approach could be useful if your use case allows it because you do not need to copy events in a new stream but simply move the pointer to the new first event of the stream and the event store will automatically delete the older events.
For example, you can consider a stream of events where you just keep the account balance of a customer, and you do not care about the past years. At the end of the current year, you can create an event that represents a snapshot of the customer’s balance and mark it with the truncate before property.
In conclusion, whichever solution fits your scenario, always ask: What happens if we need to replay the entire event stream from scratch? Assume that, sooner or later, you’ll need to. And when that time comes, you don’t want to find out your assumptions were wrong because, by then, it’s too late.
As noted at the start of this chapter, event versioning is a vast and nuanced topic. What we’ve covered here only scratches the surface, but it should give you a solid foundation for tackling the most common versioning challenges.
Summary
In this chapter, we explored the challenges and strategies for managing the evolution of events in event-sourced systems. Event versioning is an unavoidable aspect of maintaining the integrity and adaptability of modern software architecture. By addressing the immutability of events and the coexistence of old and new formats, you’ve learned how to ensure your system remains flexible and functional over time.
The skills you’ve gained in this chapter include the following:
- Understanding event immutability and its implications on system design and versioning strategies
- Implementing simple event versioning techniques, such as creating versioned event classes
- Utilizing advanced strategies such as upcasting, weak schemas, and content negotiation for event schema evolution
- Exploring copy-replace approaches for managing large-scale event transformations
- Planning for replays and long-term maintainability when designing versioning strategies
While we have covered several foundational techniques, event versioning remains a complex and expansive topic. Remember, the principles discussed here are just the beginning, and deeper exploration may be required depending on your system’s needs.
In the next chapter, we will turn our focus to another critical aspect of distributed systems: managing workflows that span multiple bounded contexts or services. We will explore sagas and process managers, two patterns for orchestrating and coordinating workflows in systems where a single transaction cannot encompass all the necessary steps. By understanding these patterns, you’ll be equipped to handle complex workflows with consistency, resilience, and efficiency.
Get this book’s PDF version and more
Scan the QR code (or go to packtpub.com/unlock ). Search for this book by name, confirm the edition, and then follow the steps on the page.
Note: Keep your invoice handy. Purchases made directly from Packt don’t require an invoice.