<?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 Jordan TEMIM on Medium]]></title>
        <description><![CDATA[Stories by Jordan TEMIM on Medium]]></description>
        <link>https://medium.com/@jordan-temim?source=rss-217b37966742------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dW1mjg6xc9JjOfizSk1eGQ.jpeg</url>
            <title>Stories by Jordan TEMIM on Medium</title>
            <link>https://medium.com/@jordan-temim?source=rss-217b37966742------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 08:20:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jordan-temim/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[Observability: from detection to understanding]]></title>
            <link>https://medium.com/@jordan-temim/observability-from-detection-to-understanding-a98d2ee1fe4f?source=rss-217b37966742------2</link>
            <guid isPermaLink="false">https://medium.com/p/a98d2ee1fe4f</guid>
            <dc:creator><![CDATA[Jordan TEMIM]]></dc:creator>
            <pubDate>Sun, 01 Feb 2026 15:06:34 GMT</pubDate>
            <atom:updated>2026-02-01T19:50:52.593Z</atom:updated>
            <content:encoded><![CDATA[<h3>Behind the scene</h3><p>As systems grow more complex, understanding what is happening becomes harder than simply detecting that something is wrong. Observability helps bridge that gap.</p><p>When an incident occurs, resolution time quickly becomes critical. The DORA metrics, and especially <strong>MTTR (Mean Time To Recovery)</strong>, highlight this impact well. But behind this global measure lies a more granular reality: incident resolution is a sequence of steps, each with its own time.</p><p>This process can be seen as a resolution <strong>lead time</strong>, made up of several <strong>touch times</strong>: defect detection, diagnosis, fix, deployment, and monitoring. From a <strong>lean</strong> perspective, the goal is not to work faster everywhere, but to reduce unnecessary time across the resolution process.</p><p>In many systems, fixing the issue and deploying the change are relatively well controlled. What often proves more complex is the phase between detection and diagnosis. Teams know that a problem exists, but understanding what is actually happening can take time.</p><p>This is where observability comes into play. It does not replace detection or diagnosis. It helps bridge the gap between the two by providing context and actionable signals when they matter the most.</p><p>Monitoring plays an essential role here. Through predefined signals such as metrics, thresholds, and alerts, it is very effective at answering known questions and detecting that something is wrong.</p><p>Detection is only the starting point. When behavior does not match expectations, teams need to explore their systems, ask new questions, and connect signals.</p><blockquote>Monitoring tells you that something is wrong. Observability helps you understand what is wrong and why.</blockquote><figure><img alt="Defect resolution" src="https://cdn-images-1.medium.com/max/1024/1*9uax0y3MBWuIEIiGUHleDQ.png" /><figcaption>Defect resolution</figcaption></figure><h3>What observability really brings</h3><p><strong>Understanding</strong> is the key, and that changes how teams approach incidents.</p><p>On the technical side, it helps teams move faster from observation to understanding. With correlated signals and proper context, teams spend less time jumping between tools and trying to connect things together.</p><p>But this value goes beyond engineering.</p><p>From a product perspective, better understanding incidents makes it easier to assess real user impact. Not all issues affect users in the same way. Some are highly visible, others barely noticeable. Observability helps connect technical signals to actual user behavior, which leads to better prioritization and clearer trade-offs.</p><p>From a business point of view, the impact is often less direct, but still very real over time. Less uncertainty usually means lower MTTR, fewer visible disruptions, and more confidence in the system. That makes decision making easier, both during incidents and when evolving the product.</p><p>In the end, observability is not just a diagnostic tool. It helps teams stay in control of complex systems, learn faster, and act with more confidence.</p><h3>The technical pillars of observability</h3><p>Observability is often described through three main pillars: <strong>logs, metrics, and traces</strong>. It’s not a strict rule, but it’s a useful way to think about how teams observe their systems.</p><p><strong>Metrics</strong> provide a high level view. They help track trends, detect anomalies, and quickly answer questions like <em>“is the system behaving normally?”</em>.</p><p><strong>Logs</strong> bring context. They describe what the system is actually doing, step by step. When something unexpected happens, logs are often what helps teams understand what occurred, with which data, and under which conditions.</p><p><strong>Traces</strong> help follow a flow end to end. In distributed systems, a single request often goes through multiple services. Traces make that path visible, showing where time was spent and where things started to go wrong.</p><p>Individually, each of these signals is useful. But observability comes from their <strong>combination</strong>. Metrics help with detection, logs with understanding, and traces with connecting the dots.</p><p>The goal is not to collect everything, but to <strong>have the right signals available at the right time</strong>, so teams can answer the questions that arise when systems don’t behave as expected. We’ll come back to this later with a tool called OpenObserve.</p><figure><img alt="Three pillars of observability" src="https://cdn-images-1.medium.com/max/1024/1*0gkK595jtbTY05gzquxsww.png" /><figcaption>Three pillars of observability</figcaption></figure><h3>The human pillars of observability</h3><p>How observability is implemented depends heavily on context. But beyond tools and architecture, it is mostly about ways of working, closely aligned with DevOps thinking: understanding the business before instrumenting the technology.</p><p>When working on <strong>new systems or products</strong>, observability is easier to introduce, but the same traps still exist. The most common one is starting with the <em>how</em>: which tools to use, which metrics to collect, which dashboards to build. A good way to start is to bring together all the different people involved right from the beginning, which is not always easy in practice.</p><p>This is where the conversation between <strong>product</strong>, <strong>developers</strong>, and <strong>ops </strong>becomes essential. Product brings an understanding of user behavior and business value, developers understands how the system behaves internally, and ops know where issues actually surface. It is this shared view that helps identify what should be observed and measured.</p><p>Around the feature being built, these discussions help answer simple but structuring questions: <em>what absolutely needs to work?</em>, <em>What signals will tell us the feature behaves as expected?</em> and <em>What will help us understand issues quickly when something goes wrong?</em></p><p>Only after that does the question of <em>how</em> come into play. Logs, metrics, and traces become tools that support shared understanding, not goals in themselves.</p><p>In that context, observability plays a key role. It helps turn unexpected behavior, incidents, or deployments into actionable signals, and improves system understanding over time.</p><p>With <strong>legacy systems</strong>, the dynamic is different: teams have to work with existing constraints and usually move incrementally. Each incident becomes an opportunity to add context and improve understanding.</p><p>Observability is not something you ever “finish”. It is a capability that evolves with the product, the system, and the teams.</p><h3>Observability in practice</h3><p>Tools like <strong>Datadog</strong> are probably among the best options on the market today when it comes to monitoring and observability. They offer a very broad range of features, from signal collection (logs, traces, metrics, and more) to incident management and on-call capabilities.</p><p>One of Datadog’s key strengths lies in its highly polished user experience and in how the different parts of the platform work together.</p><p>In this chapter, I will introduce an open-source tool I use for a personal side project: <strong>OpenObserve</strong> (also available in a cloud version).</p><p>OpenObserve is based on <strong>OpenTelemetry</strong>, an open-source observability framework that enables teams to collect signals (logs, metrics, traces) in a standardized way.</p><p>The goal is not to compare the two tools: Datadog covers a much broader scope. Instead, the aim is to use examples to show what can realistically be put in place to build truly usable observability for applications, in line with the human organization mentioned earlier in this article.</p><p>In practice, I mainly use <strong>OpenObserve</strong> for exploration. Exploring logs with proper context, moving between different signals, and reconstructing what actually happened when unexpected behavior occurs. What matters most is not data volume, but the ability to ask questions and iterate quickly.</p><p>Views and queries evolve alongside the product. Some metrics appear because an incident made them necessary. Some logs get enriched later, once it becomes clear that certain context was missing to understand a situation.</p><blockquote>Observability is built this way, incrementally, through real usage.</blockquote><p>This is also where the tool becomes a support for discussion. Screens are not only for engineers. They help product, engineering, and ops share a common understanding, based on observable facts rather than assumptions.</p><p>My goal is not to describe my side project, but I can, for example, create “themes” in my app. Here’s what it looks like on OpenObserve:</p><h4>Homepage</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xMe4q0oysTIcE3khVBBgrw.png" /><figcaption>OpenObserve homepage</figcaption></figure><h4>Logs</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dAsCF3iw-_e3aNhCDwHocQ.png" /><figcaption>OpenObserve logs</figcaption></figure><h4>Detailed log</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GHFm1G2JtAMXSiB8L6k1PA.png" /><figcaption>OpenObserve detailed log</figcaption></figure><h4>Simple dashboard</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wpuVqh1W681SBrgT3HhcGg.png" /><figcaption>Simple dashboard</figcaption></figure><p><strong>Logs retention configuration:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uT0jVPhSjL_8qW89EmpAeA.png" /><figcaption>Logs retention configuration</figcaption></figure><h3>Conclusion</h3><p>Observability is not a tool, a checklist, or a final state to reach. It is a way of thinking about the systems we build and operate.</p><p>It relies as much on technical choices as on human practices. Understanding what matters most for the product, embracing system complexity, and learning when unexpected behavior appears.</p><p>In practice, observability is built over time. It evolves with the product, with real usage, and with the incidents teams face. Each new signal, each enriched log, and each question asked helps reduce uncertainty the next time something goes wrong.</p><p>In the end, observability is not about seeing everything. It is about enabling teams to understand better, make calmer decisions, and stay in control of increasingly complex systems.</p><p>If you liked this article don’t hesitate to applaud it! Thank you.</p><h3>Sources and beyond</h3><ul><li><a href="https://about.gitlab.com/topics/devops/">https://about.gitlab.com/topics/devops/</a></li><li><a href="https://github.com/openobserve/openobserve">https://github.com/openobserve/openobserve</a></li><li><a href="https://martinfowler.com/articles/domain-oriented-observability.html">https://martinfowler.com/articles/domain-oriented-observability.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a98d2ee1fe4f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I use Merise to create ready to scale databases]]></title>
            <link>https://medium.com/@jordan-temim/how-merise-help-me-to-create-ready-to-scale-databases-bc3e9bb27406?source=rss-217b37966742------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc3e9bb27406</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[scaling]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <dc:creator><![CDATA[Jordan TEMIM]]></dc:creator>
            <pubDate>Sun, 04 Dec 2022 15:32:21 GMT</pubDate>
            <atom:updated>2024-07-20T12:37:21.454Z</atom:updated>
            <content:encoded><![CDATA[<h3>Behind the scene</h3><p>Nowadays, most developers no longer consider the persistence layer to be the foundation of an application but rather a data storage space that interacts with services.</p><p>Modeling is badly resented (when it is practiced), and ORMs are legion to allow interaction with this obscure layer that would no longer be part of the developer’s job according to some.</p><p>I am not against the use of ORMs, I use them myself in my applications. However, I don’t give them the keys to my databases and I use them for what they know best: non-complex CRUD operations. For everything else, I prefer to write my own SQL queries and use a SQL migration tool when I need to create or modify structures (like Flyway in Java, Active Record in Ruby, etc.).</p><h3>Sick applications</h3><p>For about ten years, I have seen sick applications, kept alive on life support, making the task of developers and products more and more difficult and expensive.</p><p>Whether these applications are recent (less than a year old) or rather legacy, I regularly see the same symptoms:</p><ul><li>Slow APIs (&gt; 80ms for an aggregate GET),</li><li>Models that are difficult to maintain,</li><li>Complexity related to database modeling and not to the business,</li><li>Patchwork databases,</li><li>Duplication of data,</li><li>Unexplained denormalization.</li></ul><p>In this article I will first explain how I use the Merise method to perform very rigorous database modeling.</p><p>I will then show how this rigor allows me to be serene throughout the life of an application, even when the scale pushes me to split my monolith into microservices.</p><p>I will use Domain-Driven Design (DDD) concepts, but this article is not intended to describe it, so I won’t go into the details of this approach.</p><blockquote>If you have technical “if” in your application that are not related to business cases, then you have a sick application.</blockquote><h3>From boostrap to scale</h3><p>In most cases, the subject of the persistence layer scale is often put aside, if not discredited altogether.</p><p>In recent years I have seen three main strategies when creating a tech startup, here is a roundup:</p><h4>1/ The disposable MVP</h4><p>The MVP only serves to test the product-market fit. If it is successful, we agree to throw away what has been done before and start writing a v1.</p><p>This strategy will slow down the startup in its acquisition phase because it will require a redesign from scratch and a data migration if the product meets its market.</p><h4>2/ Microservices ahead of time</h4><p>The split into microservices is designed from the start.</p><p>This strategy leads to two problems:</p><ul><li>It takes the application away from the FUC (First Use Case) of our MVP and requires a design of features whose needs are not yet a priority,</li><li>It throws the company into a potential division into squads which is not at all on the agenda and which will drive future recruitments (CONWAY’s law).</li></ul><h4>3/ The pre-cut monolith</h4><p>This solution, very elegant, allows for a monolith connected to several business databases.</p><p>In fact, a monolithic application will communicate with several databases, each of which will have its own perimeter (for example, one for user perimeter, another billing, etc.).</p><p>This is an interesting proposal, but there are two caveats:</p><ul><li>This solution can bring complexity to combining the information from the two databases, which makes the work of the Data Engineer less easy,</li><li>Some projects foresee a future that will never happen and continue with several databases and a monolith for several years. The result: longer development times with no real added value.</li></ul><h4>My suggestion: the scalable MVP</h4><p>Spoiler alert: this is the strategy that this article aims to explain through the Merise method.</p><h3>The Merise method</h3><h4>Introduction</h4><p>Merise is a method derived from systemic analysis, created by Hubert TARDIEU’s team in France in the 1970s.</p><p>The French Ministry of Industry used it as an operational project to manage the large-scale IT projects it was going to launch to modernize the country (railroads, tax collection, National Electricity Company, etc.).</p><p>The Merise method is based on the sequence of 3 cycles: the abstraction cycle, the approval cycle, and the life cycle.</p><p>Progressively challenged by SSADM, Axial or more recently UML for system modeling, this method remains a reference for the abstraction cycle related to database modeling.</p><p>Personally, I started to use it in 2016 for my modeling and I never stopped since.</p><h4>The Levels</h4><p>The Merise abstraction cycle defines three levels of models:</p><ul><li><strong>The Conceptual Data Model</strong> (CDM, or MCD in French) focuses on invariants from a business point of view. This is where we talk about entities and relationships. This first level is based directly on the work of Peter CHEN at the end of the 1970s on the Entity-Relation Model (ER Model),</li><li><strong>The Logical Data Model</strong> (LDM, or MLD in French) which concerns the organization. This is where we will have the exhaustive list of the database tables to create,</li><li><strong>The Physical Data Model</strong> (PDM, or MPD in French) which defines concretely how the system will be produced. This is where we will choose the database engine or create our DDL (Data Definition Language).</li></ul><h4>Use Case</h4><p>Through a simple example I will progressively make a database more complex to allow new business needs to be integrated in an application.</p><p>This example will be intentionally simple and reduced: the purpose of this article is not to discuss the features embedded in this application but to take it as an excuse to model our database with Merise.</p><h3>The MVP</h3><p>Batch 1 of the application will be my MVP.<br>It should allow me to test the market.</p><p>The project consists in creating a Spotify / Deezer like application.</p><p>The business defines in First Use Case (FUC) the features related to the <strong>search and play of music</strong> by the user.<br>We will not go into the technical part of the music player, we will only focus on the search.</p><p>As a reminder, in this article I will take shortcuts on purpose.</p><p><strong>Here are the business rules for managing the MVP of my application:</strong></p><ul><li>A song can have one or more artists,</li><li>A song belongs to only one album,</li><li>An artist can have written zero or more songs,</li><li>An artist can have created one or more albums.</li></ul><h4>The Business Data Dictionary</h4><p>Long before the definition of DDD by Eric Evans in 2003 and the Event Storming workshops, the Merise method proposes to bring together the different stakeholders around the table to ensure a common vocabulary.</p><p>This common vocabulary is called the <strong>Business Data Dictionary</strong>:</p><ul><li>It relates to all the data that will be stored (business objects),</li><li>It details the properties,</li><li>It is based on the business rules and only these,</li><li>It must only concern elementary data (not calculated, not composed),</li><li>It can include technical and functional elements.</li></ul><p>Here is an example of a Business Data Dictionary for our Batch 1 concerning the song business object:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a_ZII-0nYeEXAsErPrthIQ.png" /><figcaption>Exemple of a Business Data Dictionary.</figcaption></figure><p>For our first batch, we identify the business objects <strong>Song</strong>, <strong>Artist</strong>, <strong>Album</strong>.</p><h4>The CDM</h4><p>If we use the business rules defined above, we can create the following CDM:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*abU2wcMfV_gSW-nsutmqiw.png" /><figcaption>CDM of the MVP.</figcaption></figure><p><strong>Let’s take a moment to understand this diagram:</strong></p><ul><li>The entities are described in blue: they are our business objects,</li><li>Relationships are in orange, they describe an action linking the business objects (most of the time it is a verb),</li><li>The cardinalities link the entities and the relations.</li></ul><p><strong>How to read this diagram?</strong></p><ul><li>A song can be written by one or more artists (1,N),</li><li>An artist can have written zero or more songs (0,N).<br>Etc.</li></ul><p>Do you notice how easy it is to find our management rules simply by reading this CDM? That’s the whole point of going through these different levels in the Merise method!</p><h4>The transformation rules in LDM</h4><p>We have our first Merisian diagram, describing the interactions that our business objects have with each other.</p><p>The next step is to transform our CDM into a LDM by respecting 5 transformation rules:</p><p><strong>1/ Conversion of entities:<br></strong>a) An entity of the CDM becomes a table,<br>b) Its identifier becomes the Primary Key (PK)of the table,<br>c) The other properties become the attributes of the table.</p><p><strong>2/ Conversion of OneToMany relations (X,1 — X,N):<br></strong>This relationship has the maximum cardinalities positioned at “1” on one side of the relationship and “N” on the other side. It results in the creation of a Foreign Key (FK) in the relationship corresponding to the entity on side “1”. This FK refers to the PK of the relationship corresponding to the other entity.</p><p><strong>3/ Conversion of OneToOne relations (X,1 — X,1):<br></strong>This relationship has the maximum cardinalities positioned at “1” on both sides of the relationship. It results in the creation of a FK in the relationship corresponding to the entity you want. This FK refers to the PK of the relationship corresponding to the other entity.</p><p><strong>4/ Conversion of ManyToMany relations (X,N — X,N):<br></strong>This relationship has the maximum cardinalities positioned at “N” on both sides of the relationship. It results in the creation of a relationship whose PK is composed of the FK referencing the relationships corresponding to the entities linked by the relationship. The possible properties of the relation become attributes of the relation. The relation that has become a table takes the name of the two other tables to indicate that it is a linking table (<em>table1_table2</em>).</p><p><strong>5/ (1,1 — 1,1) relationship should not exist:<br></strong>If so, there must be another way to model the requirement (by merging the two entities for example).</p><h4>The LDM</h4><p>Starting from the transformation rules, we try to create a DDL allowing us to create all our tables.</p><p>To represent our modeling graphically, we use a very good advanced ER diagram tool called <a href="https://azimutt.app/">Azimutt</a> in which we import this DDL.</p><p>Here is what we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bA8G4gWi4Sak-7vAC1ZLPw.png" /></figure><p>Several comments at this point:</p><ul><li>We want to avoid circular references, but be careful not to confuse them with loops in our diagram!<br> — So how do we know if we are in the case of a circular reference?<br>When you have a loop in a diagram, you just have to try to create the tables one by one (<em>song</em>, <em>artist</em>, <em>album</em>, then the linking tables <em>artist_song</em> and <em>artist_album</em>): if you succeed, you are not in a circular reference. If, on the other hand, two tables are dependent on each other and you can’t create one before the other, then you are in the case of a circular dependency to be avoided at all costs. A good way to remember this is to think of the chicken and the egg.</li><li>The fourth rule of transformation from <strong>CDM</strong> to <strong>LDM</strong> leads us to create the linking tables <em>artist_song</em> and <em>artist_album</em>. Linking tables should always be seen as facilitators. We could make the <em>artist_album</em> table optional and navigate from an artist to an album via the <em>artist &gt; artist_song &gt; song &gt;</em> album tables. However, this is not what we want for the performance of our application.</li></ul><h4>The normal forms</h4><p>The work related to normal forms was introduced by CODD in the 70’s to avoid transactional anomalies. The Merise method uses this work.</p><p>There are different levels of normalization (or normal forms).<br>The first three levels of normalization are the most widespread and the most applied.</p><p>The classification of these first three normalization levels is based on the functional dependencies between the Primary Key of the relation and its other attributes.</p><ul><li><strong>1NF: </strong>A table is in 1NF if and only if, at the intersection of a row and a column there is only one value, never a collection of values.<br>Violation of the first normal form is one of the most important plagues in relational databases and has catastrophic consequences in terms of performance.<br> — Example not respecting the 1NF in a table:<br>A column with an email list “{<a href="/service/mailto:foo@bar.com">foo@bar.com</a>, <a href="/service/mailto:bar@foo.io">bar@foo.io</a>}”.</li><li><strong>2NF: </strong>A table is in 2NF if and only if it is in 1NF and all the columns which do not participate in the primary key are dependent on the primary key.<br> — Example not respecting the 2NF in a table:<br>A column representing a calculated field, because not dependent on the id but on one or more other data (a price with the calculated VAT for example).</li><li><strong>3NF: </strong>A table is in 3NF if and only if it is in 2NF and the columns that do not participate in the primary key are mutually independent. The columns have no functional dependencies between them.<br> — Example not respecting the 3FN in a table:<br>In a table representing an order, a column with a product reference and another column representing the product name, dependent on the product reference. This table should only contain the reference. The product name should be in a table specific to items.</li></ul><blockquote>By respecting these normal forms, we ensure that we never compromise with the data inserted in our databases!</blockquote><h3>The v1</h3><p>Congratulations!</p><p>The MVP is in production and the first customers are coming: we have just validated our product-market fit.</p><p>New features are starting to enter in the product backlog, and we are starting to think about new business objects.</p><p>Don’t panic: we have created our original model thanks to the Merise method, we are confident to build the v1 of the product.</p><p><strong>Here are the new business rules for the v1 of the application:</strong></p><ul><li>A user can follow artists,</li><li>A user can like songs,</li><li>A user can create playlists containing songs.</li></ul><p>We will go quickly through the following steps as they have already been described above.</p><h4>The CDM (again)</h4><p>We voluntarily choose to consider artist tracking and song liking as relationships: indeed, the current product need does not require us to be able to create sub-elements.</p><p>Our modeling must reflect what is required at a given moment, and not what could happen in a hypothetical future. We trust the Merise method to allow us to make the right evolution when the need arises.</p><p>We therefore consider the following new business objects: <strong>User</strong>, <strong>Playlist</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f2ALt0CWI-FhCjlGd6uipQ.png" /><figcaption>CDM of the v1.</figcaption></figure><h4><strong>The LDM (again)</strong></h4><p>Here is what we get after transformation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eVd-swxtqAs2oSxB4ea5Pw.png" /></figure><p>As expected, the <em>bookmark</em> and <em>user_artist</em> tables are linking tables, while <em>playlist</em> is a table in its own right with its own Foreign Key. We also notice the creation of a table <em>song_playlist</em> between the business object <strong>Playlist</strong> and <strong>Song</strong>.</p><h3>The microservices</h3><p>Voilà, our v1 is successful, and we start to feel the limits of the current architecture.</p><p>Our monolith is working, but it is now necessary to scale the instances (either horizontally or vertically).<br>A fine analysis of the traffic with an APM allows us to see that only 20% of the code base is coughing, while we scale 100% of it every time we want to support the overload.</p><h4>The bounded context</h4><p>As mentioned above, the approach that we are implementing is based on the application’s business domains and on the DDD approach.</p><p>We will divide our application into coherent bounded contexts, and these will drive the nature of our future microservices.</p><p>If we resume our database modeling, we can imagine the following three bounded contexts in a very basic way: <strong>Music</strong>, <strong>Artist</strong>, <strong>User</strong>.</p><p>It’s time for us to split our monolith into three microservices.</p><h4>The cutting</h4><p>The cutting is as follows:</p><ul><li>We define the microservices by their bounded context and we identify their points of contact between them,</li><li>We create a new database per microservice,</li><li>Each business table becomes a RESTFUL resource, exposed via endpoints,</li><li>The linking tables are not directly exposed in the API: we therefore remove the constraints related to the Foreign Keys which are in external databases.</li></ul><p>Here’s what we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5cthQfH05MWA34GBmpUruQ.png" /><figcaption>Database Driven Microservices.</figcaption></figure><p>Of course, this split is very arbitrary, I chose for example to put the playlist information in the user database.</p><p>As you can see, this approach is <strong>data first, not service first</strong>.</p><p>The next step is to iterate on each of the databases, following the Merisian logic <em>CDM &gt; LDM</em> each time we want to make our model evolve.</p><blockquote>The data is what I am trying to achieve and the code is the way to get there, not the contrary!</blockquote><p>If you liked this article don’t hesitate to applaud it! Thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc3e9bb27406" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ruling the Event-Driven Architecture with RabbitMQ]]></title>
            <link>https://medium.com/@jordan-temim/ruling-the-event-driven-architecture-with-rabbitmq-534798bdf17e?source=rss-217b37966742------2</link>
            <guid isPermaLink="false">https://medium.com/p/534798bdf17e</guid>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[event-notification]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <dc:creator><![CDATA[Jordan TEMIM]]></dc:creator>
            <pubDate>Thu, 20 Jan 2022 22:24:51 GMT</pubDate>
            <atom:updated>2024-04-27T08:46:06.867Z</atom:updated>
            <content:encoded><![CDATA[<h3>Behind the scene</h3><p>Everyone has encountered that moment when the system becomes so big that it is difficult to cut it up and the services become dependent on each other.</p><p>Moreover, as CONWAY’s law explains it well, some services are in fact only representations of functional domains, which can make their contact areas more complex.</p><p>When you have twenty or so services that communicate with each other, no matter how well sliced up and mono-responsible they are, complexities inevitably arise when you chain calls.</p><p>After more than ten years spent in development and architecture, I had to implement complex or basic architectures depending on the systems I was working on.</p><p>Event-Driven Architecture (EDA) is one of these.</p><h3>Event-Driven Patterns</h3><p>In accordance with the work of Martin FOWLER on the subject, we can define 4 patterns in Event-Driven Architecture:</p><ul><li>Event Notification,</li><li>Event-Carried State Transfer,</li><li>CQRS,</li><li>Event-Sourcing.</li></ul><p><strong>Event-Sourcing</strong> is probably the most well-known pattern for setting up a distributed Event-Driven system.</p><p>One of its greatest strengths lies in the fact that at any time it is possible to audit the entire system at a given moment since all state changes are recorded in an event store.</p><p>Besides that, this pattern has several problems that can be complex to deal with. Let’s mention some of them:</p><ul><li>The source of truth of the whole system becomes the place where the events are recorded, which can have a side effect on the <strong>data consistency</strong> when they are also persisted in business databases,</li><li>Access to the event store can be complex as it is often designed to support a heavy load and is therefore rarely easy to manipulate,</li><li>The content of the event store can be considered as a list of changes (past) or a list of states (current) depending on the need,</li><li>The replay of events is often complex because it is subject to successive interactions between external bricks, and dependent on each other.</li></ul><h3>Focus on the Event Notification</h3><p>As said, the EDA proposes to strongly decouple the interactions between services when possible.<br>Generally speaking, any call that can be asynchronous will be eligible for an event.</p><p>In this article, I’m going to set up a centralized system allowing all the services of a system to benefit from asynchronous discussions between them via Event-Driven. I’ll use the Notification pattern.</p><blockquote>What I particularly like about the Event Notification approach is that it can be implemented on legacy services.</blockquote><p>The principle of Event Notification is to notify of a change or more globally that a significant event has occurred on a domain.</p><h4>Task VS Event</h4><p>First of all, it is important to clarify what an event is, regarding other actions that can be performed asynchronously and which are not events.</p><p>If we want to treat a precise and well-identified need in an asynchronous way, it’s a Task.<br>Tasks represent <strong>actions</strong>, for example sending an email asynchronously or inviting a person to a meeting asynchronously.</p><p>On the contrary, events are to be considered as <strong>notifications </strong>sent in a distributed way.<br>In Event Notification, it can be a complex message (a Data Transfer Object for example) or a simple boolean.</p><p>A Task knows what action will be performed with the sent message whereas an event does not know how its message will be consumed: its only purpose is to notify, no matter who consumes the message behind it and for what reason.</p><p>It is then easy to understand that in a distributed system, <em>n</em> services can subscribe to a specific notification and process the message the way they want it.</p><p>In Kafka, we usually talk about Request VS Event.</p><h4>Advantages of Event Notification</h4><ul><li>Possible implementation on legacy: Event Notification can be easily implemented on a set of existing services, without compromising existing responsibilities.</li><li>Clear definition of the source of truth: unlike event sourcing, which we have just briefly discussed, event notification does not raise questions about the source of truth: each business application keeps its own database, which is the only source of truth.</li><li>High level of decoupling: the use of event allows the source not to worry about the processing of its notification, nor to wait for a response from the subscribers.</li><li>Parallelization of processes: a message can trigger a series of parallel, isolated and independent actions.</li><li>System resilience: when a service goes down and is no longer able to consume the messages it has subscribed to, the broker keeps the messages in its persistence layer (queue or topic, depending on the broker). When it is operational again, it resumes the consumption flow of its messages. (I’ll talk about this in the chapter <em>Overview of RabbitMQ</em>).</li><li>Pull instead of push : services are now actors and not spectators: unlike a classic REST call, in which a service can be overwhelmed by a wave of HTTP calls (and potentially fall into overload), in a system distributed around events, this service is responsible for consuming the messages it is interested in. And above all for doing so at its own pace. This is a great benefit, especially when the number of workers available to consume messages is properly configured.</li><li>Retry strategy: a maximum number of retries is configured, allowing a message to be automatically replayed if it is not consumed. Finally, the message will go to the dead queue if the message cannot be consumed and will be processed manually for verification (we’ll speak about it later).</li></ul><h4>Disadvantages of Event Notification</h4><ul><li>Observability: The element that is often forgotten when implementing this type of architecture is how we monitor our applications. Indeed, on a classic flow and logs explicitly traceable from one service to another (or on our favorite APM), by strongly decoupling the systems, we have to set up a new element capable of tracing from end to end a flow, even in event. This element is the <em>correlationId</em> (we will talk about it later).</li><li>Asynchronous only: this may seem obvious, but this architecture is reserved for calls that would normally be made asynchronously. In other words, we will always need to have some HTTP calls for GET or even some POST.</li><li>Desynchronization of models: it is essential, in this type of architecture, to have the same model on both publisher and subscriber sides. Therefore, it becomes necessary to think about the models in a different way and to communicate correctly within the different teams.</li></ul><h3>Choosing the broker: RabbitMQ</h3><p>I have a natural preference for RabbitMQ to act as a message broker. However, its competitor Kafka is also well suited.</p><p>There are some differences, especially that with Kafka everything is streaming while with RabbitMQ you can choose between streaming or messaging since the 3.9 version. Besides, the notion of <em>topic</em> is different between theses brokers and there is no priority system in Kafka.</p><h4>Why do I choose RabbitMQ to do this job?</h4><ul><li>very stable message broker, with years of experience and an active community of which I am,</li><li>allows to strongly parallelize the needs of an IT, without being dependent on an application instance and the limits of its cores,</li><li>coupled with the Spring AMQP library, allows to quickly implement logic such as retry or alternative processing on the broker side,</li><li>out-of-code retention queue,</li><li>extensive customization to achieve what you want with the available exchange types,</li><li>a tool made to absorb 300k messages load per second (at the exchange level),</li><li>a dead queue system,</li><li>a “post office” flow very easy to explain.</li></ul><h4><strong>Here is a comprehensive representation of the “post office” flow:</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2J1wWd4SfskWroCUz5ti1Q.png" /></figure><h3>Use Case</h3><p>Let’s imagine the following services in an online store called Foo Store:</p><ul><li>an <strong>Order </strong>service that handles the orders of a store,</li><li>a <strong>Catalog</strong> service that handles the inventory of a store,</li><li>a <strong>Payment </strong>service that handles the management of payments,</li><li>a <strong>Shipping </strong>service that takes care of contacting the delivery partner and retrieving the tracking number of the package,</li><li>an <strong>Email </strong>service, global to the whole IT, allowing to send an email to a recipient with a specific body.</li></ul><blockquote>As A Customer, when I order something on the store and my payment is validated, I receive an email containing the tracking number of my package.</blockquote><p><strong>As a first sequences diagram, totally synchronous, we can imagine the following :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZtCoRy94qM2zn3Ibv9yelw.png" /></figure><p>We realize that the customer will have to wait for all the services to be called before receiving his email and that the system does not explicitly say how it handles the error cases on each of the called services.</p><p><strong>We will use this specific example to illustrate concretely how we will implement the Event Notification in this IT, using RabbitMQ.</strong></p><h3>Overview of RabbitMQ</h3><h4><strong>Exchanges and Queues:</strong></h4><p>Some types of exchange are available to realize Event-Driven via RabbitMQ:</p><ul><li><strong>Fanout:</strong> it allows to route all messages arriving on all queues bound to this fanout. Unless otherwise instructed, routing keys are ignored and queues can be created on the fly by a consumer connecting to RabbitMQ. This is an example of chat. The disadvantage for what we want to do is that if the consumer disconnects, the queue is destroyed, and we then lose the messages that were not consumed. This type of exchange doesn’t seem to fit our needs.</li><li><strong>Direct:</strong> it allows to route all the messages arriving on all the bound queues thanks to the routing-key pattern. This is the choice of exchange we will make for the Tasks.</li><li><strong>Topic:</strong> it’s the same as the Direct exchange, but the routing keys are not fixed (using a wildcard). This is the choice of exchange we will make for the events.</li></ul><p>We define later a standard for the <em>routing keys</em> because of their importance in our system.</p><p>The multicast strategy is used for our system: only one exchange will be needed for all the queues and several queues can be addressed.</p><h4><strong>Nominal Queue, Retry and Dead Letter Queue:</strong></h4><p>In our model, a queue exists for each event to be notified per consumer. In other words, if we have 3 applications that want to consume the same message, we will have 3 queues.</p><p>The effort of managing RabbitMQ can be delegated to a third-party application, which we will discuss later.<br>As the name suggests, the nominal queue serves as a mailbox for messages that are waiting to be consumed.</p><p>An automatic mechanism allows to regulate the traffic of messages that cannot be consumed: after 3 attempts, the messages fall into the dead queue if the reason justifies it. This Dead Letter Queue (DLQ) serves as a buffer to keep any unconsumed event on hold and its content is the attention of the team members: if a message is in it, it means that the consuming application had a problem.</p><p><strong>Here is what we just design:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*03OpRgrbmKZB4BPRqD1BtQ.png" /></figure><h3>Standards</h3><p>The system we are designing must allow all IT services to communicate asynchronously via Event Notifications and a central bus to dispatch the messages.<br>It is, therefore, necessary to define and respect standards that will be applied by all the applications that want to use this system.</p><p>As defined above, each service subscribing to the bus will have as many name queues as the number of events it consumes. This may seem a bit cumbersome at first, but it will facilitate the management of the queues, their reading in the RabbitMQ console, and their addressing.</p><p>The most important notions are: <strong>action</strong>, <strong>object</strong>, <strong>target</strong>.</p><p>Note that the <strong>action</strong> describes what the producer has done, not what the consumers must do with the event.</p><p>The 4 possible actions are:<br><strong>→ </strong><em>create</em>: action concerning a creation.<br>→ <em>change</em>: action about a state modification.<br>→ <em>remove</em>: action concerning a deletion.<br>→ <em>notify</em>: any other action not corresponding to any of the above cases.</p><blockquote>The actions must not give orders to the services that consume the messages (for example <em>Do this</em> or <em>Trigger that</em>).</blockquote><h4><strong>The objects:</strong></h4><p>They define what the notification will be about. For example a Payment.</p><h4><strong>Targets:</strong></h4><p>These are the services that will consume the messages. Each queue must be consumed by one service only, so we suffix the queue with its target.</p><h4><strong>Exchange, Queue and Binding nomenclature:</strong></h4><p>As mentioned before, we will use the multicast strategy: only one exchange will be needed depending on the type of message.<br>In the example, sending an email is a Task, everything else is an event: we will define these two types as prefixes of the created elements.</p><p>We create the following items in RabbitMQ:</p><p><strong>Exchanges:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*Wm3UUe7BNCYWLKuNgmnZmg.png" /><figcaption>We create 4 exchanges</figcaption></figure><p><strong>Queues &amp; Bindings:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fHROeVY5ogXeQw7LbAP0jg.png" /><figcaption>We create 8 queues.</figcaption></figure><p><strong>Why do we use a dead exchange?<br></strong>When an event cannot be consumed, and for special reasons that require us to keep the event (e.g. a call to an external service that does not answer and returns a 500), we want to redirect the event to its dead queue. However, we separate the flow via a specific exchange for dead events, in order to monitor them directly from the statistics of the exchange.</p><p><strong>Why do we use a hash #?<br></strong>Concerning routing keys, we use # as wildcard. Indeed, RabbitMQ can substitue the hash (#) for zero or more words in the bindings. This way, the producer can push his event without specifying the target, while the owner queues of each service receive their copy of the event to process.</p><p><strong>Why do we have an <em>event.store</em> queue?<br></strong>As for our event store queue, also using the wildcard # in two places, it will receive a copy of all events including the notion of “event”, no matter what is before or after this word. This way, we will be able to record the event store in an asynchronous way too, thanks to this specific queue for this usage.</p><h3>Unravelling the flows</h3><p>Now that we have a good appreciation of the different elements and how we are going to orchestrate them, we can resume our flows.</p><p><strong>Here is the sequences we designed using RabbitMQ:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1grUmXe75oQOO9mpowXVeA.png" /></figure><p>The <em>X Service</em> is responsible for recording all the events. We will talk about this later.</p><p><strong>Here is the flow for the Event:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zzmTmXp6r5veechNMJuSfA.png" /><figcaption>Event flow.</figcaption></figure><p><strong>Here is the flow for the Task:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E3z3MOSk-BkFAj8lzMBPzA.png" /><figcaption>Task flow.</figcaption></figure><h3>The X Service to rule them all</h3><p>At this stage, we have set up a way to distribute our system, but very quickly several questions will arise.</p><p>We will try to provide an elegant and pragmatic answer to all our needs.</p><p>It’s time to unveil the purpose of the <em>X Service</em> !</p><p>First of all, let’s stop the teasing and let’s call it now the <strong>Rabbit Service</strong>.</p><h4>Definition</h4><p>The <strong>Rabbit Service</strong> is a building block whose vocation is to be leaned to RabbitMQ in our system. In this way, we have a brick strongly isolated from the rest of the business services to which we will delegate a number of missions:</p><p>1/ Set up of RabbitMQ,<br>2/ Guarantee the consistency of all messages from the producer to the consumer,<br>3/ Serve as an interface for the event store,<br>4/ Calling external APIs via the Task.</p><h4>Configuration of RabbitMQ</h4><p>As explained, the <strong>Rabbit Service</strong> will be in charge of the RabbitMQ configuration:</p><ul><li>First of all the creation of exchanges, queues and bindings is its responsibility,</li><li>Then, the setting of the 3 retries attempts and the exponential backoff that will be applied to them are configured via a properties file (or .yaml) using the Spring AMQP library,</li><li>Finally, we give it the responsibility to recreate exchanges and queues if they are ever destroyed (manual error or other), to ensure that we always have all elements to receive system messages. We use for that the native management system of the Spring AMQP library again, which allows for any Bean created to make sure that an element exists in RabbitMQ.</li></ul><p><strong>Here is an example of retry configuration using Spring AMQP properties:</strong></p><pre>spring.rabbitmq.listener.simple.retry.enabled=true<br>spring.rabbitmq.listener.simple.retry.initial-interval=45000<br>spring.rabbitmq.listener.simple.retry.max-attempts=3<br>spring.rabbitmq.listener.simple.retry.multiplier=1.3<br>spring.rabbitmq.listener.simple.retry.max-interval=80000<br>spring.rabbitmq.listener.simple.default-requeue-rejected=true</pre><h4>A Shared library of Models</h4><p>The biggest risk now lies in the fact that for our events to be consumed they must correspond to what is expected by the consumer.</p><p>Data consistency therefore requires that we centralize the models we exchange through the message broker.</p><p>We create a new package in our <strong>Rabbit Service</strong>, called <em>common-model</em>. This package will contain all the types exchanged between the producers and consumers of events.</p><p>Whether they are represented by class (DTO) or proto messages, the models we create will have to be integrated in the Services using them, both producer and consumer.</p><p>As we have seen above, we realize an architecture based on Event Notification. So we don’t need to create complex types representing entire models. We are only interested in useful information.</p><p><strong>Here is a simple example of event in json:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dQ03GHp9c3whf64U5Xhynw.png" /></figure><p>In the example, the purpose of this event is to allow other services to do their job.</p><p>Contrary to event sourcing, we don’t have one entity here but an object aggregating several different business notions.</p><p>The name of this object is: <em>CreateOrder</em>.</p><p>Now that we have created our <em>CreateOrder</em> event, we will compile the <em>common-model</em> package as a <em>.jar</em></p><p>We versioned this compiled file (using <a href="https://semver.org/">SemVer</a> for example) and we distribute the package on a central repo provided for this purpose (GitHub Packages, Nexus, etc.).</p><p>From then on, we make it available to all other services that can include it in their project and use it to produce or consume an event.</p><p><strong>Here is what we just designed:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hz6CjxRjDPyz79RveHnFFw.png" /></figure><h4>The Event Store</h4><p>First of all, let’s keep in mind that since we implement the Notification pattern, our source of truth is not our Event Store but our business databases.<br>The Event Store is only there to answer a need for consultation.</p><p>As we have seen, we duplicate all the messages of type events in a queue specially dedicated to record in an event store (thanks to the wildcard #).</p><p>We could have one event store per service (directly as a table in the business database), but we choose to create a unified event store to facilitate the handling and cross-referencing of all this data.</p><p>Our event store will be neither more nor less than a PostgreSQL database in our example.</p><p>The recording must serve two goals:<br>- to be able to consult past events for debugging purposes,<br>- to be able to replay any event manually, to restart a blocked process for example.</p><p>A table will be enough, let’s call it <em>event_store</em>.<br>We define its columns as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*jMTO9LRzsr24Vb6ivV7NCw.png" /></figure><p><strong>How do our Rabbit Service should record the events?<br></strong>As we have seen, all events sent to RabbitMQ will be duplicated in a queue specific to the event store.</p><p>We delegate the consumption of this queue to the <strong>Rabbit Service</strong>, which will be in charge of cutting all the events (headers and payload) and persisting them in the <em>event_store</em> table.</p><p><strong>What is the correlationId column?<br></strong>The <em>correlationId</em> is a unique event identifier used to track a complete flow.</p><p>In our example, we create a correlationId in the headers of the event sent by the <em>Order Service</em>.</p><p>This <em>correlationId</em> will be found in each copy of the event that will be consumed by the <em>Catalog Service</em>, the <em>Shipping Service</em> and the e<em>vent store.</em></p><p>Spoiler Alert: It will also be in the body of the email Task in order to identify the initial request that triggered the sending of this email.</p><p><strong>What is the jsonb type?</strong></p><p>Jsonb is a binary representation of a json data that can be indexed.</p><p>This type allows to increase the performances and brings a new syntax of request very elegant and easily understandable.</p><p>It’s available on PostgreSQL databases.</p><blockquote>This is the perfect answer to the document oriented databases, combining the convenience of a NoSQL solution with the powerful features of a RDBMS.</blockquote><p><strong>Here is what our Rabbit Service looks like now:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZQKEZ749CsSLqsALtw3Wcw.png" /></figure><h4>Handling the Tasks</h4><p>We have seen the definition of a Task above. We will leave the management of those to the <strong>Rabbit Service</strong>. This way, any asynchronous Task request will go through RabbitMQ and will trigger a specific action.</p><p>In our example we had an <strong>Email Service</strong>.<br>Let’s move the logic of sending emails to the Task specific package in the <strong>Rabbit Service</strong>.</p><p>If the service we use to send our emails provides an SDK with the expected models, we put it in the <strong>common-model</strong> package. If the templates do not exist we create them according to the API documentation of the service provider (<em>Mailchimp</em>, <em>Mailjet</em>, <em>Sendinblue</em>, etc.).</p><p>From then on, every brick in our system with the <strong>common-model</strong> library can push a task into RabbitMQ to send an email.</p><p>The <strong>Rabbit Service</strong> will then consume the messages in the queue specifically dedicated to sending emails in asynchronous mode and will call the service provider’s API.</p><p>The return is recored in a table dedicated to the Task.</p><p><strong>Isn’t it risky to call external API asynchronously?<br></strong>No. As long as you know exactly what is expected and you respect the interface contract, you can be confident. Moreover, the result is saved in a table dedicated to that.</p><p><strong>What are the advantages of using RabbitMQ to make calls to external partners?<br></strong>First of all, asynchronous task allows to free the producer from waiting for the return of the partner API.<br>Using RabbitMQ allows you to create retention queues, which is very useful when you have to send thousands of emails for instance.<br>Also, it allows to smooth the calls to the partner to avoid being blocked by a rate limit (429).<br>Finally, as we have seen before: all our messages passing through RabbitMQ benefit from retry and DLQ, which is very useful when we do not control the behavior of the service we are calling.</p><p><strong>Which external services are eligible to be Task?<br></strong>Typically a call to an external API that wait for the response to continue a process is not a Task.<br>On the other hand, creating tickets (<em>Jira</em>, <em>Trello</em>, <em>Youtrack</em>, etc.), sending emails, sending SMS, creating PDF or generating documents are good examples of Tasks that you can delegate to the <strong>Rabbit Service</strong>, which will consume the specific queues for each need.<br>Don’t think that the Tasks are necessarily external partners that you pay, it can be a service of your system that allows to generate PDF and put them on a storage like AWS S3 for instance.</p><p><strong>Finally, here is our Rabbit Service:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RYvM_tCTPaLqptsXAxsCog.png" /></figure><h3>Ack &amp; Nack</h3><p>Probably the part that is most neglected and misunderstood!<br>To make a good distributed system, it is important to see Dead Letter Queues as retention queues in their own right.</p><blockquote>The only reason to have a message in a DLQ is to have had a non-business error at consumption.</blockquote><p><strong>Let’s take two examples to illustrate when a message should be discarded in a DLQ and when it should not:<br>1/</strong> When the Catalog Service consumes its event to update the inventory of the stock, it is expected that the items concerned exist and that they can be updated.</p><p>What happens then if the database does not know the items concerned?<strong><br></strong>A defensive service would return a nice 404 NOT FOUND error and stop the process. <strong>This is called a business error.</strong><br>The event is then acknowledged (<em>ack</em>), i.e. it is indicated that it has been processed successfully.</p><p>Why not <em>nack</em> (negative acknowledged) the event since we did not find the articles in the database and did not update anything?<br>Simply because if we return a <em>nack</em> result we will replay the message 3 times, then it will go to DLQ.<br>So you understand that this message has no business being in DLQ because moving it to the nominal queue will send it back to DLQ again and again.</p><p><strong>2/</strong> When the Shipping Service consumes its service it calls the API of a partner to generate a delivery request.<br>Let’s imagine the case where the partner does not respond, which is not a business error on our side.<br>The API is down and after a nice timeout we receive a 500.</p><p>If the 3 retries are not enough, we want the message to fall in DLQ: indeed, we will pass it again in the nominal queue later, when our partner will have restored its service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*saZHhXZasbACXzef4b1AnQ.png" /></figure><p><strong>How to ack or nack an event?<br></strong>Any Exception during an event consumption will trigger a <em>nack</em>. We understand that we have to manage controlled exits, such as business errors, with care.</p><p>In general: we should always consume events in try / catch, and the same goes for external services that are called.</p><p>If you want to manage <em>nack</em> manually, methods exist in the RabbitMQ documentation, like <em>channel.basicNack()</em>.</p><p>If you liked this article don’t hesitate to applaud it! Thank you.</p><h3>Sources</h3><ul><li><a href="https://martinfowler.com/articles/201701-event-driven.html">https://martinfowler.com/articles/201701-event-driven.html</a></li><li><a href="https://docs.spring.io/spring-amqp/reference/html/amqp.html">https://docs.spring.io/spring-amqp/reference/html/amqp.html</a></li><li><a href="https://www.rabbitmq.com/amqp-0-9-1-quickref.html">https://www.rabbitmq.com/amqp-0-9-1-quickref.html</a></li><li><a href="https://www.compose.com/articles/faster-operations-with-the-jsonb-data-type-in-postgresql/">https://www.compose.com/articles/faster-operations-with-the-jsonb-data-type-in-postgresql/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=534798bdf17e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>