<?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 Daniel Battaglia on Medium]]></title>
        <description><![CDATA[Stories by Daniel Battaglia on Medium]]></description>
        <link>https://medium.com/@daniel.bytes?source=rss-c99687836b88------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*VrXp6uFTxOfcWNmJ.</url>
            <title>Stories by Daniel Battaglia on Medium</title>
            <link>https://medium.com/@daniel.bytes?source=rss-c99687836b88------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 02:56:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@daniel.bytes/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[Event-Driven Microservices with RabbitMQ and Ruby]]></title>
            <link>https://medium.com/kontenainc/event-driven-microservices-with-rabbitmq-and-ruby-7a54ae01b285?source=rss-c99687836b88------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a54ae01b285</guid>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Daniel Battaglia]]></dc:creator>
            <pubDate>Thu, 11 Jan 2018 09:29:59 GMT</pubDate>
            <atom:updated>2018-02-07T08:26:40.686Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nADkGNLzIb_3jXhTa89y5w.jpeg" /></figure><p>In <a href="http://blog.kontena.io/event-sourcing-microservices-with-kafka/">my last post</a> we discussed how event sourcing with Apache Kafka can be used to create robust reactive microservices. While event sourcing as an architectural pattern is useful to understand, it is not commonly used when starting a new project or service, which generally start their life as simple CRUD applications. Event sourcing works best when chosen as a top-level architecture for a new service from the start. As such, it is not always a great fit when trying to migrate an existing monolithic application into an event-driven microservices architecture; event sourcing is not easy to “bolt-on” to an existing application. In cases like this, there are still many great options and patterns available to move towards a reactive event-driven microservices architecture.</p><p>Today I am going to describe a pattern that is very similar to what we use here at Kontena for our <a href="https://cloud.kontena.io/">Kontena Cloud</a> product. Kontena Cloud is composed of microservices and APIs coded in Ruby (well, most of them), and a front-end application written in <a href="http://blog.kontena.io/kontena-cloud-modern-front-end-stack/">Typescript and node.js.</a> We use a mix of PostgreSQL, MongoDB and Redis for data storage, with RabbitMQ to tie it all together.</p><p>While reading thru this blog post, please also check out the accompanying <a href="https://github.com/kontena/state-machine-events-example">Github Repository</a>.</p><h3>The Architecture</h3><h4>RabbitMQ</h4><p><a href="https://www.rabbitmq.com/">RabbitMQ</a> is a very popular and stable message broker used by countless companies to implement various types of asynchronous workflows. We chose RabbitMQ here at Kontena because we needed a stable, manageable and highly-available solution for messaging. We already had a decent amount of previous institutional knowledge managing RabbitMQ at scale compared to other alternatives such as Kafka and Zookeeper.</p><p>The two most common use cases often seen for RabbitMQ are the <a href="https://www.rabbitmq.com/tutorials/tutorial-one-ruby.html">producer/consumer (work queues) pattern</a> and the <a href="https://www.rabbitmq.com/tutorials/tutorial-three-ruby.html">publish/subscribe pattern</a>. We make heavy use of both here at Kontena. For the purpose of this article, I am going to focus mainly on the publish/subscribe pattern, specifically using <a href="https://www.rabbitmq.com/tutorials/tutorial-five-ruby.html">topic exchanges</a>. If you are not already familiar with RabbitMQ and its terminology, I recommend you read through their <a href="https://www.rabbitmq.com/getstarted.html">fantastic tutorials</a> to get a feel for how RabbitMQ works.</p><p>When we discuss event driven systems, what we are referring to is a system of separate applications and services that communicate with each other in an asynchronous fashion, as loosely coupled as possible. When designing such a system, there are two factors that seem to be at odds with each other: our event publishers should not care who consumes messages, while our event consumers should never lose messages, even when all instances of the consuming service are down. RabbitMQ solves this problem using exchanges, topics and queues. Our publisher application writes an event to an exchange, with some topic routing key describing the type of event. Our consumers, on the other hand, create a durable queue that is bound to the exchange and some topic routing pattern (for example, if our publisher uses the topics product.created and product.updated, our subscriber can bind their queue to product.# to receive ALL product events).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*s_NSqbVuftoQVdDhuHi_fQ.png" /><figcaption>RabbitMQ Topic Exchange Example</figcaption></figure><p>Unlike Kafka, one feature RabbitMQ does NOT offer is an event history and storage mechanism. In RabbitMQ, events published on an exchange are ephemeral: unless they are bound to a queue, they are lost forever. And, even if it ends up in a queue, the message is gone as soon as a consumer finishes handling it. This poses a problem for an event-driven microservices architecture, as these events are essentially the source of truth for business transactions that occur <em>between</em> multiple services. Having this history allows us to leverage a lot of powerful features when adding new services, such as replaying all previous events and inspecting past events to help troubleshoot issues, not to mention potential end-user-facing features like audit history. Therefore, we need to build another layer onto our system.</p><h4>State Machines</h4><p>In event sourcing, we said that the source of truth for our service was the event stream, usually stored in some log-structured data storage or append-only database table. On the other hand, most applications store their data in an RDBMS or NoSQL data store, and the data is mutable. By mutable, we mean that every change updates an existing row or document. We could conceivably listen for changes to this entity in our code (maybe using <a href="http://guides.rubyonrails.org/active_record_callbacks.html">Active Record model callbacks</a> for example) and publish out that data over RabbitMQ, but unless we also store these events we lose all the real benefits that an event driven architecture should offer (history, replay-ability and being responsive to future changes).</p><p>A nice way to solve this is to embed a state machine engine into each of our primary entities, and build the event storage as a generic extension of the state-machine engine. Unlike event sourcing, our history table is not the source of truth for our application, but instead an artifact from any changes in the system. But, to outside systems consuming our events, these events will in fact exist as the source of truth for our services external interface to the rest of the system.</p><p>In the <a href="https://github.com/kontena/state-machine-events-example">example application</a> we are using a lightweight Ruby state machine library <a href="https://github.com/aasm/aasm">aasm</a>. Besides being lightweight, aasm has an easy to manage DSL for describing an entity’s states and events, with built in support for storing and retrieving the current state via most popular Ruby ORMs (Active Record, Sequel, Mongoid, etc).</p><h3>The Code</h3><h4>The Products Service</h4><p>Let’s imagine a Products service, which stores a catalog of various products for some eCommerce site. This will be the simplest products catalog ever, having just a single Product model type with name, price, inventory and state fields.</p><p>When adding a state machine to our model, we are immediately confronted with the question: what are the possible states our model can be in, and what are the events that get us there? One thing that becomes clear after working with state machines is that, even in other architectures that don’t use explicit state machines, the states are still there implicitly. Your Product can be in-stock, out of stock or discontinued even if there is no explicit state column in your data model stating it; you just derive that information based on the other attributes of your model (maybe an inventory integer field, as well as a is_discontinued boolean field). The explicit state machine just makes this easier to understand at a glance, as well as enforcing business rules when transitioning between states. Being able to define business rules in an easily-readable declarative manner is also a huge help for new developers trying to understand existing code they did not write (not to mention your own code 6 months later!).</p><p>Below is an example of what our Product model might look like in Ruby, stored in MongoDB:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/880005c2820968a1785ebe9a8cc1e443/href">https://medium.com/media/880005c2820968a1785ebe9a8cc1e443/href</a></iframe><p>As you can see, the various states our model can be in, as well as the events that transition between these states, are now explicitly defined. We even have some additional business logic defined in the form of guard statements.</p><h4>Modifying A Product</h4><p>Imagine we have an existing Product and we want to update its inventory, potentially changing its state. One nice way to encapsulate this business logic is via the Ruby <a href="https://github.com/cypriss/mutations">Mutations</a> library (<a href="https://github.com/kontena/kontena/tree/master/server/app/mutations">we love our Mutations here at Kontena</a>):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3758a062951a5d92ac7788038b47b3bd/href">https://medium.com/media/3758a062951a5d92ac7788038b47b3bd/href</a></iframe><h4>Storing Events</h4><p>In our example code above we have two potential events happening on our Product: add_inventory! or reduce_inventory!. In either case, we would like our framework to be able to store and publish out our events to the rest of our services. The first step to implement this is to create a new model that represents our event data:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/15104fe8a159385e95499244215fdd06/href">https://medium.com/media/15104fe8a159385e95499244215fdd06/href</a></iframe><p>The first three fields will represent the entity being stored (in our case, the Product), and the last three will represent the aasm event, previous state and current state. The key to storing this event data in a generic way is to use the aasm <a href="https://github.com/aasm/aasm#extending-aasm">extensibility hooks</a> via the AASM::Base base class. The syntax for achieving this is somewhat complicated, but the concept is simple: when we save our model’s state to the database, we need to record the event along with our model’s attributes, our model’s previous state and our current state and store all of this in the database as a new immutable record. Our aasm extension injects a class level method enable_tracking! which enables this hook for a model. Take a look at the accompanying Github repository for the <a href="https://github.com/kontena/state-machine-events-example/blob/master/api/app/helpers/state_tracking.rb">gritty details</a>.</p><h4>Publishing Our Events</h4><p>If you looked at our aasm extension, you will see we are not only storing StateTransitionEvent&#39;s but also passing them to a class method EventBus.publish_event. This is the code responsible for serializing our event data and publishing it to our RabbitMQ topic exchange.</p><p>You can view the full source for this class <a href="https://github.com/kontena/state-machine-events-example/blob/master/api/app/services/event_bus.rb">here</a>, but for now we just want to look at the publish_event method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/178ea8f64c186ee69e552acdc3b06394/href">https://medium.com/media/178ea8f64c186ee69e552acdc3b06394/href</a></iframe><p>At a high level we can see we are building a routing key, serializing our event into a JSON payload, fetching a RabbitMQ channel from our connection pool and publishing our event on a topic exchange. The one thing that might appear strange here is the prefix parameter. This is some arbitrary string that, when present, is attached to the beginning of our RabbitMQ topic routing key. Topic routing keys work similar to dot-separated namespaces in many programming languages, so adding this prefix is similar to adding a top-level namespace to our routing key. This is useful later when we want to replay messages.</p><h4>Replaying Messages</h4><p>Why would we want to ever replay messages? One idea is, what if we want to add a new microservice to our system that intends on storing its own copy of our event data? Or, as in our <a href="http://blog.kontena.io/event-sourcing-microservices-with-kafka/">last blog post</a>, what if we want to always read all events at startup and store the data in-memory? In both of these cases, being able to request a replay of all events is necessary. Of course, replaying all events can also be dangerous. What if one of the other consumers is not properly coded to handle receiving very old messages? Not to mention our services will need to handle lots of replayed messages they are not actually interested in.</p><p>One solution to this problem is for each consumer to bind to two separate queues. The first queue is bound to the entities’ standard topic routing key, such as product.# for all product events. The second queue is bound to another routing key with a unique prefix for the consumer, something like my-consumer.product.#. That way, when our service requests the products service to replay all product events, we can pass in my-consumer as the topic prefix, which will replay every event in history but only consumers bound to the my-consumer topic prefix will receive the messages. Our other existing services will not have this topic binding and thus will not need to deal with them.</p><h3>The Demo</h3><h4>Installing</h4><p>All of this is much more fun when you can run some code and watch what it’s doing. For our demo, we will run our <a href="https://github.com/kontena/state-machine-events-example/blob/master/api/app/services/event_bus.rb">example application</a> in Docker containers on top of the Kontena Platform. The easiest way to get started is to create a new account at <a href="https://cloud.kontena.io/">https://cloud.kontena.io</a> and follow the steps create a new test Kontena Platform. Don’t worry, you can run this without spending a dime using our free credits when signing up.</p><p>In Kontena Cloud, make sure you have a Platform created along with one or more compute nodes attached. Once this is done, we are going to set up a RabbitMQ cluster. This is actually much simpler than it sounds thanks to our ready built <a href="https://github.com/kontena/kontena-stacks/tree/master/rabbitmq">RabbitMQ Kontena Stack</a> (note that this is basically the same stack running in production right now connecting all of Kontena Cloud’s backend services). From the integrated web terminal, run the following commands to create the necessary data volumes and install the stack:</p><pre>&gt; volume create --scope instance --driver local harbur-rabbitmq-cluster-seed-data</pre><pre>&gt; volume create --scope instance --driver local harbur-rabbitmq-cluster-node-data</pre><pre>&gt; stack install kontena/harbur-rabbitmq-cluster</pre><p>When prompted for the amount of nodes, set it to the amount of compute nodes you have created when you created your Platform.</p><p>Next, let’s install our demo application. This is also available as a public Kontena Stack:</p><pre>&gt; stack install kontena/state-machine-events</pre><p>Just as with RabbitMQ, make sure to enter the correct number of initial nodes you want to deploy to. Note that this can be less than the amount of nodes attached to your Platform but not more.</p><h4>Testing</h4><p>Let’s start with our basic little UI application. This is just some simple Javascript hosted by a simple node.js server, with <a href="https://socket.io/">socket.io</a> and <a href="https://expressjs.com/">express</a> for handling Websockets and HTTP, respectively. To view the UI, first go to the “nodes” tab in the Kontena Cloud UI, then in the “Config” section scroll down to get the public IP of one of the available compute nodes. Enter this IP into the browser. You should be greeted with a very sparse UI (basically it just says “Products” at the top).</p><p>To get some data in, we need to make an HTTP request to our API, also running on the same IP as our UI. I will assume you have access to the curl utility, but any HTTP tool (such as <a href="https://www.getpostman.com/">Postman</a> or <a href="https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/invoke-webrequest?view=powershell-5.1">Windows Powershell</a>) will work. Enter the following command, replacing $IP with the public IP from above:</p><pre>curl http://$IP/api/products</pre><p>You should get back an empty JSON array. Let’s create some data:</p><pre>curl -XPOST -H &quot;Content-Type: application/json&quot; -d &#39;{&quot;name&quot;:&quot;candy&quot;,&quot;price&quot;:100}&#39; http://$IP/api/products</pre><p>After running this, not only should you see a response from curl with your new product, but you should immediately see the new product on the UI, thanks to RabbitMQ and Websockets. Stuff like this is where a reactive event-driven backend really starts to shine!</p><p>Next, let’s try updating and deleting our product, watching the UI between commands (replace $ID with the product’s ID from the UI):</p><pre>curl -XPUT -H &quot;Content-Type: application/json&quot; -d &#39;{ &quot;adjust_inventory&quot;: 2 }&#39; <a href="http://$ip/api/products/$ID">http://$IP/api/products/$ID</a></pre><pre>curl -XPUT -H &quot;Content-Type: application/json&quot; -d &#39;{ &quot;adjust_inventory&quot;: -2 }&#39; <a href="http://$ip/api/products/$ID">http://$IP/api/products/$ID</a></pre><pre>curl -XDELETE http://$IP/api/products/$ID</pre><p>Finally, try closing the browser tab and opening a new one with the UI URL. The UI’s backend code requests an event replay as discussed earlier, ensuring the new page has all the existing event data. Take a look at the <a href="https://github.com/kontena/state-machine-events-example/tree/master/ui">UI code</a> to see how this works.</p><h3>Why use Kontena Cloud for your microservices?</h3><p>Setting up and maintaining a complex container platform like Kubernetes (or any of its derivatives) is not where the race is won. Building stuff on top of the platform is the only thing that matters and the best platform is the one you don’t even notice being there. Proprietary platforms like Amazon ECS might be easy but comes with serious restrictions.</p><p>If you are looking for a complete, developer friendly solution that is open source, extremely easy to use and works for everybody on any infrastructure, the Kontena Cloud is for you. So, that’s why! I hope you enjoyed this article. Looking forward to hear your feedback and comments!</p><p>Disclaimer: Unless you didn’t figure it out already, I work for Kontena :) And <a href="https://www.kontena.io/jobs">we are hiring</a>!</p><p><a href="https://kontena.io/">www.kontena.io</a>.</p><p>Image Credits: Blue cube design modern cube shape by <a href="https://pixabay.com/en/users/PIRO4D-2707530/">PIRO4D</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a54ae01b285" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kontenainc/event-driven-microservices-with-rabbitmq-and-ruby-7a54ae01b285">Event-Driven Microservices with RabbitMQ and Ruby</a> was originally published in <a href="https://medium.com/kontenainc">Kontena Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Event Sourcing Microservices with Kafka]]></title>
            <link>https://medium.com/kontenainc/event-sourcing-microservices-with-kafka-2568801527d8?source=rss-c99687836b88------2</link>
            <guid isPermaLink="false">https://medium.com/p/2568801527d8</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[apache-kafka]]></category>
            <category><![CDATA[event-sourcing]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[net-core]]></category>
            <dc:creator><![CDATA[Daniel Battaglia]]></dc:creator>
            <pubDate>Fri, 13 Oct 2017 13:30:44 GMT</pubDate>
            <atom:updated>2017-10-13T13:30:44.488Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O-tsrv0ZwoPMpF1Pls3iaA.jpeg" /></figure><p>Like many software engineers, I come from the world of enterprise software development. In this world design patterns and software architecture are king. I’ve spent countless hours studying the principals of <a href="https://en.wikipedia.org/wiki/Service-oriented_architecture">SOA</a>, <a href="https://en.wikipedia.org/wiki/Domain-driven_design">Domain Driven Design</a>, <a href="https://martinfowler.com/bliki/CQRS.html">CQRS</a> and all the wonderful enterprise architecture patterns laid out for us by <a href="https://martinfowler.com/eaaCatalog/">Martin Fowler</a>. One pattern that always struck me as both fascinating and fundamentally hard was <a href="https://martinfowler.com/eaaDev/EventSourcing.html">Event Sourcing</a>:</p><blockquote>Event Sourcing ensures that all changes to application state are stored as a sequence of events. Not just can we query these events, we can also use the event log to reconstruct past states, and as a foundation to automatically adjust the state to cope with retroactive changes.</blockquote><p>That sounds great and all but, how do we actually *use* this data? How do we query it? Where does it get stored? How do I manage the sequence of events on disk? Do I have one giant “events” table, or one table per event type? Is it centralized or does each service store it’s own events? And, examples of real world event sourced systems that could be studied were few and far between.</p><p>Meanwhile, over in Silicon Valley, the “Internet Companies” (Google, Netflix, Twitter, etc.) were busy trying to figure out, how do we make these applications scale to then-unprecedented levels of data and users? Sure, posting or consuming a 140-character Tweet might sound easy, but try making it work for a billion people, all at the same time. With realtime analytics. And fast responses. And no <a href="http://www.whatisfailwhale.info/">fail-whale</a>. On top of that, the act of developing software itself needed to be scaled as companies rushed to build up massive teams of engineers. From this side of the world we started to see the concept of Microservices, where a “monolithic” application is broken out into individual services that can be developed, hosted and scaled independently. The interesting thing about these Microservices, as an architectural pattern is, they actually start to look a whole lot like SOA and Domain Driven Design from the Enterprise.</p><p>During this time, engineers at LinkedIn created and open-sourced <a href="https://kafka.apache.org/">Kafka</a>. Kakfa is a high performance, distributed, immutable event log with a publish/subscribe style interface. And, as it turns out, this is exactly the missing link for Event Sourcing.</p><p>In the rest of this post, I’m going to describe a microservice application using Kafka as the primary data store. Please also head over to the accompanying <a href="https://github.com/kontena/eventsourcing-example">Github repository</a> for an example demo application code, along with a guide for setting it up yourself on your own Kontena Platform to try it out. Getting Kafka up and running might be easier than you think.</p><h3>The Scenario</h3><p>Let’s imagine an e-commerce application, which is a collection of microservices and some front-end application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*ykDO7m-OjTZAxZczqrYooQ.png" /></figure><p>We have services for managing Customers, Products and Purchases. Classic <a href="https://en.wikipedia.org/wiki/Domain-driven_design">Domain Driven Design</a> says that each of these are <a href="https://martinfowler.com/bliki/DDD_Aggregate.html">Aggregate Roots</a> and should manage their own data, storing only references (Ids, basically) to other aggregates. Of course, <a href="http://blog.christianposta.com/microservices/the-hardest-part-about-microservices-data/">microservices are supposed to own their own data</a>, and this is the key to why Domain Driven Design really comes into its own when working on a microservice architecture. Each microservice is just an Aggregate Root, hosted and deployed on its own.</p><p>So, we are keeping our aggregates separate, <a href="https://www.amazon.com/Domain-Driven-Design-Tackling-Complexity-Software/dp/0321125215">Eric Evens</a> is finally happy with us, and the world is now our oyster. That is, until it’s time for some complicated queries. Imagine an internal admin dashboard, which requires some page to show us all products purchased by customers, with some fancy search. We would need to make 3 different REST calls to 3 different services, and join that data in-memory. That might not sound too bad, but imagine what happens when we include just a few more services in that query. It gets ugly, fast.</p><h3>Materialized Views to the Rescue</h3><p>Hopefully you are already familiar with the concept of a <a href="https://en.wikipedia.org/wiki/Materialized_view">materialized view</a> in a relational database. In short, it is some query who’s results are stored on disk and/or memory as if they were a table of their own. And, if you really think about it hard enough, under the hood even a database table is just a materialized view of events written to the database’s <a href="https://en.wikipedia.org/wiki/Transaction_log">transaction log</a>, which stores all incoming changes as an append-only log. That transaction log sounds an awful lot like how Kafka works. If that sounds interesting to you, I highly recommend you read <a href="https://www.confluent.io/blog/turning-the-database-inside-out-with-apache-samza/">this fantastic article</a> by Martin Kleppmann which explains it far better than I ever could.</p><p>So, if we start thinking about Kafka topics as the transaction log of our microservices, what are the tables? We have a lot of flexibility here. Maybe we store our current state in an RDBMS. Or maybe in some denormalized form in a document database. Or, to take it to the extreme, how about in plain memory? Gasp, you say! What happens when we start a new instance of our microservice?! The trick is in the details of how Kafka works. Unlike more traditional pub/sub systems (think RabbitMQ or Redis), Kafka stores all of the messages it has received in a topic/partition with a sequential index , and it is up to the consumer to store this index and determine where they would like to start reading from (don’t worry, most of the Kafka client libraries make this easy to deal with). So, if you want to use Kafka like RabbitMQ, just always read from the end, getting new messages pushed to you as they come. But how about instead we always read from the beginning? That means, when our service starts up, we just replay every single event that has happened, building up our state until we are done. Once the messages have been replayed, we now how an in-memory representation of our aggregates, ready to be queried. And, what if, after processing these events and storing our aggregates, we now publish out <em>another</em> event, this time with the current state of our entity after business rules and other things have been applied.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*Bq2CM6b5ryHGuox0N16pZQ.png" /></figure><p>This second event contains the stream of entities our service exposes. Other services can subscribe to this topic and store their own version of this data as they see fit. For our scenario before, our frontend’s data store is just another materialized view of real business data. We can have nice fast local data access, and we can treat this data like a cache, ready to be rebuilt at any time from our event store.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*BDNyjPtr-E7A1JQHDFGYuw.png" /></figure><p>The thing to remember is to differentiate the types of events:</p><ol><li>Events that are the direct result of some user interaction or command. These events are your event source, and the related topics should be owned by only one service.</li><li>Events that are the result of a command, used to publish the current state of the service and its entities. These topics can be subscribed to by all interested parties, including possibly the microservice itself so that it can repopulate its own state quickly at startup.</li></ol><p>An interesting variation of this architecture is to use your favorite Actor framework (such as <a href="https://akka.io/">Akka</a> for JVM or .Net, <a href="https://github.com/celluloid/celluloid">Celluloid</a> for Ruby, etc.) where each Actor represents a single instance of your aggregate, possibly sharded across a cluster of service instances. As messages come in your service, they are sent to the appropriate actor based on the event’s key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*nYkXX5SWr1IruGGW2wdq8A.png" /></figure><p>Of course I’m painting a much simpler and rosier picture than the reality of a production system. There are a lot of valid questions that will come up when trying to build a system like this. Let’s try and tackle a few.</p><h3>Won’t I Run Out of Disk Space?</h3><p>Storing each and every event since the dawn of time can lead to some serious resource usage, especially hard disk space. Luckily, Kafka topics offer some fairly advanced data retention policies. For instance, we can say that a topic is capped at some amount of bytes, some length of time, or not capped at all. In addition, Kafka offers a particularly nice feature called <a href="https://www.linkedin.com/pulse/kafka-architecture-log-compaction-jean-paul-azar/">log compaction</a>. In a nutshell, log compaction allows us to always store the latest value in the topic for any given key. That way we can save disk space while still retaining the most recent version of a record. Of course this isn’t exactly perfect for event sourcing, which wants us to store all of the events. A nice tradeoff might look like this:</p><ol><li>Any topic that stores incoming events to a service, generally end-user commands, should be stored forever if possible. This is your event source.</li><li>As your microservice processes these events, applies business rules and updates the state of your aggregates, you publish out the current state of that aggregate to another Kafka topic. This topic can have a data retention policy using log compaction, and this is the topic that other services will consume to generate materialized views.</li></ol><h3>What About Consistency?</h3><p>The key here is <a href="https://en.wikipedia.org/wiki/Eventual_consistency">eventual consistency</a>. In a distributed system, this is just a fact of life. As your services asynchronously interact with one another via Kafka topics (or some other message passing transport), the service may have to validate this state itself. If issues occur, the service may need to publish a failure event that other services need to react to. In other words, your services may need to start asking for forgiveness rather than asking for permission.</p><h3>What About HTTP?</h3><p>Even without event sourcing, the question of HTTP and request/response often comes up when discussing asynchronous/reactive systems. If everything in my system is just asynchronously passing and responding to messages, how does my HTTP-based frontend handle this? My preferred option is to use websockets. You can still use a “normal” HTTP-based REST API for issuing commands to the server (say POST /shopping_cart), but that request will just trigger some asynchronous events and return some sort of transaction_id. The frontend can then show the user that something is happening, maybe a spinner or maybe just some notice somewhere on the page. In the back end, various status events could be published for this transaction as it is processed by your backend services. These event topics are subscribed to by your websocket server, which can associate the event with an active user and push the event down to the client.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*CCRQgnMsfhJa0itoKU6eOw.png" /></figure><p>The important concept to remember is, you need to not rely on your REST API’s response as the indication of a transaction being complete, only the indication that it has begun.</p><h3>Wrapping Up</h3><p>I hope that you found this write up of Event Sourcing and Kafka interesting. Remember to go to the Github repository to learn more about the demo application, and follow the steps so you can run it yourself and see all of the concepts in action. Until next time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2568801527d8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kontenainc/event-sourcing-microservices-with-kafka-2568801527d8">Event Sourcing Microservices with Kafka</a> was originally published in <a href="https://medium.com/kontenainc">Kontena Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>