<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sam Burrows on Medium]]></title>
        <description><![CDATA[Stories by Sam Burrows on Medium]]></description>
        <link>https://medium.com/@sam.burrows?source=rss-9848122cb14a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Xv3ljexbI4IwusCQg2dxbA.jpeg</url>
            <title>Stories by Sam Burrows on Medium</title>
            <link>https://medium.com/@sam.burrows?source=rss-9848122cb14a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 08:49:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sam.burrows/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Why is Modern Software Complex?]]></title>
            <link>https://medium.com/microservicegeeks/why-is-modern-software-complex-edfbaf4796e5?source=rss-9848122cb14a------2</link>
            <guid isPermaLink="false">https://medium.com/p/edfbaf4796e5</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Sam Burrows]]></dc:creator>
            <pubDate>Tue, 09 Mar 2021 20:00:27 GMT</pubDate>
            <atom:updated>2021-03-09T20:00:27.177Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Xo5BoSroqiW_C33t" /></figure><h4>And who’s to blame</h4><p>Why is most modern software so mindbogglingly complex, with multiple layers of abstraction stacked on each other? Why do they not make simple, efficient software like they used to earlier?</p><p>A few major reasons:</p><h3><strong>1. Code Maintenance</strong></h3><p>There’s an old humor article that has circulated online for many years, titled, “If Architects Had to Work Like Programmers.” It’s written as if it’s a letter from a homebuyer who wants an architect to build a house. Here’s an excerpt:</p><blockquote><em>“Please design and build me a house. I am not sure of what I need, you should use your discretion. My house should have between two and forty-five bedrooms. Just make sure the plans are such that the bedrooms can be easily added or deleted. When you bring the blueprints to me, I will make the final decision of what I want. Also bring me the cost breakdown for each configuration so I can arbitrarily pick one.”</em></blockquote><p>This is humorous because it sounds like the way programmers are given their software requirements. Because software can be modified after it is created, the employer assumes it’s easy to do that, and that they don’t need to be specific about what they want.</p><p>People in the software development field over many years have tried their best to accommodate this, by creating more and more abstractions so that the pieces of software can be altered, combined, upgraded, or swapped out more easily.</p><p>The employer wants this because it enables them to get software on an affordable schedule, <em>without</em> forcing the employer to write detailed specifications that they probably don’t know in advance anyway.</p><p>The programmer wants this because they want to remain employed.</p><h3><strong>2. Code Reusability</strong></h3><p>A good way to increase code quality without increasing the schedule is to write less bespoke code, but instead use more code that has been written and tested well prior to your project. We call these libraries, frameworks, templates, or code generators.</p><p>You’ve probably used Lego toys, where you can build elaborate models using simple reusable bricks or other specialty pieces. You can build practically anything by using enough bricks. There are also some specialized shapes, and lots of guides showing you how to combine them to build the desired models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/0*Ou1DWqjw3hxrjWyf" /><figcaption><em>Image: </em><a href="https://commons.wikimedia.org/wiki/File%3AIMMH_Lego_Queen_Mary_2.jpg"><em>Queen Mary model in Lego</em></a><em>.</em></figcaption></figure><p>It’s a similar concept to code reusability. Software development then becomes an activity of learning all the different pieces and ways to use them together.</p><p>The code is reusable because of abstractions. Like the Lego pieces that use standard dimensions and connecting buttons so they can be fastened to other pieces.</p><h3><strong>3. Features, Features, Features</strong></h3><p>I once developed an app for a manager who was very decision-challenged. Every time I would ask him, “do you want the app to behave this way or that way?” I was often asking about two alternatives that were mutually exclusive. For example, do you want the report to arrange categories of data in rows or in columns?</p><p>He would always answer, “both.” He didn’t know how to choose, and he was afraid of making the wrong choice. So he asked me to implement both alternatives, and make the software configurable. He wanted to keep his options to change his mind later as often as he wanted to.</p><p>This at least doubled the work to implement the code, and doubled the testing needed to assure it works.</p><p>But it was worse — every time he said, “both” this doubled the number of test cases, because I had to assure that a new feature worked with <em>every</em> combination of alternatives for the past features.</p><p>Programmers can’t say “no” when their employers want some features. They can say, “okay, but here’s what it’ll cost in time and money, do you still want it?”</p><p><em>Was this article useful to you? We’d love to hear your feedback! Hit us up on </em><a href="https://twitter.com/microsrvgeeks"><em>Twitter</em></a><em> and tune in to this blog for more great news, insights and resources from the exciting world of microservices.</em></p><p>DISCLAIMER: Microservice Geeks does not employ, contract or otherwise maintain any commercial affiliations with its authors and contributors. The views expressed in this article are those of its author(s) and do not reflect those of Microservice Geeks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=edfbaf4796e5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/microservicegeeks/why-is-modern-software-complex-edfbaf4796e5">Why is Modern Software Complex?</a> was originally published in <a href="https://medium.com/microservicegeeks">Microservice Geeks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Command—Query Responsibility Segregation Pattern]]></title>
            <link>https://medium.com/microservicegeeks/the-command-query-responsibility-segregation-pattern-18e5ff8b2a4a?source=rss-9848122cb14a------2</link>
            <guid isPermaLink="false">https://medium.com/p/18e5ff8b2a4a</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[apache-kafka]]></category>
            <category><![CDATA[event-sourcing]]></category>
            <category><![CDATA[cqrs]]></category>
            <dc:creator><![CDATA[Sam Burrows]]></dc:creator>
            <pubDate>Fri, 05 Mar 2021 04:51:08 GMT</pubDate>
            <atom:updated>2021-03-05T04:51:08.981Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VYwi1Vmm-NmlOwjpgEPkvA.jpeg" /></figure><h4>The essential concepts that every developer should know</h4><p><strong>TL;DR</strong>: The <strong>Command—Query Responsibility Segregation</strong> (CQRS) pattern separates read and update operations for a data store. Implementing CQRS in your application can maximize its performance, scalability, and security. The flexibility created by migrating to CQRS allows a system to better evolve over time and prevents update commands from causing merge conflicts at the domain level.</p><h3>The problem</h3><p>In traditional architectures, the same data model is used to query and update a database. That’s simple and works well for basic CRUD operations. In more complex applications, however, this approach can become unwieldy. For example, on the read side, the application may perform many different queries, returning data transfer objects (DTOs) with different shapes. Object mapping can become complicated. On the write side, the model may implement complex validation and business logic. As a result, you can end up with an overly complex model that does too much.</p><p>Read and write workloads are often asymmetrical, with very different performance and scale requirements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/0*tQa7xSSOLQYy1Bx_.png" /></figure><ul><li>There is often a mismatch between the read and write representations of the data, such as additional columns or properties that must be updated correctly even though they aren’t required as part of an operation.</li><li>Data contention can occur when operations are performed in parallel on the same set of data.</li><li>The traditional approach can have a negative effect on performance due to load on the data store and data access layer, and the complexity of queries required to retrieve information.</li><li>Managing security and permissions can become complex, because each entity is subject to both read and write operations, which might expose data in the wrong context.</li></ul><h3>Solution</h3><p>CQRS separates reads and writes into different models, using commands to update data, and queries to read data.</p><ul><li>Commands should be task based, rather than data centric. (“Book hotel room”, not “set ReservationStatus to Reserved”).</li><li>Commands may be placed on a queue for asynchronous processing, rather than being processed synchronously.</li><li>Queries never modify the database. A query returns a DTO that does not encapsulate any domain knowledge.</li></ul><p>The models can then be isolated, as shown in the following diagram, although that’s not an absolute requirement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/0*WoDSUlDu0Mgn6hsb.png" /></figure><p>Having separate query and update models simplifies the design and implementation. However, one disadvantage is that CQRS code can’t automatically be generated from a database schema using scaffolding mechanisms such as ORM tools.</p><p>For greater isolation, you can physically separate the read data from the write data. In that case, the read database can use its own data schema that is optimized for queries. For example, it can store a materialized view of the data, in order to avoid complex joins or complex O/RM mappings. It might even use a different type of data store. For example, the write database might be relational, while the read database is a document database.</p><p>If separate read and write databases are used, they must be kept in sync. Typically this is accomplished by having the write model publish an event whenever it updates the database. For more information about using events, see <a href="https://medium.com/microservicegeeks/introduction-to-event-driven-architecture-e94ef442d824">event-driven architecture style</a>. Updating the database and publishing the event must occur in a single transaction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/0*78V_5_p5UsaYOBXo.png" /></figure><p>The read store can be a read-only replica of the write store, or the read and write stores can have a different structure altogether. Using multiple read-only replicas can increase query performance, especially in distributed scenarios where read-only replicas are located close to the application instances.</p><p>Separation of the read and write stores also allows each to be scaled appropriately to match the load. For example, read stores typically encounter a much higher load than write stores.</p><p>Some implementations of CQRS use <a href="https://medium.com/microservicegeeks/scalable-event-sourcing-with-event-stores-2d634e17a8a4">Event Sourcing</a>. With this pattern, application state is stored as a sequence of events. Each event represents a set of changes to the data. The current state is constructed by replaying the events. In a CQRS context, one benefit of Event Sourcing is that the same events can be used to notify other components — in particular, to notify the read model. The read model uses the events to create a snapshot of the current state, which is more efficient for queries. However, Event Sourcing adds complexity to the design.</p><p>Benefits of CQRS include:</p><ul><li>Independent scaling. CQRS allows the read and write workloads to scale independently, and may result in fewer lock contentions.</li><li>Optimized data schemas. The read side can use a schema that is optimized for queries, while the write side uses a schema that is optimized for updates.</li><li>Security. It’s easier to ensure that only the right domain entities are performing writes on the data.</li><li>Separation of concerns. Segregating the read and write sides can result in models that are more maintainable and flexible. Most of the complex business logic goes into the write model. The read model can be relatively simple.</li><li>Simpler queries. By storing a materialized view in the read database, the application can avoid complex joins when querying.</li></ul><h3>Implementation issues and considerations</h3><p>Some challenges of implementing this pattern include:</p><ul><li><strong>Complexity</strong>. The basic idea of CQRS is simple. But it can lead to a more complex application design, especially if they include the Event Sourcing pattern.</li><li><strong>Messaging</strong>. Although CQRS does not require messaging, it’s common to use messaging to process commands and publish update events. In that case, the application must handle message failures or duplicate messages.</li><li><strong>Eventual consistency</strong>. If you separate the read and write databases, the read data may be stale. The read model store must be updated to reflect changes to the write model store, and it can be difficult to detect when a user has issued a request based on stale read data.</li></ul><h3>When to use this pattern</h3><p>Consider CQRS for the following scenarios:</p><ul><li>Systems built around the <a href="https://medium.com/microservicegeeks/an-introduction-to-microservices-a3a7e2297ee0">microservices paradigm</a>, where the read load significantly outweighs the write load.</li><li>Collaborative domains where many users access the same data in parallel. CQRS allows you to define commands with enough granularity to minimize merge conflicts at the domain level, and conflicts that do arise can be merged by the command.</li><li>Task-based user interfaces where users are guided through a complex process as a series of steps or with complex domain models. The write model has a full command-processing stack with business logic, input validation, and business validation. The write model may treat a set of associated objects as a single unit for data changes (an aggregate, in DDD terminology) and ensure that these objects are always in a consistent state. The read model has no business logic or validation stack, and just returns a DTO for use in a view model. The read model is eventually consistent with the write model.</li><li>Scenarios where performance of data reads must be fine tuned separately from performance of data writes, especially when the number of reads is much greater than the number of writes. In this scenario, you can scale out the read model, but run the write model on just a few instances. A small number of write model instances also helps to minimize the occurrence of merge conflicts.</li><li>Scenarios where one team of developers can focus on the complex domain model that is part of the write model, and another team can focus on the read model and the user interfaces.</li><li>Scenarios where the system is expected to evolve over time and might contain multiple versions of the model, or where business rules change regularly.</li><li>Integration with other systems, especially in combination with event sourcing, where the temporal failure of one subsystem shouldn’t affect the availability of the others.</li></ul><p>This pattern isn’t recommended when:</p><ul><li>The domain or the business rules are simple.</li><li>A simple CRUD-style user interface and data access operations are sufficient.</li></ul><p>Consider applying CQRS to limited sections of your system where it will be most valuable.</p><h3>Event Sourcing and CQRS</h3><p>The CQRS pattern is often used along with the Event Sourcing pattern. CQRS-based systems use separate read and write data models, each tailored to relevant tasks and often located in physically separate stores. When used with <a href="https://medium.com/microservicegeeks/scalable-event-sourcing-with-event-stores-2d634e17a8a4">Event Sourcing</a>, the store of events is the write model, and is the official source of information. The read model of a CQRS-based system provides materialized views of the data, typically as highly denormalized views. These views are tailored to the interfaces and display requirements of the application, which helps to maximize both display and query performance.</p><p>Using the stream of events as the write store, rather than the actual data at a point in time, avoids update conflicts on a single aggregate and maximizes performance and scalability. The events can be used to asynchronously generate materialized views of the data that are used to populate the read store.</p><p>Because the event store is the official source of information, it is possible to delete the materialized views and replay all past events to create a new representation of the current state when the system evolves, or when the read model must change. The materialized views are in effect a durable read-only cache of the data.</p><p>When using CQRS combined with the Event Sourcing pattern, consider the following:</p><ul><li>As with any system where the write and read stores are separate, systems based on this pattern are only eventually consistent. There will be some delay between the event being generated and the data store being updated.</li><li>The pattern adds complexity because code must be created to initiate and handle events, and assemble or update the appropriate views or objects required by queries or a read model. The complexity of the CQRS pattern when used with the Event Sourcing pattern can make a successful implementation more difficult, and requires a different approach to designing systems. However, event sourcing can make it easier to model the domain, and makes it easier to rebuild views or create new ones because the intent of the changes in the data is preserved.</li><li>Generating materialized views for use in the read model or projections of the data by replaying and handling the events for specific entities or collections of entities can require significant processing time and resource usage. This is especially true if it requires summation or analysis of values over long periods, because all the associated events might need to be examined. Resolve this by implementing snapshots of the data at scheduled intervals, such as a total count of the number of a specific action that have occurred, or the current state of an entity.</li></ul><h3>Example</h3><p>The following code shows some extracts from an example of a CQRS implementation that uses different definitions for the read and the write models. The model interfaces don’t dictate any features of the underlying data stores, and they can evolve and be fine-tuned independently because these interfaces are separated.</p><p>The following code shows the read model definition.</p><pre>// Query interface<br>namespace ReadModel<br>{<br>  public interface ProductsDao<br>  {<br>    ProductDisplay FindById(int productId);<br>    ICollection&lt;ProductDisplay&gt; FindByName(string name);<br>    ICollection&lt;ProductInventory&gt; FindOutOfStockProducts();<br>    ICollection&lt;ProductDisplay&gt; FindRelatedProducts(int productId);<br>  }</pre><pre>  public class ProductDisplay<br>  {<br>    public int Id { get; set; }<br>    public string Name { get; set; }<br>    public string Description { get; set; }<br>    public decimal UnitPrice { get; set; }<br>    public bool IsOutOfStock { get; set; }<br>    public double UserRating { get; set; }<br>  }</pre><pre>  public class ProductInventory<br>  {<br>    public int Id { get; set; }<br>    public string Name { get; set; }<br>    public int CurrentStock { get; set; }<br>  }<br>}</pre><p>The system allows users to rate products. The application code does this using the RateProduct command shown in the following code.</p><pre>public interface ICommand<br>{<br>  Guid Id { get; }<br>}</pre><pre>public class RateProduct : ICommand<br>{<br>  public RateProduct()<br>  {<br>    this.Id = Guid.NewGuid();<br>  }<br>  public Guid Id { get; set; }<br>  public int ProductId { get; set; }<br>  public int Rating { get; set; }<br>  public int UserId {get; set; }<br>}</pre><p>The system uses the ProductsCommandHandler class to handle commands sent by the application. Clients typically send commands to the domain through a messaging system such as a queue. The command handler accepts these commands and invokes methods of the domain interface. The granularity of each command is designed to reduce the chance of conflicting requests. The following code shows an outline of the ProductsCommandHandler class.</p><pre>public class ProductsCommandHandler :<br>    ICommandHandler&lt;AddNewProduct&gt;,<br>    ICommandHandler&lt;RateProduct&gt;,<br>    ICommandHandler&lt;AddToInventory&gt;,<br>    ICommandHandler&lt;ConfirmItemShipped&gt;,<br>    ICommandHandler&lt;UpdateStockFromInventoryRecount&gt;<br>{<br>  private readonly IRepository&lt;Product&gt; repository;</pre><pre>  public ProductsCommandHandler (IRepository&lt;Product&gt; repository)<br>  {<br>    this.repository = repository;<br>  }</pre><pre>  void Handle (AddNewProduct command)<br>  {<br>    ...<br>  }</pre><pre>  void Handle (RateProduct command)<br>  {<br>    var product = repository.Find(command.ProductId);<br>    if (product != null)<br>    {<br>      product.RateProduct(command.UserId, command.Rating);<br>      repository.Save(product);<br>    }<br>  }</pre><pre>  void Handle (AddToInventory command)<br>  {<br>    ...<br>  }</pre><pre>  void Handle (ConfirmItemsShipped command)<br>  {<br>    ...<br>  }</pre><pre>  void Handle (UpdateStockFromInventoryRecount command)<br>  {<br>    ...<br>  }<br>}</pre><h3>Related patterns and guidance</h3><p>The following patterns and guidance are useful when implementing this pattern:</p><ul><li><a href="https://medium.com/microservicegeeks/an-introduction-to-microservices-a3a7e2297ee0">Microservices Architecture</a>. Explains how complex applications may be partitioned into fine-grained, autonomous services.</li><li><a href="https://medium.com/microservicegeeks/introduction-to-event-driven-architecture-e94ef442d824">Event-Driven Architecture</a>. Introduces the notion of events and illustrates how it may be used to effectively reduce coupling in a microservices architecture.</li><li>An alternative post on <a href="https://medium.com/microservicegeeks/introduction-to-cqrs-64f609544f4a">CQRS by Amanda Bennett</a>, which explains the basics of the pattern and links to other useful resources.</li></ul><p><em>Was this article useful to you? We’d love to hear your feedback! Hit us up on </em><a href="https://twitter.com/microsrvgeeks"><em>Twitter</em></a><em> and tune in to this blog for more great news, insights and resources from the exciting world of microservices.</em></p><p>DISCLAIMER: Microservice Geeks does not employ, contract or otherwise maintain any commercial affiliations with its authors and contributors. The views expressed in this article are those of its author(s) and do not reflect those of Microservice Geeks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18e5ff8b2a4a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/microservicegeeks/the-command-query-responsibility-segregation-pattern-18e5ff8b2a4a">The Command—Query Responsibility Segregation Pattern</a> was originally published in <a href="https://medium.com/microservicegeeks">Microservice Geeks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scalable Event Sourcing with Event Stores]]></title>
            <link>https://medium.com/microservicegeeks/scalable-event-sourcing-with-event-stores-2d634e17a8a4?source=rss-9848122cb14a------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d634e17a8a4</guid>
            <category><![CDATA[software-patterns]]></category>
            <category><![CDATA[event-streaming]]></category>
            <category><![CDATA[event-sourcing]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[apache-kafka]]></category>
            <dc:creator><![CDATA[Sam Burrows]]></dc:creator>
            <pubDate>Wed, 03 Mar 2021 20:07:07 GMT</pubDate>
            <atom:updated>2021-03-03T20:07:07.420Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*U2P_wrr78CU9wGmu" /></figure><h4>The essential concepts that every developer should know</h4><p>An <em>event</em> is a collection of data that describes a <em>change in state</em>, e.g. an order has been placed. An event store is just a database that stores events. This is a pretty simple idea with some very powerful implications.</p><p>Events can be used to facilitate loosely-coupled communication between services. Instead of communicating with each other directly, services can publish <a href="https://www.ben-morris.com/data-design-for-event-driven-architecture-autonomy-encapsulation-and-ordering/">events</a> when something significant happens and subscribe to events created elsewhere. This kind of <a href="https://medium.com/microservicegeeks/introduction-to-event-driven-architecture-e94ef442d824"><em>event-driven architecture</em></a> can create a rich fabric of events that can be used to build a picture of what’s happening around the system.</p><p><em>Event sourcing</em> is the process of determining the state of something by playing a set of events through some iterative logic. For example, for you might receive one event when an order is placed, another when payment has cleared and a third when the goods have been shipped. Taken together, these events can be used to hydrate the status of the order.</p><p>This approach has a number of advantages. First and foremost it can provide a reliable <em>audit trail</em> of state. Events are <em>immutable</em> in that once they have been added to the event store they are never changed. If any data needs to be corrected then a further event should be issued. This means that you can retrieve the state of data as it was understood at any point in the past.</p><p>Event sourcing can also scale very well but this does depend on a number of design decisions on the event store.</p><h3>Data design for commits</h3><p>There are a number of specific event store implementations available but you are not duty bound to use any of them. There is no reason why you can’t implement your own data store using your data persistence technology of choice.</p><p>Note that an event store should model generic <em>commits</em> here rather than specific event data. Given that events are immutable you only ever need to insert data, which can serve to eliminate any locking caused by data contention at scale.</p><p>At its most basic an event store only needs to store three pieces of information:</p><ul><li>The type of event or aggregate</li><li>The sequence number of the event</li><li>The data as a serialized blob</li></ul><p>More data can be added to help with diagnosis and audit, but the core functionality only requires a narrow set of fields. This should give rise to a very simple data design that can be heavily optimised for appending and retrieving sequences of records.</p><h3>Retrieving streams of events</h3><p>One thing developers find difficult to grasp about event sourcing is that you don’t directly query the data in each event. Queries are run by retrieving a stream of events from the store and pushing them through some iterative logic. In this sense there is a complete separation between event persistence and the logic used to process data.</p><p>Many event store designs seek to include some form of metadata about the event to help filter output. Given that an event store should try and provide the fastest possible retrieval there is a performance trade off involved in deciding how much metadata to store separately from the event itself. It can be easy for domain-specific data to start creeping into your event store design which can start to dilute the notion of providing fast, data agnostic event storage.</p><p>One approach to metadata is to group events together into <em>streams</em> where a set of similar or related events can be returned in a single query. In practical terms streams can be identified by a single text field that encapsulates any relevant metadata. This is the approach taken by Greg Young’s <a href="https://geteventstore.com/">Event Store</a> where a large implementation can involve thousands or even millions of different streams.</p><h3>Optimise with snapshots</h3><p>Retrieving large event streams can be pretty inefficient. As data accumulates in an event store you will find that you are pulling back growing streams of events every time you need to query the state of something.</p><p>“Snapshots” are an optimisation that limits the amount of data you need to retrieve from the database. A snapshot stores the aggregated state of an entity at a particular point in time. Any query only has to include the most recent snapshot along with any new events that have been added since the snapshot was created.</p><p>Snapshots can be stored and treated in the same way as any other event, though some designs use a separate database table for them as a further optimisation.</p><p>The most efficient way of creating snapshots is to use a background process that monitors event input and creates new snapshots automatically as required. Optimising this kind of process can add a fair amount of complexity to an implementation. A simpler though much less optimal approach is to create snapshots as a by-product of each query so they are available the next time a request accesses the stream.</p><h3>Caching is your friend</h3><p>Event sourcing should be pretty fast as most of the work happens in memory. The round-trip involved in fetching events from the underlying database is always the single most expensive part of any operation.</p><p>You can reduce the number of round-trips through careful planning of streams and snapshots. Further gains can be made by caching smaller, more commonly requested streams or snapshots. This caching can happen in memory or in a fast memory-resident database such as <a href="http://redis.io/">Redis</a> and can have a real impact on more predictable workloads.</p><h3>Don’t be afraid to couple to a database technology</h3><p>If you want to optimise performance then it is difficult to meaningfully abstract an event store from the underlying data persistence technology. For example, <a href="https://github.com/NEventStore">nEventStore</a> supports more than twenty different databases, it does this by focusing on abstraction at the cost of performance optimisation.</p><p>Maximising the performance of an event store inevitably involves getting your hands dirty with the underlying persistence technology. For example, in a relational database then you will need to tune your indexes to create the right balance between retrieval and update speed. Most platforms provide built-in caching features that could be used to target certain types of query. You should also be able to partition very large data sets so performance can be maintained at scale.</p><p>The more you leverage the features of a particular data persistence technology the more your implementation will become dependent on it. This isn’t something to be afraid of as it is the price of good performance at scale.</p><h3>Choosing serialization carefully</h3><p>Given that events are stored as serialized blobs your choice of serializer can have a real <a href="http://maxondev.com/serialization-performance-comparison-c-net-formats-frameworks-xmldatacontractserializer-xmlserializer-binaryformatter-json-newtonsoft-servicestack-text/">impact on performance</a>. Google’s <a href="https://developers.google.com/protocol-buffers/">Protocol Buffers</a> lends itself well to event storage as they are very fast, version tolerant, yield very small payloads and can support immutable data objects.</p><p>The one drawback of Protocol Buffers is that the payloads cannot be read directly. If legibility of stored data is important then JSON-based compromise might be more acceptable.</p><h3>Optimised inserts and batching</h3><p>Fast inserts are just as important as fast reads. Your event store will be processing incoming events which will be susceptible to demand spikes. You need to ensure that an event store can keep up with the rate at which events are being published so that queries remain current.</p><p>Any persistence should be taken care of by a single round-trip to the server. You should also provide an optimised means of batching up inserts so they clients can push sets of events up in a single round trip.</p><h3>Understand when to use event sourcing… and when not to</h3><p>Event stores cannot necessarily be used to persist data across an entire domain. Event sourcing only adds value to a relatively narrow set of use cases where being able to provide an audit trail really matters. If this kind of historical record of state is not important then it’s unlikely to be worth the overhead in terms of increased complexity.</p><p><em>Was this article useful to you? We’d love to hear your feedback! Hit us up on </em><a href="https://twitter.com/microsrvgeeks"><em>Twitter</em></a><em> and tune in to this blog for more great news, insights and resources from the exciting world of microservices.</em></p><p>DISCLAIMER: Microservice Geeks does not employ, contract or otherwise maintain any commercial affiliations with its authors and contributors. The views expressed in this article are those of its author(s) and do not reflect those of Microservice Geeks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d634e17a8a4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/microservicegeeks/scalable-event-sourcing-with-event-stores-2d634e17a8a4">Scalable Event Sourcing with Event Stores</a> was originally published in <a href="https://medium.com/microservicegeeks">Microservice Geeks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>