<?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" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Event Sourcing - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Event Sourcing - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Wed, 24 Jun 2026 10:06:32 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/event-sourcing/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Make Event Sourcing in Java Easier ]]>
                </title>
                <description>
                    <![CDATA[ By Bertil Muth Event sourcing is about persisting events instead of just the current state. Event sourcing can be helpful for auditing purposes, and to analyze or rebuild previous system states for business analysis. Let's look at it in a bit more de... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-make-event-sourcing-in-java-easier/</link>
                <guid isPermaLink="false">66d45ddd51f567b42d9f8445</guid>
                
                    <category>
                        <![CDATA[ Event Sourcing ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Fri, 21 Jan 2022 16:23:36 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/01/thisisengineering-raeng-64YrPKiguAE-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Bertil Muth</p>
<p>Event sourcing is about persisting events instead of just the current state. Event sourcing can be helpful for auditing purposes, and to analyze or rebuild previous system states for business analysis.</p>
<p>Let's look at it in a bit more detail: every time you make a change to the application state, you record the change as an event.</p>
<p>You can replay the events since the beginning of the recording, up to a certain time. Then you've recreated the state of the application at that time. And by merging the events into a different data structure, you can provide a user specific view of the state (a "query model").</p>
<p>Think of a shopping cart: a typical e-commerce application would only store the state of the cart when the user proceeds to checkout. What if you want to know which shopping cart items have been removed by the user, to optimize the purchasing flow? That's when storing each event becomes helpful, for example <code>ShoppingCartItemRemoved</code>.</p>
<h2 id="heading-event-sourcing-hello-world-example">Event Sourcing Hello World Example</h2>
<p>In this example, a user sends a POST HTTP request with the data of a <code>CreateGreeting</code> command to the backend. This command contains the name of the person to greet. </p>
<p>The backend transforms the command into a <code>GreetingCreated</code> event. This event contains the person's name from the command, and a default salutation (<code>Hello,</code>):</p>
<p><img src="https://res.cloudinary.com/practicaldev/image/fetch/s--4PlWs_1a--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nwjsupcxesbrk288j279.PNG" alt="Image description" width="600" height="400" loading="lazy"></p>
<p>The event also contains the id of the entity you see in the middle: the <code>Greeting</code> entity that consumes the commands, and produces the events. That way, the state of this entity can later be reconstructed.</p>
<p>By producing the event, the <code>Greeting</code> entity has accepted the command as valid, and the event records this as a fact. The event is now stored in a journal, for example an in-memory, relational, or NoSQL database.</p>
<p>So far, the state of the <code>Greeting</code> entity hasn't changed yet. To change the state, <code>Greeting</code> takes the event and current state as input, and produces a new instance of the state class:</p>
<p><img src="https://res.cloudinary.com/practicaldev/image/fetch/s--gRyVptBX--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uiy6jr5ipknxjpz5vqy6.png" alt="Image description" width="600" height="400" loading="lazy"></p>
<p>Objects of <code>GreetingState</code> are immutable. <code>Greeting</code> replaces the old state with the new state after applying the event.</p>
<p>What if you want to change the salutation for Jill's greeting later on? This can be done with a <code>ChangeSalutation</code> command. If you encode the id of Jill's <code>Greeting</code> entity in the request URL, the command handling looks like this:</p>
<p><img src="https://res.cloudinary.com/practicaldev/image/fetch/s--PB5bLgHr--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a5sc976cdgdy3ff8cing.PNG" alt="Image description" width="600" height="400" loading="lazy"></p>
<p>Note that the event captures only the information that is relevant for the change about to happen. It doesn't need to capture all information in <code>GreetingState</code>.</p>
<p>Applying the <code>SalutationChanged</code> event looks like this:</p>
<p><img src="https://res.cloudinary.com/practicaldev/image/fetch/s--4yzt35Bt--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9ujrmctd31vcdlebtejz.PNG" alt="Image description" width="600" height="400" loading="lazy"></p>
<p>The interesting thing is this: <code>Greeting</code> takes the salutation from the event, and combines it with the <code>personName</code> from its current state, to produce the new state.</p>
<h2 id="heading-implementing-event-sourcing-is-hard">Implementing Event Sourcing is Hard</h2>
<p>The problem I've seen in this. When building an event-sourced application, there is a steep learning curve. Not only do you need to get adjusted to this new way of thinking about state – you also need to learn the event sourcing library/framework details.</p>
<p>I want to change that. I created the Being library. It aims to cut down the technical complexity as far as possible. You can find it on <a target="_blank" href="https://github.com/bertilmuth/being">GitHub</a>. It's in an early stage of development, so I'm very thankful for any feedback you might have.</p>
<h2 id="heading-command-and-event-handling-code">Command and event handling code</h2>
<p>When you use Being, you need to define the command handlers: which types of commands the entity consumes, and which event(s) it produces as a reaction to each command.</p>
<p>You also need to define the event handlers: for each of the event types, which new entity state to create as a reaction to it.</p>
<p>The behavior of the <code>Greeting</code> entity shown below has the following <a target="_blank" href="https://github.com/bertilmuth/being-samples/blob/main/greetings/src/main/java/org/requirementsascode/being/samples/greeting/model/Greeting.java">code</a>:</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Greeting</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">AggregateBehavior</span>&lt;<span class="hljs-title">GreetingCommand</span>, <span class="hljs-title">GreetingState</span>&gt; </span>{
    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> GreetingState <span class="hljs-title">initialState</span><span class="hljs-params">(<span class="hljs-keyword">final</span> String id)</span> </span>{
        <span class="hljs-keyword">return</span> GreetingState.identifiedBy(id);
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> CommandHandlers&lt;GreetingCommand, GreetingState&gt; <span class="hljs-title">commandHandlers</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> CommandHandlers.handle(
            commandsOf(CreateGreeting.class).with((cmd, state) -&gt; <span class="hljs-keyword">new</span> GreetingCreated(state.id, <span class="hljs-string">"Hello,"</span>, cmd.personName)),
            commandsOf(ChangeSalutation.class).with((cmd, state) -&gt; <span class="hljs-keyword">new</span> SalutationChanged(state.id, cmd.salutation)));
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> EventHandlers&lt;GreetingState&gt; <span class="hljs-title">eventHandlers</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> EventHandlers.handle(
            eventsOf(GreetingCreated.class)
                .with((event, state) -&gt; <span class="hljs-keyword">new</span> GreetingState(event.id, event.salutation, event.personName)),
            eventsOf(SalutationChanged.class)
                .with((event, state) -&gt; <span class="hljs-keyword">new</span> GreetingState(event.id, event.salutation, state.personName)));
    }
}
</code></pre>
<p>Apart from the <code>initialState()</code> method that defines the starting state of <code>Greeting</code>, this should look pretty familiar.</p>
<p>The first command handler consumes a <code>CreateGreeting</code> command that contains the name of the person to greet, and produces a <code>GreetingCreated</code> event.</p>
<p>But a user can also change the salutation via a <code>ChangeSalutation</code> command. This command contains only the new text for the salutation, not the person's name. The person is identified by the entity's id, <code>state.id</code>.</p>
<p>Both the command handlers and the event handlers can use the current state of the entity. So when a <code>SalutationChanged</code> event is applied, the person name is not taken from the event, but from the current state of the entity: <code>(event,state) -&gt; new GreetingState(event.id, event.salutation, state.personName)</code>.</p>
<h2 id="heading-code-for-the-greeting-entitys-state">Code for the Greeting entity's state</h2>
<p>Here's the code for the <code>GreetingState</code> class that represents the state of the entity:</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">GreetingState</span> </span>{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> String id;
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> String salutation;
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> String personName;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> GreetingState <span class="hljs-title">identifiedBy</span><span class="hljs-params">(<span class="hljs-keyword">final</span> String id)</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> GreetingState(id, <span class="hljs-string">""</span>, <span class="hljs-string">""</span>);
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">GreetingState</span><span class="hljs-params">(<span class="hljs-keyword">final</span> String id, <span class="hljs-keyword">final</span> String salutation, <span class="hljs-keyword">final</span> String personName)</span> </span>{
        <span class="hljs-keyword">this</span>.id = id;
        <span class="hljs-keyword">this</span>.salutation = salutation;
        <span class="hljs-keyword">this</span>.personName = personName;
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">toString</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-string">"GreetingState [id="</span> + id + <span class="hljs-string">", salutation="</span> + salutation + <span class="hljs-string">", personName="</span> + personName + <span class="hljs-string">"]"</span>;
    }

    <span class="hljs-comment">// hashCode() and equals() omitted for brevity</span>
}
</code></pre>
<p>As you can see, objects of the state class are immutable.</p>
<h2 id="heading-code-for-commands-and-events">Code for commands and events</h2>
<p>Commands are simple POJOs, as you can see in the following example:</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CreateGreeting</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">GreetingCommand</span></span>{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> String personName;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">CreateGreeting</span><span class="hljs-params">(String personName)</span> </span>{
        <span class="hljs-keyword">this</span>.personName = personName;
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">toString</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-string">"CreateGreeting [personName="</span> + personName + <span class="hljs-string">"]"</span>;
    }
}
</code></pre>
<p>Commands of an entity implement a common interface, like <code>GreetingCommand</code> in the example, which may be empty:</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">GreetingCommand</span> </span>{
}
</code></pre>
<p>The reason for having a common interface for the commands is type safety. Use this command interface as the first type parameter of the entity class, as shown above.</p>
<p>Each event class must be a subclass of <code>IdentifiedDomainEvent</code>:</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">GreetingCreated</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">IdentifiedDomainEvent</span> </span>{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> String id;
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> String salutation;
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> String personName;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">GreetingCreated</span><span class="hljs-params">(<span class="hljs-keyword">final</span> String id, <span class="hljs-keyword">final</span> String salutation, String personName)</span> </span>{
        <span class="hljs-keyword">super</span>(SemanticVersion.from(<span class="hljs-string">"1.0.0"</span>).toValue());
        <span class="hljs-keyword">this</span>.id = id;
        <span class="hljs-keyword">this</span>.salutation = salutation;
        <span class="hljs-keyword">this</span>.personName = personName;
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">identity</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> id;
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">toString</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-string">"GreetingCreated [id="</span> + id + <span class="hljs-string">", salutation="</span> + salutation + <span class="hljs-string">", personName="</span> + personName + <span class="hljs-string">"]"</span>;
    }
}
</code></pre>
<p>Being is based on the powerful <a target="_blank" href="https://docs.vlingo.io/">VLINGO XOOM</a> platform that defines the <code>IdentifiedDomainEvent</code> super class.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Apart from what I've shown above, you also need to define the HTTP request handlers. The <a target="_blank" href="https://github.com/bertilmuth/being">Being</a> website explains how to do that.</p>
<p>I want to invite you to have a look at it, if you find this topic interesting. And I'm very grateful for feedback.</p>
<p>To drop me a note, visit the <a target="_blank" href="https://gitter.im/requirementsascode/community">Gitter community</a> or contact <a target="_blank" href="https://twitter.com/BertilMuth">me</a> on Twitter.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Kissing the state machine goodbye ]]>
                </title>
                <description>
                    <![CDATA[ By Bertil Muth Recently, I have written about simplifying an event sourced application. The article starts with code from a talk by Jakub Pilimon and Kenny Bastani. And it ends with building a model  for events in the code: how they are applied, and ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/kissing-the-state-machine-goodbye/</link>
                <guid isPermaLink="false">66d45de04a7504b7409c334b</guid>
                
                    <category>
                        <![CDATA[ coding ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Event Sourcing ]]>
                    </category>
                
                    <category>
                        <![CDATA[ finite state machine ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Statecharts ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Thu, 27 Jun 2019 21:05:06 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2019/06/Kissing.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Bertil Muth</p>
<p>Recently, I have written about <a target="_blank" href="https://www.freecodecamp.org/news/simplifying-an-event-sourced-application/">simplifying an event sourced application</a>.</p>
<p>The article starts with <a target="_blank" href="https://gitlab.com/pilloPl/eventsourced-credit-cards/blob/4329a0aac283067f1376b3802e13f5a561f18753/src/main/java/io/pillopl/eventsourcing/">code</a> from a <a target="_blank" href="https://youtu.be/r7AGQsM7ncA">talk</a> by Jakub Pilimon and Kenny Bastani. And it ends with building a model  for events in the code: how they are applied, and under which  conditions.</p>
<p>The sample application is about Credit Card management. You can:</p>
<ul>
<li><strong>Assign a credit limit</strong>. But only once, otherwise the application throws an <code>IllegalStateException</code>.</li>
<li><strong>Withdraw money</strong>. But you can't make more than 45 withdrawals in a certain cycle. Or you'll get an exception as well.</li>
<li><strong>Repay money</strong></li>
</ul>
<p>I played around with the <code>CreditCard</code> class. I had a feeling that something might be wrong with the <code>withdraw</code> method. So I wrote a test that checks for the correct behavior.</p>
<pre><code class="lang-java"><span class="hljs-meta">@Test(expected = IllegalStateException.class)</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">withdrawWithoutLimitAssignedThrowsIllegalStateException</span><span class="hljs-params">()</span> </span>{
    CreditCard card = <span class="hljs-keyword">new</span> CreditCard(UUID.randomUUID());
    card.withdraw(BigDecimal.ZERO);
}
</code></pre>
<p>The test attempts to withdraw an amount of zero. But no credit limit  has been assigned before. The application should reject this, and throw  an <code>IllegalStateException</code>.<br>Instead, the application threw a <code>NullPointerException</code>.</p>
<p>The application assumed that the limit had been assigned before.<br>Now: this is a sample application. If it covered all cases it probably wouldn't be as understandable as it is.</p>
<p>Let's pretend we're dealing with a real world application. What if  the required order of commands/events depends on a multitude of  conditions and states?</p>
<p>If you have ever tried to implement this with conditional statements  only, you probably know it's easy to lose the overview. But there is a  standard solution for managing complicated flows and changes in  behavior.</p>
<h2 id="heading-state-machine-to-the-rescue">State machine to the rescue</h2>
<p>In computer science, state machines have been around for decades.  They are well understood in theory. They are battle proven in practice.  They are the de facto standard for dealing with state dependent  behavior.</p>
<p>So I decided to create a UML state machine model for the sample  application. I asked myself first: Do I want to deal with commands or  events in the state machine?</p>
<p>Commands are about something the application should do in the future.<br>Events are about something that has happened in the past.</p>
<p>I wanted to <em>prevent</em> withdrawals without a credit limit assigned.<br>So the state machine model needed to deal with commands. </p>
<p>The syntax of a transition in the diagram is <code>command[condition] / commandHandler()</code>. It means: when a command object has been received, and the condition is  fulfilled if present, handle the command and go to the next state.</p>
<p><img src="https://res.cloudinary.com/practicaldev/image/fetch/s--IsFVxafc--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/3laq9tz8h82nwvjsmugv.png" alt="State machine" width="600" height="400" loading="lazy"></p>
<p>The model fixes what is allowed to happen, and what not. For example: repaying is only possible after withdrawing.</p>
<p>But that precision has a price. If you want the state machine model  to be executed and to control the behavior at runtime, you need to model  every possible transition from every state. Including its condition, if  there are two transitions with the same event.</p>
<p>That's why there is a lot more repetition in the state machine than in the original code with the <code>if</code> statements. A way to reduce the amount of repetition is to use <em>super states</em> and <em>sub states</em>:</p>
<p><img src="https://res.cloudinary.com/practicaldev/image/fetch/s--CCZSYf5s--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/2cwl67ddaa64l2szlp4s.png" alt="State machine with sub states" width="600" height="400" loading="lazy"></p>
<p>It is easy to define state dependent behavior in a state machine model. But a state independent rule like <em>in any state (when condition X holds), do Y</em> leads to several transitions. For example, I needed to add <code>requestToCloseCycle</code> to every super state.</p>
<p>You need people with the right skills to create the models. And it's  not easy to communicate about the models with non-technical  stakeholders. It's not the way they normally speak about user journeys.</p>
<h2 id="heading-saying-goodbye">Saying goodbye</h2>
<p>It seems there are two options so far.</p>
<p>In the left corner: the <code>if</code> statement. Easy to start  with. Low overhead. Best fit for applications that have no complicated  flows of behavior. But it's easy to lose the overview when the behavior  gets complicated.</p>
<p>In the right corner: the executable state machine model. Powerful.  Proven. Precise. Gives you an overview of the behavior. But it's hard to  define state independent rules. And state machine models are difficult  to communicate about with non-technical stakeholders.</p>
<p>I stand in the third corner. I have found an alternative to state machines.<br>A solution that</p>
<ul>
<li>enables you to define conditions. But you don't have to in most cases.</li>
<li>makes state dependent and independent rules equally easy to specify.</li>
<li>uses language that all stakeholders can relate to.</li>
</ul>
<p>Before I dig into the details, here's the sample state machine model rewritten using that solution:</p>
<pre><code class="lang-java">Model model = Model.builder()
  .useCase(useCreditCard)
    .basicFlow()
        .step(assigningLimit).user(requestsToAssignLimit).systemPublish(assignedLimit)
        .step(withdrawingCard).user(requestsWithdrawingCard).systemPublish(withdrawnCard).reactWhile(accountIsOpen)
        .step(repaying).user(requestsRepay).systemPublish(repay).reactWhile(accountIsOpen)

    .flow(<span class="hljs-string">"Withdraw again"</span>).after(repaying)
        .step(withdrawingCardAgain).user(requestsWithdrawingCard).systemPublish(withdrawnCard)
        .step(repeating).continuesAt(withdrawingCard)

    .flow(<span class="hljs-string">"Cycle is over"</span>).anytime()
        .step(closingCycle).on(requestToCloseCycle).systemPublish(closedCycle)

    .flow(<span class="hljs-string">"Limit can only be assigned once"</span>).condition(limitAlreadyAssigned)
        .step(assigningLimitTwice).user(requestsToAssignLimit).system(throwsAssignLimitException)

    .flow(<span class="hljs-string">"Too many withdrawals"</span>).condition(tooManyWithdrawalsInCycle) 
        .step(withdrawingCardTooOften).user(requestsWithdrawingCard).system(throwsTooManyWithdrawalsException)
.build();
<span class="hljs-keyword">return</span> model;
</code></pre>
<p>As you can see, the model is <a target="_blank" href="https://github.com/bertilmuth/requirementsascode/blob/master/requirementsascodeexamples/creditcard_eventsourcing/src/main/java/creditcard_eventsourcing/model/CreditCardAggregateRoot.java">in the code</a>.  A model runner executes this model. The runner reacts to commands/events, similar to a state machine.</p>
<p>The basic flow is the "happy day scenario". The steps of a user to  reach her goal. The other flows cover alternative and error scenarios.</p>
<p>A flow can define an <em>explicit condition</em> for its first step to run - e.g. <code>after(...)</code>, <code>anytime()</code> or <code>condition()</code> in the sample.<br>If a flow has an explicit condition, the flow starts when the condition  is fulfilled and the runner is currently in a different flow.<br>If a flow has no explicit condition (e.g. the basic flow in the sample),  the first step runs after the runner has started, when no step has been  run so far.</p>
<p>Starting with the second step of a flow, each step has an <em>implicit condition</em>.  That condition is: run the step after the previous step in the same  flow, unless a different flow with an explicit condition can start.<br>So in contrast to state machines, you don't need to specify the conditions after the first step.</p>
<p>Internally, state depending behavior is realized by checking a condition.<br>Every step contains its complete condition that defines exactly when the step can run. That's how <a target="_blank" href="https://github.com/bertilmuth/requirementsascode">requirements as code</a> can treat state dependent and independent behavior alike.</p>
<p>Have a look at <a target="_blank" href="https://github.com/bertilmuth/requirementsascode/tree/master/requirementsascodeexamples/helloworld">further examples</a> to dig deeper.</p>
<h2 id="heading-when-to-use-requirements-as-code">When to use requirements as code</h2>
<p>Many applications have dynamic internal behavior. This is true for  distributed applications in particular. They need to deal with the fact  that "the other party" is not available.</p>
<p>But from a user's perspective, these applications look quite  predictable and regular. When I want to watch a show on Netflix or  Amazon Prime, I follow the exact same steps each time until I can watch  it. It looks like one step just follows the other.</p>
<p>That's the sweet spot for requirements as code, if used as an alternative to a state machine: defining the <em>visible behavior</em> of an application.</p>
<h2 id="heading-how-the-credit-card-application-works-now">How the Credit Card application works now</h2>
<ul>
<li>A <a target="_blank" href="https://github.com/bertilmuth/requirementsascode/blob/master/requirementsascodeexamples/creditcard_eventsourcing/src/main/java/creditcard_eventsourcing/EventsourcingApplication.java">client</a> sends a command to the <code>CreditCardAggregateRoot</code></li>
<li>The <a target="_blank" href="https://github.com/bertilmuth/requirementsascode/blob/master/requirementsascodeexamples/creditcard_eventsourcing/src/main/java/creditcard_eventsourcing/model/CreditCardAggregateRoot.java">CreditCardAggregateRoot</a> uses the event repository to replay all the events for the credit card, to restore it</li>
<li>The <code>CreditCardAggregateRoot</code> uses the above model to dispatch the command to a command handling method</li>
<li>The command handling method produces an event and applies it to the <code>CreditCard</code> instance.</li>
<li>The event handling model of the <a target="_blank" href="https://github.com/bertilmuth/requirementsascode/blob/master/requirementsascodeexamples/creditcard_eventsourcing/src/main/java/creditcard_eventsourcing/model/CreditCard.java">CreditCard</a> instance dispatches the event to a state changing method</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>I hope you enjoyed my article. I also want to invite you to look at <a target="_blank" href="https://github.com/bertilmuth/requirementsascode">the library</a> that I used throughout the article. Try it out in practice, and let me know the result.</p>
<p><em>If you want to keep up with what I'm doing or drop me a note, follow me on <a target="_blank" href="https://www.linkedin.com/in/bertilmuth/">LinkedIn</a> or <a target="_blank" href="https://twitter.com/BertilMuth">Twitter</a>. To learn about agile software development, visit my <a target="_blank" href="https://skl.sh/2Cq497P">online course</a>.</em><br><em>Last edited April 27, 2020: updated event sourcing process</em></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Simplifying an event sourced application ]]>
                </title>
                <description>
                    <![CDATA[ By Bertil Muth Every time you make a change to the application state, you record the change as an event.You can replay the events since the beginning of the recording, up to a  certain time. Then you've recreated the state of the application at that ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/simplifying-an-event-sourced-application/</link>
                <guid isPermaLink="false">66d45def182810487e0ce119</guid>
                
                    <category>
                        <![CDATA[ coding ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Event Sourcing ]]>
                    </category>
                
                    <category>
                        <![CDATA[ events ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Fri, 21 Jun 2019 12:43:28 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2019/06/EventSourcing.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Bertil Muth</p>
<p>Every time you make a change to the application state, you record the change as an event.<br>You can replay the events since the beginning of the recording, up to a  certain time. Then you've recreated the state of the application at that  time.</p>
<p>That's what <a target="_blank" href="https://martinfowler.com/eaaDev/EventSourcing.html">Event Sourcing</a> is about. It's like you can time travel to the past. I find it fascinating.</p>
<p>Event sourcing provides an audit trail when you need to meet  regulatory requirements. It can help with debugging. And you can even  explore alternate realities: what would have happened if...</p>
<p>I recently saw a <a target="_blank" href="https://youtu.be/r7AGQsM7ncA">great talk</a> by <a target="_blank" href="https://twitter.com/JakubPilimon">Jakub Pilimon</a> and <a target="_blank" href="https://twitter.com/kennybastani">Kenny Bastani</a> about event sourcing.</p>
<p>The talk is a 1 hour session of life coding. The two speakers start with a simple application that is <em>not</em> event sourced. Then they refactor it to use events.</p>
<p>They end up wiring the application up with Apache Kafka. I will skip  that part in this article and focus on the conceptual part of event  sourcing instead.</p>
<h2 id="heading-a-recap-of-the-talk">A recap of the talk</h2>
<p>As a user of a Credit Card management application, you can:</p>
<ul>
<li>Assign a limit to the credit card</li>
<li>Withdraw money</li>
<li>Repay money</li>
</ul>
<p>For each of these commands, there is a method in the <code>CreditCard</code> class.<br>Here's the original code of the <code>assignLimit</code> method:</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">assignLimit</span><span class="hljs-params">(BigDecimal amount)</span> </span>{ 
  <span class="hljs-keyword">if</span>(limitAlreadyAssigned()) {  
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> IllegalStateException(); 
  }
  <span class="hljs-keyword">this</span>.initialLimit = amount; 
}
</code></pre>
<p>Here's the <code>withdraw</code> method:</p>
<pre><code class="lang-java">    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">withdraw</span><span class="hljs-params">(BigDecimal amount)</span> </span>{
        <span class="hljs-keyword">if</span>(notEnoughMoneyToWithdraw(amount)) {
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> IllegalStateException();
        }
        <span class="hljs-keyword">if</span>(tooManyWithdrawalsInCycle()) {
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> IllegalStateException();
        }
        <span class="hljs-keyword">this</span>.usedLimit = usedLimit.add(amount);
        withdrawals++;
    }
</code></pre>
<p>The <code>repay</code> method is similiar.</p>
<p>Remember that for event sourcing, you need to record an event<br>any time the application changes its state?<br>So the speakers extract each state change to its own method in the <a target="_blank" href="https://gitlab.com/pilloPl/eventsourced-credit-cards/blob/4329a0aac283067f1376b3802e13f5a561f18753/src/main/java/io/pillopl/eventsourcing/model/CreditCard.java">CreditCard</a> class.</p>
<p>Here's the refactored <code>withdraw</code> method:</p>
<pre><code class="lang-java">   <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">withdraw</span><span class="hljs-params">(BigDecimal amount)</span> </span>{
        <span class="hljs-keyword">if</span>(notEnoughMoneyToWithdraw(amount)) {
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> IllegalStateException();
        }
        <span class="hljs-keyword">if</span>(tooManyWithdrawalsInCycle()) {
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> IllegalStateException();
        }
        cardWithdrawn(<span class="hljs-keyword">new</span> CardWithdrawn(uuid, amount, Instant.now()));
    }

    <span class="hljs-function"><span class="hljs-keyword">private</span> CreditCard <span class="hljs-title">cardWithdrawn</span><span class="hljs-params">(CardWithdrawn event)</span> </span>{
        <span class="hljs-keyword">this</span>.usedLimit = usedLimit.add(event.getAmount());
        withdrawals++;
        pendingEvents.add(event);
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>;
    }
</code></pre>
<p>An instance of <code>CardWithdrawn</code> represents the event that a user has successfully withdrawn money. <em>After</em> the state has changed, the event is added to the list of pending events.</p>
<p>You call the <code>save</code> method of the <a target="_blank" href="https://gitlab.com/pilloPl/eventsourced-credit-cards/blob/4329a0aac283067f1376b3802e13f5a561f18753/src/main/java/io/pillopl/eventsourcing/persistence/CreditCardRepository.java">CreditCardRepository</a> class to flush the pending events to the event stream. Event listeners may handle the events then.</p>
<p>Apart from the payload, each event has its own unique identifier and timestamp. So you can sequence and replay the events later.<br>To replay the events for a specific credit card, the repository calls the <code>recreateFrom</code> method of the <a target="_blank" href="https://gitlab.com/pilloPl/eventsourced-credit-cards/blob/4329a0aac283067f1376b3802e13f5a561f18753/src/main/java/io/pillopl/eventsourcing/model/CreditCard.java">CreditCard</a> class, passing in the id of the card and the events stored for it:</p>
<pre><code class="lang-java">    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> CreditCard <span class="hljs-title">recreateFrom</span><span class="hljs-params">(UUID uuid, List&lt;DomainEvent&gt; events)</span> </span>{
        <span class="hljs-keyword">return</span> ofAll(events).foldLeft(<span class="hljs-keyword">new</span> CreditCard(uuid), CreditCard::handle);
    }

    <span class="hljs-function"><span class="hljs-keyword">private</span> CreditCard <span class="hljs-title">handle</span><span class="hljs-params">(DomainEvent event)</span> </span>{
        <span class="hljs-keyword">return</span> Match(event).of(
                Case($(Predicates.instanceOf(LimitAssigned.class)), <span class="hljs-keyword">this</span>::limitAssigned),
                Case($(Predicates.instanceOf(CardWithdrawn.class)), <span class="hljs-keyword">this</span>::cardWithdrawn),
                Case($(Predicates.instanceOf(CardRepaid.class)), <span class="hljs-keyword">this</span>::cardRepaid),
                Case($(Predicates.instanceOf(CycleClosed.class)), <span class="hljs-keyword">this</span>::cycleWasClosed)
        );
    }
</code></pre>
<p>This code uses the <a target="_blank" href="http://www.vavr.io/">vavr.io</a> library to call the <code>handle</code> method for each event. The <code>handle</code> method dispatches the event object to the appropriate method.<br>For example: for each <code>LimitAssigned</code> event, the <code>handle</code> method calls the <code>limitAssigned</code> method with the event as parameter.</p>
<h2 id="heading-simplifying-the-application">Simplifying the application</h2>
<p>I used the <a target="_blank" href="https://github.com/bertilmuth/requirementsascode">requirements as code</a> library for simplifying the code. First, I put all of the event classes and the handling methods in a model. Like this:</p>
<pre><code class="lang-java"><span class="hljs-keyword">this</span>.eventHandlingModel = 
        Model.builder()
           .on(LimitAssigned.class).system(<span class="hljs-keyword">this</span>::limitAssigned)
           .on(CardWithdrawn.class).system(<span class="hljs-keyword">this</span>::cardWithdrawn)
           .on(CardRepaid.class).system(<span class="hljs-keyword">this</span>::cardRepaid)
           .on(CycleClosed.class).system(<span class="hljs-keyword">this</span>::cycleWasClosed)
       .build();
</code></pre>
<p>I had to change the return type of the handling methods (e.g. <code>limitAssigned</code>) to <code>void</code>. Apart from that, the conversion from <a target="_blank" href="http://www.vavr.io/">vavr.io</a> was straight forward.</p>
<p>Then, I created a runner and started it for the model:</p>
<pre><code class="lang-java"><span class="hljs-keyword">this</span>.modelRunner = <span class="hljs-keyword">new</span> ModelRunner();
modelRunner.run(eventHandlingModel);
</code></pre>
<p>After that, I changed the <code>recreateFrom</code> and <code>handle</code> methods to this:</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> CreditCard <span class="hljs-title">recreateFrom</span><span class="hljs-params">(UUID uuid, List&lt;DomainEvent&gt; events)</span> </span>{
    CreditCard creditCard = <span class="hljs-keyword">new</span> CreditCard(uuid);
    events.forEach(ev -&gt; creditCard.handle(ev));
    <span class="hljs-keyword">return</span> creditCard;
}

<span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">handle</span><span class="hljs-params">(DomainEvent event)</span> </span>{
    modelRunner.reactTo(event);
}
</code></pre>
<p>At that point, I could get rid of the dependency to <a target="_blank" href="http://www.vavr.io/">vavr.io</a>.<br>Transition complete. Now I could get some more simplifying done.</p>
<p>I revisited the <code>withdraw</code> method:</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">withdraw</span><span class="hljs-params">(BigDecimal amount)</span> </span>{
    <span class="hljs-keyword">if</span>(notEnoughMoneyToWithdraw(amount)) {
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> IllegalStateException();
    }
    <span class="hljs-keyword">if</span>(tooManyWithdrawalsInCycle()) {
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> IllegalStateException();
    }
    cardWithdrawn(<span class="hljs-keyword">new</span> CardWithdrawn(uuid, amount, Instant.now()));
}
</code></pre>
<p>The check <code>tooManyWithdrawalsInCycle()</code> didn't depend on the data of the event. It only depended on the state of the <code>CreditCard</code>.<br>State checks like this can be represented in the model as <code>conditions</code>.</p>
<p>After I moved all state checks for all methods to the model, it looked like this:</p>
<pre><code class="lang-java"><span class="hljs-keyword">this</span>.eventHandlingModel = 
  Model.builder()
    .condition(<span class="hljs-keyword">this</span>::limitNotAssigned)
        .on(LimitAssigned.class).system(<span class="hljs-keyword">this</span>::limitAssigned)
    .condition(<span class="hljs-keyword">this</span>::limitAlreadyAssigned)
        .on(LimitAssigned.class).system(<span class="hljs-keyword">this</span>::throwsException)
    .condition(<span class="hljs-keyword">this</span>::notTooManyWithdrawalsInCycle)
        .on(CardWithdrawn.class).system(<span class="hljs-keyword">this</span>::cardWithdrawn)
    .condition(<span class="hljs-keyword">this</span>::tooManyWithdrawalsInCycle)
        .on(CardWithdrawn.class).system(<span class="hljs-keyword">this</span>::throwsException)
    .on(CardRepaid.class).system(<span class="hljs-keyword">this</span>::cardRepaid)
    .on(CycleClosed.class).system(<span class="hljs-keyword">this</span>::cycleWasClosed)
.build();
</code></pre>
<p>For this to work, I needed to replace the direct calls to methods that change the state with the <code>handle</code> method. After that, the <code>assignLimit</code> and <code>withdraw</code> methods looked like this:</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">assignLimit</span><span class="hljs-params">(BigDecimal amount)</span> </span>{ 
    handle(<span class="hljs-keyword">new</span> LimitAssigned(uuid, amount, Instant.now()));
}

<span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">limitAssigned</span><span class="hljs-params">(LimitAssigned event)</span> </span>{
    <span class="hljs-keyword">this</span>.initialLimit = event.getAmount(); 
    pendingEvents.add(event);
}

