<?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 Aziz Ghuloum on Medium]]></title>
        <description><![CDATA[Stories by Aziz Ghuloum on Medium]]></description>
        <link>https://medium.com/@aghuloum?source=rss-47d0a3e3e83------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_98ee_ii4V16zuq4k9DSqQ.png</url>
            <title>Stories by Aziz Ghuloum on Medium</title>
            <link>https://medium.com/@aghuloum?source=rss-47d0a3e3e83------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 11:54:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aghuloum/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[ES2. Building a Simple Event Store]]></title>
            <link>https://medium.com/@aghuloum/building-a-simple-event-store-98d7a804427?source=rss-47d0a3e3e83------2</link>
            <guid isPermaLink="false">https://medium.com/p/98d7a804427</guid>
            <category><![CDATA[database-design]]></category>
            <category><![CDATA[data-architecture]]></category>
            <category><![CDATA[event-sourcing]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <category><![CDATA[system-architecture]]></category>
            <dc:creator><![CDATA[Aziz Ghuloum]]></dc:creator>
            <pubDate>Mon, 29 May 2023 14:23:12 GMT</pubDate>
            <atom:updated>2023-05-29T14:27:58.697Z</atom:updated>
            <content:encoded><![CDATA[<p>In the first part of this tutorial, we explained what events are and what they are used for. Today, we are going to build a very simple implementation of an event store. The event store should satisfy the following requirements:</p><ol><li>Events should be durable (i.e., committed so disk, not in memory), immutable, and append-only.</li><li>All interactions with the event store should be through well-defined and minimalistic APIs.</li><li>The database, the API server, and the API client may be on different hosts (or containers).</li></ol><p>The APIs for the event store should provide methods for</p><ol><li>Inserting a new event: this operation must be idempotent in order to guarantee exactly-once semantics for insertion.</li><li>Querying the event store for the index of the last event inserted.</li><li>Getting a specific event by index.</li><li>Tailing the event store from a specific index so that we can process the events in real time as they happen.</li></ol><p>The following are out of scope for this tutorial but would need to be addressed at some point in the future:</p><ol><li>Security and access control to the APIs.</li><li>Backups and replication of the data stored.</li><li>Validation of the events data structures.</li></ol><p>So, let’s get started …</p><h3>PostgreSQL for Events Storage</h3><p>I pick PostgreSQL as the storage server for this tutorial for many reasons including: (1) it is free and open source, (2) it is extremely reliable and battle tested for decades, (3) it is familiar to most developers, and (4) it has subscribe/notify facility which will be tremendously useful for real-time event processing. The database is straightforward with exactly one table for events defined as follows:</p><pre>CREATE TABLE events (<br>  idx       bigint     not null primary key,<br>  inserted  timestamp  not null default now(),<br>  payload   jsonb      not null<br>);</pre><p>In order to do quick lookup on events by index, we need to create a separate index for the idx column:</p><pre>CREATE INDEX events_idx_index ON events(idx);</pre><p>Now in order for the events to be inserted sequentially and without gaps, we add a trigger that gets executed before each row is inserted. This trigger ensures that the idx provided for the new event is indeed the expected next index according to the events stored in the database.</p><pre>CREATE FUNCTION check_index() <br>   RETURNS TRIGGER <br>   LANGUAGE PLPGSQL<br>AS $$<br>BEGIN<br>   IF NEW.idx = (select coalesce(max(idx), 0) from events) + 1 THEN<br>     RETURN NEW;<br>   ELSE<br>     RAISE EXCEPTION &#39;invalid idx&#39;;<br>   END IF;<br>END;<br>$$;<br><br>CREATE TRIGGER check_index_trigger<br>  BEFORE INSERT ON events<br>  FOR EACH ROW EXECUTE PROCEDURE check_index();</pre><p>Finally we need to handle notifications. The idea here is to emit information about the event every time a new event is committed. To guard against programmer error for missing an event, the task of sending the notifications is performed via a trigger as follows:</p><pre>CREATE FUNCTION emit_event()<br>  RETURNS TRIGGER<br>  LANGUAGE PLPGSQL<br>AS $$<br>DECLARE payload text;<br>BEGIN<br>  payload = concat_ws(&#39;,&#39;,<br>    NEW.idx::TEXT,<br>    replace(NEW.inserted::TEXT, &#39; &#39;, &#39;T&#39;),<br>    NEW.payload::TEXT);<br>  IF length(payload) &gt;= 8000 THEN<br>    payload = concat_ws(&#39;,&#39;,<br>      NEW.idx::TEXT,<br>      replace(NEW.inserted::TEXT, &#39; &#39;, &#39;T&#39;));<br>  END IF;<br>  PERFORM pg_notify(&#39;event&#39;, payload);<br>  RETURN NEW;<br>END;<br>$$;<br><br>CREATE TRIGGER emit_event_on_insert<br>  AFTER INSERT ON events<br>  FOR EACH ROW EXECUTE PROCEDURE emit_event();</pre><p>For example, if we do insert into events (idx, payload) values (1, &#39;{&quot;msg&quot;:&quot;hello&quot;}&#39;::JSONB) , what we get is a notification on the channel event and with the following message:</p><pre>1,2023-05-27T16:30:32.282192,{&quot;msg&quot;: &quot;hello&quot;}</pre><p>Quirk: PostgreSQL restricts the size of the message to be sent to be strictly less than 8000 characters. If the event payload is too big, we may exceed that limit, and in that case, we send a notification message that includes the idx and the timestamp but without the payload. The program that listens for the events must be prepared to parse the message format and to handle the case of missing payload by issuing a separate SELECT query. In practice, most events are pretty small, in the 10s or 100s of bytes, but there are the rare occasions where the event data may be too big, and these are handled properly albeit less efficiently.</p><h4>Deploy it</h4><p>I have created github repositories for this tutorial under, well, <a href="https://github.com/event-sourcing-tutorial">https://github.com/event-sourcing-tutorial</a> project. To get started, you need to have docker and docker-compose already installed on your machine. Once installed, you need to do the following steps:</p><pre>$ mkdir event-sourcing-tutorial<br>$ cd event-sourcing-tutorial<br>$ git clone git@github.com:event-sourcing-tutorial/eventsdb.git<br>$ git clone git@github.com:event-sourcing-tutorial/deployment.git<br>$ cd deployment<br>$ echo &#39;EVENTSDB_PASSWORD=putsomethinghere&#39; &gt; .env<br>$ docker-compose up -d --build</pre><p>This should build and deploy your eventsdb container with PostgreSQL running and the tables of this tutorial initialized and ready to go.</p><h4>Test it</h4><p>From the terminal window, we start the psql client, listen for events, insert an event, and see the notification echoed back:</p><pre>$ docker-compose exec -u postgres eventsdb psql<br>psql (15.3 (Debian 15.3-1.pgdg110+1))<br>Type &quot;help&quot; for help.<br><br>postgres=# listen events;<br>LISTEN<br>postgres=# insert into events (idx, payload) values (1, &#39;{&quot;foo&quot;:&quot;bar&quot;}&#39;);<br>INSERT 0 1<br>Asynchronous notification &quot;event&quot; with payload &quot;1,2023-05-29T14:10:03.255323,{&quot;foo&quot;: &quot;bar&quot;}&quot; received from server process with PID 200.<br>postgres=# </pre><p>(Note that if you try to listen from another session, you will not actually see the notification until you issue the next SQL command. This happens because the psql client only polls the events and displays them at the end of each command sent. This is an implementation detail of how the psql client itself is implemented. In the next tutorial, we will see that notifications do get sent in real time. So, if you see psql not showing notifications, this is a psql issue. Things are fine.)</p><p>This article is part of a series of articles that I’m planning to write on event sourcing. I plan on diving deeper into (1) the concepts, (2) the systems-level implementations, and (3) the application-level details and programmer experience. If you have any questions or feel that a certain topic needs further elaboration, please feel free to ask.</p><p><a href="https://medium.com/@aghuloum/event-sourcing-background-information-ca113c632936">Part 1. Event Sourcing — Background Information</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98d7a804427" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Event Sourcing — Background Information]]></title>
            <link>https://medium.com/@aghuloum/event-sourcing-background-information-ca113c632936?source=rss-47d0a3e3e83------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca113c632936</guid>
            <category><![CDATA[data-architecture]]></category>
            <category><![CDATA[event-sourcing]]></category>
            <category><![CDATA[system-architecture]]></category>
            <category><![CDATA[database-design]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <dc:creator><![CDATA[Aziz Ghuloum]]></dc:creator>
            <pubDate>Tue, 23 May 2023 15:40:20 GMT</pubDate>
            <atom:updated>2023-05-29T14:29:11.643Z</atom:updated>
            <content:encoded><![CDATA[<h3>ES1. Event Sourcing — Background Information</h3><p>Over the last few years, I have been the chief architect of the Jumla platform which connected thousands of suppliers and consumers in the food industry. One of the key aspects of the design of Jumla was the adoption of event sourcing as the cornerstone of the architecture.</p><h3>What is Event Sourcing?</h3><p>Event sourcing is the organization of all of a system’s data as an append-only sequence of immutable events. An event denotes information about something that happened in the past. At first, there is nothing, then the first event happens, then the second, and the third, and so on, and so forth, until the end of time. Since events are about things that happened in the past, we cannot delete them, change them, or change their order.</p><p>Let’s take a simple example of an events type definition in Rust:</p><pre>enum Event { <br>  UserAdded {user_id: String, user_name: Option&lt;String&gt;},<br>  UserNameChanged {user_id: String, user_name: String},<br>  UserProfileUrlChanged {user_id: String, profile_url: String},<br>  UserRemoved {user_id: String},<br>}</pre><p>Just by looking at the type definition, we can probably infer that this is a system in which</p><ol><li>there are users who get added, possibly with a specified name, and</li><li>users are identified by their user id, and</li><li>each user has a name (optional) and a profile url (also optional), both of which can change over time, and</li><li>users eventually may get removed.</li></ol><p>Here is a possible sequence of events that can happen in a system, each expressed in a JSON record:</p><pre>{&quot;name&quot;: &quot;UserAdded&quot;, data: {&quot;user_id&quot;: &quot;user1&quot;, &quot;user_name&quot;: &quot;Alice&quot;}}<br>{&quot;name&quot;: &quot;UserAdded&quot;, data: {&quot;user_id&quot;: &quot;user2&quot;}}<br>{&quot;name&quot;: &quot;UserNameChanged&quot;, data: {&quot;user_id&quot;: &quot;user2&quot;, &quot;user_name&quot;: &quot;Bob&quot;}}<br>{&quot;name&quot;: &quot;UserProfileUrlChanged&quot;, data: {&quot;user_id&quot;: &quot;user2&quot;, &quot;profile_url&quot;: &quot;https://bob.example.com&quot;}}<br>{&quot;name&quot;: &quot;UserNameChanged&quot;, data: {&quot;user_id&quot;: &quot;user2&quot;, &quot;user_name&quot;: &quot;Bobby&quot;}}<br>{&quot;name&quot;: &quot;UserRemoved&quot;, data: {&quot;user_id&quot;: &quot;user1&quot;}}</pre><p>Note that we are only explaining the concept, not the implementation, of event sourcing. What is important is that the events are recorded in a durable immutable storage and that they can be retrieved sequentially in the order in which they were added.</p><p>Event sourcing does not mean that we have to let go of a relational database model. On the contrary, event sourcing can be used to populate the data in a relational model. By reading the events sequentially, and performing certain rules associated with each event type, one can build the database, from scratch, using the events that were recorded.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/185/1*5l01pQ9-sTVBUjfgKWqK0A.png" /><figcaption>In an event sourcing system, the events exist separately from the database and the data in the database is derived purely from the events.</figcaption></figure><h3>Why Event Sourcing?</h3><p>When designing a brand new system, it is often the case that the full requirements of the system are not known in advance. In the case of Jumla, we were to build the platform with minimal features (an MVP) that are known at the beginning, but the system had to be flexible enough to accommodate all yet unknown future features.</p><p>Traditionally, and as I have taught in university courses in the past, one would start with taking the functional requirements of the system and translating them into a relational database schema. Cool, but what happens tomorrow when the requirements change? What if the changes happen on daily basis? How do you rapidly implement these changes with no downtime and without losing any data?</p><p>System evolution is a hard problem using a traditional relational databases. When the database schema changes, we often write one-shot migration scripts. A migration script may be written in SQL or in any other language. The purpose of the migration script is to create, alter, or drop tables from the database, and move data around. Once the migration script is run to completion, one would just hope that all went well and that no data is lost or corrupted. This is very problematic even if the migration script was heavily tested on non-production data. To restate Murphy’s law: if you keep on doing migration scripts, eventually one will go wrong.</p><p>With event sourcing, the problem of system evolution is solved in a totally different way. Instead of modifying the production database A, what we do is build a new database B from scratch. Database B exists separately from, and in parallel to, database A.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/1*avbrEZ2LOWSHFfBK8Ija6g.png" /><figcaption>Two databases are built in parallel using the same set of events.</figcaption></figure><p>What event sourcing gives us is the ability to do A/B testing on the primary production database. If the new processing rules (B) are deployed and they produce the desired database (B), we can swap A and B and voila, we have migrated the database to the new system. If, on the other hand, the new processing rules were found to be erroneous, and they did not produce the desired outcome, the database B can be dropped, completely, then the rules are fixed and the cycle repeats. There is never any danger of corrupting the database because the events themselves are immutable.</p><h3>Other advantages?</h3><p>The section above highlights the main advantage of using event-sourcing; one that sold me on events as a core architectural foundation for Jumla. There are other advantages of course and they may be equally important. These advantages include:</p><ol><li>Events are processed in real-time leading to an overall real-time system.</li><li>All database records are annotated with information about the events that made them what they are, leading to getting record audits for free.</li><li>One can process events up to a certain point in time, and observing the state of the system at that time. The database is a “time-machine”</li><li>Deriving new data and information that are not conceived in the original design.</li></ol><p>This article is the first of a series of articles that I’m planning to write on event sourcing. I plan on diving deeper into (1) the concepts, (2) the systems-level implementations, and (3) the application-level details and programmer experience. If you have any questions or feel that a certain topic needs further elaboration, please feel free to ask.</p><p><a href="https://medium.com/@aghuloum/building-a-simple-event-store-98d7a804427">Part 2: Building a Simple Event Store</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca113c632936" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>