{"id":257727,"date":"2021-05-24T21:00:40","date_gmt":"2021-05-24T18:00:40","guid":{"rendered":"https:\/\/en.buradabiliyorum.com\/how-event-sourcing-helps-you-track-your-applications-state-cloudsavvy-it\/"},"modified":"2021-05-24T21:00:40","modified_gmt":"2021-05-24T18:00:40","slug":"how-event-sourcing-helps-you-track-your-applications-state-cloudsavvy-it","status":"publish","type":"post","link":"https:\/\/buradabiliyorum.com\/en\/how-event-sourcing-helps-you-track-your-applications-state-cloudsavvy-it\/","title":{"rendered":"#How Event Sourcing Helps You Track Your Application\u2019s State \u2013 CloudSavvy IT"},"content":{"rendered":"<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_85 counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<label for=\"ez-toc-cssicon-toggle-item-6a3941689d4f8\" class=\"ez-toc-cssicon-toggle-label\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #dd3333;color:#dd3333\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #dd3333;color:#dd3333\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/label><input type=\"checkbox\"  id=\"ez-toc-cssicon-toggle-item-6a3941689d4f8\" checked aria-label=\"Toggle\" \/><nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/buradabiliyorum.com\/en\/how-event-sourcing-helps-you-track-your-applications-state-cloudsavvy-it\/#The_Fundamentals\" >The Fundamentals<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/buradabiliyorum.com\/en\/how-event-sourcing-helps-you-track-your-applications-state-cloudsavvy-it\/#Reconstructing_An_Objects_State\" >Reconstructing An Object\u2019s State<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/buradabiliyorum.com\/en\/how-event-sourcing-helps-you-track-your-applications-state-cloudsavvy-it\/#Event_Sourcing_in_The_Real_World\" >Event Sourcing in The Real World<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/buradabiliyorum.com\/en\/how-event-sourcing-helps-you-track-your-applications-state-cloudsavvy-it\/#Combining_Event_Sourcing_and_CQRS\" >Combining Event Sourcing and CQRS<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/buradabiliyorum.com\/en\/how-event-sourcing-helps-you-track-your-applications-state-cloudsavvy-it\/#Conclusion\" >Conclusion<\/a><\/li><\/ul><\/nav><\/div>\n<p><strong>&#8220;#How Event Sourcing Helps You Track Your <a href=\"https:\/\/buradabiliyorum.com\/en\/category\/download-scripts-themes-apps\/\" data-internallinksmanager029f6b8e52c=\"9\" title=\"Download Scripts &amp; Themes &amp; Apps\" target=\"_blank\" rel=\"noopener\">App<\/a>lication\u2019s State \u2013 CloudSavvy IT&#8221;<\/strong><\/p>\n<div id=\"article-content-area\">\n<figure style=\"width: 2458px\" class=\"wp-caption alignnone\"><img loading=\"lazy\" decoding=\"async\" class=\"type:primaryImage wp-image-11493 size-full\" data-pagespeed-lazy-src=\"https:\/\/www.cloudsavvyit.com\/p\/uploads\/2021\/05\/bbc95cef.png?width=1200&amp;trim=1,1&amp;bg-color=000&amp;pad=1,1\" alt=\"code on screen\" width=\"2458\" height=\"1074\" src=\"\/pagespeed_static\/1.JiBnMqyl6S.gif\" onload=\"pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\" onerror=\"this.onerror=null;pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\"\/><figcaption class=\"wp-caption-text\"><span class=\"type:primaryImage imagecredit\"><a rel=\"nofollow noopener\" target=\"_blank\" href=\"https:\/\/www.shutterstock.com\/image-illustration\/programming-code-abstract-technology-background-software-432008923\">Shutterstock\/whiteMocca<\/a><\/span><\/figcaption><\/figure>\n<p>Event sourcing is a software architecture where changes to the application\u2019s state are captured as a <a href=\"https:\/\/buradabiliyorum.com\/en\/category\/watch-movies-tv-seriess\/\" data-internallinksmanager029f6b8e52c=\"8\" title=\"Watch Movies &amp; TV Series\" target=\"_blank\" rel=\"noopener\">series<\/a> of perpetually stored \u201cevents.\u201d Whereas most systems only expose their current state, event sourcing creates a complete record of all prior states.<\/p>\n<h2 id=\"the-fundamentals\"><span class=\"ez-toc-section\" id=\"The_Fundamentals\"><\/span>The Fundamentals<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Event sourcing is most often used with time- or linear process-based systems. A shop ordering app might transition transactions between \u201cpending\u201d, \u201capproved\u201d and \u201cshipped\u201d states. The transition between each state is a distinct \u201cevent\u201d in the lifecycle of that order.<\/p>\n<p>This system could be modelled using a traditional relational database:<\/p>\n<pre>order_id | order_status&#13;\n---------|-------------&#13;\n1000     | APPROVED<\/pre>\n<p>In most systems, knowing the current status isn\u2019t enough though. You also want to see <em>when<\/em> the order became approved. We could do this by adding extra fields:<\/p>\n<pre>order_id | order_created_time | order_approved_time | order_shipping_time&#13;\n---------|--------------------|---------------------|---------------------&#13;\n1000     | 2021-04-30         | 2021-05-01          | NULL<\/pre>\n<p>Now it\u2019s clear the order was created on April 30th and approved on May 1st; its shipping is still pending. For many applications, this structure works well. It can become restrictive as more states are added though.<\/p>\n<p>Let\u2019s now look at this example restructured to use event sourcing:<\/p>\n<pre>event_id | event_order_id | event_type     | event_timestamp&#13;\n---------|---------------------|----------------|----------------&#13;\n2        | 1000                | order.approved | 2021-05-01&#13;\n1        | 1000                | order.created  | 2021-04-30<\/pre>\n<p>The order\u2019s state transitions have been separated into a dedicated event log. With this model, it\u2019s trivial to add a new event type in the future. If a customer needs to cancel an order, we can write an <code>order.cancelled<\/code> event into the log.<\/p>\n<p>Event sourcing could also be used to track data about the order itself. You might add event types for <code>order.apply_discount<\/code> or <code>order.process_refund<\/code>. You can record an event at any time, creating a new state for the order while keeping its previous states accessible.<\/p>\n<h2 id=\"reconstructing-an-objects-state\"><span class=\"ez-toc-section\" id=\"Reconstructing_An_Objects_State\"><\/span>Reconstructing An Object\u2019s State<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>You can determine an object\u2019s current state by fetching all the events that relate to it. If you want to know whether an order\u2019s been approved, check whether its event collection contains an <code>order.approved<\/code> event.<\/p>\n<p>You can reconstruct historical states in exactly the same way. If you need to know the order\u2019s state on a particular date, fetch all the events logged on or before that day.<\/p>\n<p>Event sourcing is an incremental model that tracks an object\u2019s chronology automatically. Every change to the object\u2019s state <a rel=\"nofollow noopener\" target=\"_blank\" href=\"https:\/\/martinfowler.com\/eaaDev\/EventSourcing.html\">should be captured<\/a> as a timestamped event. When you use event sourcing, you have automatic version control and a complete audit log of state transitions.<\/p>\n<p>If you ever need to rebuild an object\u2019s history, you can discard any events created after a given date. Imagine that a user\u2019s account was compromised by a malicious actor who took various actions on their behalf. In a fully event-sourced system, you could delete any events linked to that user in the questionable timeframe. This would recover their account to a good state.<\/p>\n<p>To preserve this ability, you must ensure events are immutable. Once an event has been logged, you should never alter its properties. If an event needs adjustment, you\u2019d log another event to effect the change.<\/p>\n<p>The system\u2019s immutability means you can safely use it to <a href=\"https:\/\/buradabiliyorum.com\/en\/category\/trip-and-travel\/\" data-internallinksmanager029f6b8e52c=\"10\" title=\"Trip &amp; Travel\" target=\"_blank\" rel=\"noopener\">travel<\/a> back in time and rebuild historical states. If you wanted to reproduce your database as it was two years ago, you could discard all the events logged in the intervening time.<\/p>\n<p>Another benefit of event sourcing is increased visibility into the state of the system. If a user reports a bug, you can clone the database, discard new events and repeat their steps from a known good point. Analysing logged events can help you pinpoint bugs in your codebase.<\/p>\n<h2 id=\"event-sourcing-in-the-real-world\"><span class=\"ez-toc-section\" id=\"Event_Sourcing_in_The_Real_World\"><\/span>Event Sourcing in The Real World<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Event sourcing has a reputation for being complex, unwieldy and overcomplicated. Historically, event sourcing has been tied to applications with stringent audit requirements and a proven need to replay events.<\/p>\n<p>This doesn\u2019t have to be the case though. If you\u2019re an experienced developer, you\u2019ve probably implemented something close to event sourcing in the past. Any system which keeps a record of \u201cevents\u201d \u2013 such as user login attempts, website page hits, or order processing stages \u2013 naturally gravitates towards an event sourced approach, even if you\u2019re not implementing one intentionally.<\/p>\n<p>A deliberate implementation of event sourcing in code can be cumbersome. Developers usually assume that data fetched from databases is an accurate representation of an object\u2019s current state. With event sourcing, the data you fetch carries little value on its own. You need to \u201creplay\u201d events in your codebase to create a representation of the state.<\/p>\n<p>Event sourcing can give rise to performance overheads. In the example above, creating a complete representation of the order object now requires much more data to be fetched. In the traditional model, a single selection provides all the data associated with the order.<\/p>\n<p>There\u2019s other downsides too. In the event something does go wrong, event sourcing can be harder to fix. You can\u2019t write a quick patch or manually hotfix the database. You\u2019ll need to gracefully transition your event schemas while ensuring the historical chronology remains intact.<\/p>\n<h2 id=\"combining-event-sourcing-and-cqrs\"><span class=\"ez-toc-section\" id=\"Combining_Event_Sourcing_and_CQRS\"><\/span>Combining Event Sourcing and CQRS<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Event sourcing is commonly combined with <a rel=\"nofollow noopener\" target=\"_blank\" href=\"https:\/\/martinfowler.com\/bliki\/CQRS.html\">CQRS<\/a> (Command Query Responsibility Segregation). This pattern advocates the separation of <em>commands<\/em> (which write data) from <em>queries<\/em> (which read data).<\/p>\n<p>The use of event sourcing necessitates a degree of CQRS. Data is written into your database via events. The write model is therefore execeedingly simple: it\u2019s a one-way append-only log of the events that occur. Events are a manifestation of the \u201ccommands\u201d described by CQRS.<\/p>\n<p>The data retrieval model is completely independent. You can use the most appropriate query system to fetch events and layer them into the application\u2019s current state. The <em>commands<\/em> (events) transition the system into a new state; queries expose the state aspects that your application requests.<\/p>\n<p>Put a different way, the read and write models have no awareness of how the other functions. The entities in your codebase (such as an Order) are stored as a sequence of chronological events. The stored events can\u2019t be rehydrated into the entity they pertain to without knowledge of how that entity\u2019s state is derived. That knowledge is implemented within the read (query) model, which brings data back into your application.<\/p>\n<p>This characteristic allows the persistence layer to be simplified to a single record insertion for each operation. The stored data doesn\u2019t need to precisely represent any particular entity as the query model will manipulate it later. This contrasts with a \u201ctraditional\u201d relational database where table fields often closely align with the properties of objects in your codebase.<\/p>\n<p>The output of the query model is known as a <em>projection<\/em>. A projection is <a rel=\"nofollow noopener\" target=\"_blank\" href=\"https:\/\/eventsourcing.readthedocs.io\/en\/v6.0.0\/topics\/projections.html\">a representation<\/a> of data using a different perspective to its storage system. When using event sourcing, data is stored as a stream of events but <em>projected<\/em> into a representation of the application\u2019s current state. That representation is stateless, immutable and idempotent \u2013 creating the representation doesn\u2019t modify the underlying event data in any way.<\/p>\n<p>A single projection might need to interact with several different event types. Projections look at the data in aggregate, in a way that makes sense to the application\u2019s functions. In our example from earlier, an Order projection could output an object containing <code>CreatedDate<\/code>, <code>ApprovedDate<\/code> and <code>ShippedData<\/code> properties by examining the events associated with the subject order.<\/p>\n<h2 id=\"conclusion\"><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span>Conclusion<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Event sourcing is a specialised software architecture with innate support for accountability, chronology and state recreation. The pattern can significantly simplify the implementation of applications where these qualities are desirable.<\/p>\n<p>Event sourcing can also be useful in other scenarios, although diminishing returns may be encountered. Adopting event sourcing requires developers implement code to determine the current state, adding overheads which don\u2019t arise in systems which only store the current state in their database.<\/p>\n<p>Event sourcing is best combined with other software architecture techniques such as CQRS, the observer pattern and <a rel=\"nofollow noopener\" target=\"_blank\" href=\"https:\/\/hackernoon.com\/eventual-vs-strong-consistency-in-distributed-databases-282fdad37cf7\">eventual consistency<\/a>. You don\u2019t need to use event sourcing across your entire app \u2013 often, individual submodules will benefit from event sourcing while the bulk of your project sticks with a traditional relational database.\n<\/div>\n<blockquote><p><strong><span style=\"color: #ff6600;\">If you liked the article, do not forget to share it with your friends. Follow us on\u00a0<span style=\"color: #ff0000;\"><a style=\"color: #ff0000;\" href=\"https:\/\/news.google.com\/publications\/CAAqBwgKMLG0nwswvr63Aw\" target=\"_blank\" rel=\"nofollow noopener noreferrer\">Google News<\/a><\/span>\u00a0too, click on the star and choose us from your favorites.<\/span><\/strong><\/p><\/blockquote>\n<blockquote>\n<p style=\"text-align: center;\">For forums sites go to <span style=\"color: #ff9900;\"><a style=\"color: #ff9900;\" href=\"https:\/\/forum.buradabiliyorum.com\/\" target=\"_blank\" rel=\"noopener\">Forum.BuradaBiliyorum.Com<\/a><\/span><\/strong><\/p>\n<\/blockquote>\n<blockquote>\n<p style=\"text-align: center;\"><strong>If you want to read more like this article, you can visit our <span style=\"color: #ff9900;\"><a style=\"color: #ff9900;\" href=\"https:\/\/en.buradabiliyorum.com\/technology\/\" target=\"_blank\" rel=\"noopener\">Technology category.<\/a><\/span><\/strong><\/p>\n<\/blockquote>\n<p><span style=\"color: black;\"><a style=\"color: #ff9900;\" href=\"https:\/\/www.cloudsavvyit.com\/11000\/how-event-sourcing-helps-you-track-your-applications-state\/\" target=\"_blank\" rel=\"noopener\">Source<\/a><\/span><\/p>\n","protected":false},"excerpt":{"rendered":"<p>&#8220;#How Event Sourcing Helps You Track Your Application\u2019s State \u2013 CloudSavvy IT&#8221; Shutterstock\/whiteMocca Event sourcing is a software architecture where changes to the application\u2019s state are captured as a series of perpetually stored \u201cevents.\u201d Whereas most systems only expose their current state, event sourcing creates a complete record of all prior states. The Fundamentals Event&#8230;<\/p>\n","protected":false},"author":1,"featured_media":257728,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"fifu_image_url":"https:\/\/www.cloudsavvyit.com\/p\/uploads\/2021\/05\/bbc95cef.png","fifu_image_alt":"","footnotes":""},"categories":[18],"tags":[],"class_list":["post-257727","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-technology"],"_links":{"self":[{"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/posts\/257727","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/comments?post=257727"}],"version-history":[{"count":0,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/posts\/257727\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/media\/257728"}],"wp:attachment":[{"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/media?parent=257727"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/categories?post=257727"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/tags?post=257727"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}