<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">withdraw</span><span class="hljs-params">(BigDecimal amount)</span> </span>{
    <span class="hljs-keyword">if</span>(notEnoughMoneyToWithdraw(amount)) {
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> IllegalStateException();
    }
    handle(<span class="hljs-keyword">new</span> CardWithdrawn(uuid, amount, Instant.now()));
}

<span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">cardWithdrawn</span><span class="hljs-params">(CardWithdrawn event)</span> </span>{
    <span class="hljs-keyword">this</span>.usedLimit = usedLimit.add(event.getAmount());
    withdrawals++;
    pendingEvents.add(event);
}
</code></pre>
<p>As you can see, most of the conditional logic has moved out of the  methods into the model. This makes the methods easier to understand.</p>
<p>One thing that bothered me is that you must not forget to add the  event to the pending events. Every time. Or your code won't work.</p>
<p><a target="_blank" href="https://github.com/bertilmuth/requirementsascode">Requirements as code</a> allows you to control how the system handles the events. So I extracted <code>pendingEvents.add(event)</code> from the methods as well:</p>
<pre><code class="lang-java">modelRunner.handleWith(<span class="hljs-keyword">this</span>::addingPendingEvents);
...

<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">addingPendingEvents</span><span class="hljs-params">(StepToBeRun stepToBeRun)</span> </span>{
    stepToBeRun.run();
    DomainEvent domainEvent = (DomainEvent) stepToBeRun.getEvent().get();
    pendingEvents.add(domainEvent);
}
</code></pre>
<p>I could have gone further and extract the validation logic as well.<br>But I leave that as a thought exercise to you, dear reader.</p>
<h2 id="heading-whats-the-point">What's the point?</h2>
<p>What I tried to achieve is a clear separation of concerns:</p>
<ul>
<li>The state dependent execution of methods is defined in the model</li>
<li>The data validation and state changes are in the implementations of the methods</li>
<li>The events are automatically added to the pending events. In  general: the infrastructure code is clearly separated from the business  logic.</li>
</ul>
<p>Simplifying an example that is already very simple is good for explaining.<br>But that's not the point I want to make.</p>
<p>The point is: having such a clear separation of concerns pays out in practice.<br>Especially, if you work with multiple teams. On complicated problems.</p>
<p>Separation of concerns helps with changing different parts of code at  a different pace. You have simple rules where to find something. The  code is easier to understand. And it's easier to isolate units for  testing purposes.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>I hope you enjoyed my article. Please give me feedback.</p>
<p>Have you been working on event sourcing applications?<br>What were your experiences like?<br>Can you relate to what I wrote in this article?</p>
<p>I also want to invite you to look at <a target="_blank" href="https://github.com/bertilmuth/requirementsascode">my library</a> that I used throughout the article. I would be thrilled if you try it out in practice, and tell me what you think.</p>
<p><em>This article was first published on <a target="_blank" href="https://dev.to/bertilmuth/simplifying-an-event-sourced-application-1klp">dev.to</a></em></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Event sourcing essentials you need to know when starting out ]]>
                </title>
                <description>
                    <![CDATA[ By Noël Widmer Event Sourcing is a thought challenge when starting out. In this story, I will describe my experiences from the perspective of an engineer. My goal is to help you decide if you want to invest the resources to get started with Event Sou... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/event-sourcing-essentials-you-need-to-know-when-starting-out-13af35d9f932/</link>
                <guid isPermaLink="false">66c349e89972b7c5c7624e3b</guid>
                
                    <category>
                        <![CDATA[ #Domain-Driven-Design ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Event Sourcing ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Productivity ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ technology ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Fri, 15 Mar 2019 18:47:14 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*6-84rquRE2oH4sJXRIabKA.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Noël Widmer</p>
<p>Event Sourcing is a thought challenge when starting out. In this story, I will describe my experiences from the perspective of an engineer.</p>
<p>My goal is to help you decide if you want to invest the resources to get started with Event Sourcing.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/vRIbN9ppLB4ixj1hzxbGQ6AcoQKdy-8Fi-xn" alt="Image" width="800" height="330" loading="lazy">
_[The Matrix](https://www.amazon.com/Complete-Trilogy-Reloaded-Revolutions-Blu-ray/dp/B001CEE1YE/ref=sr_1_6?keywords=the+matrix&amp;qid=1550756146&amp;s=movies-tv&amp;sr=1-6" rel="noopener" target="<em>blank" title="): Neo is offered a choice.</em></p>
<h3 id="heading-about-the-author">About The Author</h3>
<p>Hi ? I’m Noël. I live near Zurich (Switzerland) and am proudly working on Switzerland’s largest E-Commerce platform. My team and I have applied Event Sourcing throughout the last 12 months, and w<strong>e learned a lot.</strong></p>
<p>I want to share four essentials with you that I wish we knew one year ago.</p>
<h3 id="heading-a-tiny-introduction-to-event-sourcing">A Tiny Introduction To Event Sourcing</h3>
<p>This article is not about introducing you to the concepts of Event Sourcing.<br>I still feel like I should take <strong>one step</strong> back though — to paint a clearer picture.</p>
<p>In state-oriented applications, you store the result of some computation in your data store. You might also keep a log where you archive old states for auditing or debugging purposes. But by storing state you lose the information about the transition from one state to the other. If a user’s username has disappeared, you’ll be wondering how that could have happened.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/w-5nI8fUU3m3DDBwt8QBX-g1g5YtG5F7A4OU" alt="Image" width="605" height="235" loading="lazy">
<em>Storing state in a state-oriented application.</em></p>
<p>Sourcing events preserves that information. This is achieved by storing state transitions rather than the resulting state.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/H9prmbzan1lBxdV6YTG2H9xzWvxT8iLzrXZl" alt="Image" width="605" height="239" loading="lazy">
<em>Storing state transitions (events) in an event sourced application.</em></p>
<p>The current state can be restored by applying all events to an empty canvas. That means we can still access the current state but need to invest computational resources to do so.</p>
<p>There are many articles on the web that go into more detail. Martin Fowler <a target="_blank" href="https://martinfowler.com/eaaDev/EventSourcing.html">wrote one about it</a>. And Greg Young <a target="_blank" href="https://youtu.be/kZL41SMXWdM?t=2">talks a lot about Event Sourcing</a>. Greg is so obsessed with event sourcing that <a target="_blank" href="https://eventstore.org/">he implemented a data store which is specifically designed for event sourcing</a>. My team is using Greg’s event store — it’s great!</p>
<h3 id="heading-1-event-sourcing-is-not-a-silver-bullet">1) Event Sourcing Is Not A Silver Bullet</h3>
<p>Once you fall for the bitter sweet taste of Event Sourcing it becomes compelling to apply the concept to all your problems.</p>
<p>This will provide you with loads of data to analyze and you will have a powerful foundation to detect interesting correlations in it. You’ll be able to detect inefficient processes and make them more efficient.</p>
<p>And every engineer’s (my) favorite:</p>
<p>Tracking down a bug becomes much easier when you can “time travel” to the exact moment when the bug happened. In the end you will save time and money.</p>
<p>Well — not quite. ☝️</p>
<p>Sourcing your events sure allows you to do the analysis. <strong>But you still need to do it.</strong> This will cost time. Luckily, “time travel” comes for free. Enhanced debugging is thus guaranteed from day one.</p>
<p>Seth Godin wrote a <a target="_blank" href="https://seths.blog/2019/02/the-am-pm-problem-the-curse-of-too-much-data/">great blog post</a> on the subject. It’s a 2 minute read, so check it out.</p>
<p>Now you know about the price you’ll pay if you use your events for analytical purposes which is the main business benefit of Event Sourcing after all.</p>
<p>There is another cost though. Event Sourcing will increase the complexity of your application. Instead of dealing with your application’s current state you’ll have to deal with everything that has ever happened since it went live. Events that are no longer used will remain in your data store and you’ll have to support them for a long time.</p>
<p>It’s great if you deploy a feature and keep iterating on it. Just be aware that there are now multiple versions of that feature’s events in your data store and you’ll have to support all of them. Even if you no longer create new instances of those events.</p>
<p>Event Sourcing imposes additional time complexities that you will have to get used to. Apply it where you see a non-zero chance that the collected data becomes relevant. Where I’d define “relevant” as:</p>
<ul>
<li>the data could give you more insight into your domain</li>
<li>the data could help your business to improve their processes on their own</li>
<li>the data could help you find bugs faster</li>
</ul>
<p>Note that I added the word “could” in each of the last three bullet points. It’s likely you won’t know the exact benefit of Event Sourcing in advance. Make your best guess.</p>
<h3 id="heading-2-recognize-the-functional-nature-of-event-sourcing">2) Recognize The Functional Nature Of Event Sourcing</h3>
<p>The authors of the famous <a target="_blank" href="https://www.amazon.com/Patterns-Principles-Practices-Domain-Driven-Design/dp/1118714709">Patterns, Principles, and Practices of Domain-Driven Design</a> recommend object-oriented programming languages like C# or Java.</p>
<p>I assume that the implicit reasoning behind that recommendation is the number of people using such languages. It’s true. New team members will likely have an easier start into the domain when confronted with familiar languages.</p>
<p>But I disagree. <a target="_blank" href="https://youtu.be/kZL41SMXWdM?t=2">So does Greg Young</a>. <strong>Event Sourcing is not an object-oriented concept.</strong></p>
<p>One might argue that state transitions are objects too. And indeed. You can model everything as objects. Just because you can does not imply that this is the best model to use.</p>
<p>Consider using a language that supports functional paradigms. Especially <a target="_blank" href="https://en.wikipedia.org/wiki/Tagged_union">tagged unions</a> and <a target="_blank" href="https://en.wikipedia.org/wiki/Pattern_matching">pattern matching</a> are extremely valuable. Working with your events will feel natural and you won’t have to fight your language’s type system. If your team has no experience with the functional world it might be best to stick to familiar languages though.</p>
<p>Even more important to understand is that <strong>choosing a relational data store will be a painful experience</strong>. You’re not dealing with relational data when sourcing your events. Each event has its own schema which can change over time. Using a relational data store will hurt.</p>
<blockquote>
<p><a target="_blank" href="https://youtu.be/kZL41SMXWdM?t=1597">SQL is the master of nothing but it sucks at nothing.</a> - Greg Young</p>
</blockquote>
<h3 id="heading-3-expect-a-steep-learning-curve">3) Expect A Steep Learning Curve</h3>
<p>As with all new things there will be learning involved. Don’t try to sidestep it. That won’t work.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/0jNwGHRNDnjJDzwwr2h76zYC7XkT91P1oIv2" alt="Image" width="800" height="331" loading="lazy">
_[The Matrix](https://www.amazon.com/Complete-Trilogy-Reloaded-Revolutions-Blu-ray/dp/B001CEE1YE/ref=sr_1_6?keywords=the+matrix&amp;qid=1550756146&amp;s=movies-tv&amp;sr=1-6" rel="noopener" target="<em>blank" title="): Neo learns something special.</em></p>
<p>A great way to learn is to prototype. Try this:</p>
<ul>
<li>build at least one prototype of your first event sourced application</li>
<li>run and observe your prototype for a while</li>
<li>implement new features and get used to iterating on what you’ve built</li>
</ul>
<p>Iterate as often as possible before your go live. Once you are live it won’t be as easy to implement new learnings.</p>
<p>Go live once your team feels confident with maintaining the application.</p>
<p>Also think about how your team will introduce new team members to Event Sourcing. New joiners are already in an overwhelming position and learning new concepts won’t make it any easier for them.</p>
<p>Figure out a way to introduce them to Event Sourcing in a soft and safe way. This is important to figure out once you start getting new team members. It’s fine to delay it until that happens.</p>
<h3 id="heading-4-prepare-for-political-debates">4) Prepare for political debates</h3>
<p>Have you realized that your company wants <strong>cheap</strong> and <strong>quality</strong> results <strong>today</strong>?</p>
<p>Oh my, who am I talking to — of course you did. ?</p>
<p>Will <em>they</em> like it when you experiment with a mind-bending concept <em>they</em> might never heard of? And what is your company’s tech stack like? Do you usually use object-oriented programming languages in combination with relational data stores? Will <em>they</em> like it when you switch to a functional tech stack?</p>
<p>Depending on your companies culture you might have to fight your colleagues on multiple fronts. Act as an example. Tell the truth. You know it will be hard, especially in the beginning. Share your concerns. Make sure everyone involved knows the risks and what you’ll do to prevent them.</p>
<p>And don’t leave out how you picture the Event Sourcing paradise. Get the business on board by allowing them to build reports based on your valuable events. They’ll love it.</p>
<p>Get the concerned engineering people on board by sharing the improved debugging experience. Engineers are stubborn, they might still not like it.</p>
<p>I found it useful to practice such debates with my colleagues. Establish a safe environment for training and encourage your team members to take part.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/Y7d79Cv8qbHMWOoWken3t-86JsVOnSWRJ-n3" alt="Image" width="800" height="330" loading="lazy">
_[The Matrix](https://www.amazon.com/Complete-Trilogy-Reloaded-Revolutions-Blu-ray/dp/B001CEE1YE/ref=sr_1_6?keywords=the+matrix&amp;qid=1550756146&amp;s=movies-tv&amp;sr=1-6" rel="noopener" target="<em>blank" title="): Neo trains in a safe environment.</em></p>
<p>Be ready and know your stuff. You’ll make it! ?</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Let me summarize.</p>
<ul>
<li>More data isn’t always good.</li>
<li>Additional data without the time to analyze it is useless.</li>
<li>Analysis without the intention and time to act on the result is useless.</li>
<li>Event Sourcing enhances the ability to debug your application.</li>
<li>Event Sourcing is a functional paradigm.</li>
<li>Expect a steep learning curve.</li>
<li>Not everybody will be happy about your plans.</li>
</ul>
<p>That’s it. My intention was to prepare your expectations to my experiences. Don’t worry. Be determined and <strong>choose the red pill!</strong></p>
<h3 id="heading-the-matrix">The Matrix</h3>
<p>All images in this story are borrowed from the movie <a target="_blank" href="https://www.amazon.com/Complete-Trilogy-Reloaded-Revolutions-Blu-ray/dp/B001CEE1YE/ref=sr_1_6?keywords=the+matrix&amp;qid=1550756146&amp;s=movies-tv&amp;sr=1-6">The Matrix</a>.</p>
<p>I’ve spent 9 years writing object-oriented code and working with relational data stores. About two years ago I started to experiment with functional code and non-relational data stores. The mind shift has been one of the most important lessons in my career to date.</p>
<p>Question your environment. Find the flaws. Exit the Matrix and get to experience a whole new world.</p>
<p>Farewell. Until next time. And good luck!</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/nCTTljApCmGwNVYDCtgOabSoZ6V7wjQIvAC0" alt="Image" width="800" height="331" loading="lazy">
_[The Matrix](https://www.amazon.com/Complete-Trilogy-Reloaded-Revolutions-Blu-ray/dp/B001CEE1YE/ref=sr_1_6?keywords=the+matrix&amp;qid=1550756146&amp;s=movies-tv&amp;sr=1-6" rel="noopener" target="<em>blank" title="): Neo receives a goodbye gift.</em></p>
<p><strong>I only write about programming and technology. If you follow me, I won’t waste your time.</strong> ?</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
