<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0"
  xmlns:atom="http://www.w3.org/2005/Atom"
  xmlns:content="http://purl.org/rss/1.0/modules/content/"
  xmlns:media="http://search.yahoo.com/mrss/">
  <channel>
    <title>Billy Okeyo</title>
    <link>https://billyokeyo.dev/</link>
    <description>Articles on idempotency, transactions, sagas, CQRS, and building production-grade backend systems. A practical guide for engineers moving beyond CRUD.</description>
    <language>en</language>
    <lastBuildDate>Fri, 31 Jul 2026 15:13:33 +0000</lastBuildDate>
    <atom:link href="https://billyokeyo.dev/rss.xml" rel="self" type="application/rss+xml" />
    <managingEditor>billycartel360@gmail.com (Billy Okeyo)</managingEditor>
    <webMaster>billycartel360@gmail.com (Billy Okeyo)</webMaster>
    <copyright>© 2026 Billy Okeyo</copyright>




  
  





  



  


    <item>
      <title>Event-Driven Architecture Explained: Building Systems That React to Events</title>
      <link>https://billyokeyo.dev/posts/event-driven-architecture/</link>
      <guid isPermaLink="true">https://billyokeyo.dev/posts/event-driven-architecture/</guid>
      <pubDate>Fri, 31 Jul 2026 00:00:00 +0000</pubDate>
  
      <atom:updated>2026-07-31T00:00:00+00:00</atom:updated>
  
      <description><![CDATA[Event-Driven Architecture is a pattern for building systems that react to events. This article explains what Event-Driven Architecture is, why it is important, and how it works.]]></description>
      <content:encoded><![CDATA[<blockquote>
  <p><em>“The most scalable systems don’t constantly ask what’s happening. They simply react when something happens.”</em></p>
</blockquote>

<p>Imagine you’re building an online marketplace. A customer places an order. At first, the workflow seems straightforward. The application creates the order, charges the customer’s card, reserves inventory, schedules shipment, sends a confirmation email, updates analytics, awards loyalty points, and notifies the warehouse. A traditional implementation might have the Order Service call each of these services directly.</p>

<pre><code class="language-text">Order Service

     │

     ├── Payment Service

     ├── Inventory Service

     ├── Shipping Service

     ├── Email Service

     ├── Analytics Service

     └── Loyalty Service
</code></pre>

<p>At first, this architecture feels perfectly reasonable. Each service performs its work and returns a response. As the business grows, however, the Order Service slowly becomes responsible for more and more integrations. Marketing introduces a Recommendation Service, finance adds an Accounting Service, customer success wants a CRM integration, and fraud detection joins the platform. Before long, every new feature requires modifying the Order Service. A service that originally knew only how to create orders now knows almost everything about the entire company. The result is tight coupling. Every new integration increases complexity, every downstream outage affects the original request, and every deployment becomes slightly more risky.</p>

<p>Eventually, developers begin asking a different question. Instead of asking:</p>

<blockquote>
  <p><strong>“Which services should I call?”</strong></p>
</blockquote>

<p>They begin asking:</p>

<blockquote>
  <p><strong>“What happened?”</strong></p>
</blockquote>

<p>That small change in thinking fundamentally changes the architecture. Instead of directly calling every interested service, the Order Service simply announces:</p>

<blockquote>
  <p><strong>“An order has been created.”</strong></p>
</blockquote>

<p>It doesn’t care who listens and doesn’t even know who listens. It simply publishes an event, and every interested service reacts independently. The Shipping Service prepares delivery, the Email Service sends a confirmation, analytics records another sale, loyalty awards points, fraud detection evaluates the transaction, and recommendation engines update customer preferences. The Order Service never calls any of them directly.</p>

<p>This architectural style is known as <strong>Event-Driven Architecture (EDA)</strong>. Instead of services communicating through tightly coupled request-response interactions, they communicate through events describing things that have already happened. This shift may seem subtle, but in reality, it completely changes how distributed systems evolve, scale, and recover from failure.</p>

<hr />

<h3 id="what-is-an-event">What Is an Event?</h3>

<p>Before discussing Event-Driven Architecture, it’s important to understand what an event actually is. An event is simply a record that something meaningful has already happened. It is not something that might happen, and not something another service should do, but something that has already occurred. Examples include:</p>

<ul>
  <li>Order Created</li>
  <li>Payment Completed</li>
  <li>Customer Registered</li>
  <li>Loan Approved</li>
  <li>Inventory Reserved</li>
  <li>Shipment Delivered</li>
</ul>

<p>Notice the wording: every event is written in the past tense because events describe facts. Once an event has occurred, it becomes part of the system’s history. Unlike commands, events don’t tell another service what to do. They simply communicate what has already happened. This distinction is incredibly important. Consider the difference between these two messages.</p>

<pre><code class="language-text">Command

Charge Customer
</code></pre>

<pre><code class="language-text">Event

Customer Charged
</code></pre>

<p>The first message expects another service to perform work; the second informs the rest of the system that the work has already been completed. Commands ask; events announce. That simple distinction lies at the heart of Event-Driven Architecture.</p>

<hr />

<h3 id="how-event-driven-systems-work">How Event-Driven Systems Work</h3>

<p>Imagine a borrower submits a loan application. The Loan Service validates the request, stores the application, and commits its transaction. Rather than directly calling every downstream service, it publishes a <strong>LoanApplicationSubmitted</strong> event, and from there every interested service works independently.</p>

<pre><code class="language-text">Loan Service

      │

LoanApplicationSubmitted

      │

──────── Event Broker ────────

      │

      ├── Risk Service

      ├── Notification Service

      ├── Fraud Detection

      ├── CRM

      └── Analytics
</code></pre>

<p>Notice what changed: the Loan Service no longer knows anything about these downstream systems. Adding another consumer doesn’t require modifying the Loan Service, and removing one doesn’t either. Every service simply subscribes to the events it cares about. That loose coupling is one of the defining advantages of Event-Driven Architecture.</p>

<hr />

<h3 id="why-this-improves-scalability">Why This Improves Scalability</h3>

<p>Suppose your application suddenly doubles in size. Marketing introduces three new services, operations introduces two more, and finance adds another. In a request-response architecture, every one of those integrations often requires modifying the originating service. In an event-driven architecture, nothing changes. The new services simply subscribe to existing events, and the publisher remains exactly the same. This dramatically reduces coupling and allows applications to evolve much more independently. Instead of building systems that know about one another, you’re building systems that share facts. That distinction becomes increasingly valuable as applications grow.</p>

<h3 id="event-brokers-the-backbone-of-event-driven-systems">Event Brokers: The Backbone of Event-Driven Systems</h3>

<p>At this point, a natural question arises. If services no longer call one another directly, how do events actually travel through the system? The answer is an <strong>event broker</strong>. An event broker acts as the central communication hub for your architecture. Instead of sending events directly to every interested service, a publisher sends the event to the broker, and the broker becomes responsible for delivering it to every subscriber. Conceptually, the architecture looks like this:</p>

<pre><code class="language-text">                Order Service

                     │

      OrderCreated Event

                     │

                     ▼

             Event Broker

     ┌─────────┼─────────┐

     ▼         ▼         ▼

 Inventory   Shipping   Analytics

   Service    Service     Service
</code></pre>

<p>Notice what has disappeared: the Order Service no longer knows how many consumers exist, doesn’t know whether the Analytics Service is online, and doesn’t know whether another team introduces a Recommendation Service next month. Its only responsibility is publishing the event. Everything else becomes someone else’s concern. Several technologies can act as event brokers. Apache Kafka is widely used for high-throughput event streaming. RabbitMQ is popular for traditional message queuing. Cloud platforms offer managed services such as Amazon EventBridge, Amazon SQS, Azure Service Bus, and Google Pub/Sub. Each has different strengths, but they all serve the same purpose: moving events from producers to consumers without tightly coupling the two.</p>

<hr />

<h3 id="why-event-driven-architecture-matters">Why Event-Driven Architecture Matters</h3>

<p>At first glance, publishing events instead of calling APIs might not seem like a revolutionary change. In practice, however, it fundamentally changes how software evolves. Consider our online marketplace again. The Order Service publishes an <strong>OrderCreated</strong> event. Initially, only three services consume it.</p>

<ul>
  <li>Shipping</li>
  <li>Email</li>
  <li>Inventory</li>
</ul>

<p>A year later, the business introduces:</p>

<ul>
  <li>Fraud Detection</li>
  <li>Recommendation Engine</li>
  <li>Customer Rewards</li>
  <li>CRM Integration</li>
  <li>Business Intelligence</li>
  <li>Machine Learning</li>
</ul>

<p>The Order Service doesn’t change. It continues publishing exactly the same event, and the new services simply subscribe. This is one of the greatest strengths of Event-Driven Architecture: applications grow by adding consumers rather than modifying existing publishers, which greatly reduces the ripple effect of change.</p>

<hr />

<h3 id="the-trade-offs">The Trade-Offs</h3>

<p>Like every architectural style, Event-Driven Architecture solves some problems while introducing others. One important difference is that communication becomes asynchronous. When a customer places an order, the application may respond immediately even though several downstream services are still processing events. This improves responsiveness but introduces <strong>eventual consistency</strong>.</p>

<p>For a short period, different services may have slightly different views of the system. The order may already exist while the reporting dashboard hasn’t yet been updated, or the shipment may still be pending while the payment has already completed. This isn’t necessarily a problem; it’s simply a different consistency model, and applications must be designed with that reality in mind. Debugging also becomes more challenging. In a request-response architecture, tracing a workflow often means following a sequence of API calls. In an event-driven architecture, the workflow is distributed across many independent services reacting to events at different times, so good observability becomes essential. Correlation IDs, distributed tracing, structured logging, and monitoring tools become increasingly valuable as systems grow.</p>

<hr />

<h3 id="common-mistakes">Common Mistakes</h3>

<p>One of the biggest mistakes teams make is publishing events for everything. Not every database update deserves an event. Good events represent meaningful business occurrences. Examples include:</p>

<ul>
  <li>Customer Registered</li>
  <li>Order Completed</li>
  <li>Loan Approved</li>
  <li>Payment Received</li>
</ul>

<p>Poor events often expose internal implementation details. Examples include:</p>

<ul>
  <li>CustomerTableUpdated</li>
  <li>RowModified</li>
  <li>AddressFieldChanged</li>
</ul>

<p>Consumers should care about business facts, not database implementation. Another common mistake is assuming events are delivered exactly once. In reality, duplicates can occur, messages can be delayed, and consumers can retry. This is why patterns we’ve already explored, such as <strong>Idempotency</strong>, remain critically important. Reliable event-driven systems assume events may be delivered more than once and design consumers accordingly. Finally, avoid replacing every API with events. Not every interaction should be asynchronous. Some operations naturally require an immediate response. For example:</p>

<ul>
  <li>User authentication</li>
  <li>Payment authorization</li>
  <li>Real-time validation</li>
</ul>

<p>A healthy architecture often combines synchronous APIs with asynchronous events, using each where it makes the most sense.</p>

<hr />

<h3 id="request-response-vs-event-driven">Request-Response vs Event-Driven</h3>

<p>A useful way to compare these architectures is to think about who controls the conversation.</p>

<p>In a request-response system, one service explicitly asks another service to perform work, and the caller waits for an answer before continuing. In an event-driven system, a service simply announces what has already happened. Anyone interested may react, and anyone uninterested simply ignores the event. Neither architecture is universally better. Request-response communication is often simpler and easier to understand, while event-driven communication provides greater flexibility and scalability as systems become more complex. Most modern applications use both. User-facing requests frequently begin as synchronous API calls, and once the business transaction completes, the application publishes events that allow the rest of the system to react independently.</p>

<hr />

<h3 id="how-everything-fits-together">How Everything Fits Together</h3>

<p>If you’ve followed this series from the beginning, you’ve probably noticed a pattern. Each article answered a question created by the previous one.</p>

<table>
  <thead>
    <tr>
      <th>Concept</th>
      <th>Question It Answers</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><strong>Idempotency</strong></td>
      <td>What if the same request arrives twice?</td>
    </tr>
    <tr>
      <td><strong>Race Conditions</strong></td>
      <td>What if multiple requests modify the same data?</td>
    </tr>
    <tr>
      <td><strong>Database Transactions</strong></td>
      <td>How do I keep related database operations atomic?</td>
    </tr>
    <tr>
      <td><strong>Isolation Levels</strong></td>
      <td>What should concurrent transactions be allowed to see?</td>
    </tr>
    <tr>
      <td><strong>Distributed Locks</strong></td>
      <td>How do multiple application instances coordinate work?</td>
    </tr>
    <tr>
      <td><strong>Outbox Pattern</strong></td>
      <td>How do I reliably publish events after committing data?</td>
    </tr>
    <tr>
      <td><strong>Saga Pattern</strong></td>
      <td>How do multiple services complete one business process?</td>
    </tr>
    <tr>
      <td><strong>CQRS</strong></td>
      <td>Should reads and writes use the same model?</td>
    </tr>
    <tr>
      <td><strong>Event-Driven Architecture</strong></td>
      <td>How do independent services communicate and evolve together?</td>
    </tr>
  </tbody>
</table>

<p>Notice that none of these patterns exists in isolation. An event-driven application might use:</p>

<ul>
  <li><strong>Idempotency</strong> to safely handle duplicate events.</li>
  <li><strong>Transactions</strong> to protect local database operations.</li>
  <li>The <strong>Outbox Pattern</strong> to reliably publish domain events.</li>
  <li><strong>Saga Pattern</strong> to coordinate long-running business workflows.</li>
  <li><strong>CQRS</strong> to optimize read and write workloads independently.</li>
  <li><strong>Distributed Locks</strong> where multiple application instances must coordinate exclusive work.</li>
</ul>

<p>The real power doesn’t come from mastering one pattern. It comes from understanding how they complement one another.</p>

<hr />

<h3 id="final-thoughts">Final Thoughts</h3>

<p>Software architecture isn’t about collecting design patterns. It’s about solving real problems with the right level of complexity. Event-Driven Architecture has become popular because it reflects how modern organizations grow. Teams become independent. Services evolve at different speeds. New features appear continuously. Direct dependencies become increasingly expensive to maintain. By allowing services to communicate through events rather than tightly coupled API calls, Event-Driven Architecture enables systems that are more flexible, more scalable, and more resilient to change. Like every pattern we’ve explored, however, it isn’t a silver bullet. Small applications may never need an event broker, and a well-designed monolith may outperform a poorly designed event-driven system. Architecture should always follow business needs, not trends. The goal isn’t to build the most sophisticated system possible. It’s to build the simplest system capable of solving today’s problem while leaving room for tomorrow’s growth.</p>

<hr />

<h3 id="beyond-crud-chapter-one-complete">Beyond CRUD: Chapter One Complete</h3>

<p>When we began this series, we started with a deceptively simple question:</p>

<blockquote>
  <p><strong>What happens if the same request arrives twice?</strong></p>
</blockquote>

<p>From there, we explored race conditions, transactions, concurrency, distributed coordination, reliable messaging, long-running workflows, scalable read models, and event-driven communication. Each article introduced a new piece of the puzzle, and together they form a foundation for understanding how modern backend systems remain reliable under retries, failures, concurrency, and scale.</p>

<p>If there’s one lesson to carry forward, it’s this:</p>

<blockquote>
  <p><strong>Reliable software isn’t built by avoiding failure. It’s built by expecting failure, understanding where it can occur, and designing systems that recover gracefully when it does.</strong></p>
</blockquote>

<p>That mindset, more than any single framework, language, or database, is what separates production-ready systems from code that only works under perfect conditions. The journey beyond CRUD doesn’t end here. It begins here.</p>
]]></content:encoded>
      <author>billycartel360@gmail.com (Billy Okeyo)</author>
  
      <media:content url="https://billyokeyo.dev/assets/img/event-driven.jpg" medium="image" />
  
  
    
      <category>Distributed Systems</category>
    
      <category>Concurrency</category>
    
  
  
    
      <category>Distributed Systems</category>
    
      <category>Concurrency</category>
    
  
    </item>

  
  





  



  


    <item>
      <title>CQRS Explained: Separating Reads and Writes for Scalable Systems</title>
      <link>https://billyokeyo.dev/posts/cqrs-explained/</link>
      <guid isPermaLink="true">https://billyokeyo.dev/posts/cqrs-explained/</guid>
      <pubDate>Mon, 27 Jul 2026 00:00:00 +0000</pubDate>
  
      <atom:updated>2026-07-27T00:00:00+00:00</atom:updated>
  
      <description><![CDATA[CQRS is a pattern for separating reads and writes for scalable systems. This article explains what CQRS is, why it is important, and how it works.]]></description>
      <content:encoded><![CDATA[<blockquote>
  <p><em>“The way you write data isn’t always the best way to read it.”</em></p>
</blockquote>

<p>Imagine you’re building an online marketplace. Every day, thousands of customers browse products, place orders, track deliveries, and review their purchase history. At the same time, administrators manage inventory, warehouse staff update shipments, finance teams generate reports, and recommendation engines continuously analyze customer behavior.</p>

<p>From a user’s perspective, everything appears seamless. Behind the scenes, however, the application is performing two fundamentally different kinds of work. Some requests are <strong>changing</strong> data: a customer places an order, an administrator updates inventory, a payment is processed, or a shipment is marked as delivered. Other requests simply <strong>read</strong> data: customers search for products, managers open dashboards, support agents review order histories, and executives generate monthly reports.</p>

<p>At first, it’s tempting to handle both using the same database tables and the same application models. After all, an order is an order. Whether you’re creating it or displaying it, why shouldn’t the same model work for both? For many applications, that’s exactly what happens. The same entity is used for inserting records, updating records, validating business rules, and serving data to the user interface.</p>

<p>As applications grow, however, this approach begins to reveal its limitations. The information required to create an order is often very different from the information required to display one. Creating an order might require validating inventory, calculating taxes, applying discounts, verifying payment details, and enforcing business rules. Displaying an order, on the other hand, may require customer information, shipping updates, product images, payment status, warehouse progress, and delivery estimates, all combined into a single view optimized for the user.</p>

<p>Trying to satisfy both responsibilities with one model often leads to increasingly complicated code. The write model becomes cluttered with fields needed only for reporting, the read model becomes constrained by rules that exist only for data modification, queries grow more complex, performance begins to suffer, and developers start adding workarounds that make the system harder to maintain.</p>

<p>Eventually, an important realization emerges.</p>

<blockquote>
  <p><strong>The way we write data isn’t necessarily the best way to read it.</strong></p>
</blockquote>

<p>That simple observation led to a pattern known as <strong>Command Query Responsibility Segregation</strong>, more commonly called <strong>CQRS</strong>. Rather than forcing one model to satisfy two very different responsibilities, CQRS separates them completely. Commands become responsible for changing data, queries become responsible for reading data, and each side can then evolve independently, optimized for its own purpose. Before exploring how CQRS works, let’s first understand why combining reads and writes into the same model eventually becomes a problem.</p>

<h3 id="why-one-model-eventually-becomes-a-problem">Why One Model Eventually Becomes a Problem</h3>

<p>When most applications begin, life is simple. Suppose you’re building a loan management platform. A borrower submits a loan application. The application validates the input, saves the record, and later retrieves the same information whenever a loan officer opens the application. The same model handles both writing and reading.</p>

<pre><code>LoanApplication
</code></pre>

<p>Everything works perfectly. As the platform grows, however, different users begin asking for different views of the same information. A loan officer wants to see repayment history, guarantors, collateral, risk score, and supporting documents on one screen; finance wants reports showing outstanding balances grouped by branch; executives want dashboards displaying portfolio performance; and customers simply want to know whether their application has been approved.</p>

<p>Notice what’s happening: everyone is looking at the same business entity, but nobody wants exactly the same data. To satisfy these different requirements, the application gradually starts joining more tables.</p>

<pre><code class="language-sql">Loan

JOIN Customer

JOIN Branch

JOIN RiskAssessment

JOIN LoanOfficer

JOIN Repayments

JOIN Documents

JOIN Guarantors
</code></pre>

<p>The queries become larger, response times increase, and the code becomes harder to maintain. Ironically, the information required to <strong>display</strong> a loan has become far more complicated than the information required to <strong>create</strong> one. This is where many systems begin struggling. The write model keeps accumulating fields that only reports need, the read model becomes constrained by business rules that only matter during updates, and eventually one model is trying to solve two completely different problems.</p>

<hr />

<h3 id="commands-and-queries-are-different">Commands and Queries Are Different</h3>

<p>One of the core ideas behind CQRS is recognizing that not every request has the same purpose. Some requests change data; others simply read it. These are fundamentally different operations. A <strong>command</strong> tells the system to perform an action. For example:</p>

<ul>
  <li>Create Order</li>
  <li>Approve Loan</li>
  <li>Reserve Inventory</li>
  <li>Charge Payment</li>
  <li>Register Customer</li>
</ul>

<p>Commands represent intent. They usually contain business validation, enforce rules, and modify application state. A <strong>query</strong>, on the other hand, doesn’t change anything. Its only responsibility is returning information. For example:</p>

<ul>
  <li>Get Customer Profile</li>
  <li>List Outstanding Loans</li>
  <li>View Order History</li>
  <li>Search Products</li>
  <li>Display Dashboard</li>
</ul>

<p>Queries don’t perform business logic. They answer questions. This distinction may seem small, but in reality, it changes how applications are designed.</p>

<hr />

<h3 id="what-is-cqrs">What Is CQRS?</h3>

<p>CQRS stands for <strong>Command Query Responsibility Segregation</strong>. Despite the intimidating name, the underlying idea is surprisingly simple. Instead of using one model for everything, CQRS separates the write side from the read side. Commands become responsible for modifying data, and queries become responsible for retrieving it. Conceptually, the architecture looks like this.</p>

<pre><code class="language-text">                Application

                     │

      ┌──────────────┴──────────────┐

      │                             │

   Commands                     Queries

      │                             │

Write Model                  Read Model

      │                             │

Database                 Optimized View
</code></pre>

<p>The important thing to notice is that the read model no longer has to look like the write model. Each side is free to evolve independently.</p>

<hr />

<h3 id="the-write-model">The Write Model</h3>

<p>The write model exists to protect business rules. Suppose a customer places an order. The application needs to verify inventory, calculate discounts, validate payment, reserve stock, and create the order. All of those steps belong on the write side. The write model isn’t concerned with how information will later appear on a dashboard. Its only responsibility is ensuring the business operation is correct. Think of it as the gatekeeper for your data. Nothing enters the system without passing through the write model.</p>

<hr />

<h3 id="the-read-model">The Read Model</h3>

<p>The read model has a completely different job. Its responsibility isn’t enforcing business rules, it’s returning information as efficiently as possible. Imagine displaying an order summary. The customer expects to see:</p>

<ul>
  <li>Order number</li>
  <li>Customer name</li>
  <li>Product images</li>
  <li>Shipping status</li>
  <li>Payment status</li>
  <li>Delivery estimate</li>
  <li>Total price</li>
</ul>

<p>The write model probably stores all of this across multiple tables, but the read model doesn’t have to. Instead, it can store exactly the shape required by the user interface, so instead of executing six joins every time someone opens an order, the read model may already contain everything in one place.</p>

<p>This dramatically simplifies queries while improving performance.</p>

<hr />

<h3 id="why-this-improves-performance">Why This Improves Performance</h3>

<p>Suppose an online store receives ten thousand requests every minute. Only five hundred of those requests create or update orders. The remaining nine thousand five hundred simply display information. Traditional CRUD applications often force both workloads through the same models and database structures. CQRS recognizes that reads and writes have completely different characteristics. Reads are usually far more frequent, while writes are usually more complicated. By separating them, each side can be optimized independently: the write model focuses on correctness, the read model focuses on speed, and neither compromises the other.</p>

<hr />

<h3 id="a-real-world-example">A Real-World Example</h3>

<p>Think about YouTube. Uploading a video and watching a video are two completely different operations. Uploading requires validation, virus scanning, metadata extraction, thumbnail generation, transcoding, and storage. Watching a video requires none of those things. The viewer simply wants the video to start playing immediately. Trying to optimize both operations using exactly the same model would make little sense.</p>

<p>CQRS applies the same principle to business applications. The model responsible for creating data doesn’t have to be the same model responsible for presenting it. Recognizing that difference is the first step toward understanding why CQRS has become such a popular architectural pattern in modern backend systems.</p>

<hr />

<p>At this point, we’ve separated reads from writes conceptually. The next question naturally follows:</p>

<blockquote>
  <p><strong>If the read model and write model are separate, how do they stay synchronized?</strong></p>
</blockquote>

<h3 id="keeping-the-read-model-up-to-date">Keeping the Read Model Up to Date</h3>

<p>One of the first questions developers ask after learning about CQRS is:</p>

<blockquote>
  <p><strong>“If my read model is separate from my write model, how does it stay up to date?”</strong></p>
</blockquote>

<p>The answer depends on the architecture, but in most modern systems, the read model is updated using <strong>events</strong>.</p>

<p>Suppose a customer places an order. The write model validates the request, checks inventory, processes payment, and commits the transaction. Once the transaction succeeds, an event such as <strong>OrderCreated</strong> is published, and one or more components responsible for maintaining the read model receive that event and update their own optimized view of the data.</p>

<p>Conceptually, the flow looks like this:</p>

<pre><code class="language-text">Customer

      │

      ▼

Command

(Create Order)

      │

      ▼

Write Model

      │

      ▼

Database

      │

      ▼

OrderCreated Event

      │

      ▼

Read Model Updated

      │

      ▼

User Queries Data
</code></pre>

<p>Notice something important: the user’s query never touches the write model. Instead, it reads from a model specifically designed for displaying information.</p>

<hr />

<h3 id="eventual-consistency">Eventual Consistency</h3>

<p>Because the read model is updated after the write completes, there is usually a short delay before the latest information becomes visible. This is known as <strong>eventual consistency</strong>. Imagine placing an order on a large e-commerce platform. The checkout page immediately confirms that your purchase was successful, but if you refresh your order history a fraction of a second later, the new order might not appear immediately. A moment later, it does. Nothing is wrong: the write completed instantly, and the read model simply needed a short amount of time to catch up. For many applications, this tiny delay is perfectly acceptable. Users rarely notice a difference measured in milliseconds or even a few seconds, and the benefit is that reads become dramatically faster and easier to scale.</p>

<hr />

<h3 id="does-cqrs-require-microservices">Does CQRS Require Microservices?</h3>

<p>One of the biggest misconceptions about CQRS is that it only works in microservice architectures. It doesn’t. CQRS is simply a design pattern. A single monolithic application can separate its command handlers from its query handlers just as effectively as a distributed system. Likewise, CQRS doesn’t require Kafka, RabbitMQ, Event Sourcing, or multiple databases. Many applications implement CQRS using a single database while maintaining separate command and query models inside the same application. As systems grow, those models may eventually evolve into separate databases or services, but that’s a scaling decision, not a requirement of the pattern itself.</p>

<hr />

<h3 id="when-should-you-use-cqrs">When Should You Use CQRS?</h3>

<p>CQRS isn’t a solution to every problem. Many applications work perfectly well using traditional CRUD architecture. If your application has simple business rules, relatively small datasets, and straightforward queries, introducing CQRS often adds unnecessary complexity. On the other hand, CQRS becomes increasingly valuable when reads and writes have very different characteristics. Common examples include:</p>

<ul>
  <li>High-traffic e-commerce platforms.</li>
  <li>Banking and financial systems.</li>
  <li>Loan management platforms.</li>
  <li>Logistics and supply chain applications.</li>
  <li>Reporting and analytics dashboards.</li>
  <li>SaaS products with complex administrative views.</li>
</ul>

<p>In these systems, the information required to display data is often very different from the information required to modify it. Separating those responsibilities makes the application easier to optimize and easier to maintain.</p>

<hr />

<h3 id="cqrs-vs-traditional-crud">CQRS vs Traditional CRUD</h3>

<p>A useful way to understand CQRS is to compare it with the architecture most developers already know.</p>

<table>
  <thead>
    <tr>
      <th>Traditional CRUD</th>
      <th>CQRS</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>One model for reads and writes</td>
      <td>Separate models for reads and writes</td>
    </tr>
    <tr>
      <td>Simpler to build</td>
      <td>More flexible at scale</td>
    </tr>
    <tr>
      <td>Easier for small systems</td>
      <td>Better suited for complex domains</td>
    </tr>
    <tr>
      <td>Queries often become increasingly complex</td>
      <td>Read models are optimized for specific use cases</td>
    </tr>
    <tr>
      <td>Business rules and presentation concerns frequently mix together</td>
      <td>Responsibilities remain clearly separated</td>
    </tr>
  </tbody>
</table>

<p>Neither approach is universally better. CRUD is an excellent choice for many applications. CQRS becomes valuable when the complexity of the domain begins to outweigh the simplicity of using a single model.</p>

<hr />

<h3 id="common-mistakes">Common Mistakes</h3>

<p>One mistake developers frequently make is adopting CQRS simply because they’ve heard it’s a “best practice.” Like every architectural pattern, CQRS introduces additional moving parts. You’ll often have separate models, additional event handling, and the possibility of eventual consistency. If those complexities don’t solve a real business problem, they’re simply unnecessary overhead. Another common mistake is trying to create one read model that satisfies every possible screen. The real strength of CQRS lies in allowing each query to have a model optimized for its own purpose. A customer dashboard, an administrative report, and a mobile application may each deserve different read models. Finally, don’t confuse CQRS with Event Sourcing. Although the two patterns are often used together, they solve different problems. CQRS separates reads from writes, while Event Sourcing stores state as a sequence of events. You can implement one without the other.</p>

<hr />

<h3 id="bringing-it-all-together">Bringing It All Together</h3>

<p>Throughout this series, we’ve gradually built a collection of patterns that solve different reliability and scalability challenges.</p>

<table>
  <thead>
    <tr>
      <th>Concept</th>
      <th>Question It Answers</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><strong>Idempotency</strong></td>
      <td>What if the same request arrives twice?</td>
    </tr>
    <tr>
      <td><strong>Race Conditions</strong></td>
      <td>What if multiple requests modify the same data simultaneously?</td>
    </tr>
    <tr>
      <td><strong>Database Transactions</strong></td>
      <td>How do I keep database operations atomic?</td>
    </tr>
    <tr>
      <td><strong>Isolation Levels</strong></td>
      <td>What should concurrent transactions be allowed to see?</td>
    </tr>
    <tr>
      <td><strong>Distributed Locks</strong></td>
      <td>How do multiple application instances coordinate work?</td>
    </tr>
    <tr>
      <td><strong>Outbox Pattern</strong></td>
      <td>How do I reliably publish events after committing data?</td>
    </tr>
    <tr>
      <td><strong>Saga Pattern</strong></td>
      <td>How do multiple services complete one business process reliably?</td>
    </tr>
    <tr>
      <td><strong>CQRS</strong></td>
      <td>Should the same model be responsible for both reading and writing data?</td>
    </tr>
  </tbody>
</table>

<p>Notice how the series has gradually expanded in scope. We began by making individual API requests reliable, then learned how to coordinate transactions, communicate between services, and manage distributed business workflows. CQRS adds another important lesson: sometimes the best way to scale an application isn’t by making one model do everything, but by giving different responsibilities to different models.</p>

<hr />

<h3 id="final-thoughts">Final Thoughts</h3>

<p>One of the biggest lessons in software architecture is that different problems deserve different solutions. Reading data and writing data may involve the same business entity, but they rarely have the same requirements. Writes prioritize correctness, validation, and enforcing business rules; reads prioritize speed, simplicity, and delivering information in the shape users actually need. CQRS embraces this difference instead of trying to hide it. For small applications, a traditional CRUD architecture is often the right choice. As systems become larger and business requirements become more demanding, separating reads from writes can lead to simpler queries, clearer responsibilities, and applications that scale far more gracefully. Like every pattern we’ve explored in the <strong>Beyond CRUD</strong> series, CQRS isn’t about making software more complicated. It’s about choosing the right level of complexity to solve the problem in front of you.</p>

<hr />

<h3 id="whats-next">What’s Next?</h3>

<p>So far, we’ve explored several patterns that improve reliability, scalability, and maintainability. One question still remains: how do all these patterns fit together to build applications where services communicate entirely through events instead of direct API calls?</p>

<p>In the next article, we’ll explore <strong>Event-Driven Architecture Explained: Building Systems That React to Events</strong>, where we’ll connect concepts like the Outbox Pattern, Saga Pattern, and CQRS into a cohesive architectural style used by many modern distributed systems.</p>

]]></content:encoded>
      <author>billycartel360@gmail.com (Billy Okeyo)</author>
  
      <media:content url="https://billyokeyo.dev/assets/img/cqrs-explained.jpg" medium="image" />
  
  
    
      <category>Distributed Systems</category>
    
      <category>Concurrency</category>
    
  
  
    
      <category>Distributed Systems</category>
    
      <category>Concurrency</category>
    
  
    </item>

  
  





  



  


    <item>
      <title>Saga Pattern Explained: Managing Distributed Transactions Across Microservices</title>
      <link>https://billyokeyo.dev/posts/saga-pattern-explained/</link>
      <guid isPermaLink="true">https://billyokeyo.dev/posts/saga-pattern-explained/</guid>
      <pubDate>Fri, 24 Jul 2026 00:00:00 +0000</pubDate>
  
      <atom:updated>2026-07-24T00:00:00+00:00</atom:updated>
  
      <description><![CDATA[The Saga Pattern is a pattern for managing distributed transactions across microservices. This article explains what the Saga Pattern is, why it is important, and how it works.]]></description>
      <content:encoded><![CDATA[<blockquote>
  <p><em>“A transaction can roll back one database. A Saga coordinates many databases that have never even met.”</em></p>
</blockquote>

<p>Imagine you’re building an online marketplace. A customer clicks <strong>Place Order</strong>, expecting what feels like a single operation. Behind the scenes, however, that simple button sets off a chain of events involving several independent services. The Order Service creates a new order, the Inventory Service reserves the purchased items, the Payment Service charges the customer’s card, the Shipping Service schedules delivery, and the Notification Service sends a confirmation email.</p>

<p>From the customer’s perspective, it’s one transaction. From your system’s perspective, it’s anything but. Each service owns its own database, each commits its own transaction independently, none of them has direct control over the others, and no single database transaction can span all of them.</p>

<p>Now imagine the following sequence: the Order Service successfully creates the order, the Inventory Service reserves the last laptop in stock, and the Payment Service charges the customer’s credit card. Then, just as the Shipping Service begins preparing the shipment, it discovers that delivery isn’t available to the customer’s location. The order already exists, the customer’s card has already been charged, and inventory has already been reserved, but the shipment can never be created. Unlike a traditional database transaction, there is no single <strong>ROLLBACK</strong> command capable of undoing work performed across multiple independent databases.</p>

<p>This is one of the defining challenges of distributed systems. As applications evolve from monoliths into microservices, business processes increasingly span services that are independently deployed, independently scaled, and independently owned. While this architecture offers tremendous flexibility, it also introduces a difficult question:</p>

<blockquote>
  <p><strong>How do you maintain business consistency when a workflow spans multiple services and one of them fails halfway through?</strong></p>
</blockquote>

<p>The answer is not a larger transaction. It’s a different way of thinking. Instead of trying to make every service commit simultaneously, modern distributed systems break long-running business processes into a sequence of smaller local transactions. If every step succeeds, the workflow completes successfully. If a step fails, previously completed work is undone using carefully designed <strong>compensating actions</strong> rather than database rollbacks.</p>

<p>This approach is known as the <strong>Saga Pattern</strong>. Like the Outbox Pattern, the Saga Pattern embraces the reality that failures are inevitable. Rather than pretending distributed transactions behave like local database transactions, it provides a practical way to recover when things don’t go according to plan. Before we explore how Sagas work, it’s important to understand why traditional transactions stop working once your application crosses service boundaries.</p>

<hr />

<h3 id="why-database-transactions-dont-scale-across-microservices">Why Database Transactions Don’t Scale Across Microservices</h3>

<p>Earlier in this series, we explored database transactions and learned how they guarantee that multiple operations either succeed together or fail together. If an online banking application deducts money from one account and credits another within the same database, a transaction ensures that both operations are treated as a single unit of work. If anything fails before the transaction commits, every change is rolled back automatically, leaving the database in a consistent state.</p>

<p>That model works beautifully when everything happens inside one database, but microservices change the picture completely. Imagine an order workflow involving four independent services.</p>

<pre><code class="language-text">Customer

      │

      ▼

Order Service

      │

      ▼

Inventory Service

      │

      ▼

Payment Service

      │

      ▼

Shipping Service
</code></pre>

<p>Each service owns its own database. The Order Service cannot directly roll back changes made by the Payment Service, the Payment Service cannot undo inventory reservations, and the Shipping Service has no authority over the Order database. Every service commits its own transaction independently. This independence is one of the greatest strengths of microservices, and it’s also one of their biggest challenges. Suppose the workflow progresses like this:</p>

<pre><code class="language-text">Create Order ✅

↓

Reserve Inventory ✅

↓

Charge Payment ✅

↓

Create Shipment ❌
</code></pre>

<p>At this point, three services have already committed their work, and nothing can simply “roll back.” Unlike a single database transaction, there is no global undo button. This challenge is often referred to as a <strong>distributed transaction</strong>, and solving it using traditional database techniques quickly becomes impractical.</p>

<p>Years ago, distributed systems experimented with approaches such as <strong>Two-Phase Commit (2PC)</strong>, where every participating system agreed to either commit or roll back together. While theoretically elegant, 2PC introduced significant coordination overhead, reduced availability, increased latency, and created situations where entire systems could become blocked waiting for slow or unavailable participants. Modern cloud-native architectures generally avoid this approach. Instead of attempting to make every service commit simultaneously, they accept that each service commits independently and focus on coordinating the overall business process.</p>

<p>That’s exactly what the Saga Pattern does. Instead of one large transaction, a Saga is a sequence of smaller transactions linked together by business logic. If every step succeeds, the Saga completes successfully; if one step fails, previously completed steps are compensated through additional business actions designed to reverse their effects. That distinction is subtle but incredibly important: a Saga doesn’t roll back database transactions, it performs new transactions whose purpose is to restore the system to a valid business state. Understanding that difference is the key to understanding everything else about the Saga Pattern.</p>

<h3 id="understanding-compensating-transactions">Understanding Compensating Transactions</h3>

<p>One of the biggest misconceptions developers have when they first encounter the Saga Pattern is assuming it somehow provides a distributed version of <code>ROLLBACK</code>. It doesn’t, and in fact, that’s one of the defining characteristics of a Saga. Once a service commits its local transaction, that transaction is permanent. The database has already saved the changes, and there is no mechanism for another service to rewind history. Instead of rolling back completed work, a Saga performs <strong>compensating transactions</strong>. A compensating transaction is simply another business operation whose purpose is to undo the effects of a previous one.</p>

<p>Suppose an order has already been created, inventory has been reserved, and payment has been successfully processed. If shipping later fails because the customer’s address falls outside the delivery area, the system cannot ask every database to roll back, because those transactions finished long ago. Instead, the application performs a series of new operations: the payment service issues a refund, the inventory service releases the reserved stock, and the order service changes the order status from <strong>Pending</strong> to <strong>Cancelled</strong>.</p>

<p>Notice something important: nothing has been deleted and nothing has been rolled back. The system simply performs additional work that restores the business to a valid state.</p>

<p>Conceptually, the workflow now looks like this:</p>

<pre><code class="language-text">Create Order ✅

↓

Reserve Inventory ✅

↓

Charge Payment ✅

↓

Create Shipment ❌

↓

Refund Payment

↓

Release Inventory

↓

Cancel Order
</code></pre>

<p>This is the heart of the Saga Pattern. Rather than pretending failures never happened, the system accepts them and responds with carefully designed business actions. This approach is much more realistic because, in distributed systems, failures aren’t exceptional, they’re inevitable.</p>

<hr />

<h3 id="a-banking-example">A Banking Example</h3>

<p>Imagine a customer applies for a personal loan. Several independent services participate in the approval process: the Loan Service creates the application, the Credit Service performs a credit check, the Risk Service evaluates affordability, and the Notification Service informs the customer of the decision. Everything proceeds normally until the Risk Service determines that the customer’s debt-to-income ratio exceeds the organization’s lending policy. At this point, the application cannot continue. If this were a single database transaction, we would simply issue a rollback.</p>

<p>In a microservice architecture, however, the Loan Service has already committed the new application and the Credit Service has already stored the completed credit assessment. Neither service can magically erase its work because another service encountered a problem. Instead, the Saga performs compensating actions: the Loan Service marks the application as withdrawn, the Credit Service archives its assessment, and the Notification Service informs the customer that the application could not proceed. Each action is itself a normal transaction, and collectively they restore the overall business process to a consistent state.</p>

<hr />

<h3 id="rollback-vs-compensation">Rollback vs Compensation</h3>

<p>Although these ideas sound similar, they’re fundamentally different. A database rollback behaves like this:</p>

<pre><code class="language-text">BEGIN

↓

Update Balance

↓

Insert Payment

↓

Failure

↓

ROLLBACK
</code></pre>

<p>When the rollback occurs, the database behaves as though none of the changes ever happened. It’s as if the transaction never existed. A Saga works very differently.</p>

<pre><code class="language-text">Reserve Inventory

↓

Charge Payment

↓

Shipment Fails

↓

Refund Payment

↓

Release Inventory
</code></pre>

<p>The original payment really happened, the refund also really happened, and both become part of the permanent history of the system. That’s an important distinction, and many business domains actually require this behavior. Consider financial systems. Deleting payment records would make auditing impossible, so recording both the payment and the subsequent refund creates a complete, traceable history of what occurred. Compensation isn’t about pretending mistakes never happened, it’s about correcting them transparently.</p>

<hr />

<h3 id="designing-good-compensating-actions">Designing Good Compensating Actions</h3>

<p>Writing a compensating transaction isn’t simply a matter of reversing database changes. You’re reversing business operations. For example, suppose a hotel booking system reserves a room.</p>

<p>The compensating action isn’t:</p>

<blockquote>
  <p>Delete reservation row.</p>
</blockquote>

<p>It’s:</p>

<blockquote>
  <p>Release the room back into available inventory.</p>
</blockquote>

<p>Similarly, if an airline charges a customer’s credit card, the compensation isn’t:</p>

<blockquote>
  <p>Delete payment record.</p>
</blockquote>

<p>It’s:</p>

<blockquote>
  <p>Create a refund transaction.</p>
</blockquote>

<p>This distinction matters because business systems are usually audited. Historical events should remain visible, and what changes is the current business state. Whenever you design a Saga, a useful question to ask is:</p>

<blockquote>
  <p><strong>“If this step succeeds but a later step fails, what business action restores the system to a valid state?”</strong></p>
</blockquote>

<p>Thinking in terms of business operations rather than database updates leads to much more reliable designs.</p>

<hr />

<h3 id="every-step-is-independent">Every Step Is Independent</h3>

<p>Another characteristic of Sagas is that every step represents a complete, independent transaction. Suppose an order workflow consists of four services.</p>

<pre><code class="language-text">Order Service

↓

Inventory Service

↓

Payment Service

↓

Shipping Service
</code></pre>

<p>Each service commits its own database transaction before the next service begins, which means failures are isolated. If the Shipping Service experiences an outage, it doesn’t corrupt the Payment Service’s database; likewise, if the Payment Service fails, it doesn’t leave the Inventory Service with an unfinished SQL transaction.</p>

<p>Each service remains responsible for its own data, and the Saga simply coordinates how those independent pieces fit together. This separation of responsibility is one of the reasons microservice architectures scale so well. Services remain loosely coupled while still participating in larger business workflows.</p>

<hr />

<h3 id="thinking-in-business-processes">Thinking in Business Processes</h3>

<p>One of the biggest mindset shifts when working with Sagas is realizing that you’re no longer designing database transactions. You’re designing business processes. Database transactions answer questions like:</p>

<blockquote>
  <p>“How do I keep these SQL statements consistent?”</p>
</blockquote>

<p>Sagas answer a much broader question:</p>

<blockquote>
  <p>“How does my business recover when part of this workflow succeeds and another part fails?”</p>
</blockquote>

<p>That’s why Sagas often involve business concepts rather than technical ones: refunds, reservation cancellations, order cancellations, inventory releases, and account reversals. These aren’t database operations; they’re business operations that happen to involve databases. Once you begin thinking at that level, the Saga Pattern becomes much easier to understand because it mirrors how real businesses operate. Companies don’t erase history when something goes wrong, they perform additional actions to correct it, and software simply follows the same principle.</p>

<h3 id="two-ways-to-coordinate-a-saga">Two Ways to Coordinate a Saga</h3>

<p>Now that we understand what a Saga is, another important question emerges: <strong>Who is responsible for coordinating all these steps?</strong></p>

<p>Imagine once again that a customer places an order. The Order Service creates the order, the Inventory Service reserves the stock, the Payment Service charges the customer, and the Shipping Service prepares the shipment. If everything succeeds, the Saga completes; if one step fails, compensating transactions begin. Someone, or something, must decide what happens next.</p>

<p>There are two common ways to achieve this coordination:</p>

<ul>
  <li><strong>Choreography</strong></li>
  <li><strong>Orchestration</strong></li>
</ul>

<p>Both accomplish the same goal, but they do so in very different ways.</p>

<hr />

<h3 id="choreography">Choreography</h3>

<p>Think about a group of experienced dancers performing together. Nobody stands at the front giving instructions. Each dancer knows exactly when to move because they respond to the music and to one another. Saga choreography works in much the same way. Instead of a central coordinator directing every step, each service reacts to events published by other services. Consider our order workflow.</p>

<pre><code class="language-text">Customer Places Order

        │

        ▼

Order Service

Publishes

OrderCreated

        │

        ▼

Inventory Service

Publishes

InventoryReserved

        │

        ▼

Payment Service

Publishes

PaymentCompleted

        │

        ▼

Shipping Service

Publishes

ShipmentCreated
</code></pre>

<p>Every service only knows two things:</p>

<ul>
  <li>The events it listens for.</li>
  <li>The events it publishes.</li>
</ul>

<p>The Payment Service doesn’t know the Shipping Service exists, and the Shipping Service doesn’t know anything about the Inventory Service. Each service simply reacts whenever an event arrives. This loose coupling is one of choreography’s greatest strengths. Because services know very little about one another, adding or removing services often becomes much easier.</p>

<p>Suppose your business introduces a Loyalty Service that awards reward points whenever an order is completed. Nothing else needs to change. The new service simply subscribes to the <strong>PaymentCompleted</strong> event, and the rest of the system continues operating exactly as before. This flexibility makes choreography extremely attractive in event-driven architectures. However, it comes with a cost. As systems grow, understanding the overall business workflow becomes increasingly difficult. Instead of one visible process, the Saga becomes scattered across many services.</p>

<p>To understand why a shipment wasn’t created, you may need to inspect logs from the Order Service, Inventory Service, Payment Service, Shipping Service, and Notification Service. The workflow still exists, it’s simply distributed across the entire system.</p>

<hr />

<h3 id="orchestration">Orchestration</h3>

<p>Now imagine the same dancers performing with a conductor standing at the front. Instead of reacting to one another, every performer follows instructions from a single leader. This is orchestration. Rather than allowing services to coordinate themselves, a dedicated component, often called the <strong>Saga Orchestrator</strong>, controls the entire workflow. The orchestrator tells each service what to do next.</p>

<pre><code class="language-text">Saga Orchestrator

        │

        ▼

Create Order

        │

        ▼

Reserve Inventory

        │

        ▼

Charge Payment

        │

        ▼

Create Shipment
</code></pre>

<p>If every step succeeds, the orchestrator declares the Saga complete. If a failure occurs, it explicitly instructs previous services to execute their compensating transactions.</p>

<pre><code class="language-text">Shipment Failed

        │

        ▼

Refund Payment

        │

        ▼

Release Inventory

        │

        ▼

Cancel Order
</code></pre>

<p>Unlike choreography, every decision is visible in one place. Need to understand the business process? Read the orchestrator. Need to change the workflow? Modify one component instead of updating several independent services. This centralized view makes orchestration particularly appealing for complex business processes involving many steps, conditional logic, or approval workflows. The trade-off, however, is tighter coupling. The orchestrator must understand every participating service, making it more aware of the overall system than any individual service would be in a choreographed Saga. Neither approach is universally better. The right choice depends on the complexity of the workflow and the level of control your application requires.</p>

<hr />

<h3 id="choreography-vs-orchestration">Choreography vs Orchestration</h3>

<p>A useful way to compare them is to think about where the business logic lives. With choreography, the workflow is distributed across many services, and every service contributes a small piece of the overall process by responding to events. With orchestration, the workflow lives inside a single coordinator that explicitly directs every participant.</p>

<table>
  <thead>
    <tr>
      <th>Choreography</th>
      <th>Orchestration</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Event-driven</td>
      <td>Command-driven</td>
    </tr>
    <tr>
      <td>Highly decoupled</td>
      <td>Central coordinator</td>
    </tr>
    <tr>
      <td>Easy to extend</td>
      <td>Easy to understand</td>
    </tr>
    <tr>
      <td>Workflow spread across services</td>
      <td>Workflow visible in one place</td>
    </tr>
    <tr>
      <td>Can become difficult to trace</td>
      <td>Coordinator becomes more complex</td>
    </tr>
  </tbody>
</table>

<p>Small event-driven systems often benefit from choreography because new consumers can easily subscribe to existing events. Larger enterprise workflows frequently choose orchestration because business rules remain easier to understand and maintain.</p>

<hr />

<h3 id="real-world-examples">Real-World Examples</h3>

<p>By now, you’ve probably encountered situations where the Saga Pattern would be useful without realizing it. An online retailer processing orders, a loan management platform approving applications, an airline booking system reserving flights, or a hotel reservation platform coordinating room availability all involve multiple independent services participating in a single business process. Consider a digital lending platform. When a borrower accepts a loan offer, several services may participate:</p>

<ul>
  <li>The Loan Service creates the loan account.</li>
  <li>The Disbursement Service sends funds.</li>
  <li>The Accounting Service records journal entries.</li>
  <li>The Notification Service sends an SMS.</li>
  <li>The Credit Bureau Service updates the borrower’s status.</li>
</ul>

<p>If the disbursement fails because the customer’s bank account is invalid, the system shouldn’t leave behind a partially created loan. Instead, compensating actions mark the loan as cancelled, reverse accounting entries where necessary, and notify the customer that disbursement was unsuccessful. No database rollback spans all these services, and the Saga restores business consistency through coordinated business actions.</p>

<hr />

<h3 id="common-mistakes">Common Mistakes</h3>

<p>The Saga Pattern is powerful, but it’s not a silver bullet. One common mistake is trying to treat compensating transactions as database rollbacks. They aren’t. Compensation should reverse business effects, not erase history. Another mistake is making Saga steps too large. Every local transaction should remain focused and complete quickly. Long-running database transactions reduce scalability and increase the likelihood of contention. It’s also important to remember that messaging is rarely perfect. Duplicate events, delayed delivery, and retries are normal in distributed systems. Every participating service should therefore be designed with idempotency in mind. Finally, don’t introduce a Saga simply because your application uses microservices. If a workflow only involves one service and one database, a normal database transaction is usually the simpler and better solution. Sagas solve distributed coordination problems, not ordinary CRUD operations.</p>

<hr />

<h3 id="saga-pattern-vs-traditional-transactions">Saga Pattern vs Traditional Transactions</h3>

<p>At first glance, Sagas and database transactions appear to solve similar problems. In reality, they operate at completely different levels. A database transaction guarantees consistency within a single database; a Saga guarantees business consistency across multiple independent services. One relies on rollback, the other relies on compensation. One typically completes in milliseconds, while the other may run for several minutes, or even hours, depending on the business process. They’re not competing approaches. As you’ve seen throughout this series, they complement one another. In fact, a single Saga step usually contains its own local database transaction.</p>

<hr />

<h3 id="bringing-it-all-together">Bringing It All Together</h3>

<p>At this point in the <strong>Beyond CRUD</strong> series, we’ve gradually built a toolkit for designing reliable backend systems. Each concept answers a different engineering question.</p>

<table>
  <thead>
    <tr>
      <th>Concept</th>
      <th>Question It Answers</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><strong>Idempotency</strong></td>
      <td>What if the same request arrives twice?</td>
    </tr>
    <tr>
      <td><strong>Race Conditions</strong></td>
      <td>What if multiple requests modify the same data simultaneously?</td>
    </tr>
    <tr>
      <td><strong>Database Transactions</strong></td>
      <td>How do I keep multiple database operations atomic?</td>
    </tr>
    <tr>
      <td><strong>Isolation Levels</strong></td>
      <td>What should concurrent transactions be allowed to see?</td>
    </tr>
    <tr>
      <td><strong>Distributed Locks</strong></td>
      <td>How do multiple application instances coordinate shared work?</td>
    </tr>
    <tr>
      <td><strong>Outbox Pattern</strong></td>
      <td>How do I reliably publish events after committing data?</td>
    </tr>
    <tr>
      <td><strong>Saga Pattern</strong></td>
      <td>How do multiple services complete one business process reliably?</td>
    </tr>
  </tbody>
</table>

<p>Notice how every concept builds upon the previous one. None replaces the others, and reliable distributed systems emerge when these patterns work together.</p>

<hr />

<h3 id="final-thoughts">Final Thoughts</h3>

<p>Building software inside a single database is relatively straightforward. Building software that spans dozens of independent services is something else entirely. The challenge isn’t simply writing correct code, it’s ensuring that business processes continue making sense even when networks fail, services restart, or one step succeeds while another doesn’t.</p>

<p>The Saga Pattern embraces these realities rather than fighting them. Instead of relying on one enormous transaction that spans every service, it coordinates many smaller transactions while providing a structured way to recover when failures occur. That mindset has become one of the defining characteristics of modern cloud-native architecture. As your systems continue growing, you’ll discover that reliable software isn’t built by eliminating failures, it’s built by designing systems that expect failures and know exactly how to recover from them.</p>

<hr />

<h3 id="whats-next">What’s Next?</h3>

<p>So far, we’ve focused primarily on making writes reliable, but as applications grow, another challenge begins to emerge. Reading data efficiently often requires very different models from writing it. Should the same model be responsible for both, or should we optimize reads and writes independently?</p>

<p>In the next article, we’ll explore <strong>CQRS Explained: Separating Reads and Writes for Scalable Systems</strong>, a pattern that allows applications to scale, simplify complex queries, and build richer user experiences without overloading their write models.</p>
]]></content:encoded>
      <author>billycartel360@gmail.com (Billy Okeyo)</author>
  
      <media:content url="https://billyokeyo.dev/assets/img/saga-pattern.jpg" medium="image" />
  
  
    
      <category>Distributed Systems</category>
    
      <category>Concurrency</category>
    
  
  
    
      <category>Distributed Systems</category>
    
      <category>Concurrency</category>
    
  
    </item>

  
  





  



  


    <item>
      <title>The Outbox Pattern Explained: Publishing Events Without Losing Data</title>
      <link>https://billyokeyo.dev/posts/outbox-patterns-explained/</link>
      <guid isPermaLink="true">https://billyokeyo.dev/posts/outbox-patterns-explained/</guid>
      <pubDate>Mon, 20 Jul 2026 00:00:00 +0000</pubDate>
  
      <atom:updated>2026-07-20T00:00:00+00:00</atom:updated>
  
      <description><![CDATA[The Outbox Pattern is a technique for ensuring that a database update and an event publication either happen together, or are eventually made consistent. This article explains what the Outbox Pattern is, why it is important, and how it works.]]></description>
      <content:encoded><![CDATA[<blockquote>
  <p><em>“A database transaction can guarantee your data is correct. It cannot guarantee the rest of your system knows about it.”</em></p>
</blockquote>

<p>Imagine you’re building an e-commerce platform. A customer places an order, and your application begins processing the request. Inside a database transaction, it creates the order, deducts the purchased items from inventory, records the payment, and commits the transaction successfully. From the perspective of the database, everything has gone exactly as planned. Every change has been saved, every business rule has been respected, and the transaction completes without error.</p>

<p>If this were a monolithic application, the story might end there, but modern software rarely consists of a single application. The moment an order is created, several other systems need to react. A shipping service must prepare the package, an email service needs to send an order confirmation, an analytics platform wants to record another sale, a loyalty service may award reward points, and an accounting system might need to generate journal entries. Rather than constantly querying the orders table looking for changes, these services usually rely on events published through a message broker such as Kafka, RabbitMQ, Azure Service Bus, or Amazon SQS.</p>

<p>A straightforward implementation seems almost obvious: once the transaction commits successfully, publish an <strong>OrderCreated</strong> event.</p>

<pre><code class="language-text">BEGIN TRANSACTION

↓

Create Order

↓

Reduce Inventory

↓

Record Payment

↓

COMMIT

↓

Publish OrderCreated Event
</code></pre>

<p>At first glance, there’s nothing wrong with this approach, until something fails. Suppose the database transaction commits successfully, permanently saving the customer’s order. A fraction of a second later, however, Kafka becomes temporarily unavailable. Perhaps RabbitMQ disconnects, or maybe the application crashes before it can publish the event.</p>

<p>The order now exists in the database, the customer’s payment has been processed, and inventory has already been reduced, yet none of the downstream services know the purchase ever happened. The warehouse never receives instructions to prepare the shipment, the customer never receives a confirmation email, the analytics dashboard quietly reports incorrect sales figures, and the accounting system never records the transaction.</p>

<p>Nothing inside the database is inconsistent. The inconsistency exists <strong>between systems</strong>.</p>

<p>This subtle failure is one of the most common reliability problems in distributed architectures. It’s known as the <strong>Dual-Write Problem</strong>, and it’s surprisingly easy to introduce because writing to a database and publishing an event are two completely independent operations. One can succeed while the other fails, leaving different parts of the system with different versions of reality.</p>

<p>In our previous articles, we’ve explored how transactions protect database operations, how isolation levels govern concurrent access to data, and how distributed locks coordinate work across multiple application servers. The Outbox Pattern builds on those concepts by solving a different challenge: ensuring that once your database commits a change, the rest of your system will eventually learn about it as well.</p>

<p>Before we look at the solution, let’s first understand why this seemingly simple problem is much harder than it appears.</p>

<hr />

<h4 id="the-dual-write-problem">The Dual-Write Problem</h4>

<p>The Dual-Write Problem occurs whenever an application attempts to update two independent systems as part of a single business operation. One system is usually your database; the other is typically a message broker, search index, cache, analytics platform, or another external service. Although these updates feel like one logical operation, they are technically two completely separate actions.</p>

<p>Consider an online banking application. When a customer transfers money, the application updates account balances inside the database. Afterward, it publishes a <strong>MoneyTransferred</strong> event so other services can respond. A fraud detection system may inspect the transaction, a notification service may send an SMS, and an accounting platform may update its ledgers.</p>

<p>Conceptually, all of this represents one business event, but technically, it looks more like this:</p>

<pre><code class="language-text">Update Database

↓

Publish Event
</code></pre>

<p>The problem is that neither system knows anything about the other. Your database has no idea whether Kafka accepted the message, and Kafka has no knowledge of whether your SQL transaction committed successfully. They’re completely independent, and that independence creates four possible outcomes.</p>

<table>
  <thead>
    <tr>
      <th>Database</th>
      <th>Event</th>
      <th>Result</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>✅ Success</td>
      <td>✅ Success</td>
      <td>Everything works correctly.</td>
    </tr>
    <tr>
      <td>❌ Failure</td>
      <td>❌ Failure</td>
      <td>Nothing happens, which is acceptable.</td>
    </tr>
    <tr>
      <td>❌ Failure</td>
      <td>✅ Success</td>
      <td>Downstream systems react to an event for data that doesn’t exist.</td>
    </tr>
    <tr>
      <td>✅ Success</td>
      <td>❌ Failure</td>
      <td>The database is correct, but no other service knows the change occurred.</td>
    </tr>
  </tbody>
</table>

<p>The first two outcomes are easy to reason about, but it’s the final two that create serious problems. If an event is published for data that never commits, downstream services begin processing information that doesn’t actually exist. Equally dangerous is the opposite scenario, where the database commits successfully but the event is never published. From that moment onward, every service in the architecture has a different understanding of reality. This isn’t merely an inconvenience; it’s a consistency problem that becomes increasingly difficult to detect as systems grow.</p>

<hr />

<h3 id="why-transactions-cant-solve-this">Why Transactions Can’t Solve This</h3>

<p>A natural question follows: why not simply include the message broker inside the database transaction? Unfortunately, that’s not how database transactions work. Transactions provide atomicity because every operation is coordinated by the same database engine. The database controls when the transaction begins, when it commits, and when it rolls back. Every SQL statement participates in that process because they’re all executed by the same system.</p>

<p>A message broker lives outside that boundary. Kafka doesn’t participate in your PostgreSQL transaction, RabbitMQ doesn’t know your SQL Server transaction exists, and PostgreSQL has no mechanism for asking Kafka whether a message was published successfully before committing the transaction. In other words, there is no shared transaction manager coordinating both systems.</p>

<p>Years ago, technologies such as <strong>Two-Phase Commit (2PC)</strong> attempted to solve this problem by coordinating transactions across multiple systems. Although theoretically appealing, they introduced significant complexity, increased latency, reduced availability, and often became bottlenecks in distributed environments.</p>

<p>As microservices became more popular, the industry gradually moved toward simpler, more resilient approaches. Rather than trying to make two systems commit simultaneously, engineers began asking a different question:</p>

<blockquote>
  <p><strong>What if we only committed to one system first and made the second system eventually consistent?</strong></p>
</blockquote>

<p>That shift in thinking led to one of the most influential patterns in modern backend architecture: the <strong>Outbox Pattern</strong>.</p>

<h3 id="what-is-the-outbox-pattern">What Is the Outbox Pattern?</h3>

<p>The Outbox Pattern solves the Dual-Write Problem by changing the order in which work is performed. Instead of attempting to update the database and publish an event as part of the same operation, the application first commits everything it needs to the database, including the event itself. That last part is the key. Rather than sending the event directly to Kafka or RabbitMQ, the application writes the event into a dedicated database table commonly known as the <strong>outbox</strong>.</p>

<p>Because the business data and the outbox record are written inside the <strong>same database transaction</strong>, they succeed or fail together. If the transaction commits, both the business data and the event are safely stored; if it rolls back, neither exists. Only after the transaction has completed does another process read events from the outbox table and publish them to the message broker.</p>

<p>Conceptually, the workflow changes from this:</p>

<pre><code class="language-text">Update Database

↓

Publish Event
</code></pre>

<p>to this:</p>

<pre><code class="language-text">BEGIN TRANSACTION

↓

Update Business Data

↓

Insert Event Into Outbox

↓

COMMIT

↓

Background Publisher Reads Outbox

↓

Publish Event

↓

Mark Event As Published
</code></pre>

<p>At first glance, this may seem like a small adjustment, but in reality, it completely changes the reliability characteristics of your application. The application is no longer trying to coordinate two independent systems within the same request. Instead, it commits to a single source of truth, the database, and lets another process handle communication with external systems afterward. If the message broker is temporarily unavailable, nothing is lost. The event is already safely stored inside the database and simply waits until the publisher can deliver it.</p>

<hr />

<h3 id="understanding-the-outbox-table">Understanding the Outbox Table</h3>

<p>The outbox itself is usually nothing more than a normal database table. A simplified version might look like this:</p>

<table>
  <thead>
    <tr>
      <th style="text-align: right">id</th>
      <th>event_type</th>
      <th>payload</th>
      <th>created_at</th>
      <th>published_at</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td style="text-align: right">1</td>
      <td>OrderCreated</td>
      <td>{…}</td>
      <td>2026-07-01 10:15</td>
      <td>NULL</td>
    </tr>
    <tr>
      <td style="text-align: right">2</td>
      <td>PaymentReceived</td>
      <td>{…}</td>
      <td>2026-07-01 10:16</td>
      <td>NULL</td>
    </tr>
    <tr>
      <td style="text-align: right">3</td>
      <td>UserRegistered</td>
      <td>{…}</td>
      <td>2026-07-01 10:18</td>
      <td>2026-07-01 10:18</td>
    </tr>
  </tbody>
</table>

<p>Each row represents an event that should eventually be delivered. Notice the <code>published_at</code> column: rows where this value is <code>NULL</code> haven’t yet been published, while rows with a timestamp have already been successfully delivered.</p>

<p>The outbox isn’t intended to become a permanent event store. Instead, it acts as a reliable staging area between your transactional database and your messaging infrastructure. Once an event has been published successfully, and your retention policy allows, it can be archived or deleted.</p>

<hr />

<h3 id="a-complete-walkthrough">A Complete Walkthrough</h3>

<p>Let’s revisit our e-commerce example. A customer purchases a laptop. Inside a single transaction, the application performs three operations: first, it creates the order; second, it deducts one item from inventory; and finally, instead of publishing an event immediately, it inserts a new row into the outbox table describing what happened.</p>

<pre><code class="language-text">BEGIN TRANSACTION

↓

INSERT Order

↓

UPDATE Inventory

↓

INSERT Outbox Event

↓

COMMIT
</code></pre>

<p>At this point, the customer’s purchase has been committed successfully, and just as importantly, the event describing that purchase has also been committed. Suppose Kafka goes offline immediately afterward: the request still succeeds, nothing has been lost, and the application doesn’t need to roll back the order because the event hasn’t disappeared. It is sitting safely inside the outbox table waiting to be delivered.</p>

<p>A separate publisher service periodically checks the outbox. When Kafka becomes available again, it publishes the event and updates the record to indicate that delivery succeeded.</p>

<pre><code class="language-text">Outbox Publisher

↓

Read Unpublished Events

↓

Publish To Kafka

↓

Success?

      │

   Yes │ No

      │

Mark Published

      │

Retry Later
</code></pre>

<p>Notice something important: the user’s request is no longer responsible for talking to Kafka. Its only responsibility is ensuring that the event is safely recorded, and publishing becomes a separate concern. That separation dramatically improves reliability because temporary failures in external systems no longer affect the original business transaction.</p>

<hr />

<h3 id="why-this-works">Why This Works</h3>

<p>The elegance of the Outbox Pattern comes from the fact that it reduces a distributed systems problem to a database problem. Earlier in this series, we spent considerable time discussing transactions and learned that they guarantee a group of related database operations either all succeed or all fail together. The Outbox Pattern deliberately takes advantage of that guarantee: instead of asking a database and a message broker to commit simultaneously, a task they were never designed to perform, it asks only the database to commit. Since both the business data and the outbox record live inside the same database, the transaction naturally guarantees their consistency.</p>

<p>Everything after that becomes a delivery problem rather than a consistency problem. Even if the publisher crashes, Kafka becomes unavailable, or the network experiences intermittent failures, the event remains safely stored. The publisher will eventually retry, and the event will eventually be delivered. The system moves from requiring <strong>immediate consistency</strong> between the database and the message broker to achieving <strong>eventual consistency</strong> in a reliable and predictable way. That single shift in mindset is what has made the Outbox Pattern one of the most widely adopted reliability patterns in modern distributed systems.</p>

<hr />

<h3 id="why-not-publish-immediately-after-the-commit">Why Not Publish Immediately After the Commit?</h3>

<p>Some developers look at the Outbox Pattern and ask a reasonable question: “If the transaction has already committed successfully, why not simply publish the event right afterward and retry if it fails?” The problem is that retries only work if the application survives long enough to perform them.</p>

<p>Imagine the following sequence of events:</p>

<pre><code class="language-text">COMMIT Transaction

↓

Application Crashes

↓

Restart
</code></pre>

<p>The order exists, the event was never published, and the application has no memory that it still owes Kafka an event because that information was never persisted anywhere. With an outbox table, the event survives the crash because it was committed alongside the business data. When the publisher starts again, it simply resumes reading unpublished events from the database. The application doesn’t have to remember what happened because the database already does.</p>

<p>This is one of the reasons the Outbox Pattern is so resilient. It relies on durable storage rather than application memory, making it naturally tolerant of crashes, restarts, and temporary infrastructure failures.</p>

<h3 id="how-events-leave-the-outbox">How Events Leave the Outbox</h3>

<p>By now, we’ve established that the application’s responsibility ends once the business data and the corresponding event have been committed to the database. The next challenge is equally important: <strong>How do those events actually reach Kafka, RabbitMQ, or another messaging system?</strong></p>

<p>Broadly speaking, there are two common approaches. The first is a <strong>Polling Publisher</strong>, where a background worker periodically checks the outbox table for unpublished events. Every few seconds, or even every few milliseconds, it queries the database, publishes any pending events, and marks them as successfully delivered.</p>

<p>Conceptually, the process looks like this:</p>

<pre><code class="language-text">Background Publisher

↓

Query Outbox

↓

Find Unpublished Events

↓

Publish Event

↓

Success?

     │

 Yes │ No

     │

Mark Published

     │

Retry Later
</code></pre>

<p>This approach is simple to understand, easy to implement, and works well for many applications. Since the publisher operates independently of the original request, temporary failures in Kafka or RabbitMQ don’t affect users. If publishing fails, the worker simply retries later.</p>

<p>The second approach is <strong>Change Data Capture (CDC)</strong>. Instead of periodically querying the outbox table, a CDC tool monitors the database’s transaction log and automatically detects newly inserted outbox records. As soon as a new event appears, the tool publishes it to the message broker.</p>

<p>One of the most popular CDC solutions is <strong>Debezium</strong>, which integrates with databases such as PostgreSQL, MySQL, and SQL Server. Rather than polling the database repeatedly, Debezium continuously streams database changes, reducing unnecessary queries while providing near real-time event publication. Both approaches solve the same problem. Polling is generally simpler and perfectly adequate for many systems, while CDC becomes attractive when applications process very large numbers of events or require lower publishing latency.</p>

<hr />

<h3 id="real-world-examples">Real-World Examples</h3>

<p>The Outbox Pattern appears in many more places than developers often realize. Once you begin recognizing the Dual-Write Problem, you start seeing it almost everywhere.</p>

<h4 id="e-commerce">E-Commerce</h4>

<p>A customer places an order. The transaction creates the order, updates inventory, and inserts an <strong>OrderCreated</strong> event into the outbox. Later, the publisher delivers that event to Kafka, and other services respond independently:</p>

<ul>
  <li>Shipping prepares the package.</li>
  <li>Email sends the confirmation.</li>
  <li>Analytics records the sale.</li>
  <li>Loyalty awards points.</li>
</ul>

<p>Every service receives exactly the same event without the original request needing to coordinate them.</p>

<hr />

<h4 id="loan-management-systems">Loan Management Systems</h4>

<p>Suppose a borrower makes a repayment. Inside a transaction, the application updates the loan balance, records the payment, recalculates outstanding interest, and inserts a <strong>LoanRepaymentReceived</strong> event into the outbox. Once published, other systems can react independently. The accounting service posts journal entries, the notification service sends an SMS receipt, reporting dashboards update repayment statistics, and credit scoring services refresh customer profiles. The repayment itself remains fast because none of these downstream systems participate in the original transaction.</p>

<hr />

<h4 id="user-registration">User Registration</h4>

<p>A customer creates a new account. The application stores the user’s information and writes a <strong>UserRegistered</strong> event into the outbox. Later, other services consume the event. An email service sends a welcome message, a CRM platform creates a customer profile, a marketing system subscribes the user to onboarding campaigns, and a recommendation engine begins generating personalized suggestions. The registration endpoint doesn’t need to know anything about those systems; its only responsibility is recording that the registration occurred.</p>

<hr />

<h4 id="payment-processing">Payment Processing</h4>

<p>Imagine a payment gateway confirms a successful transaction. The payment service updates account balances, records the payment, and inserts a <strong>PaymentCompleted</strong> event. Even if Kafka becomes unavailable immediately afterward, the payment itself isn’t lost. Once messaging resumes, the event is delivered and downstream systems continue exactly where they left off.</p>

<hr />

<h3 id="benefits-of-the-outbox-pattern">Benefits of the Outbox Pattern</h3>

<p>One of the reasons the Outbox Pattern has become so widely adopted is that it solves several problems simultaneously. First, it provides <strong>reliability</strong>. Once an event has been written into the outbox, it becomes durable. Temporary network failures, message broker outages, or application crashes no longer result in permanently lost events. Second, it simplifies application code. Rather than forcing every request to coordinate database updates and message publication, the request focuses exclusively on committing business data, and event publication becomes the responsibility of a dedicated background process. Third, it improves scalability. Because event publication happens asynchronously, user requests complete more quickly, and slow downstream systems no longer delay the original transaction. Finally, it naturally embraces <strong>eventual consistency</strong>. Instead of requiring every service to update simultaneously, the system guarantees that every interested service will eventually receive the event once communication becomes available.</p>

<hr />

<h3 id="common-mistakes">Common Mistakes</h3>

<p>Like every architectural pattern, the Outbox Pattern can be implemented incorrectly.</p>

<p>One common mistake is assuming that publishing an event means the work is finished. Publishing only guarantees that the message reached the broker. Consumers may still fail, messages may still be retried, and downstream services must therefore remain resilient and, where appropriate, idempotent.</p>

<p>Another common mistake is forgetting to clean up the outbox table. If events remain forever, the table will continue growing until queries become unnecessarily expensive. Most production systems archive or remove published events after an appropriate retention period.</p>

<p>Developers also sometimes attempt to perform expensive business logic inside the publisher. The publisher should remain intentionally simple. Its responsibility is publishing events, not recalculating business rules or modifying application state.</p>

<p>Finally, don’t assume every database change requires an event. Publishing unnecessary events creates noise, increases infrastructure costs, and makes systems more difficult to understand. Good events represent meaningful business occurrences, not individual SQL statements.</p>

<hr />

<h3 id="outbox-pattern-vs-distributed-transactions">Outbox Pattern vs Distributed Transactions</h3>

<p>At first glance, the Outbox Pattern and distributed transactions appear to solve the same problem. Both attempt to coordinate work across multiple systems, but the difference lies in how they approach consistency. Distributed transactions attempt to make every participating system commit or roll back together. The Outbox Pattern accepts that this is often impractical in distributed architectures. Instead, it commits business data first and guarantees that events will eventually be delivered. This approach sacrifices immediate consistency in exchange for simplicity, resilience, and availability. For modern cloud-native applications, that trade-off is often the better engineering decision.</p>

<hr />

<h3 id="outbox-pattern-vs-event-sourcing">Outbox Pattern vs Event Sourcing</h3>

<p>The Outbox Pattern is also frequently confused with Event Sourcing. Although both involve events, they solve entirely different problems. With the Outbox Pattern, the database remains the primary source of truth, and events simply communicate that something has happened. With Event Sourcing, events <strong>are</strong> the source of truth. Instead of storing the current state of an order or account, the system stores every event that led to its current state, and the application reconstructs state by replaying those events.</p>

<p>An outbox event might say:</p>

<blockquote>
  <p>Order Created.</p>
</blockquote>

<p>An event-sourced system would permanently record every event throughout the order’s lifetime:</p>

<ul>
  <li>Order Created</li>
  <li>Payment Authorized</li>
  <li>Inventory Reserved</li>
  <li>Shipment Prepared</li>
  <li>Order Delivered</li>
</ul>

<p>Both patterns involve events, but only Event Sourcing uses them to reconstruct application state.</p>

<hr />

<h3 id="best-practices">Best Practices</h3>

<p>If you’re considering adopting the Outbox Pattern, several practices consistently lead to reliable implementations.</p>

<p>Keep the outbox in the same database as your business data so that both participate in the same transaction.</p>

<p>Design your publisher to be idempotent wherever possible. Network failures and retries are inevitable, and duplicate publication attempts should never produce incorrect results.</p>

<p>Monitor the outbox table. A growing backlog of unpublished events is often the earliest warning sign that something is wrong with your messaging infrastructure.</p>

<p>Treat event schemas as part of your public contract. Once other services depend on them, changing them carelessly becomes just as risky as changing a public API.</p>

<p>Finally, remember that publishing an event doesn’t guarantee it has been processed. Downstream services should always be designed to handle retries, duplicates, and temporary failures gracefully.</p>

<hr />

<h3 id="bringing-it-all-together">Bringing It All Together</h3>

<p>At this point in the series, we’ve explored several techniques for building reliable software systems. Each one addresses a different question.</p>

<table>
  <thead>
    <tr>
      <th>Concept</th>
      <th>Question It Answers</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><strong>Idempotency</strong></td>
      <td>What if the same request is sent twice?</td>
    </tr>
    <tr>
      <td><strong>Race Conditions</strong></td>
      <td>What if multiple requests modify the same data simultaneously?</td>
    </tr>
    <tr>
      <td><strong>Database Transactions</strong></td>
      <td>What if part of my database operation fails?</td>
    </tr>
    <tr>
      <td><strong>Isolation Levels</strong></td>
      <td>What should concurrent transactions be allowed to see?</td>
    </tr>
    <tr>
      <td><strong>Distributed Locks</strong></td>
      <td>How do multiple servers coordinate work?</td>
    </tr>
    <tr>
      <td><strong>Outbox Pattern</strong></td>
      <td>How do I reliably notify other systems after committing data?</td>
    </tr>
  </tbody>
</table>

<p>Notice the progression: the concepts don’t replace one another, they build upon one another. Modern backend systems are reliable precisely because they combine multiple patterns, each solving a different class of failure.</p>

<hr />

<h3 id="final-thoughts">Final Thoughts</h3>

<p>One of the defining characteristics of distributed systems is that communication eventually fails. Networks become unreliable, applications restart, and message brokers experience outages. Trying to eliminate these failures entirely is unrealistic.</p>

<p>The Outbox Pattern embraces this reality by changing the problem. Instead of attempting to guarantee that two independent systems succeed simultaneously, it guarantees that business data is safely committed first and that communication will eventually catch up. This seemingly small architectural decision dramatically improves reliability because it removes timing from the equation. Your application no longer depends on Kafka, RabbitMQ, or another messaging system being available at the exact moment a customer submits a request. Instead, it relies on something your database already does exceptionally well: storing data reliably.</p>

<p>The next time you find yourself writing code that updates a database and immediately publishes an event, pause for a moment and ask yourself:</p>

<blockquote>
  <p><strong>“What happens if my database succeeds but my message broker doesn’t?”</strong></p>
</blockquote>

<p>If the answer is “my systems become inconsistent,” you’ve probably found a place where the Outbox Pattern belongs.</p>

<hr />

<h3 id="whats-next">What’s Next?</h3>

<p>So far in this series, we’ve focused on making individual operations reliable. But what happens when a single business process spans <strong>multiple microservices</strong>, each with its own database and transaction?</p>

<p>Imagine placing an order that requires the payment service, inventory service, shipping service, and notification service to all complete successfully. What happens if one of those services fails halfway through?</p>

<p>In the next article, we’ll explore the <strong>Saga Pattern</strong>, one of the most widely used approaches for coordinating long-running business transactions across distributed systems.</p>

]]></content:encoded>
      <author>billycartel360@gmail.com (Billy Okeyo)</author>
  
      <media:content url="https://billyokeyo.dev/assets/img/outbox-pattern.jpg" medium="image" />
  
  
    
      <category>Distributed Systems</category>
    
      <category>Concurrency</category>
    
  
  
    
      <category>Distributed Systems</category>
    
      <category>Concurrency</category>
    
  
    </item>

  
  





  



  


    <item>
      <title>Distributed Locks Explained: Technologies That Implement Distributed Locks</title>
      <link>https://billyokeyo.dev/posts/distributed-locks-explained-part-2/</link>
      <guid isPermaLink="true">https://billyokeyo.dev/posts/distributed-locks-explained-part-2/</guid>
      <pubDate>Fri, 17 Jul 2026 00:00:00 +0000</pubDate>
  
      <atom:updated>2026-07-17T00:00:00+00:00</atom:updated>
  
      <description><![CDATA[Distributed locks are a coordination mechanism that allows multiple independent servers to agree that only one of them may perform a particular operation at a given time. This article explains what distributed locks are, why they are important, and how they work.]]></description>
      <content:encoded><![CDATA[<p>Now that we understand how distributed locks work conceptually, the next question becomes:</p>

<blockquote>
  <p><strong>Where do these locks actually live?</strong></p>
</blockquote>

<p>Unlike database transactions, distributed locks cannot rely on the memory of a single application server. Remember, our application might be running on five, ten, or even hundreds of machines, and every server must consult the same source of truth before deciding whether it may perform a particular operation.</p>

<p>Over the years, several technologies have emerged to solve this coordination problem. Although they all provide distributed locking capabilities, they were designed with slightly different goals in mind. Let’s look at the most common ones.</p>

<hr />

<h2 id="redis">Redis</h2>

<p>For most web applications, <strong>Redis</strong> is by far the most popular choice. Originally designed as an in-memory data store, Redis is incredibly fast, making it an excellent candidate for lightweight coordination tasks.</p>

<p>Acquiring a lock in Redis is surprisingly straightforward. A server attempts to create a key using an atomic command that says, in effect:</p>

<blockquote>
  <p>“Create this key only if it doesn’t already exist.”</p>
</blockquote>

<p>If Redis successfully creates the key, the server owns the lock; if the key already exists, another server is already performing the work. Because Redis executes this operation atomically, two servers can never successfully create the same lock at the same time.</p>

<p>A simplified example looks like this:</p>

<pre><code class="language-text">SET invoice-generation

Server-A

NX

EX 30
</code></pre>

<p>The command says:</p>

<ul>
  <li>Create the key only if it doesn’t already exist (<code>NX</code>).</li>
  <li>Automatically expire it after thirty seconds (<code>EX 30</code>).</li>
</ul>

<p>In one atomic operation, Redis both acquires the lock and ensures it won’t remain forever if the server crashes. For many applications, this is all that’s needed.</p>

<hr />

<h2 id="why-redis-is-so-popular">Why Redis Is So Popular</h2>

<p>Redis has become the default choice for distributed locks because it satisfies three important requirements. First, it’s extremely fast: since Redis stores data in memory rather than on disk, lock acquisition usually takes only a few milliseconds. Second, many applications already use Redis for caching, sessions, queues, or rate limiting, so adding distributed locking often requires little additional infrastructure. Finally, Redis has mature client libraries for virtually every programming language, with Laravel, Django, Spring Boot, .NET, Node.js, and Go all providing excellent Redis support.</p>

<p>For the vast majority of business applications, Redis offers an excellent balance between simplicity, performance, and reliability.</p>

<hr />

<h2 id="the-challenge-with-a-single-redis-instance">The Challenge with a Single Redis Instance</h2>

<p>Suppose your entire application depends on one Redis server. Everything works perfectly, then Redis crashes. Suddenly, no application server can acquire new locks, and even worse, if Redis loses its in-memory state during a restart, locks may disappear unexpectedly.</p>

<p>This introduces a new challenge: the coordinator itself has become a single point of failure. For many applications, this risk is acceptable. For others, particularly financial systems or globally distributed services, it isn’t. This challenge led to one of the most discussed topics in distributed systems: the <strong>Redlock algorithm</strong>.</p>

<hr />

<h2 id="the-redlock-algorithm">The Redlock Algorithm</h2>

<p>Redlock was proposed by Redis creator <strong>Salvatore Sanfilippo</strong> as a way to make Redis-based distributed locks more resilient. Instead of relying on one Redis server, Redlock uses multiple independent Redis instances.</p>

<p>Imagine five Redis servers.</p>

<pre><code>Redis 1

Redis 2

Redis 3

Redis 4

Redis 5
</code></pre>

<p>When acquiring a lock, the application attempts to obtain it from all five servers, and the lock is considered successful only if a majority agree.</p>

<p>For example:</p>

<pre><code>Acquire Lock

↓

Redis 1 ✅

Redis 2 ✅

Redis 3 ✅

Redis 4 ❌

Redis 5 ❌
</code></pre>

<p>Three out of five succeeded, so the application proceeds. If only two servers grant the lock, the operation fails because a majority wasn’t reached. This approach significantly reduces the impact of individual Redis failures.</p>

<p>However, Redlock is also one of the most debated algorithms in distributed systems. Some engineers argue that it’s sufficient for many practical systems, while others, including Martin Kleppmann, have published detailed critiques explaining situations where Redlock may not provide the guarantees developers expect. The important lesson isn’t that Redlock is good or bad; it’s that distributed systems involve trade-offs, and understanding those trade-offs matters more than memorizing algorithms.</p>

<hr />

<h2 id="zookeeper">ZooKeeper</h2>

<p>Long before Redis became popular for distributed locking, many large distributed systems relied on <strong>Apache ZooKeeper</strong>. ZooKeeper was designed specifically for coordination. Rather than functioning as a cache, it provides services such as:</p>

<ul>
  <li>Distributed locks</li>
  <li>Leader election</li>
  <li>Configuration management</li>
  <li>Service discovery</li>
</ul>

<p>Think of ZooKeeper as a highly reliable coordinator for distributed applications. Its primary goal isn’t speed, it’s correctness. Large systems such as Apache Kafka, Hadoop, and HBase have historically relied on ZooKeeper to coordinate clusters of machines. If your application requires complex distributed coordination rather than simple locking, ZooKeeper remains an excellent choice.</p>

<hr />

<h2 id="etcd">etcd</h2>

<p>If you’ve worked with Kubernetes, you’ve already encountered <strong>etcd</strong>, even if you didn’t realize it. Every Kubernetes cluster stores its configuration inside etcd. Like ZooKeeper, etcd is a distributed key-value store designed for coordination rather than caching. It provides:</p>

<ul>
  <li>Distributed locks</li>
  <li>Leader election</li>
  <li>Configuration storage</li>
  <li>Consensus</li>
  <li>Service coordination</li>
</ul>

<p>Unlike Redis, etcd prioritizes consistency over raw performance. Its API is also designed around long-lived leases, making lock management particularly elegant. Modern cloud-native applications frequently choose etcd when they already operate within Kubernetes ecosystems.</p>

<hr />

<h2 id="consul">Consul</h2>

<p>HashiCorp <strong>Consul</strong> occupies a similar space. Although many developers know Consul for service discovery, it also provides distributed locking capabilities through sessions. Organizations using Consul often rely on it for:</p>

<ul>
  <li>Service registration</li>
  <li>Health checks</li>
  <li>Distributed configuration</li>
  <li>Leader election</li>
  <li>Distributed locks</li>
</ul>

<p>Like ZooKeeper and etcd, Consul focuses on reliable coordination across distributed infrastructure.</p>

<hr />

<h2 id="which-technology-should-you-choose">Which Technology Should You Choose?</h2>

<p>There isn’t a universal answer. Instead, the right choice depends on your application’s requirements. If you’re building a typical web application that already uses Redis, implementing distributed locks with Redis is usually the simplest and most practical solution. If you’re coordinating hundreds of services across a Kubernetes cluster, etcd may integrate more naturally with your infrastructure. If your organization already uses Consul or ZooKeeper for service coordination, leveraging those existing systems often makes more sense than introducing Redis solely for locking.</p>

<p>Choosing a technology isn’t just about features. It’s also about operational complexity, existing infrastructure, and the guarantees your business requires. The important thing to remember is this: distributed locks are a concept, while Redis, ZooKeeper, etcd, and Consul are simply different tools for implementing that concept. Understanding the underlying idea is far more valuable than becoming attached to a specific technology.</p>

<hr />

<h2 id="do-you-always-need-a-distributed-lock">Do You Always Need a Distributed Lock?</h2>

<p>Reading this article, it might be tempting to conclude that distributed locks are the solution to every concurrency problem. They’re not. In fact, many applications never need them. If your application runs on a single server, ordinary in-memory locks are often sufficient, and if your database transaction already guarantees correctness, introducing a distributed lock may simply add unnecessary complexity.</p>

<p>Distributed locks are powerful, but they should be introduced only when multiple independent application instances genuinely need to coordinate shared work. Like every distributed systems technique, they solve a very specific class of problems, and the best engineering decision is often knowing when <strong>not</strong> to use them.</p>

<h2 id="common-mistakes-when-using-distributed-locks">Common Mistakes When Using Distributed Locks</h2>

<p>Like many distributed systems concepts, distributed locks appear deceptively simple: acquire a lock, perform some work, release the lock. In practice, however, there are several subtle mistakes that can introduce bugs that are even harder to diagnose than the problem the lock was intended to solve. Understanding these pitfalls is just as important as understanding distributed locks themselves.</p>

<hr />

<h3 id="assuming-a-lock-lasts-forever">Assuming a Lock Lasts Forever</h3>

<p>One of the most common mistakes is forgetting that distributed locks usually have an expiration time. Suppose a server acquires a lock with a TTL of thirty seconds, and the developer assumes the operation will always finish within that window. Months later, a new feature makes the operation take forty-five seconds. The lock expires while the first server is still working, another server acquires the same lock and begins executing the exact same task, and suddenly, duplicate work appears again.</p>

<p>Choosing an appropriate TTL, and renewing it for long-running tasks when necessary, is essential.</p>

<hr />

<h3 id="forgetting-to-release-the-lock">Forgetting to Release the Lock</h3>

<p>Although expiration protects against permanent deadlocks, applications should still release locks as soon as the protected work finishes. Holding a lock longer than necessary reduces concurrency and delays other servers waiting to perform legitimate work.</p>

<p>A good rule is simple:</p>

<blockquote>
  <p>Hold the lock only for the work that genuinely requires exclusive access.</p>
</blockquote>

<p>Everything else should happen outside the lock whenever possible.</p>

<hr />

<h3 id="protecting-too-much-code">Protecting Too Much Code</h3>

<p>Developers sometimes wrap entire workflows inside a distributed lock. For example:</p>

<pre><code class="language-text">Acquire Lock

↓

Call External Payment API

↓

Generate PDF

↓

Upload File

↓

Send Email

↓

Release Lock
</code></pre>

<p>This means every other server waits while network requests, file generation, and email delivery are taking place. Often, only a small portion of the workflow actually requires exclusive access. A better approach is to keep the critical section as short as possible.</p>

<pre><code class="language-text">Acquire Lock

↓

Update Shared Resource

↓

Release Lock

↓

Generate PDF

↓

Send Email
</code></pre>

<p>The shorter the lock, the better the system scales.</p>

<hr />

<h2 id="distributed-locks-vs-database-locks">Distributed Locks vs Database Locks</h2>

<p>At first glance, distributed locks and database locks appear very similar. Both prevent concurrent operations and both coordinate access to shared resources, but they operate at completely different levels.</p>

<p>A database lock protects <strong>data inside the database</strong>. For example, when two transactions attempt to update the same customer record, the database can lock that row until one transaction completes. Everything happens within the database engine itself.</p>

<p>A distributed lock protects <strong>work performed by application servers</strong>. Instead of preventing two transactions from updating the same row, it prevents two application instances from starting the same business process. Consider generating monthly invoices: before any invoice rows even exist in the database, every server must first decide whether it should begin the job. That decision happens outside the database, and a distributed lock coordinates that decision.</p>

<p>An easy way to remember the difference is:</p>

<blockquote>
  <p><strong>Database locks protect data. Distributed locks protect business operations.</strong></p>
</blockquote>

<p>In many systems, you’ll use both together. A distributed lock ensures only one server begins generating invoices, and database transactions then ensure every invoice is written consistently.</p>

<hr />

<h2 id="distributed-locks-vs-optimistic-concurrency">Distributed Locks vs Optimistic Concurrency</h2>

<p>Another concept frequently confused with distributed locks is optimistic concurrency. Optimistic concurrency assumes conflicts are relatively rare. Instead of preventing multiple users from editing the same record, it detects whether someone else changed the data before saving.</p>

<p>Suppose two employees open the same customer profile, and each begins editing. The system stores a version number alongside the record. When Employee A saves, the version changes from <strong>5</strong> to <strong>6</strong>. When Employee B later attempts to save, the application notices that the version has already changed. Rather than silently overwriting Employee A’s work, it rejects the update and asks Employee B to refresh the page. No locking was required; the conflict was simply detected before committing.</p>

<p>Distributed locks take a different approach. Instead of detecting conflicts afterward, they prevent conflicting work from starting in the first place. Neither technique is universally better: optimistic concurrency works well when conflicts are uncommon, while distributed locks work best when duplicate execution would be expensive or dangerous.</p>

<hr />

<h2 id="best-practices">Best Practices</h2>

<p>As with most distributed systems techniques, simplicity is your friend. If you’re considering introducing distributed locks into your application, the following guidelines will help you avoid many common problems.</p>

<h4 id="keep-critical-sections-small">Keep Critical Sections Small</h4>

<p>Acquire the lock immediately before modifying shared resources, and release it immediately afterward. The less work performed while holding the lock, the better your system scales.</p>

<hr />

<h4 id="always-use-lock-expiration">Always Use Lock Expiration</h4>

<p>Servers crash, containers restart, and networks fail. Never assume your application will always release its lock correctly. Expiration protects the rest of the system from waiting forever.</p>

<hr />

<h4 id="verify-lock-ownership">Verify Lock Ownership</h4>

<p>Before releasing a lock, ensure your application still owns it. Ownership checks prevent one server from accidentally deleting another server’s lock after an expiration or retry.</p>

<hr />

<h4 id="design-for-failure">Design for Failure</h4>

<p>Distributed systems should always assume that something will eventually fail. Ask yourself:</p>

<ul>
  <li>What happens if Redis becomes unavailable?</li>
  <li>What happens if the server crashes?</li>
  <li>What happens if the network partitions?</li>
  <li>What happens if the lock expires unexpectedly?</li>
</ul>

<p>Thinking through failure scenarios early often prevents painful production incidents later.</p>

<hr />

<h4 id="combine-reliability-patterns">Combine Reliability Patterns</h4>

<p>Distributed locks are rarely used in isolation. Production systems often combine multiple reliability techniques. For example:</p>

<ul>
  <li><strong>Idempotency</strong> prevents duplicate requests.</li>
  <li><strong>Transactions</strong> guarantee atomic database updates.</li>
  <li><strong>Isolation Levels</strong> provide predictable views of data.</li>
  <li><strong>Distributed Locks</strong> coordinate multiple application servers.</li>
</ul>

<p>Each technique solves a different problem. Together, they create systems that continue behaving correctly even under heavy load and unexpected failures.</p>

<hr />

<h2 id="bringing-it-all-together">Bringing It All Together</h2>

<p>At this point in the series, we’ve explored several concepts that all contribute to building reliable backend systems. Each one addresses a different question.</p>

<table>
  <thead>
    <tr>
      <th>Concept</th>
      <th>Question It Answers</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><strong>Idempotency</strong></td>
      <td>What if the same request is sent twice?</td>
    </tr>
    <tr>
      <td><strong>Race Conditions</strong></td>
      <td>What if multiple requests modify the same data simultaneously?</td>
    </tr>
    <tr>
      <td><strong>Database Transactions</strong></td>
      <td>What if part of my operation fails?</td>
    </tr>
    <tr>
      <td><strong>Isolation Levels</strong></td>
      <td>What should transactions be allowed to see while others are running?</td>
    </tr>
    <tr>
      <td><strong>Distributed Locks</strong></td>
      <td>How do multiple servers agree who should perform a task?</td>
    </tr>
  </tbody>
</table>

<p>Notice how these concepts complement one another. None replaces the others; reliable systems are built by combining the right tools for the right problems.</p>

<hr />

<h2 id="final-thoughts">Final Thoughts</h2>

<p>As applications grow, the biggest challenges often aren’t writing business logic. They’re coordinating work across multiple users, multiple requests, multiple transactions, and eventually multiple servers.</p>

<p>Distributed locks exist because modern applications are no longer confined to a single machine. They’re deployed across clusters, containers, cloud regions, and worker nodes that all need to cooperate without constantly stepping on each other’s toes.</p>

<p>Like transactions and isolation levels, distributed locks aren’t something you’ll use for every feature. But when you do need them, they can be the difference between a system that behaves predictably and one that quietly creates duplicate invoices, repeated payments, or inconsistent business data.</p>

<p>The next time you design a background job, scheduled task, or critical workflow, ask yourself one simple question:</p>

<blockquote>
  <p><strong>“What happens if two servers try to do this at exactly the same time?”</strong></p>
</blockquote>

<p>If the answer is “something bad,” you’ve probably found a place where a distributed lock belongs.</p>

<hr />

<h2 id="whats-next">What’s Next?</h2>

<p>We’ve now covered:</p>

<ul>
  <li>Contract Testing</li>
  <li>Idempotency</li>
  <li>Race Conditions</li>
  <li>Database Transactions</li>
  <li>Database Concurrency</li>
  <li>Database Isolation Levels</li>
  <li>Distributed Locks</li>
</ul>

<p>So far, every concept has focused on keeping operations consistent <strong>while they’re happening</strong>. But there’s another challenge waiting. Imagine you’ve successfully updated your database inside a transaction and now need to publish an event to Kafka, RabbitMQ, or another message broker. What happens if the database commit succeeds, but publishing the event fails? Or worse, what if the event is published but the transaction rolls back?</p>

<p>This problem has caused countless production incidents in distributed systems. In the next article, we’ll explore <strong>The Outbox Pattern Explained: Publishing Events Without Losing Data</strong>, one of the most widely used patterns for ensuring your database and message broker stay in sync.</p>
]]></content:encoded>
      <author>billycartel360@gmail.com (Billy Okeyo)</author>
  
      <media:content url="https://billyokeyo.dev/assets/img/distributed-locks-2.jpg" medium="image" />
  
  
    
      <category>Distributed Systems</category>
    
      <category>Concurrency</category>
    
  
  
    
      <category>Distributed Systems</category>
    
      <category>Concurrency</category>
    
  
    </item>

  
  





  



  


    <item>
      <title>Distributed Locks Explained: Coordinating Work Across Multiple Servers</title>
      <link>https://billyokeyo.dev/posts/distributed-locks-explained/</link>
      <guid isPermaLink="true">https://billyokeyo.dev/posts/distributed-locks-explained/</guid>
      <pubDate>Mon, 13 Jul 2026 00:00:00 +0000</pubDate>
  
      <atom:updated>2026-07-13T00:00:00+00:00</atom:updated>
  
      <description><![CDATA[Distributed locks are a coordination mechanism that allows multiple independent servers to agree that only one of them may perform a particular operation at a given time. This article explains what distributed locks are, why they are important, and how they work.]]></description>
      <content:encoded><![CDATA[<blockquote>
  <p><em>“Database locks protect rows. Distributed locks protect systems.”</em></p>
</blockquote>

<p>Imagine your application has been wildly successful. What started as a simple web application running on a single server now runs across multiple machines behind a load balancer. Requests are shared between application instances, background workers process jobs independently, and scheduled tasks run on every server.</p>

<p>From the outside, everything looks better than ever: pages load faster, traffic scales effortlessly, and users are happy. Then one morning, your finance department calls. Every customer has received <strong>four monthly invoices</strong>.</p>

<p>Nothing appears wrong with the code. The invoice generation job is scheduled to run once every month, so why did it execute four times? The answer is surprisingly simple: you now have four application servers. At midnight, every server woke up, checked the scheduler, and independently decided that it was responsible for generating invoices. From each server’s perspective, everything was perfectly correct; collectively, however, they created a costly mistake.</p>

<p>Now imagine a different scenario. Your payment gateway sends a webhook confirming a successful payment. The webhook is delivered to one of your load-balanced servers, but a retry occurs because the payment provider doesn’t receive a response quickly enough, so another server processes the same webhook. Both servers begin updating balances, both create accounting entries, and both generate receipts.</p>

<p>You’ve already learned how <strong>idempotency</strong> protects against duplicate requests and how <strong>transactions</strong> ensure database operations succeed together.</p>

<p>But neither of those concepts answers a new question:</p>

<blockquote>
  <p><strong>How do multiple application servers agree that only one of them should perform a particular piece of work?</strong></p>
</blockquote>

<p>That problem is solved by <strong>distributed locks</strong>.</p>

<p>As applications grow beyond a single server, distributed locks become one of the most important coordination mechanisms in modern software engineering.</p>

<hr />

<h2 id="why-database-locks-are-no-longer-enough">Why Database Locks Are No Longer Enough</h2>

<p>Earlier in this series, we explored database transactions and row-level locking.</p>

<p>Suppose two transactions attempt to update the same bank account.</p>

<p>Using a statement such as:</p>

<pre><code class="language-sql">SELECT *
FROM accounts
WHERE id = 1
FOR UPDATE;
</code></pre>

<p>the database ensures only one transaction can modify that row at a time.</p>

<p>This works beautifully because both transactions are coordinating through the same database.</p>

<p>Now consider a different problem.</p>

<p>Suppose you have four application servers running the exact same code, and each server has a scheduler responsible for calculating monthly loan interest. Midnight arrives, and every server starts the same scheduled job. None of them are updating the same database row immediately. Instead, they’re deciding whether to begin an entire business process. The database has nothing to lock yet, and by the time one server begins writing data, the others have already started processing. The result is duplicated work.</p>

<p>Database locks are excellent at protecting individual records, but they are not designed to coordinate entire applications spread across multiple machines. This is the gap distributed locks were created to fill.</p>

<hr />

<h2 id="what-is-a-distributed-lock">What Is a Distributed Lock?</h2>

<p>A distributed lock is a coordination mechanism that allows multiple independent servers to agree that <strong>only one of them</strong> may perform a particular operation at a given time. Instead of protecting a single database row, a distributed lock protects an entire business activity.</p>

<p>Imagine a conference room with a single key. Anyone can use the room, but only the person holding the key may enter, and everyone else must wait until the key is returned. A distributed lock works in much the same way: before performing an operation, a server first attempts to acquire the lock. If the lock is available, the server proceeds; if another server already owns the lock, the operation waits, retries, or exits.</p>

<p>The important point is that <strong>every server asks the same central authority for permission before beginning work.</strong> That authority might be Redis, ZooKeeper, etcd, or another distributed coordination system.</p>

<hr />

<h2 id="a-simple-example">A Simple Example</h2>

<p>Imagine four application servers.</p>

<pre><code class="language-text">        Load Balancer
              │
   ┌──────────┼──────────┐
   │          │          │
Server A   Server B   Server C
   │          │          │
        Server D
</code></pre>

<p>At midnight, each server checks whether it’s time to generate invoices.</p>

<p>Without a distributed lock:</p>

<pre><code class="language-text">Server A → Generate invoices ✅

Server B → Generate invoices ✅

Server C → Generate invoices ✅

Server D → Generate invoices ✅
</code></pre>

<p>Four executions, four invoices, and one very unhappy finance department.</p>

<p>With a distributed lock:</p>

<pre><code class="language-text">Server A → Acquire Lock ✅

Server B → Lock Exists

Server C → Lock Exists

Server D → Lock Exists
</code></pre>

<p>Only Server A proceeds, and everyone else exits. The invoices are generated exactly once.</p>

<hr />

<h2 id="real-world-examples">Real-World Examples</h2>

<p>Distributed locks appear in far more places than most developers realize. Whenever multiple application instances could accidentally perform the same work, a distributed lock becomes a potential solution.</p>

<h3 id="scheduled-jobs">Scheduled Jobs</h3>

<p>Suppose your loan management platform calculates accrued interest every night at midnight. Without coordination, every application server performs the calculation independently, interest may be applied multiple times, and a distributed lock ensures exactly one server performs the calculation.</p>

<hr />

<h3 id="payment-processing">Payment Processing</h3>

<p>Imagine receiving a payment webhook from M-Pesa. Network retries cause multiple servers to receive the same notification, and without coordination, several servers may attempt to update balances simultaneously. A distributed lock allows only one server to process the payment while the others simply exit.</p>

<hr />

<h3 id="inventory-management">Inventory Management</h3>

<p>Only one laptop remains in stock, and two servers receive purchase requests simultaneously. Each attempts to reserve the item. Although transactions protect database consistency, a distributed lock can coordinate reservation workflows across multiple application instances before they even begin modifying inventory.</p>

<hr />

<h3 id="sending-emails">Sending Emails</h3>

<p>Marketing decides to send a promotional email to one million subscribers, and your email scheduler is deployed across five worker nodes. Without coordination, every worker starts sending the campaign and customers receive the same email five times. With a distributed lock, only one worker initiates the campaign while the others remain idle.</p>

<hr />

<h3 id="report-generation">Report Generation</h3>

<p>Generating annual financial reports may take several minutes. Without coordination, multiple servers might begin generating the exact same report simultaneously, wasting CPU time and increasing database load. A distributed lock ensures only one report generation process is active.</p>

<hr />

<h2 id="when-should-you-consider-a-distributed-lock">When Should You Consider a Distributed Lock?</h2>

<p>A useful rule of thumb is to ask yourself a simple question:</p>

<blockquote>
  <p><strong>What would happen if two servers performed this operation at exactly the same time?</strong></p>
</blockquote>

<p>If the answer is:</p>

<ul>
  <li>Duplicate invoices</li>
  <li>Duplicate payments</li>
  <li>Duplicate notifications</li>
  <li>Duplicate accounting entries</li>
  <li>Duplicate interest calculations</li>
</ul>

<p>then the operation is probably a candidate for a distributed lock.</p>

<p>Not every feature needs one. Most HTTP requests don’t, reading data doesn’t, and serving web pages doesn’t. Distributed locks are primarily useful for <strong>shared background work</strong> and <strong>critical business processes</strong> where duplicate execution would produce incorrect results.</p>

<hr />

<h2 id="distributed-locks-are-about-coordination">Distributed Locks Are About Coordination</h2>

<p>One misconception worth addressing early is that distributed locks replace database transactions.</p>

<p>They don’t. Transactions guarantee consistency <strong>inside the database</strong>; distributed locks coordinate <strong>between application servers</strong>. The two solve different problems.</p>

<p>In practice, many enterprise systems use both together. A server first acquires a distributed lock, then begins a database transaction. When the transaction completes successfully, the server releases the distributed lock. The lock ensures only one server performs the work, and the transaction ensures the database remains consistent while that work is being performed. Together, they provide a powerful foundation for building reliable distributed systems.</p>

<hr />

<p>At this point, we’ve answered <strong>why distributed locks exist</strong>.</p>

<p>The next question is equally important:</p>

<p><strong>How do multiple servers actually agree on who owns the lock?</strong></p>

<h2 id="how-distributed-locks-work">How Distributed Locks Work</h2>

<p>At a high level, every distributed lock follows the same basic workflow.</p>

<p>Before performing a critical operation, an application asks a shared coordination service for permission to proceed. If the lock is available, the application acquires it and begins its work; if another server already owns the lock, the application waits, retries later, or simply exits. Once the work has been completed, the lock is released, allowing another server to acquire it.</p>

<p>Although different technologies implement this process differently, the underlying idea remains remarkably simple.</p>

<pre><code class="language-text">Application Server

        │

Request Lock

        │

───────────────
 Lock Service
───────────────

Lock Available?

   │          │

  Yes         No

   │          │

Acquire      Wait / Retry / Exit

   │

Perform Work

   │

Release Lock
</code></pre>

<p>The important detail is that <strong>every application instance talks to the same lock service</strong>. Without a shared source of truth, each server would simply believe it owned the lock.</p>

<hr />

<h2 id="acquiring-a-lock">Acquiring a Lock</h2>

<p>Imagine four servers attempting to generate monthly invoices.</p>

<p>Each server sends a request to Redis asking for a lock called:</p>

<pre><code class="language-text">invoice-generation
</code></pre>

<p>Redis receives the requests almost simultaneously. The first request succeeds, and Redis stores something similar to:</p>

<pre><code class="language-text">invoice-generation

Owner: Server A

Expires: 30 seconds
</code></pre>

<p>When the remaining servers ask for the same lock, Redis responds that the lock already exists. Only Server A continues. Servers B, C, and D either wait, retry after a short delay, or abandon the operation altogether.</p>

<p>The beauty of distributed locks lies in their simplicity: instead of every server making its own decision, they all trust a single coordinator.</p>

<hr />

<h2 id="holding-the-lock">Holding the Lock</h2>

<p>Once a server has successfully acquired the lock, it proceeds with the protected operation.</p>

<p>This might involve:</p>

<ul>
  <li>Generating invoices.</li>
  <li>Processing a payment.</li>
  <li>Calculating loan interest.</li>
  <li>Sending reminder emails.</li>
  <li>Synchronizing inventory.</li>
</ul>

<p>During this period, every other server attempting the same operation sees that the lock is already owned. Rather than performing duplicate work, those servers simply back off. The lock effectively becomes a reservation saying that someone is already doing this work and others should wait.</p>

<hr />

<h2 id="releasing-the-lock">Releasing the Lock</h2>

<p>When the protected work completes successfully, the server releases the lock.</p>

<pre><code class="language-text">Acquire Lock

↓

Process Work

↓

Release Lock
</code></pre>

<p>Once Redis removes the lock, another server is free to acquire it if necessary. Releasing the lock is just as important as acquiring it. A lock that is never released eventually blocks every future attempt to perform that operation.</p>

<hr />

<h2 id="the-problem-with-permanent-locks">The Problem with Permanent Locks</h2>

<p>Now consider something less pleasant.</p>

<p>Server A acquires the invoice-generation lock, but halfway through generating invoices, the server crashes. Perhaps the machine loses power, perhaps Kubernetes terminates the container, or perhaps someone accidentally restarts the application. The important point is that Server A never gets the opportunity to release its lock.</p>

<p>If the lock remained permanent, every future invoice generation attempt would fail because the system would forever believe Server A still owned the lock. This is one of the biggest differences between traditional application locks and distributed locks: distributed systems must always assume that servers can disappear without warning.</p>

<hr />

<h2 id="lock-expiration-ttl">Lock Expiration (TTL)</h2>

<p>To solve this problem, distributed locks almost always include an expiration time, often called a <strong>Time-To-Live (TTL).</strong></p>

<p>Instead of storing only the lock name, the lock service stores something like:</p>

<pre><code class="language-text">Lock:

invoice-generation

Owner:

Server A

Expires:

30 seconds
</code></pre>

<p>If Server A completes successfully, it releases the lock before those thirty seconds expire. If Server A crashes, Redis automatically deletes the lock after the TTL expires, allowing another server to continue the work instead of waiting forever.</p>

<p>Think of it like borrowing a meeting room: rather than reserving it indefinitely, your booking automatically expires after one hour. If you forget to leave, the reservation eventually disappears and someone else can use the room. TTL prevents abandoned locks from permanently blocking the system.</p>

<hr />

<h2 id="choosing-the-right-ttl">Choosing the Right TTL</h2>

<p>Choosing a lock duration isn’t as straightforward as it might seem.</p>

<p>Suppose generating invoices normally takes ten seconds, and a thirty-second TTL provides plenty of room for occasional delays. But what if one month the process unexpectedly takes forty-five seconds? The lock expires after thirty seconds, another server acquires it, and now both servers are generating invoices simultaneously. You’ve accidentally recreated the very problem the lock was supposed to prevent.</p>

<p>On the other hand, choosing an extremely long TTL isn’t ideal either. If a server crashes while holding a lock that expires after thirty minutes, every other server must wait half an hour before continuing. Finding the right TTL therefore requires understanding how long your operation normally takes, while leaving enough room for occasional delays.</p>

<p>Some distributed lock implementations even allow servers to periodically renew the TTL while they’re still actively working. This approach, often called a <strong>heartbeat</strong>, keeps long-running operations alive without requiring excessively long expiration times.</p>

<hr />

<h2 id="what-happens-if-two-servers-ask-at-the-same-time">What Happens If Two Servers Ask at the Same Time?</h2>

<p>One question naturally arises: what happens if two servers request the lock at exactly the same millisecond? The answer depends on the lock service.</p>

<p>Redis, ZooKeeper, etcd, and similar systems perform lock acquisition atomically. That means checking whether the lock exists and creating it happen as a single indivisible operation. There is never a moment when both servers successfully acquire the same lock: one request succeeds and the other fails. This atomicity is exactly what makes distributed locks reliable; without it, two servers could both believe they owned the lock, defeating the entire purpose.</p>

<hr />

<h2 id="lock-ownership-matters">Lock Ownership Matters</h2>

<p>Imagine Server A acquires a lock. Before finishing its work, the lock expires because the TTL was too short, and Server B now acquires the same lock. Moments later, Server A finally finishes and attempts to release it. If the lock service simply deleted the lock without checking ownership, Server A would accidentally remove Server B’s lock, Server C could now acquire it, and suddenly two servers are working simultaneously again.</p>

<p>To prevent this, distributed lock implementations associate every lock with a unique owner identifier. When releasing a lock, the application must prove that it is still the owner; if ownership has already changed, the release request is ignored. This simple verification prevents one server from accidentally deleting another server’s lock.</p>

<hr />

<h2 id="distributed-locks-arent-magic">Distributed Locks Aren’t Magic</h2>

<p>It’s important to understand that distributed locks don’t eliminate failures. Servers can still crash, networks can still become partitioned, and Redis instances can still fail. Distributed locks simply provide a coordinated way for multiple application instances to make decisions despite those realities. They reduce duplicate work, improve consistency, and coordinate critical business operations, but like every distributed systems technique, they must be implemented carefully and combined with other reliability mechanisms such as transactions, retries, idempotency, and monitoring.</p>

<p>In the next section, we’ll explore the most common technologies used to implement distributed locks, including <strong>Redis</strong>, <strong>Redlock</strong>, <strong>ZooKeeper</strong>, <strong>etcd</strong>, and <strong>Consul</strong>, along with the strengths and weaknesses of each approach.</p>

]]></content:encoded>
      <author>billycartel360@gmail.com (Billy Okeyo)</author>
  
      <media:content url="https://billyokeyo.dev/assets/img/distributed-locks.jpg" medium="image" />
  
  
    
      <category>Distributed Systems</category>
    
      <category>Concurrency</category>
    
  
  
    
      <category>Distributed Systems</category>
    
      <category>Concurrency</category>
    
      <category>Database</category>
    
  
    </item>

  
  





  



  


    <item>
      <title>Database Isolation Levels Explained: Choosing the Right Consistency Guarantees</title>
      <link>https://billyokeyo.dev/posts/database-isolation-levels-part-2/</link>
      <guid isPermaLink="true">https://billyokeyo.dev/posts/database-isolation-levels-part-2/</guid>
      <pubDate>Fri, 10 Jul 2026 00:00:00 +0000</pubDate>
  
      <atom:updated>2026-07-10T00:00:00+00:00</atom:updated>
  
      <description><![CDATA[Database isolation levels determine what one transaction can see while another transaction is still running. This article explains why isolation levels exist, the four SQL standard isolation levels, and how to choose the right one for your application.]]></description>
      <content:encoded><![CDATA[<h1 id="understanding-the-four-sql-isolation-levels">Understanding the Four SQL Isolation Levels</h1>

<p>Now that we’ve seen the kinds of problems concurrent transactions can create, the next question is obvious:</p>

<p><strong>How does a database prevent them?</strong></p>

<p>The answer lies in isolation levels.</p>

<p>Rather than enforcing a single set of rules for every application, relational databases allow developers to choose how isolated transactions should be from one another.</p>

<p>This flexibility exists because different applications have different priorities.</p>

<p>A banking application transferring millions of shillings every day values consistency above almost everything else.</p>

<p>A reporting dashboard displaying website traffic may prefer speed over perfect accuracy.</p>

<p>Isolation levels allow the database to balance these competing requirements.</p>

<p>As isolation becomes stronger, transactions observe more consistent data, but the database also has to coordinate more aggressively, often reducing concurrency.</p>

<p>As isolation becomes weaker, transactions execute more freely, improving performance but increasing the likelihood of observing changing data.</p>

<p>The SQL standard defines four isolation levels.</p>

<p>Each one builds upon the guarantees of the previous level.</p>

<hr />

<h2 id="read-uncommitted">Read Uncommitted</h2>

<p>Read Uncommitted is the weakest isolation level defined by the SQL standard.</p>

<p>At this level, transactions are allowed to read changes made by other transactions even if those changes haven’t yet been committed.</p>

<p>Returning to our banking example, imagine Alice begins transferring <strong>KES 20,000</strong> to another account.</p>

<p>The database deducts the money from her balance but hasn’t yet committed the transaction.</p>

<p>Another transaction immediately reads Alice’s account.</p>

<p>Instead of seeing <strong>KES 50,000</strong>, it now sees <strong>KES 30,000</strong>, even though the transfer could still fail and be rolled back.</p>

<p>That second transaction has just performed a dirty read.</p>

<p>The advantage of Read Uncommitted is that transactions almost never wait for one another.</p>

<p>Because the database performs very little coordination, throughput can be extremely high.</p>

<p>The downside is that applications may make decisions using data that never officially existed.</p>

<p>For most business applications, this is unacceptable.</p>

<p>Imagine calculating payroll using salaries that are eventually rolled back or approving a loan based on a balance that disappears moments later.</p>

<p>Fortunately, very few modern relational databases actually encourage Read Uncommitted.</p>

<p>Many databases either discourage it entirely or internally behave more conservatively even when it’s requested.</p>

<p>In practice, you’ll rarely choose this isolation level for production systems.</p>

<hr />

<h2 id="read-committed">Read Committed</h2>

<p>Read Committed is the default isolation level in databases such as PostgreSQL, Oracle, and SQL Server.</p>

<p>Instead of allowing transactions to read uncommitted changes, the database only exposes data that has already been committed.</p>

<p>This immediately eliminates dirty reads.</p>

<p>Returning to Alice’s transfer, suppose another transaction checks her balance while the transfer is still running.</p>

<p>Instead of seeing the temporary balance of <strong>KES 30,000</strong>, it continues seeing the previously committed balance of <strong>KES 50,000</strong> until the transfer completes.</p>

<p>Only after the transaction commits does the new balance become visible.</p>

<p>This makes Read Committed an excellent general-purpose isolation level.</p>

<p>Applications never observe incomplete work, while the database still allows a high degree of concurrency.</p>

<p>However, Read Committed doesn’t solve every problem.</p>

<p>Suppose your transaction reads Alice’s balance at the beginning of a report.</p>

<p>A few seconds later, another transaction deposits <strong>KES 100,000</strong> into the account and commits.</p>

<p>If your report queries the balance again before finishing, you’ll now see a different value.</p>

<p>The same row has changed during your transaction.</p>

<p>Read Committed prevents dirty reads, but it still allows non-repeatable reads and phantom reads.</p>

<p>For many applications, that’s a perfectly acceptable trade-off.</p>

<hr />

<h2 id="read-committed-timeline">Read Committed Timeline</h2>

<pre><code class="language-text">Transaction A                     Transaction B

BEGIN

Read Balance = 50,000

                               BEGIN

                               Deposit 100,000

                               COMMIT

Read Balance = 150,000

COMMIT
</code></pre>

<p>Both values are valid.</p>

<p>The important difference is that Transaction A never sees incomplete or rolled-back data.</p>

<p>It only observes committed changes.</p>

<hr />

<h2 id="repeatable-read">Repeatable Read</h2>

<p>Suppose you’re generating an end-of-day financial report.</p>

<p>Your transaction calculates the total account balance across thousands of customers.</p>

<p>Halfway through generating the report, another transaction updates several account balances.</p>

<p>If your report re-reads those accounts later, the totals may no longer match the values used earlier in the report.</p>

<p>This is exactly the situation Repeatable Read was designed to solve.</p>

<p>At this isolation level, once a transaction reads a row, subsequent reads of that same row always return the same version for the lifetime of the transaction.</p>

<p>Even if another transaction updates the row and commits, your transaction continues working with the original version.</p>

<p>It’s as though your transaction receives its own private snapshot of the database.</p>

<p>This provides a much more consistent view of the data, making it particularly useful for reporting systems and financial calculations.</p>

<p>However, Repeatable Read doesn’t necessarily prevent new rows from appearing that satisfy your query conditions.</p>

<p>Depending on the database implementation, phantom reads may still occur, although databases like PostgreSQL use <strong>Multi-Version Concurrency Control (MVCC)</strong> to eliminate many of these anomalies without locking every row.</p>

<p>This is one of the reasons database behavior differs slightly across vendors.</p>

<p>We’ll return to that shortly.</p>

<hr />

<h2 id="repeatable-read-timeline">Repeatable Read Timeline</h2>

<pre><code class="language-text">Transaction A                     Transaction B

BEGIN

Read Balance = 50,000

                               BEGIN

                               Deposit 100,000

                               COMMIT

Read Balance = 50,000 ✅

COMMIT
</code></pre>

<p>Although the database now contains <strong>KES 150,000</strong>, Transaction A continues seeing <strong>KES 50,000</strong> because it is working from a consistent snapshot.</p>

<hr />

<h2 id="serializable">Serializable</h2>

<p>Serializable is the strongest isolation level defined by the SQL standard.</p>

<p>The easiest way to understand it is to imagine that every transaction runs one after another instead of simultaneously.</p>

<p>Internally, the database may still execute many transactions concurrently, but it guarantees that the final result is identical to some serial execution order.</p>

<p>Returning to our concert ticket example, suppose only one seat remains.</p>

<p>Customer A begins purchasing the ticket.</p>

<p>Customer B attempts to purchase the same seat at exactly the same time.</p>

<p>Under Serializable isolation, the database ensures that only one transaction succeeds.</p>

<p>The other transaction must either wait, retry, or fail.</p>

<p>The database refuses to produce a result that couldn’t happen if the transactions had executed one after another.</p>

<p>This provides the strongest possible consistency guarantees.</p>

<p>It also comes at the highest performance cost.</p>

<p>Serializable transactions often require additional locking, conflict detection, or transaction retries.</p>

<p>For systems processing large volumes of concurrent requests, this can reduce throughput significantly.</p>

<p>Because of this, Serializable is typically reserved for situations where correctness is absolutely critical.</p>

<p>Financial ledgers, securities trading systems, and certain accounting operations are common examples.</p>

<hr />

<h2 id="isolation-levels-at-a-glance">Isolation Levels at a Glance</h2>

<table>
  <thead>
    <tr>
      <th>Isolation Level</th>
      <th>Dirty Reads</th>
      <th>Non-Repeatable Reads</th>
      <th>Phantom Reads</th>
      <th>Performance</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Read Uncommitted</td>
      <td>❌ Possible</td>
      <td>❌ Possible</td>
      <td>❌ Possible</td>
      <td>⭐⭐⭐⭐⭐</td>
    </tr>
    <tr>
      <td>Read Committed</td>
      <td>✅ Prevented</td>
      <td>❌ Possible</td>
      <td>❌ Possible</td>
      <td>⭐⭐⭐⭐</td>
    </tr>
    <tr>
      <td>Repeatable Read</td>
      <td>✅ Prevented</td>
      <td>✅ Prevented</td>
      <td>⚠ Depends on database</td>
      <td>⭐⭐⭐</td>
    </tr>
    <tr>
      <td>Serializable</td>
      <td>✅ Prevented</td>
      <td>✅ Prevented</td>
      <td>✅ Prevented</td>
      <td>⭐⭐</td>
    </tr>
  </tbody>
</table>

<p>The table makes an important pattern clear.</p>

<p>As isolation increases, the number of concurrency anomalies decreases.</p>

<p>At the same time, the amount of coordination required by the database increases.</p>

<p>This is why there is no universally “best” isolation level.</p>

<p>The appropriate choice always depends on the requirements of your application.</p>

<h2 id="database-isolation-levels-in-popular-databases">Database Isolation Levels in Popular Databases</h2>

<p>One detail that often surprises developers is that not every relational database implements isolation levels in exactly the same way.</p>

<p>The SQL standard defines the four isolation levels, but database vendors have some flexibility in how they achieve those guarantees.</p>

<p>For example, PostgreSQL relies heavily on <strong>Multi-Version Concurrency Control (MVCC)</strong>. Instead of locking rows aggressively, PostgreSQL keeps multiple versions of a row and allows transactions to read a consistent snapshot of the data. This approach provides excellent concurrency while maintaining strong consistency.</p>

<p>MySQL’s InnoDB storage engine also supports MVCC but implements certain isolation behaviors differently. In particular, its default <strong>Repeatable Read</strong> isolation level prevents many phantom reads by using a combination of snapshot reads and gap locks.</p>

<p>SQL Server, on the other hand, traditionally relies more heavily on locking, although it also offers snapshot-based isolation levels that can be enabled when appropriate.</p>

<p>As a developer, you don’t need to memorize every implementation detail.</p>

<p>The important lesson is this:</p>

<blockquote>
  <p><strong>Always understand how your specific database implements isolation before assuming its behavior.</strong></p>
</blockquote>

<p>The SQL standard provides the vocabulary, but your database documentation explains the exact behavior.</p>

<hr />

<h2 id="choosing-the-right-isolation-level">Choosing the Right Isolation Level</h2>

<p>After learning about all four isolation levels, it’s natural to ask:</p>

<p><strong>“Which one should I actually use?”</strong></p>

<p>The honest answer is:</p>

<p><strong>It depends on what you’re building.</strong></p>

<p>Suppose you’re developing a dashboard that displays the number of users currently online.</p>

<p>If the number changes while someone refreshes the page, that’s perfectly acceptable.</p>

<p>There’s little value in sacrificing performance just to ensure every count remains identical throughout a transaction.</p>

<p>Read Committed is usually more than sufficient.</p>

<p>Now consider a payroll system.</p>

<p>Calculating employee salaries requires reading thousands of records while ensuring the figures don’t change halfway through the calculation.</p>

<p>If one employee’s salary is updated while payroll is being processed, the final report could contain inconsistent totals.</p>

<p>Repeatable Read becomes a much better fit because it provides a stable snapshot throughout the transaction.</p>

<p>Finally, imagine a securities trading platform or a banking ledger where even a single inconsistency could have significant financial consequences.</p>

<p>Here, correctness is more important than throughput.</p>

<p>Serializable isolation is often the safest choice, even if it means transactions occasionally wait or retry.</p>

<p>The goal isn’t to choose the strongest isolation level.</p>

<p>The goal is to choose the weakest isolation level that still guarantees the correctness your application requires.</p>

<p>Doing so allows the database to maximize concurrency without sacrificing business integrity.</p>

<hr />

<h2 id="isolation-levels-and-performance">Isolation Levels and Performance</h2>

<p>One mistake developers sometimes make is assuming higher isolation is always better.</p>

<p>In reality, every additional guarantee comes at a cost.</p>

<p>Higher isolation levels typically require the database to:</p>

<ul>
  <li>Coordinate more transactions.</li>
  <li>Acquire additional locks or maintain more snapshots.</li>
  <li>Detect conflicts more aggressively.</li>
  <li>Delay or retry conflicting transactions.</li>
</ul>

<p>As concurrency increases, these costs become more noticeable.</p>

<p>A high-traffic e-commerce platform processing thousands of orders every minute cannot afford unnecessary waiting if a lower isolation level already satisfies its business rules.</p>

<p>Likewise, a financial institution cannot sacrifice correctness simply to process a few extra transactions per second.</p>

<p>Finding the right balance is part of designing reliable software.</p>

<hr />

<h2 id="isolation-levels-vs-transactions-vs-race-conditions">Isolation Levels vs Transactions vs Race Conditions</h2>

<p>At this point in the series, we’ve covered three concepts that are closely related but often confused.</p>

<p>Let’s put them side by side.</p>

<h3 id="transactions">Transactions</h3>

<p>Transactions answer the question:</p>

<blockquote>
  <p><strong>What happens if my operation fails halfway through?</strong></p>
</blockquote>

<p>They ensure a group of related database operations either all succeed together or all fail together.</p>

<p>Without transactions, partial updates can leave your data inconsistent.</p>

<hr />

<h3 id="race-conditions">Race Conditions</h3>

<p>Race conditions answer a different question:</p>

<blockquote>
  <p><strong>What happens if two requests modify the same data at the same time?</strong></p>
</blockquote>

<p>These problems arise because multiple users or systems interact with shared data concurrently.</p>

<p>The outcome often depends entirely on timing.</p>

<p>Transactions alone don’t eliminate race conditions.</p>

<p>Additional mechanisms such as locking, optimistic concurrency, or stronger isolation levels are often required.</p>

<hr />

<h3 id="isolation-levels">Isolation Levels</h3>

<p>Isolation levels answer yet another question:</p>

<blockquote>
  <p><strong>While another transaction is running, what am I allowed to see?</strong></p>
</blockquote>

<p>Should your transaction observe unfinished work?</p>

<p>Should it continue seeing the same data even after another transaction commits?</p>

<p>Should it behave as though it’s the only transaction running?</p>

<p>Isolation levels define these rules.</p>

<p>Together, these three concepts form the foundation of reliable database applications.</p>

<p>They complement one another rather than compete.</p>

<p>A payment system, for example, might use:</p>

<ul>
  <li><strong>Idempotency</strong> to prevent duplicate payment requests.</li>
  <li><strong>Transactions</strong> to ensure payment records and account balances remain synchronized.</li>
  <li><strong>Read Committed</strong> or <strong>Serializable</strong> isolation to guarantee consistent reads.</li>
  <li><strong>Locking</strong> to prevent concurrent modifications of the same account.</li>
</ul>

<p>No single technique solves every reliability problem.</p>

<p>Reliable systems combine several techniques, each addressing a different class of failure.</p>

<hr />

<h2 id="practical-advice-for-backend-developers">Practical Advice for Backend Developers</h2>

<p>If you’re just beginning your backend engineering journey, don’t feel pressured to master every isolation level immediately.</p>

<p>Instead, focus on developing the habit of asking the right questions whenever you design a feature.</p>

<p>For example:</p>

<ul>
  <li>Could another user modify this data while I’m reading it?</li>
  <li>If the same query runs twice, should it return the same result?</li>
  <li>What happens if another transaction inserts new rows before mine finishes?</li>
  <li>Is perfect consistency necessary, or is slightly stale data acceptable?</li>
  <li>Would optimistic concurrency or explicit locking be a better solution?</li>
</ul>

<p>Thinking through these questions early in the design process often prevents bugs that are incredibly difficult to diagnose later in production.</p>

<p>Many concurrency issues aren’t caused by writing incorrect code.</p>

<p>They’re caused by making incorrect assumptions about how multiple users interact with the same data simultaneously.</p>

<hr />

<h2 id="final-thoughts">Final Thoughts</h2>

<p>Database isolation levels are often presented as a collection of definitions that developers are expected to memorize.</p>

<p>In reality, they’re much simpler than they first appear.</p>

<p>They’re simply different answers to one question:</p>

<p><strong>How much should one transaction be allowed to observe while another transaction is still working?</strong></p>

<p>Lower isolation levels prioritize concurrency, allowing more users to interact with the database simultaneously.</p>

<p>Higher isolation levels prioritize consistency, ensuring every transaction sees a predictable view of the data.</p>

<p>Neither approach is universally correct.</p>

<p>The right choice depends entirely on the problem you’re solving.</p>

<p>As your applications grow, understanding isolation levels becomes increasingly important because concurrency is no longer the exception—it’s the norm.</p>

<p>Every online store, banking application, inventory system, booking platform, and loan management system eventually reaches a point where multiple transactions compete for the same data.</p>

<p>The developers who understand isolation levels don’t simply build applications that work.</p>

<p>They build applications that continue working correctly under real-world load.</p>

<hr />

<h2 id="whats-next">What’s Next?</h2>

<p>In this series we’ve explored:</p>

<ul>
  <li>Idempotency</li>
  <li>Race Conditions</li>
  <li>Database Transactions</li>
  <li>Database Isolation Levels</li>
</ul>

<p>We’ve learned how to protect our systems from duplicate requests, concurrent updates, partial failures, and inconsistent reads.</p>

<p>But one challenge still remains.</p>

<p>Everything we’ve discussed assumes our application is running on a single database.</p>

<p>What happens when your application is running on <strong>ten servers</strong>, each processing requests simultaneously?</p>

<p>A normal database lock isn’t always enough.</p>

<p>In the next article, we’ll explore <strong>Distributed Locks Explained: Coordinating Work Across Multiple Servers</strong>, where we’ll see how systems like Redis, ZooKeeper, and etcd help ensure that only one application instance performs a critical operation at a time.</p>

]]></content:encoded>
      <author>billycartel360@gmail.com (Billy Okeyo)</author>
  
      <media:content url="https://billyokeyo.dev/assets/img/database-isolation-levels-2.jpg" medium="image" />
  
  
    
      <category>Database</category>
    
      <category>Concurrency</category>
    
  
  
    
      <category>Database</category>
    
      <category>Concurrency</category>
    
  
    </item>

  
  





  



  


    <item>
      <title>Database Isolation Levels Explained: Why Two Transactions Can See Different Data</title>
      <link>https://billyokeyo.dev/posts/database-isolation-levels/</link>
      <guid isPermaLink="true">https://billyokeyo.dev/posts/database-isolation-levels/</guid>
      <pubDate>Mon, 06 Jul 2026 00:00:00 +0000</pubDate>
  
      <atom:updated>2026-07-06T00:00:00+00:00</atom:updated>
  
      <description><![CDATA[Database isolation levels determine what one transaction can see while another transaction is still running. This article explains why isolation levels exist, the four SQL standard isolation levels, and how to choose the right one for your application.]]></description>
      <content:encoded><![CDATA[<blockquote>
  <p><em>“Transactions guarantee that your work completes correctly. Isolation levels determine what everyone else is allowed to see while that work is happening.”</em></p>
</blockquote>

<hr />

<p>In the previous article, we explored database transactions and learned how they ensure multiple database operations either succeed together or fail together. Transactions protect applications from partial execution, preventing situations where money is deducted from one account without being deposited into another or where inventory is reduced without successfully creating an order.</p>

<p>But transactions solve only part of the problem.</p>

<p>Modern applications rarely have just one user interacting with the database at a time. Thousands of customers may be placing orders, updating records, making payments, or querying reports simultaneously. Each of these actions runs inside its own transaction, and more often than not, several transactions are accessing the same data at exactly the same time.</p>

<p>This raises an important question:</p>

<p><strong>What should one transaction be allowed to see while another transaction is still running?</strong></p>

<p>Imagine opening your banking application to check your account balance.</p>

<p>At the exact same moment, your employer’s payroll system is depositing your monthly salary into the same account.</p>

<p>Should your transaction see the new balance immediately?</p>

<p>Should it continue seeing the old balance until the salary transaction finishes?</p>

<p>Should it wait until the payroll transaction completes before showing you anything at all?</p>

<p>Each answer is technically valid depending on how the database is configured.</p>

<p>Now imagine an online store where only one laptop remains in stock.</p>

<p>Customer A begins placing an order.</p>

<p>Before their transaction finishes, Customer B checks the product page.</p>

<p>Should Customer B still see one laptop available?</p>

<p>Should they see zero?</p>

<p>Should they wait until Customer A’s purchase either succeeds or fails?</p>

<p>Again, the answer depends on the database’s isolation level.</p>

<p>Isolation levels define the rules governing how concurrent transactions interact with one another. They determine whether one transaction can observe another transaction’s work before it has been completed, whether repeated reads always return the same result, and whether new rows appearing during a transaction should be visible immediately.</p>

<p>Although isolation levels are often introduced as an advanced database topic, they’re really about one simple idea:</p>

<blockquote>
  <p><strong>How much of another transaction’s work should your transaction be allowed to see?</strong></p>
</blockquote>

<p>The answer has significant consequences for both correctness and performance.</p>

<p>In this article, we’ll explore why isolation levels exist, the concurrency problems they solve, the four SQL standard isolation levels, and how to choose the right one for your application.</p>

<hr />

<h1 id="why-isolation-exists">Why Isolation Exists</h1>

<p>To understand isolation, imagine you’re reading a book in a library.</p>

<p>Halfway through chapter three, someone walks over, quietly replaces several pages with new ones, and walks away.</p>

<p>You continue reading without realizing anything changed.</p>

<p>The beginning of the chapter describes one story.</p>

<p>The ending describes another.</p>

<p>Nothing makes sense.</p>

<p>Databases can experience a remarkably similar problem.</p>

<p>When multiple transactions execute simultaneously, each transaction may be reading data while another transaction is actively changing it.</p>

<p>Without rules governing these interactions, applications could make decisions based on incomplete information, outdated values, or data that is eventually discarded.</p>

<p>Isolation exists to prevent these situations.</p>

<p>Rather than allowing every transaction unrestricted access to every change happening in the database, the database controls what each transaction can observe and when it can observe it.</p>

<p>Think of it as putting walls between transactions.</p>

<p>Some walls are very thin.</p>

<p>Transactions can see almost everything happening around them.</p>

<p>Other walls are much thicker.</p>

<p>Transactions operate almost as though they’re the only users of the database.</p>

<p>The thicker the wall, the more isolated the transaction becomes.</p>

<hr />

<h1 id="the-trade-off-between-consistency-and-performance">The Trade-Off Between Consistency and Performance</h1>

<p>At first glance, it might seem obvious that every database should simply use the highest possible isolation level.</p>

<p>After all, if stronger isolation produces more consistent data, why wouldn’t every system choose it?</p>

<p>The answer lies in performance.</p>

<p>Imagine a supermarket with only one checkout counter.</p>

<p>Every customer waits patiently in line.</p>

<p>Because only one cashier is serving customers, inventory updates happen one at a time.</p>

<p>Mistakes are rare.</p>

<p>Unfortunately, the queue becomes enormous.</p>

<p>Now imagine opening ten checkout counters.</p>

<p>Customers move much faster.</p>

<p>However, all ten cashiers are now updating the same inventory system simultaneously.</p>

<p>Keeping everything synchronized becomes much more difficult.</p>

<p>Databases face exactly the same challenge.</p>

<p>Higher isolation levels provide stronger guarantees about data consistency, but they often require additional locking, coordination, and waiting.</p>

<p>Lower isolation levels allow more transactions to execute concurrently, increasing throughput and reducing latency, but they also increase the likelihood that transactions observe changing data.</p>

<p>Isolation levels are therefore a balancing act between two competing goals:</p>

<ul>
  <li><strong>Consistency</strong>, ensuring every transaction sees predictable and reliable data.</li>
  <li><strong>Concurrency</strong>, allowing as many users as possible to interact with the system simultaneously.</li>
</ul>

<p>Different applications make different choices.</p>

<p>A banking application processing financial transfers typically prioritizes correctness over raw performance.</p>

<p>An analytics dashboard generating sales reports might tolerate slightly older data if it means thousands of users can run reports simultaneously without slowing the system.</p>

<p>Neither approach is universally correct.</p>

<p>The appropriate isolation level depends entirely on your business requirements.</p>

<hr />

<h1 id="concurrency-anomalies-the-problems-isolation-levels-exist-to-solve">Concurrency Anomalies: The Problems Isolation Levels Exist to Solve</h1>

<p>Isolation levels were not invented simply to make databases more complicated.</p>

<p>They exist because concurrent transactions can produce behaviors that most developers would consider surprising—or even dangerous.</p>

<p>These unexpected behaviors are collectively known as <strong>concurrency anomalies</strong>.</p>

<p>Every isolation level is essentially a trade-off between preventing these anomalies and maintaining good performance.</p>

<p>Before discussing the isolation levels themselves, it’s important to understand the problems they are designed to solve.</p>

<p>The four anomalies you’ll encounter most often are:</p>

<ul>
  <li>Dirty Reads</li>
  <li>Non-Repeatable Reads</li>
  <li>Phantom Reads</li>
  <li>Lost Updates</li>
</ul>

<p>Each represents a different way concurrent transactions can interfere with one another.</p>

<p>Let’s begin with the simplest.</p>

<hr />

<h1 id="dirty-reads">Dirty Reads</h1>

<p>Imagine Alice has <strong>KES 50,000</strong> in her account.</p>

<p>She initiates a transfer of <strong>KES 20,000</strong> to another account.</p>

<p>The banking system begins processing the transaction.</p>

<p>The first step deducts the money from Alice’s balance.</p>

<p>Before the transaction finishes, another process—perhaps an ATM balance inquiry or an online banking session—checks Alice’s account.</p>

<p>At that moment, it sees a balance of <strong>KES 30,000</strong>.</p>

<p>Everything seems perfectly normal.</p>

<p>Then something unexpected happens.</p>

<p>The transfer fails because the destination account no longer exists.</p>

<p>The database rolls back the transaction.</p>

<p>Alice’s balance immediately returns to <strong>KES 50,000</strong>.</p>

<p>The second transaction has now made a decision based on information that never officially existed.</p>

<p>It observed data that was eventually discarded.</p>

<p>This is known as a <strong>Dirty Read</strong>.</p>

<p>A dirty read occurs when one transaction reads data written by another transaction <strong>before that transaction has been committed</strong>.</p>

<p>The easiest way to understand it is to imagine reading someone’s unfinished draft before they’ve decided whether to keep or delete it.</p>

<p>The version you read may never become the final version.</p>

<p>Making business decisions based on that draft could lead to incorrect outcomes.</p>

<p>Fortunately, most modern relational databases prevent dirty reads by default because they are rarely desirable in business applications.</p>

<p>The SQL standard still defines them because they help explain the spectrum of isolation levels.</p>

<hr />

<h1 id="timeline-of-a-dirty-read">Timeline of a Dirty Read</h1>

<pre><code class="language-text">Transaction A                     Transaction B

BEGIN

Balance = 50,000

↓

Update Balance = 30,000

                               Read Balance = 30,000 ❌

↓

Transfer Fails

↓

ROLLBACK

Balance returns to 50,000
</code></pre>

<p>Transaction B has observed a value that disappeared moments later.</p>

<p>From the perspective of the database, that balance never officially existed.</p>

<p>Yet another transaction already acted as though it did.</p>

<p>This is precisely the type of inconsistency isolation levels are designed to prevent.</p>

<hr />
<h1 id="non-repeatable-reads">Non-Repeatable Reads</h1>

<p>Suppose you’re building an online banking application.</p>

<p>A customer opens the app and views their account balance. At that moment, the database reports a balance of <strong>KES 50,000</strong>.</p>

<p>The customer decides to transfer <strong>KES 40,000</strong> to another account, but before confirming the transfer, the application performs one final balance check to ensure sufficient funds are still available.</p>

<p>This seems like a perfectly reasonable workflow.</p>

<p>However, between the first balance check and the second, another transaction deposits <strong>KES 100,000</strong> into the same account.</p>

<p>When the application performs the second query, the balance is no longer <strong>KES 50,000</strong>.</p>

<p>It’s now <strong>KES 150,000</strong>.</p>

<p>Nothing is technically wrong.</p>

<p>The second transaction committed successfully.</p>

<p>The balance genuinely changed.</p>

<p>The surprising part is that <strong>the same transaction read the same row twice and received two different answers</strong>.</p>

<p>This phenomenon is known as a <strong>Non-Repeatable Read</strong>.</p>

<p>Unlike a dirty read, the second transaction isn’t reading uncommitted data. Every value it sees has been permanently committed to the database.</p>

<p>The inconsistency comes from the fact that another transaction modified the row while the first transaction was still running.</p>

<p>Imagine reading yesterday’s newspaper while someone keeps replacing pages with today’s edition.</p>

<p>The information isn’t incorrect.</p>

<p>It’s simply inconsistent because the document changed while you were reading it.</p>

<p>For many applications, this isn’t a problem.</p>

<p>If you’re refreshing a weather dashboard or checking the number of users currently online, it’s perfectly acceptable for values to change between two queries.</p>

<p>However, systems that rely on a stable snapshot of data—such as financial reporting, payroll processing, or end-of-day reconciliation—often require the same query to return the same result throughout the entire transaction.</p>

<hr />

<h1 id="timeline-of-a-non-repeatable-read">Timeline of a Non-Repeatable Read</h1>

<pre><code class="language-text">Transaction A                     Transaction B

BEGIN

Read Balance = 50,000

                               BEGIN

                               Deposit 100,000

                               COMMIT

Read Balance = 150,000 ❌

COMMIT
</code></pre>

<p>Transaction A never modified the balance itself.</p>

<p>It simply asked the same question twice and received two different answers because another committed transaction changed the underlying data in the meantime.</p>

<hr />

<h1 id="real-world-example-updating-a-customer-profile">Real-World Example: Updating a Customer Profile</h1>

<p>Consider an insurance application where a customer service representative opens a customer’s profile.</p>

<p>The representative spends several minutes reviewing the information before approving a policy update.</p>

<p>Meanwhile, another employee updates the customer’s phone number and address.</p>

<p>When the representative finally clicks <strong>Save</strong>, the application may now be working with information that is different from what was originally displayed.</p>

<p>Depending on how the application handles these changes, it could accidentally overwrite newer data or make decisions using outdated information.</p>

<p>This isn’t a database bug.</p>

<p>It’s simply the natural consequence of multiple users interacting with the same record at the same time.</p>

<p>Applications that require users to work with a consistent view of the data often use higher isolation levels or optimistic concurrency controls to detect these situations before committing changes.</p>

<hr />

<h1 id="phantom-reads">Phantom Reads</h1>

<p>Now let’s consider a different scenario.</p>

<p>Instead of reading a single row twice, imagine you’re querying an entire collection of rows.</p>

<p>Suppose you’re generating a report showing all loan applications submitted today.</p>

<p>Your first query returns:</p>

<pre><code class="language-text">Loan Applications Submitted Today

-------------------------------

Loan #101

Loan #102

Loan #103

Total: 3
</code></pre>

<p>While your report is still running, another loan application is submitted and committed to the database.</p>

<p>A few moments later, your transaction performs the exact same query again.</p>

<p>This time the results look different.</p>

<pre><code class="language-text">Loan Applications Submitted Today

-------------------------------

Loan #101

Loan #102

Loan #103

Loan #104

Total: 4
</code></pre>

<p>Notice what changed.</p>

<p>None of the existing rows were modified.</p>

<p>Instead, an entirely <strong>new row appeared</strong>.</p>

<p>This is called a <strong>Phantom Read</strong>.</p>

<p>A phantom read occurs when the same query returns a different set of rows because another transaction inserted, updated, or deleted records that match the query’s search criteria.</p>

<p>Think of it like counting the number of people in a room.</p>

<p>You count 20 people.</p>

<p>While you’re writing the number down, someone walks into the room.</p>

<p>You count again.</p>

<p>Now there are 21 people.</p>

<p>Nothing about the original twenty people changed.</p>

<p>The difference is that a new “phantom” appeared between your two observations.</p>

<hr />

<h1 id="timeline-of-a-phantom-read">Timeline of a Phantom Read</h1>

<pre><code class="language-text">Transaction A                     Transaction B

BEGIN

SELECT *

WHERE loan_date = TODAY

Returns 3 rows

                               BEGIN

                               INSERT Loan #104

                               COMMIT

SELECT *

WHERE loan_date = TODAY

Returns 4 rows ❌

COMMIT
</code></pre>

<p>Unlike a non-repeatable read, where an existing row changes, phantom reads involve the appearance or disappearance of entire rows.</p>

<hr />

<h1 id="why-phantom-reads-matter">Why Phantom Reads Matter</h1>

<p>Imagine you’re calculating today’s total revenue for financial reporting.</p>

<p>Your reporting transaction begins at 5:00 PM and starts aggregating sales.</p>

<p>While it’s still processing, new sales continue being recorded.</p>

<p>Different parts of the report may now be working with different datasets.</p>

<p>The total revenue calculated on page one might not match the detailed transaction list generated on page five because new rows appeared while the report was still executing.</p>

<p>In reporting systems, this can produce confusing and inconsistent results.</p>

<p>Higher isolation levels solve this problem by ensuring the transaction sees a consistent snapshot of the data throughout its lifetime, even if other transactions continue inserting new rows.</p>

<hr />

<h1 id="lost-updates">Lost Updates</h1>

<p>The final concurrency anomaly is perhaps the most dangerous because it silently discards valid work.</p>

<p>Imagine two warehouse employees looking at the same inventory record.</p>

<p>The system currently shows:</p>

<pre><code class="language-text">Laptop Stock = 10
</code></pre>

<p>Employee A sells one laptop.</p>

<p>Employee B also sells one laptop at almost exactly the same time.</p>

<p>Both employees read the current stock before making their update.</p>

<p>Each calculates the new quantity as:</p>

<pre><code class="language-text">10 - 1 = 9
</code></pre>

<p>Employee A saves.</p>

<p>The inventory becomes:</p>

<pre><code class="language-text">9
</code></pre>

<p>A fraction of a second later, Employee B saves.</p>

<p>The inventory is still:</p>

<pre><code class="language-text">9
</code></pre>

<p>One of the updates has effectively disappeared.</p>

<p>The correct inventory should now be <strong>8</strong>, but because both transactions started from the same original value, one update overwrote the other.</p>

<p>This is known as a <strong>Lost Update</strong>.</p>

<p>Unlike the previous anomalies, nothing appears obviously wrong.</p>

<p>No errors occur.</p>

<p>No constraints are violated.</p>

<p>The database happily accepts both updates.</p>

<p>The problem is that one user’s work has unintentionally replaced another’s.</p>

<p>Lost updates are one of the primary reasons databases provide row locking, optimistic concurrency control, and stronger isolation levels.</p>

<p>Without these protections, applications that receive many simultaneous updates—such as inventory systems, banking platforms, or booking applications—can slowly drift away from reality without anyone noticing.</p>

<p>Now that we understand the problems, the next question is obvious: How do databases prevent them? That’s exactly what we’ll cover in Part 2.”</p>

]]></content:encoded>
      <author>billycartel360@gmail.com (Billy Okeyo)</author>
  
      <media:content url="https://billyokeyo.dev/assets/img/database-isolation-levels.jpg" medium="image" />
  
  
    
      <category>Database</category>
    
      <category>Concurrency</category>
    
  
  
    
      <category>Database</category>
    
      <category>Concurrency</category>
    
  
    </item>

  
  





  



  


    <item>
      <title>Database Transactions Explained: Keeping Data Correct When Things Go Wrong</title>
      <link>https://billyokeyo.dev/posts/database-transactions-explained/</link>
      <guid isPermaLink="true">https://billyokeyo.dev/posts/database-transactions-explained/</guid>
      <pubDate>Fri, 03 Jul 2026 00:00:00 +0000</pubDate>
  
      <atom:updated>2026-07-03T00:00:00+00:00</atom:updated>
  
      <description><![CDATA[Database transactions are a fundamental concept in database management systems that ensure data integrity and consistency. This article explains what database transactions are, why they are important, and how they work.]]></description>
      <content:encoded><![CDATA[<blockquote>
  <p><em>“Transactions are not just a database feature—they’re one of the fundamental building blocks of reliable software.”</em></p>
</blockquote>

<p>Imagine you’re transferring <strong>KES 10,000</strong> from your savings account to a friend.</p>

<p>From your perspective, it’s a single action. You tap <strong>“Send Money”</strong>, authenticate the transaction, and wait for confirmation. Behind the scenes, however, the banking system performs several independent operations. It verifies that you have sufficient funds, deducts the amount from your account, credits your friend’s account, records the transaction in a ledger, updates account balances, and generates a receipt.</p>

<p>Each of these operations is important, but together they represent a single business action: <strong>a money transfer</strong>.</p>

<p>Now imagine the server crashes immediately after deducting the money from your account but before crediting your friend.</p>

<p>The result is disastrous. Your balance has decreased, your friend never receives the money, and unless additional recovery mechanisms exist, the system is left in an inconsistent state. From a customer’s perspective, the money has simply disappeared.</p>

<p>The same problem appears outside banking.</p>

<p>An e-commerce application might create an order, reduce inventory, process a payment, generate an invoice, and send a confirmation email. If the payment succeeds but the order creation fails, the customer has paid for a product that the system doesn’t believe exists. Likewise, in a loan management system, a repayment may update the outstanding balance, post accounting entries, and generate a receipt. If only some of those updates complete, financial records quickly become unreliable.</p>

<p>These problems aren’t caused by bad algorithms or poor business logic. They’re caused by <strong>partial execution</strong> when only part of a larger operation succeeds.</p>

<p>This is precisely the problem database transactions were designed to solve.</p>

<p>A transaction ensures that multiple database operations behave as a single unit of work. Either every operation succeeds together, or every operation is rolled back as though nothing ever happened. There is no halfway point where your system is left in an inconsistent state.</p>

<p>For backend developers, understanding transactions is just as important as understanding APIs or databases themselves. They are the foundation upon which reliable financial systems, booking platforms, inventory systems, healthcare applications, and countless other business-critical systems are built.</p>

<hr />

<h1 id="what-is-a-database-transaction">What Is a Database Transaction?</h1>

<p>A database transaction is a collection of one or more database operations that the database treats as a single logical operation.</p>

<p>Instead of thinking about individual SQL statements, think about the business process they represent.</p>

<p>Suppose a customer purchases the last laptop in your online store. That single purchase might require your application to:</p>

<ul>
  <li>Create an order.</li>
  <li>Deduct one item from inventory.</li>
  <li>Reserve the shipment.</li>
  <li>Record the payment.</li>
  <li>Create an invoice.</li>
</ul>

<p>Although these are separate SQL statements, they represent one business event. Either all of them should succeed, or none of them should.</p>

<p>That’s exactly what a transaction guarantees.</p>

<p>Without transactions, every statement executes independently. If statement number four fails, the previous three remain committed, leaving your data inconsistent.</p>

<p>With transactions, the database waits until you’re satisfied that every operation has completed successfully. Only then are the changes permanently saved.</p>

<hr />

<h1 id="understanding-transactions-through-a-simple-example">Understanding Transactions Through a Simple Example</h1>

<p>Let’s return to the banking example.</p>

<p>Alice wants to transfer <strong>KES 10,000</strong> to Bob.</p>

<p>A simplified version of the SQL might look like this:</p>

<pre><code class="language-sql">UPDATE accounts
SET balance = balance - 10000
WHERE account_id = 1;

UPDATE accounts
SET balance = balance + 10000
WHERE account_id = 2;
</code></pre>

<p>At first glance, this seems perfectly reasonable.</p>

<p>But imagine the database crashes immediately after the first statement executes.</p>

<p>Alice’s balance has already been reduced.</p>

<p>Bob’s balance has not increased.</p>

<p>The system now contains incorrect financial data.</p>

<p>This is why production systems rarely execute related operations independently.</p>

<p>Instead, they wrap them inside a transaction.</p>

<pre><code class="language-sql">BEGIN;

UPDATE accounts
SET balance = balance - 10000
WHERE account_id = 1;

UPDATE accounts
SET balance = balance + 10000
WHERE account_id = 2;

COMMIT;
</code></pre>

<p>If every statement succeeds, the database executes the <code>COMMIT</code>, making the changes permanent.</p>

<p>If any statement fails before that point, the application issues a <code>ROLLBACK</code>, and the database restores itself to exactly the state it was in before the transaction began.</p>

<p>To the outside world, it appears as though the failed transfer never happened.</p>

<p>This “all-or-nothing” behavior is what makes transactions so valuable.</p>

<hr />

<h1 id="the-lifecycle-of-a-transaction">The Lifecycle of a Transaction</h1>

<p>Every transaction follows a predictable lifecycle.</p>

<pre><code class="language-text">BEGIN
   │
Execute SQL Operations
   │
Everything Successful?
   │
 ┌─ Yes ─────────────┐
 │                   │
COMMIT          Changes Saved
 │
 └─ No ──────────────┐
                     │
                 ROLLBACK
                     │
          Database Restored
</code></pre>

<p>The process begins with <code>BEGIN</code>, which tells the database to temporarily hold all modifications rather than immediately committing them.</p>

<p>The application then performs one or more operations. These could involve inserting records, updating balances, deleting data, or modifying relationships between tables.</p>

<p>If every operation succeeds, the application calls <code>COMMIT</code>. At that point, the database permanently saves all changes.</p>

<p>If anything goes wrong along the way, perhaps a validation error, a database constraint violation, or even an unexpected server failure, the transaction is rolled back, discarding every change made since <code>BEGIN</code>.</p>

<p>The beauty of this model is that the database itself guarantees consistency. Developers don’t need to manually undo every failed operation because the database handles that responsibility.</p>

<hr />

<h1 id="the-four-acid-properties">The Four ACID Properties</h1>

<p>When developers discuss transactions, you’ll almost always hear the term <strong>ACID</strong>.</p>

<p>Despite sounding intimidating, ACID simply describes the guarantees that modern relational databases provide when executing transactions.</p>

<h2 id="atomicity">Atomicity</h2>

<p>Atomicity means that a transaction is indivisible.</p>

<p>Either every operation succeeds, or none of them do.</p>

<p>Returning to our banking example, it makes no sense for money to be deducted from one account without being added to another. The transaction must succeed completely or fail completely.</p>

<p>Think of flipping a light switch.</p>

<p>The light cannot be half on.</p>

<p>Similarly, a transaction cannot be half completed.</p>

<hr />

<h2 id="consistency">Consistency</h2>

<p>Consistency ensures that every transaction leaves the database in a valid state.</p>

<p>Business rules should always remain true.</p>

<p>If your application enforces that inventory can never become negative, then a successful transaction should never violate that rule.</p>

<p>Likewise, if your accounting system requires every journal entry to balance, no committed transaction should ever leave the ledger unbalanced.</p>

<p>Consistency isn’t about preventing bugs in your application logic; it’s about ensuring that completed transactions respect the rules defined by your database and your business.</p>

<hr />

<h2 id="isolation">Isolation</h2>

<p>Isolation becomes important when multiple users interact with the system simultaneously.</p>

<p>Imagine two customers attempting to purchase the last available ticket for a concert.</p>

<p>Without proper isolation, both requests may read the inventory before either updates it. Both believe the ticket is available, and both complete the purchase.</p>

<p>You’ve now sold the same seat twice.</p>

<p>Isolation ensures that concurrent transactions don’t interfere with one another in ways that produce inconsistent results.</p>

<p>In our previous article, we discussed <strong>race conditions</strong> situations where multiple requests compete to modify the same data. Isolation is one of the database mechanisms used to prevent those concurrency problems.</p>

<p>We’ll explore isolation levels in greater depth in the next article because they deserve an entire discussion of their own.</p>

<hr />

<h2 id="durability">Durability</h2>

<p>Durability guarantees that once a transaction has been committed, the changes are permanent.</p>

<p>Even if the server loses power immediately after the commit, the database ensures that committed data survives.</p>

<p>Modern databases achieve this through techniques such as write-ahead logging, transaction logs, and crash recovery.</p>

<p>For developers, the important takeaway is simple: once the database confirms a successful commit, you can trust that the data has been safely stored.</p>

<hr />

<h1 id="transactions-solve-partial-failures-not-every-problem">Transactions Solve Partial Failures: Not Every Problem</h1>

<p>One misconception among newer developers is that transactions magically solve every data consistency problem.</p>

<p>They don’t.</p>

<p>Transactions protect against <strong>partial execution</strong>.</p>

<p>Suppose your application updates three tables and crashes after updating the second one. A transaction ensures that the database rolls everything back, preventing inconsistent data. However, transactions don’t automatically solve concurrency problems.</p>

<p>Imagine two users attempting to withdraw money from the same account simultaneously.
Each transaction independently checks the balance before either completes. If both see the same balance and both proceed, the final result may still be incorrect depending on your isolation level. This isn’t a transaction problem. It’s a concurrency problem.</p>

<p>That’s why understanding race conditions and transactions together is so important. They solve different classes of reliability issues.</p>

<hr />

<h1 id="common-places-youll-use-transactions">Common Places You’ll Use Transactions</h1>

<p>Transactions appear almost everywhere in modern backend systems.</p>

<p>Payment processing is perhaps the most obvious example. Charging a customer’s card, recording the payment, updating invoices, and generating accounting entries should either all succeed or all fail together.</p>

<p>Inventory management systems use transactions to ensure stock counts remain accurate even when multiple customers are purchasing products simultaneously.</p>

<p>Booking platforms rely on transactions to reserve hotel rooms, airline seats, or event tickets without creating conflicting reservations.</p>

<p>Loan management systems use transactions when posting repayments, updating outstanding balances, calculating accrued interest, and recording accounting entries.</p>

<p>Healthcare systems use them to ensure patient records, prescriptions, billing information, and appointment schedules remain synchronized.</p>

<p>Any time a business operation spans multiple database changes, a transaction is usually involved.</p>

<hr />

<h1 id="common-mistakes-developers-make">Common Mistakes Developers Make</h1>

<p>One of the most common mistakes is keeping transactions open for too long.</p>

<p>Imagine starting a transaction, calling a third-party payment API, waiting several seconds for a response, and only then committing the transaction.</p>

<p>During that entire period, database resources may remain locked, reducing performance for other users.</p>

<p>A better approach is to perform external API calls before starting the transaction whenever possible, keeping the transaction focused solely on database operations.</p>

<p>Another common mistake is assuming transactions automatically protect against concurrent updates. As we’ve already seen, concurrency introduces an entirely different set of challenges that require locking strategies or appropriate isolation levels.</p>

<p>Finally, developers sometimes forget that transactions should represent business operations not individual SQL statements. Wrapping every single query in its own transaction rarely provides meaningful benefits.</p>

<hr />

<h1 id="transactions-in-modern-frameworks">Transactions in Modern Frameworks</h1>

<p>Fortunately, most frameworks make transactions straightforward to use.</p>

<p>Laravel offers the <code>DB::transaction()</code> helper.</p>

<p>Django provides <code>transaction.atomic()</code>.</p>

<p>Entity Framework supports <code>BeginTransactionAsync()</code>.</p>

<p>Spring Boot uses the <code>@Transactional</code> annotation.</p>

<p>Although the syntax differs, the underlying principle never changes. The framework simply tells the database when to begin the transaction, when to commit it, and when to roll it back if something goes wrong.</p>

<p>Understanding the concept matters far more than memorizing framework-specific syntax.</p>

<hr />

<h1 id="transactions-idempotency-and-race-conditions">Transactions, Idempotency, and Race Conditions</h1>

<p>If you’ve been following this series, you may have noticed that each concept addresses a different reliability challenge.</p>

<p><strong>Idempotency</strong> protects against duplicate requests by ensuring that repeating the same request doesn’t produce duplicate side effects.</p>

<p><strong>Race conditions</strong> occur when multiple requests compete to modify shared data simultaneously, leading to unpredictable outcomes.</p>

<p><strong>Transactions</strong> ensure that a group of related database operations either all succeed together or all fail together.</p>

<p>Reliable backend systems typically rely on all three.</p>

<p>Imagine a payment API.</p>

<p>Idempotency prevents customers from being charged twice if they retry a request.</p>

<p>Transactions ensure that charging the customer, recording the payment, and updating account balances either all succeed or all fail.</p>

<p>Proper concurrency control ensures that two simultaneous payment requests don’t corrupt shared data.</p>

<p>Each concept complements the others rather than replacing them.</p>

<hr />

<h1 id="final-thoughts">Final Thoughts</h1>

<p>Transactions are one of the reasons relational databases remain so powerful. They provide developers with a reliable mechanism for preserving data integrity even when failures occur.</p>

<p>As systems become larger and more distributed, failures become inevitable. Servers crash, networks fail, APIs time out, and users submit requests simultaneously. Transactions don’t eliminate those realities, but they ensure your database remains consistent when they happen.</p>

<p>Whenever you’re implementing a feature that modifies multiple pieces of related data, pause for a moment and ask yourself:</p>

<blockquote>
  <p><strong>What happens if this operation fails halfway through?</strong></p>
</blockquote>

<p>If the answer is “my system ends up in an inconsistent state,” then you’ve almost certainly found a place where a database transaction belongs.</p>

<p>In the next article, we’ll build on this foundation by exploring <strong>database isolation levels</strong> and why two perfectly valid transactions can still interfere with one another when they run at the same time.</p>
]]></content:encoded>
      <author>billycartel360@gmail.com (Billy Okeyo)</author>
  
      <media:content url="https://billyokeyo.dev/assets/img/database-transactions-explained.jpg" medium="image" />
  
  
    
      <category>Database</category>
    
      <category>Software Engineering</category>
    
  
  
    
      <category>Database</category>
    
      <category>Software Engineering</category>
    
  
    </item>

  
  





  



  


    <item>
      <title>Race Conditions Explained: The Concurrency Bug Every Backend Developer Should Understand</title>
      <link>https://billyokeyo.dev/posts/race-conditions-explained/</link>
      <guid isPermaLink="true">https://billyokeyo.dev/posts/race-conditions-explained/</guid>
      <pubDate>Sun, 28 Jun 2026 00:00:00 +0000</pubDate>
  
      <atom:updated>2026-06-28T00:00:00+00:00</atom:updated>
  
      <description><![CDATA[Race conditions are among the hardest bugs to reproduce because they don't happen every time. They may only appear under heavy traffic, high concurrency, or perfect timing. Everything works during testing—until your application reaches production. This article explains what race conditions are, why they happen, how they relate to idempotency, and the techniques developers use to prevent them.]]></description>
      <content:encoded><![CDATA[<p>Imagine you’re trying to buy the last ticket for your favorite concert.</p>

<p>The website shows:</p>

<blockquote>
  <p><strong>Only 1 ticket remaining.</strong></p>
</blockquote>

<p>At exactly the same moment, someone else clicks <strong>Buy</strong>.</p>

<p>Both of you complete payment.</p>

<p>Both of you receive confirmation emails.</p>

<p>But there was only one ticket.</p>

<p>How did two people successfully purchase the same seat?</p>

<p>Now imagine the same thing happening in a banking application.</p>

<p>Two ATM withdrawals happen at almost the same time.</p>

<p>Both check the balance before either transaction finishes.</p>

<p>Both think there’s enough money.</p>

<p>Both approve the withdrawal.</p>

<p>The account ends up with a negative balance.</p>

<p>Neither application is necessarily “broken.”</p>

<p>Instead, they suffer from one of the most common problems in software engineering:</p>

<p><strong>Race conditions.</strong></p>

<p>Race conditions are among the hardest bugs to reproduce because they don’t happen every time. They may only appear under heavy traffic, high concurrency, or perfect timing. Everything works during testing until your application reaches production.</p>

<p>In this article, we’ll explore what race conditions are, why they happen, how they relate to idempotency, and the techniques developers use to prevent them.</p>

<hr />

<h1 id="what-is-a-race-condition">What Is a Race Condition?</h1>

<p>A race condition occurs when <strong>two or more operations access and modify the same piece of data at the same time, and the final result depends on the order in which they execute.</strong></p>

<p>The important phrase is:</p>

<blockquote>
  <p><strong>The outcome depends on timing.</strong></p>
</blockquote>

<p>That’s what makes race conditions so dangerous.</p>

<p>Sometimes everything works.</p>

<p>Sometimes everything breaks.</p>

<p>The exact same code can produce different results simply because two requests happened a few milliseconds apart.</p>

<hr />

<h1 id="a-simple-analogy">A Simple Analogy</h1>

<p>Imagine two people standing in front of a cookie jar.</p>

<p>The jar contains exactly one cookie.</p>

<p>Both people look inside.</p>

<p>Both see one cookie.</p>

<p>Both reach in.</p>

<p>Both believe they’ll get the cookie.</p>

<p>Reality says otherwise.</p>

<p>Only one cookie exists.</p>

<p>The mistake happened because both people <strong>checked the state before either updated it.</strong></p>

<p>Software behaves exactly the same way.</p>

<hr />

<h1 id="a-real-banking-example">A Real Banking Example</h1>

<p>Suppose an account has:</p>

<pre><code class="language-text">Balance = $100
</code></pre>

<p>Two withdrawal requests arrive simultaneously.</p>

<pre><code>Request A → Withdraw $80

Request B → Withdraw $50
</code></pre>

<p>Without synchronization:</p>

<pre><code>Request A
↓

Read Balance ($100)

------------

Request B

↓

Read Balance ($100)

------------

Request A

Balance = $20

------------

Request B

Balance = $50
</code></pre>

<p>Depending on timing, the final balance might be:</p>

<pre><code>$20

or

$50

or

-$30
</code></pre>

<p>None of these outcomes are guaranteed.</p>

<p>This is a race condition.</p>

<hr />

<h1 id="why-it-works-during-development">Why It Works During Development</h1>

<p>Most developers test applications alone.</p>

<p>One request.</p>

<p>One browser.</p>

<p>One user.</p>

<p>Everything works perfectly.</p>

<p>Production is different.</p>

<p>Imagine:</p>

<ul>
  <li>5,000 users</li>
  <li>Hundreds of requests per second</li>
  <li>Multiple application servers</li>
  <li>Database replication</li>
  <li>Network latency</li>
</ul>

<p>The probability of two requests colliding becomes much higher.</p>

<p>Race conditions often appear only after an application becomes successful.</p>

<p>Ironically, scaling your application can reveal bugs that never existed during development.</p>

<hr />

<h1 id="race-conditions-vs-idempotency">Race Conditions vs Idempotency</h1>

<p>If you’ve read my previous article on idempotency, if not, read it first <a href="https://billyokeyo.dev/posts/idempotency-explained/">here</a>. You might wonder whether they’re the same thing.</p>

<p>They’re related, but they solve different problems.</p>

<h3 id="idempotency-answers">Idempotency answers:</h3>

<blockquote>
  <p>What if the <strong>same request</strong> is sent twice?</p>
</blockquote>

<p>Example:</p>

<pre><code>POST /payments

↓

Retry

↓

POST /payments
</code></pre>

<p>The solution is an <strong>Idempotency-Key</strong>.</p>

<p>The same request produces the same result.</p>

<hr />

<h3 id="race-conditions-answer">Race conditions answer:</h3>

<blockquote>
  <p>What if <strong>different requests</strong> happen at the same time?</p>
</blockquote>

<p>Example:</p>

<pre><code>User A buys last ticket

↓

User B buys last ticket
</code></pre>

<p>These are two legitimate requests from different users.</p>

<p>An idempotency key won’t help because the requests are not duplicates.</p>

<p>Race conditions require synchronization, not deduplication.</p>

<hr />

<h1 id="real-world-examples">Real-World Examples</h1>

<h2 id="airline-seat-booking">Airline Seat Booking</h2>

<p>Only one seat remains.</p>

<p>Two customers purchase it simultaneously.</p>

<p>Without proper locking:</p>

<ul>
  <li>Seat sold twice</li>
  <li>Refund required</li>
  <li>Customer frustration</li>
</ul>

<hr />

<h2 id="e-commerce-inventory">E-Commerce Inventory</h2>

<p>Stock:</p>

<pre><code>Laptop

Quantity = 1
</code></pre>

<p>Two customers purchase simultaneously.</p>

<p>Without protection:</p>

<p>Inventory becomes:</p>

<pre><code>-1
</code></pre>

<p>Now you’ve sold a product you don’t have.</p>

<hr />

<h2 id="loan-approval-systems">Loan Approval Systems</h2>

<p>Imagine two loan officers reviewing the same application.</p>

<p>Officer A:</p>

<p>Approve.</p>

<p>Officer B:</p>

<p>Reject.</p>

<p>If both updates happen simultaneously without coordination, the final loan status depends entirely on timing.</p>

<hr />

<h2 id="coupon-redemption">Coupon Redemption</h2>

<p>Promotion:</p>

<pre><code>First 100 customers only
</code></pre>

<p>If multiple requests update the redemption count simultaneously, you might accidentally issue:</p>

<pre><code>103

105

110

coupons.
</code></pre>

<hr />

<h1 id="how-race-conditions-happen">How Race Conditions Happen</h1>

<p>Most race conditions follow this pattern:</p>

<pre><code>Read

↓

Modify

↓

Write
</code></pre>

<p>The danger lies between <strong>Read</strong> and <strong>Write</strong>.</p>

<p>Example:</p>

<pre><code>Read Balance

↓

Calculate New Balance

↓

Update Balance
</code></pre>

<p>If another request changes the balance between those steps, your calculation becomes outdated.</p>

<p>This is known as a <strong>Lost Update</strong> problem.</p>

<hr />

<h1 id="solution-1-database-transactions">Solution 1: Database Transactions</h1>

<p>Transactions ensure multiple operations succeed or fail together.</p>

<p>Example:</p>

<pre><code class="language-sql">BEGIN;

SELECT balance
FROM accounts
WHERE id = 1;

UPDATE accounts
SET balance = balance - 80
WHERE id = 1;

COMMIT;
</code></pre>

<p>Transactions protect data consistency.</p>

<p>However, they don’t automatically eliminate every race condition.</p>

<p>Isolation levels matter too.</p>

<hr />

<h1 id="solution-2-row-level-locks">Solution 2: Row-Level Locks</h1>

<p>Many relational databases allow locking a row while it’s being updated.</p>

<p>Example:</p>

<pre><code class="language-sql">SELECT *
FROM accounts
WHERE id = 1
FOR UPDATE;
</code></pre>

<p>Now:</p>

<p>Request A locks the row.</p>

<p>Request B must wait.</p>

<p>Only after Request A finishes can Request B continue.</p>

<p>This guarantees consistent updates.</p>

<hr />

<h1 id="solution-3-optimistic-locking">Solution 3: Optimistic Locking</h1>

<p>Instead of preventing conflicts, optimistic locking detects them.</p>

<p>Imagine a version number.</p>

<pre><code>Account

Balance = 100

Version = 5
</code></pre>

<p>Update:</p>

<pre><code>WHERE Version = 5
</code></pre>

<p>If another request updates the row first:</p>

<pre><code>Version = 6
</code></pre>

<p>Your update fails.</p>

<p>The client retries with fresh data.</p>

<p>Optimistic locking works well when collisions are relatively rare.</p>

<hr />

<h1 id="solution-4-distributed-locks">Solution 4: Distributed Locks</h1>

<p>What if your application runs on multiple servers?</p>

<pre><code>Server A

↓

Database

↑

Server B
</code></pre>

<p>A normal in-memory lock won’t work because each server has its own memory.</p>

<p>Instead, developers use distributed locking systems like:</p>

<ul>
  <li>Redis (Redlock)</li>
  <li>ZooKeeper</li>
  <li>etcd</li>
  <li>Consul</li>
</ul>

<p>These coordinate access across multiple application instances.</p>

<hr />

<h1 id="solution-5-atomic-database-operations">Solution 5: Atomic Database Operations</h1>

<p>Sometimes you don’t need to:</p>

<pre><code>Read

↓

Calculate

↓

Write
</code></pre>

<p>Instead, let the database perform the update atomically.</p>

<p>Bad:</p>

<pre><code class="language-sql">SELECT quantity;

quantity--;

UPDATE products;
</code></pre>

<p>Better:</p>

<pre><code class="language-sql">UPDATE products

SET quantity = quantity - 1

WHERE quantity &gt; 0;
</code></pre>

<p>Now the database guarantees consistency.</p>

<hr />

<h1 id="detecting-race-conditions">Detecting Race Conditions</h1>

<p>One reason race conditions are difficult is that they rarely appear during manual testing.</p>

<p>Ways to uncover them include:</p>

<ul>
  <li>Load testing with concurrent users</li>
  <li>Stress testing</li>
  <li>Running parallel integration tests</li>
  <li>Simulating delayed responses</li>
  <li>Chaos engineering</li>
  <li>Monitoring production logs</li>
</ul>

<p>If a bug only appears “sometimes,” concurrency should be one of your first suspects.</p>

<hr />

<h1 id="best-practices">Best Practices</h1>

<p>When designing systems that handle shared data:</p>

<ul>
  <li>Keep transactions short.</li>
  <li>Avoid long-running locks.</li>
  <li>Prefer atomic database operations where possible.</li>
  <li>Use optimistic locking when contention is low.</li>
  <li>Use pessimistic locking for critical resources.</li>
  <li>Test with concurrent requests, not just sequential ones.</li>
  <li>Understand your database’s transaction isolation levels.</li>
</ul>

<p>Most importantly, always ask:</p>

<blockquote>
  <p><strong>“What happens if two users do this at exactly the same time?”</strong></p>
</blockquote>

<hr />

<h1 id="final-thoughts">Final Thoughts</h1>

<p>Race conditions aren’t caused by bad developers, they’re caused by systems becoming concurrent.</p>

<p>As applications grow, users interact simultaneously, background jobs overlap, and services communicate in parallel. Timing becomes unpredictable.</p>

<p>That’s why building reliable software isn’t just about writing correct logic for one request. It’s about ensuring your logic remains correct when hundreds or thousands of requests happen together.</p>

<p>If idempotency protects you from duplicate requests, race condition handling protects you from competing requests.</p>

<p>Together, they form two of the most important building blocks for designing resilient APIs and distributed systems.</p>

<p>The next time you write code that reads, modifies, and writes shared data, pause for a moment and ask:</p>

<blockquote>
  <p><strong>“What happens if someone else does this at the exact same time?”</strong></p>
</blockquote>

<p>If you don’t know the answer, you’ve just found your next engineering problem to solve.</p>
]]></content:encoded>
      <author>billycartel360@gmail.com (Billy Okeyo)</author>
  
      <media:content url="https://billyokeyo.dev/assets/img/race-conditions-explained.jpg" medium="image" />
  
  
    
      <category>API Design</category>
    
      <category>Software Testing</category>
    
  
  
    
      <category>Race Conditions</category>
    
      <category>API Design</category>
    
      <category>Software Testing</category>
    
  
    </item>

  
  





  



  


    <item>
      <title>Idempotency Explained: Building APIs That Survive Retries</title>
      <link>https://billyokeyo.dev/posts/idempotency-explained/</link>
      <guid isPermaLink="true">https://billyokeyo.dev/posts/idempotency-explained/</guid>
      <pubDate>Thu, 25 Jun 2026 00:00:00 +0000</pubDate>
  
      <atom:updated>2026-06-25T00:00:00+00:00</atom:updated>
  
      <description><![CDATA[Idempotency is a critical concept in API design that ensures that an operation can be performed multiple times without changing the final result beyond the first successful execution. This article explains what idempotency is, why it matters, and how to implement it in your own APIs.]]></description>
      <content:encoded><![CDATA[<p>Imagine you’re purchasing a product online.</p>

<p>You click the <strong>“Pay Now”</strong> button.</p>

<p>Nothing happens.</p>

<p>After a few seconds, you assume the request failed, so you click the button again.</p>

<p>And again.</p>

<p>A few minutes later, you discover you’ve been charged three times.</p>

<p>What happened?</p>

<p>From the user’s perspective, the payment seemed to fail. From the server’s perspective, however, it successfully processed every request it received.</p>

<p>This is one of the most common problems in distributed systems, and it’s exactly why idempotency exists.</p>

<p>Whether you’re building payment systems, booking platforms, inventory management software, or any API that changes data, retries are inevitable. Networks fail, clients time out, mobile connections drop, and users double-click buttons.</p>

<p>A well-designed API should survive these retries without creating duplicate side effects.</p>

<p>In this article, we’ll explore what idempotency is, why it matters, and how to implement it in your own APIs.</p>

<hr />

<h1 id="what-is-idempotency">What Is Idempotency?</h1>

<p>In simple terms, <strong>an idempotent operation can be performed multiple times without changing the final result beyond the first successful execution.</strong></p>

<p>For example:</p>

<pre><code>Turn on the light.
Turn on the light again.
Turn on the light again.
</code></pre>

<p>The light is still <strong>ON</strong>.</p>

<p>Nothing new happened after the first request.</p>

<p>The final state remains the same.</p>

<p>That’s idempotency.</p>

<p>Now compare it with this:</p>

<pre><code>Deposit $100
Deposit $100
Deposit $100
</code></pre>

<p>Your account balance increases by <strong>$300</strong>.</p>

<p>This operation is <strong>not idempotent</strong> because every request changes the system.</p>

<hr />

<h1 id="why-retries-happen">Why Retries Happen</h1>

<p>Many developers assume users only send one request.</p>

<p>Reality is different.</p>

<p>Requests are retried because of:</p>

<ul>
  <li>Slow internet connections</li>
  <li>Gateway timeouts</li>
  <li>Reverse proxies</li>
  <li>Mobile network interruptions</li>
  <li>Browser refreshes</li>
  <li>Double-clicking buttons</li>
  <li>Client retry mechanisms</li>
  <li>Load balancers</li>
  <li>Microservice communication failures</li>
</ul>

<p>Imagine this timeline:</p>

<pre><code>Client -------- POST /payments --------&gt; API

             Payment succeeds

API -------- 200 OK --------X

(Response never reaches client)

Client waits...

Client retries.

POST /payments again.
</code></pre>

<p>The client believes the payment failed.</p>

<p>The server already completed it.</p>

<p>Without idempotency…</p>

<p>The payment happens twice.</p>

<hr />

<h1 id="http-methods-and-idempotency">HTTP Methods and Idempotency</h1>

<p>HTTP itself distinguishes between idempotent and non-idempotent methods.</p>

<h3 id="get">GET</h3>

<pre><code>GET /users/10
</code></pre>

<p>Read the user.</p>

<p>Call it once.</p>

<p>Call it 100 times.</p>

<p>Nothing changes.</p>

<p>Idempotent</p>

<hr />

<h3 id="put">PUT</h3>

<pre><code>PUT /users/10
{
   "name": "Billy"
}
</code></pre>

<p>Replacing the same resource repeatedly produces the same result.</p>

<p>Idempotent</p>

<hr />

<h3 id="delete">DELETE</h3>

<pre><code>DELETE /users/10
</code></pre>

<p>Delete the user.</p>

<p>Deleting an already deleted user doesn’t delete them twice.</p>

<p>The final state is still:</p>

<pre><code>User does not exist.
</code></pre>

<p>Idempotent</p>

<hr />

<h3 id="post">POST</h3>

<pre><code>POST /orders
</code></pre>

<p>Create a new order.</p>

<p>Call it twice.</p>

<p>You now have two orders.</p>

<p>Not idempotent</p>

<p>This is why POST requests often require additional protection.</p>

<hr />

<h1 id="why-payment-apis-use-idempotency-keys">Why Payment APIs Use Idempotency Keys</h1>

<p>Payment providers like Stripe popularized the use of <strong>Idempotency Keys</strong>.</p>

<p>The idea is simple.</p>

<p>The client generates a unique identifier.</p>

<p>Example:</p>

<pre><code>Idempotency-Key:
6ab89d3b-acde-4d71-b20d-483d8d0ef091
</code></pre>

<p>Every retry sends the same key.</p>

<pre><code>POST /payments

Idempotency-Key:
6ab89d3b-acde-4d71-b20d-483d8d0ef091
</code></pre>

<p>When the server receives the request:</p>

<ol>
  <li>Check if this key already exists.</li>
  <li>If not, process the payment.</li>
  <li>Save both the key and the response.</li>
  <li>Return the response.</li>
</ol>

<p>If the same request arrives again with the same key:</p>

<p>Instead of charging the customer again…</p>

<p>Return the previously stored response.</p>

<pre><code>Client

POST /payments
Key: ABC123

↓

Server

Charge customer

↓

Store

ABC123 → Payment #456

↓

Return success

---

Retry

POST /payments
Key: ABC123

↓

Lookup

ABC123 exists

↓

Return Payment #456

No second charge.
</code></pre>

<hr />

<h1 id="implementing-idempotency">Implementing Idempotency</h1>

<p>A common workflow looks like this.</p>

<h2 id="step-1">Step 1</h2>

<p>Receive request.</p>

<pre><code>POST /orders
</code></pre>

<p>Headers</p>

<pre><code>Idempotency-Key:
XYZ987
</code></pre>

<hr />

<h2 id="step-2">Step 2</h2>

<p>Search database.</p>

<pre><code>SELECT *
FROM idempotency_keys
WHERE key = 'XYZ987'
</code></pre>

<p>Found?</p>

<p>Yes.</p>

<p>Return stored response.</p>

<p>Done.</p>

<hr />

<h2 id="step-3">Step 3</h2>

<p>Not found?</p>

<p>Create the resource.</p>

<pre><code>Create Order
</code></pre>

<hr />

<h2 id="step-4">Step 4</h2>

<p>Store:</p>

<pre><code>Key

Response

Status Code

Timestamp
</code></pre>

<p>Now every retry returns the same response.</p>

<hr />

<h1 id="example-in-nodejs-express">Example in Node.js (Express)</h1>

<pre><code class="language-javascript">app.post("/payments", async (req, res) =&gt; {
    const key = req.header("Idempotency-Key");

    const existing = await Idempotency.findOne({ key });

    if (existing) {
        return res.status(existing.status).json(existing.response);
    }

    const payment = await processPayment(req.body);

    await Idempotency.create({
        key,
        status: 201,
        response: payment,
    });

    return res.status(201).json(payment);
});
</code></pre>

<h2 id="python-fastapi">Python (FastAPI)</h2>

<pre><code class="language-python">from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse

app = FastAPI()

@app.post("/payments")
async def create_payment(request: Request):
    key = request.headers.get("Idempotency-Key")

    existing = await Idempotency.find_one(key=key)

    if existing:
        return JSONResponse(
            content=existing.response,
            status_code=existing.status,
        )

    body = await request.json()
    payment = await process_payment(body)

    await Idempotency.create(
        key=key,
        status=201,
        response=payment,
    )

    return JSONResponse(content=payment, status_code=201)
</code></pre>

<h2 id="c-aspnet-core">C# (ASP.NET Core)</h2>

<pre><code class="language-csharp">app.MapPost("/payments", async (
    HttpRequest request,
    IdempotencyStore store,
    PaymentService payments) =&gt;
{
    var key = request.Headers["Idempotency-Key"].ToString();

    var existing = await store.FindAsync(key);
    if (existing is not null)
    {
        return Results.Json(existing.Response, statusCode: existing.Status);
    }

    var body = await request.ReadFromJsonAsync&lt;PaymentRequest&gt;();
    var payment = await payments.ProcessAsync(body!);

    await store.CreateAsync(new IdempotencyRecord(key, 201, payment));

    return Results.Json(payment, statusCode: StatusCodes.Status201Created);
});
</code></pre>

<h2 id="go">Go</h2>

<pre><code class="language-go">func createPayment(w http.ResponseWriter, r *http.Request) {
    key := r.Header.Get("Idempotency-Key")

    existing, err := idempotency.FindOne(r.Context(), key)
    if err == nil &amp;&amp; existing != nil {
        w.WriteHeader(existing.Status)
        json.NewEncoder(w).Encode(existing.Response)
        return
    }

    var body PaymentRequest
    if err := json.NewDecoder(r.Body).Decode(&amp;body); err != nil {
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }

    payment, err := processPayment(r.Context(), body)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    if err := idempotency.Create(r.Context(), IdempotencyRecord{
        Key:      key,
        Status:   http.StatusCreated,
        Response: payment,
    }); err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    w.WriteHeader(http.StatusCreated)
    json.NewEncoder(w).Encode(payment)
}
</code></pre>

<h2 id="laravel">Laravel</h2>

<pre><code class="language-php">Route::post('/payments', function (Request $request) {
    $key = $request-&gt;header('Idempotency-Key');

    $existing = Idempotency::where('key', $key)-&gt;first();

    if ($existing) {
        return response()-&gt;json($existing-&gt;response, $existing-&gt;status);
    }

    $payment = processPayment($request-&gt;all());

    Idempotency::create([
        'key' =&gt; $key,
        'status' =&gt; 201,
        'response' =&gt; $payment,
    ]);

    return response()-&gt;json($payment, 201);
});
</code></pre>

<p>The logic is surprisingly simple.</p>

<p>The complexity comes from storing and managing the keys correctly.</p>

<hr />

<h1 id="where-should-idempotency-keys-be-stored">Where Should Idempotency Keys Be Stored?</h1>

<p>Options include:</p>

<h2 id="database">Database</h2>

<p>Best for most applications.</p>

<p>Pros:</p>

<ul>
  <li>Persistent</li>
  <li>Reliable</li>
  <li>Easy to query</li>
</ul>

<p>Cons:</p>

<ul>
  <li>Slightly slower</li>
</ul>

<hr />

<h2 id="redis">Redis</h2>

<p>Excellent for high-volume APIs.</p>

<p>Pros:</p>

<ul>
  <li>Extremely fast</li>
  <li>TTL support</li>
  <li>Easy expiration</li>
</ul>

<p>Many APIs automatically expire keys after 24 hours.</p>

<hr />

<h2 id="in-memory">In-Memory</h2>

<p>Useful only during development.</p>

<p>Not recommended for production.</p>

<p>Restarting the server loses everything.</p>

<hr />

<h1 id="common-mistakes">Common Mistakes</h1>

<h2 id="reusing-keys">Reusing Keys</h2>

<p>Every logical operation should have its own unique key.</p>

<p>Bad:</p>

<pre><code>ABC123

used today

used tomorrow
</code></pre>

<p>Good:</p>

<pre><code>New checkout

↓

Generate new UUID
</code></pre>

<hr />

<h2 id="ignoring-request-differences">Ignoring Request Differences</h2>

<p>Suppose the first request is:</p>

<pre><code>$50
</code></pre>

<p>The retry is:</p>

<pre><code>$500
</code></pre>

<p>Same key.</p>

<p>Different body.</p>

<p>The server should reject this request because the key is being reused for a different operation.</p>

<hr />

<h2 id="never-expiring-keys">Never Expiring Keys</h2>

<p>Keeping millions of old keys forever wastes storage.</p>

<p>Most APIs expire them after:</p>

<ul>
  <li>24 hours</li>
  <li>48 hours</li>
  <li>7 days</li>
</ul>

<p>depending on business requirements.</p>

<hr />

<h1 id="real-world-use-cases">Real-World Use Cases</h1>

<p>Idempotency is valuable anywhere duplicate requests could have costly consequences.</p>

<p>Examples include:</p>

<ul>
  <li>Payment processing</li>
  <li>Bank transfers</li>
  <li>Order creation</li>
  <li>Hotel reservations</li>
  <li>Flight bookings</li>
  <li>Ticket purchases</li>
  <li>Subscription billing</li>
  <li>Inventory updates</li>
  <li>Webhook processing</li>
  <li>Email sending</li>
  <li>Message queues</li>
</ul>

<p>If performing the same action twice could create an incorrect outcome, idempotency is worth considering.</p>

<hr />

<h1 id="when-you-dont-need-idempotency">When You Don’t Need Idempotency</h1>

<p>Not every endpoint needs an idempotency key.</p>

<p>For example:</p>

<pre><code>GET /posts
</code></pre>

<p>No state changes.</p>

<p>No duplicates.</p>

<p>No problem.</p>

<p>Likewise, endpoints such as:</p>

<ul>
  <li>Search</li>
  <li>Filtering</li>
  <li>Reading reports</li>
  <li>Viewing profiles</li>
</ul>

<p>are already naturally idempotent.</p>

<p>Reserve idempotency mechanisms for operations where retries could create unintended side effects.</p>

<hr />

<h1 id="final-thoughts">Final Thoughts</h1>

<p>Idempotency isn’t just an implementation detail—it’s a reliability feature.</p>

<p>In distributed systems, retries are normal. Networks are unreliable, users click buttons more than once, and clients retry requests automatically. Instead of hoping those situations never happen, design your APIs to handle them gracefully.</p>

<p>By using idempotency keys, storing responses, validating retries, and choosing the right storage strategy, you can prevent duplicate orders, repeated payments, and other costly errors.</p>

<p>A resilient API isn’t one that never receives duplicate requests.</p>

<p>It’s one that produces the correct outcome even when duplicate requests inevitably arrive.</p>

<p>The next time you design a <code>POST</code> endpoint, ask yourself:</p>

<blockquote>
  <p><strong>“What happens if this request is sent twice?”</strong></p>
</blockquote>

<p>If the answer is “something bad,” it’s probably time to add idempotency.</p>
]]></content:encoded>
      <author>billycartel360@gmail.com (Billy Okeyo)</author>
  
      <media:content url="https://billyokeyo.dev/assets/img/idempotency-explained.jpg" medium="image" />
  
  
    
      <category>API Design</category>
    
      <category>Software Testing</category>
    
  
  
    
      <category>Idempotency</category>
    
      <category>API Design</category>
    
      <category>Software Testing</category>
    
  
    </item>

  
  





  



  


    <item>
      <title>Lessons Learned from Writing My First 72 Blog Posts</title>
      <link>https://billyokeyo.dev/posts/lessons-learned-fron-writing/</link>
      <guid isPermaLink="true">https://billyokeyo.dev/posts/lessons-learned-fron-writing/</guid>
      <pubDate>Wed, 17 Jun 2026 00:00:00 +0000</pubDate>
  
      <atom:updated>2026-06-17T00:00:00+00:00</atom:updated>
  
      <description><![CDATA[Writing articles has made me a better developer. This post breaks down the mindset and process of effective writing, with practical steps and real examples to help you become a better problem solver. I wrote my first blog post in 2023 and have written 72 blog posts since then.]]></description>
      <content:encoded><![CDATA[<p>When I published my first blog post, I wasn’t thinking about reaching 72 articles.</p>

<p>I wasn’t thinking about traffic, search engine rankings, personal branding, or becoming a better writer. I simply wanted a place to share my thoughts, document what I was learning, and build something that belonged to me.</p>

<p>Like many developers, I started blogging because I was learning new things every day and wanted to keep track of my progress. At the time, I had no idea how much writing would teach me—not just about technology, but about consistency, communication, patience, and personal growth.</p>

<p>Now, after publishing my first 72 blog posts, I’ve learned lessons that extend far beyond blogging itself. Some lessons came from successes, while others came from mistakes and moments of frustration.</p>

<p>In this article, I want to share the most important lessons I’ve learned from publishing my first 72 blog posts.</p>

<h2 id="1-consistency-beats-perfection">1. Consistency Beats Perfection</h2>

<p>One of the biggest mistakes I made early on was trying to make every article perfect.</p>

<p>I would spend hours tweaking sentences, rewriting paragraphs, and overthinking every detail. Sometimes I delayed publishing because I felt an article wasn’t “good enough.”</p>

<p>Over time, I realized that perfection is the enemy of progress.</p>

<p>The articles that helped me grow weren’t necessarily my best articles. They were simply the articles I published.</p>

<p>Consistency creates momentum.</p>

<p>Publishing one article every week for a year is far more valuable than spending months trying to create a single masterpiece.</p>

<p>The biggest breakthrough came when I stopped chasing perfection and started focusing on showing up consistently.</p>

<h2 id="2-writing-clarifies-thinking">2. Writing Clarifies Thinking</h2>

<p>Many times, I thought I understood a topic until I tried to explain it in writing.</p>

<p>That’s when the gaps in my knowledge became obvious.</p>

<p>Writing forced me to organize my thoughts, simplify complex ideas, and identify areas where my understanding was incomplete.</p>

<p>The process taught me that learning and explaining are not the same thing.</p>

<p>If I couldn’t explain a concept clearly, I probably didn’t understand it as well as I thought.</p>

<p>This lesson made me a better learner and a better developer.</p>

<h2 id="3-nobody-reads-your-first-postsand-thats-okay">3. Nobody Reads Your First Posts—And That’s Okay</h2>

<p>One of the hardest realities for new bloggers is that almost nobody reads your early content.</p>

<p>I remember publishing articles and checking analytics repeatedly, hoping to see visitors.</p>

<p>Most of the time, there were very few.</p>

<p>At first, that felt discouraging.</p>

<p>But eventually I realized something important:</p>

<p>The purpose of your first blog posts isn’t to attract thousands of readers.</p>

<p>The purpose is to learn how to write.</p>

<p>Your first posts are practice.</p>

<p>Every article improves your skills, your confidence, and your ability to communicate.</p>

<p>The audience comes later.</p>

<h2 id="4-the-habit-matters-more-than-motivation">4. The Habit Matters More Than Motivation</h2>

<p>Motivation is unreliable.</p>

<p>Some days you’ll feel inspired.</p>

<p>Other days you’ll have no desire to write.</p>

<p>If blogging depends entirely on motivation, consistency becomes impossible.</p>

<p>One of the most valuable lessons I learned is that habits outperform motivation.</p>

<p>The writers who succeed aren’t necessarily the most talented.</p>

<p>They’re the ones who continue writing even when they don’t feel like it.</p>

<p>Creating a writing habit transformed blogging from an occasional activity into a regular part of my routine.</p>

<h2 id="5-every-post-doesnt-need-to-be-revolutionary">5. Every Post Doesn’t Need to Be Revolutionary</h2>

<p>Early in my blogging journey, I believed every article needed a unique insight or groundbreaking idea.</p>

<p>I was wrong.</p>

<p>Many of my most useful posts covered topics that had already been discussed countless times.</p>

<p>The difference was that I shared my own perspective and experience.</p>

<p>Your value doesn’t come from inventing entirely new ideas.</p>

<p>It comes from explaining ideas through your own lens.</p>

<p>There’s always someone who needs the explanation that only you can provide.</p>

<h2 id="6-writing-builds-confidence">6. Writing Builds Confidence</h2>

<p>Publishing online can feel intimidating.</p>

<p>You’re sharing your thoughts with strangers.</p>

<p>You’re exposing your ideas to criticism.</p>

<p>You’re putting your work in public.</p>

<p>At first, this can be uncomfortable.</p>

<p>But over time, each article builds confidence.</p>

<p>You become more comfortable expressing your opinions.</p>

<p>You stop worrying about being perfect.</p>

<p>You gain confidence in your ability to communicate and contribute valuable ideas.</p>

<p>That confidence eventually extends beyond blogging into other areas of life and work.</p>

<h2 id="7-blogging-is-a-long-term-game">7. Blogging Is a Long-Term Game</h2>

<p>One of the most important lessons I learned is that blogging rewards patience.</p>

<p>Results rarely happen overnight.</p>

<p>Traffic grows slowly.</p>

<p>Authority builds gradually.</p>

<p>Opportunities emerge unexpectedly.</p>

<p>Many people quit because they expect immediate results.</p>

<p>The reality is that blogging is similar to investing.</p>

<p>Small contributions made consistently over time eventually compound into significant outcomes.</p>

<p>The key is staying committed long enough to experience those benefits.</p>

<h2 id="8-publishing-teaches-more-than-consuming">8. Publishing Teaches More Than Consuming</h2>

<p>Before I started blogging, I spent most of my time consuming content.</p>

<p>I watched tutorials.</p>

<p>I read articles.</p>

<p>I followed courses.</p>

<p>While these activities were helpful, publishing taught me far more.</p>

<p>Creating content forces you to think deeply, research thoroughly, and communicate clearly.</p>

<p>It transforms you from a consumer into a creator.</p>

<p>That shift changed the way I learn forever.</p>

<h2 id="9-your-blog-becomes-a-personal-archive">9. Your Blog Becomes a Personal Archive</h2>

<p>One unexpected benefit of blogging is having a permanent record of your journey.</p>

<p>Looking back at my older articles shows how much I’ve grown.</p>

<p>I can see:</p>

<ul>
  <li>How my thinking evolved.</li>
  <li>What I was learning.</li>
  <li>Problems I was solving.</li>
  <li>Mistakes I made.</li>
</ul>

<p>The blog becomes more than a collection of articles.</p>

<p>It becomes a timeline of personal growth.</p>

<h2 id="10-small-efforts-compound-over-time">10. Small Efforts Compound Over Time</h2>

<p>When I published my first article, it felt insignificant.</p>

<p>The same was true for my second, third, and tenth article.</p>

<p>But by the time I reached fifty posts, those small efforts had accumulated into something meaningful.</p>

<p>Fifty articles represent:</p>

<ul>
  <li>Hundreds of hours of learning.</li>
  <li>Hundreds of hours of writing.</li>
  <li>Dozens of lessons learned.</li>
  <li>A growing body of work.</li>
</ul>

<p>This reminded me that success is rarely the result of a single big action.</p>

<p>It’s usually the result of many small actions repeated consistently over time.</p>

<h2 id="11-the-real-reward-isnt-traffic">11. The Real Reward Isn’t Traffic</h2>

<p>When people think about blogging success, they often think about page views, followers, and analytics.</p>

<p>Those metrics matter, but they’re not the greatest reward.</p>

<p>The greatest reward is who you become during the process.</p>

<p>Blogging made me:</p>

<ul>
  <li>A better writer.</li>
  <li>A better learner.</li>
  <li>A better communicator.</li>
  <li>A more disciplined creator.</li>
  <li>A more thoughtful developer.</li>
</ul>

<p>Those benefits are far more valuable than any traffic number.</p>

<h2 id="looking-ahead">Looking Ahead</h2>

<p>Reaching 72 blog posts feels like an important milestone, but it also feels like the beginning.</p>

<p>There’s still so much to learn.</p>

<p>So many topics to explore.</p>

<p>So many experiences to share.</p>

<p>The goal isn’t simply to publish more articles.</p>

<p>The goal is to continue learning, improving, and documenting the journey.</p>

<p>If the first 72 posts taught me anything, it’s that growth comes from consistency, curiosity, and the willingness to keep showing up.</p>

<h2 id="conclusion">Conclusion</h2>

<p>Publishing my first 72 blog posts taught me lessons that extend far beyond writing.</p>

<p>It taught me patience when growth was slow.</p>

<p>It taught me discipline when motivation disappeared.</p>

<p>It taught me confidence when self-doubt appeared.</p>

<p>Most importantly, it taught me that meaningful progress is often the result of small actions repeated consistently over time.</p>

<p>If you’re thinking about starting a blog, my advice is simple:</p>

<p>Start now.</p>

<p>Don’t wait until you’re an expert.</p>

<p>Don’t wait until everything is perfect.</p>

<p>Write your first post.</p>

<p>Then write your second.</p>

<p>Then your third.</p>

<p>One day, you’ll look back and realize those small steps created something much bigger than you ever imagined.</p>

<p>I did an article about <a href="https://blogs.innova.co.ke/importance-of-writing-for-devs/">importance of writing for developers</a> which you can check out.</p>
]]></content:encoded>
      <author>billycartel360@gmail.com (Billy Okeyo)</author>
  
      <media:content url="https://billyokeyo.dev/assets/img/72-blogs-later.jpg" medium="image" />
  
  
    
      <category>Writing</category>
    
      <category>Blogging</category>
    
      <category>Career</category>
    
  
  
    
      <category>writing</category>
    
      <category>blogging</category>
    
      <category>career advice</category>
    
  
    </item>

  
  





  



  


    <item>
      <title>Debugging Is a Skill Nobody Teaches You</title>
      <link>https://billyokeyo.dev/posts/debugging-is-a-skill-noone-teaches-you/</link>
      <guid isPermaLink="true">https://billyokeyo.dev/posts/debugging-is-a-skill-noone-teaches-you/</guid>
      <pubDate>Mon, 04 May 2026 00:00:00 +0000</pubDate>
  
      <atom:updated>2026-05-04T00:00:00+00:00</atom:updated>
  
      <description><![CDATA[Debugging is a critical skill that many developers struggle with. This post breaks down the mindset and process of effective debugging, with practical steps and real examples to help you become a better problem solver.]]></description>
      <content:encoded><![CDATA[<blockquote>
  <p><em>You’ve been staring at the same bug for 2 hours.</em>
You’ve restarted the server. Cleared cache. Added random <code>console.log</code>s.
Somehow… it still doesn’t work.</p>
</blockquote>

<p>At some point, you stop coding and start guessing.</p>

<p><img src="https://media.giphy.com/media/3o7btPCcdNniyf0ArS/giphy.gif" alt="Frustrated Coding" /></p>

<p>And that’s the real problem.</p>

<blockquote>
  <p><strong>The issue isn’t the bug.
It’s that nobody actually teaches debugging as a skill.</strong></p>
</blockquote>

<hr />

<h2 id="the-way-most-developers-debug">The Way Most Developers Debug</h2>

<p>Let’s be honest. Most of us learned debugging like this:</p>

<ul>
  <li>Sprinkle <code>console.log</code> everywhere</li>
  <li>Change random lines and hope something works</li>
  <li>Copy-paste error messages into Google</li>
  <li>Restart everything “just in case”</li>
</ul>

<p><img src="https://media.giphy.com/media/13HgwGsXF0aiGY/giphy.gif" alt="Random Typing" /></p>

<p>It <em>sometimes</em> works.</p>

<p>But it’s slow, frustrating, and unreliable.</p>

<p>It’s not debugging.</p>

<p>It’s <strong>trial and error disguised as progress</strong>.</p>

<hr />

<h2 id="what-debugging-actually-is">What Debugging Actually Is</h2>

<p>Here’s the mindset shift that changes everything:</p>

<blockquote>
  <p><strong>Debugging is not about fixing code.
It’s about finding where your mental model diverges from reality.</strong></p>
</blockquote>

<p>You <em>think</em> the system works one way.</p>

<p>Reality says otherwise.</p>

<p>Your job is to <strong>close that gap</strong>.</p>

<hr />

<h2 id="the-debugging-mindset">The Debugging Mindset</h2>

<p>Before tools, before techniques, this is what matters most.</p>

<h3 id="1-assume-your-assumptions-are-wrong">1. Assume Your Assumptions Are Wrong</h3>

<p>If something doesn’t work, at least one thing you believe is false.</p>

<p>Your job is to find it.</p>

<hr />

<h3 id="2-narrow-the-problem-space">2. Narrow the Problem Space</h3>

<p>Bad debugging:</p>

<blockquote>
  <p>“Something is wrong with the app”</p>
</blockquote>

<p>Good debugging:</p>

<blockquote>
  <p>“The issue happens only when this function runs after login”</p>
</blockquote>

<p><img src="https://media.giphy.com/media/l0IylOPCNkiqOgMyA/giphy.gif" alt="Analyzing Clues" /></p>

<hr />

<h3 id="3-reproduce-before-fixing">3. Reproduce Before Fixing</h3>

<p>If you can’t reliably reproduce the bug, you don’t understand it.</p>

<p>And if you don’t understand it, your fix is luck—not skill.</p>

<hr />

<h3 id="4-one-change-at-a-time">4. One Change at a Time</h3>

<p>If you change 5 things and it works…
which one fixed it?</p>

<p>You don’t know.</p>

<p>That’s how bugs come back later.</p>

<hr />

<h3 id="5-understand-before-you-patch">5. Understand Before You Patch</h3>

<p>Quick fixes feel good.</p>

<p>Understanding the root cause makes you dangerous (in a good way).</p>

<hr />

<h2 id="a-repeatable-debugging-process">A Repeatable Debugging Process</h2>

<p>This is where things become practical.</p>

<hr />

<h3 id="step-1-reproduce-the-bug"><strong>Step 1: Reproduce the Bug</strong></h3>

<p>Make it happen consistently.</p>

<pre><code class="language-bash">Click button → error appears  
Refresh → still happens  
Different browser → still happens
</code></pre>

<p>If it’s inconsistent, your first task is to <strong>find the pattern</strong>.</p>

<hr />

<h3 id="step-2-define-expected-vs-actual"><strong>Step 2: Define Expected vs Actual</strong></h3>

<p>Write it down clearly.</p>

<pre><code class="language-text">Expected: API returns user data  
Actual: API returns empty array
</code></pre>

<p>This step alone eliminates confusion.</p>

<hr />

<h3 id="step-3-isolate-the-problem"><strong>Step 3: Isolate the Problem</strong></h3>

<p>Shrink the scope.</p>

<ul>
  <li>Comment out unrelated code</li>
  <li>Remove layers (UI → API → DB)</li>
  <li>Test pieces independently</li>
</ul>

<p>Think of it like this:</p>

<pre><code>[ UI ] → [ API ] → [ Database ]

Which layer is lying?
</code></pre>

<hr />

<h3 id="step-4-form-a-hypothesis"><strong>Step 4: Form a Hypothesis</strong></h3>

<p>Be explicit:</p>

<blockquote>
  <p>“I think the API is returning empty data because the query filter is wrong.”</p>
</blockquote>

<p>Now you’re not guessing—you’re <strong>testing a theory</strong>.</p>

<hr />

<h3 id="step-5-test-the-hypothesis"><strong>Step 5: Test the Hypothesis</strong></h3>

<p>Use targeted tools:</p>

<ul>
  <li>Logs</li>
  <li>Breakpoints</li>
  <li>Network inspector</li>
</ul>

<p><img src="https://media.giphy.com/media/26ufdipQqU2lhNA4g/giphy.gif" alt="Experimenting" /></p>

<p>Example:</p>

<pre><code class="language-js">console.log("User ID:", userId)
</code></pre>

<p>But intentional—not random.</p>

<hr />

<h3 id="step-6-fix-and-verify"><strong>Step 6: Fix and Verify</strong></h3>

<p>Fix it.</p>

<p>Then confirm:</p>

<ul>
  <li>Does it work in all cases?</li>
  <li>Did you break something else?</li>
</ul>

<p><img src="https://media.giphy.com/media/26gsspfbt1HfVQ9va/giphy.gif" alt="Calm Focus" /></p>

<hr />

<h3 id="step-7-understand-the-root-cause"><strong>Step 7: Understand the Root Cause</strong></h3>

<p>This is where most devs stop too early.</p>

<p>Don’t just fix it—<strong>explain it</strong>:</p>

<blockquote>
  <p>“The bug happened because the state updated asynchronously, and we read it too early.”</p>
</blockquote>

<p>Now you’ve learned something reusable.</p>

<hr />

<h2 id="real-example-the-api-is-broken-but-its-not">Real Example: “The API Is Broken” (But It’s Not)</h2>

<p>Let’s walk through a real scenario.</p>

<hr />

<h3 id="the-bug">The Bug</h3>

<blockquote>
  <p>Frontend shows: <strong>No data available</strong></p>
</blockquote>

<hr />

<h3 id="initial-assumption">Initial Assumption</h3>

<blockquote>
  <p>“The API is broken.”</p>
</blockquote>

<hr />

<h3 id="step-1-check-network-tab">Step 1: Check Network Tab</h3>

<p>You open DevTools → Network:</p>

<p>API returns correct data</p>

<p>So… not the API.</p>

<hr />

<h3 id="step-2-check-state">Step 2: Check State</h3>

<pre><code class="language-js">console.log(data)
</code></pre>

<p>It logs:</p>

<pre><code class="language-js">[]
</code></pre>

<p>Empty array.</p>

<hr />

<h3 id="step-3-trace-the-flow">Step 3: Trace the Flow</h3>

<pre><code class="language-js">useEffect(() =&gt; {
  fetchData()
}, [])
</code></pre>

<p>Inside <code>fetchData</code>:</p>

<pre><code class="language-js">setData(response.data)
console.log(data) // still empty
</code></pre>

<hr />

<h3 id="the-problem">The Problem</h3>

<p>React state updates are <strong>asynchronous</strong>.</p>

<p>You’re logging <strong>before state updates</strong>.</p>

<hr />

<h3 id="the-fix">The Fix</h3>

<pre><code class="language-js">useEffect(() =&gt; {
  fetchData()
}, [])

useEffect(() =&gt; {
  console.log(data)
}, [data])
</code></pre>

<h2><img src="https://media.giphy.com/media/111ebonMs90YLu/giphy.gif" alt="Victory" /></h2>

<h3 id="the-lesson">The Lesson</h3>

<blockquote>
  <p>The bug wasn’t in the API.
It was in your mental model of how state updates work.</p>
</blockquote>

<hr />

<h2 id="tools-that-actually-help">Tools That Actually Help</h2>

<p>Not everything is about tools—but the right ones matter.</p>

<hr />

<h3 id="1-browser-devtools-underrated-powerhouse">1. Browser DevTools (Underrated Powerhouse)</h3>

<ul>
  <li><strong>Network tab</strong> → verify API calls</li>
  <li><strong>Console</strong> → inspect runtime values</li>
  <li><strong>Application tab</strong> → check storage</li>
</ul>

<hr />

<h3 id="2-breakpoints-game-changer">2. Breakpoints (Game Changer)</h3>

<p>Instead of spamming logs:</p>

<p>Pause execution and inspect state <em>live</em></p>

<hr />

<h3 id="3-intentional-logging">3. Intentional Logging</h3>

<p>Bad:</p>

<pre><code class="language-js">console.log("here")
</code></pre>

<p>Good:</p>

<pre><code class="language-js">console.log("User after login:", user)
</code></pre>

<hr />

<h3 id="4-stack-traces">4. Stack Traces</h3>

<p>Read them.</p>

<p>They literally tell you:</p>

<ul>
  <li>Where the error happened</li>
  <li>What triggered it</li>
</ul>

<hr />

<h3 id="5-rubber-duck-debugging">5. Rubber Duck Debugging</h3>

<p>Explain the bug out loud.</p>

<p>Yes, seriously.</p>

<p>You’ll often solve it mid-explanation.</p>

<hr />

<pre><code>Problem → Hypothesis → Test → Learn → Repeat
</code></pre>

<hr />

<h2 id="common-debugging-traps">Common Debugging Traps</h2>

<p>Avoid these and you’ll already be ahead of most devs:</p>

<hr />

<h3 id="fixing-symptoms-instead-of-causes">Fixing Symptoms Instead of Causes</h3>

<p>You silence the error… but the bug is still there.</p>

<hr />

<h3 id="changing-too-many-things-at-once">Changing Too Many Things at Once</h3>

<p>Now you don’t know what worked.</p>

<hr />

<h3 id="ignoring-error-messages">Ignoring Error Messages</h3>

<p>The error is literally telling you what’s wrong.</p>

<p>Read it.</p>

<hr />

<h3 id="assuming-the-bug-is-weird">Assuming the Bug Is “Weird”</h3>

<p>It’s almost never weird.</p>

<p>It’s misunderstood.</p>

<hr />

<h3 id="it-works-on-my-machine">“It Works on My Machine”</h3>

<p>This is not a flex.</p>

<p>It’s a clue.</p>

<hr />

<h2 id="a-better-mental-model">A Better Mental Model</h2>

<pre><code>Expectation ≠ Reality  
        ↓  
Investigate the gap
</code></pre>

<p>That’s debugging.</p>

<hr />

<h2 id="final-thought">Final Thought</h2>

<blockquote>
  <p>The best developers aren’t the ones who write perfect code.
They’re the ones who can <strong>quickly understand why things break</strong>.</p>
</blockquote>

<p>Debugging isn’t a side skill.</p>

<p>It <em>is</em> the job.</p>

]]></content:encoded>
      <author>billycartel360@gmail.com (Billy Okeyo)</author>
  
      <media:content url="https://billyokeyo.dev/assets/img/find-the-bug.png" medium="image" />
  
  
    
      <category>Programming</category>
    
      <category>Software Development</category>
    
      <category>Career</category>
    
  
  
    
      <category>debugging</category>
    
      <category>software development</category>
    
      <category>programming</category>
    
      <category>career advice</category>
    
  
    </item>

  
  





  



  


    <item>
      <title>Stripe Connect on Accounts v2 — Standard, Express, and Custom, Rebuilt Around Configurations (with HTTP, Python, C#, and PHP)</title>
      <link>https://billyokeyo.dev/posts/stripe-connect-accounts-v2/</link>
      <guid isPermaLink="true">https://billyokeyo.dev/posts/stripe-connect-accounts-v2/</guid>
      <pubDate>Mon, 06 Apr 2026 00:00:00 +0000</pubDate>
  
      <atom:updated>2026-04-06T00:00:00+00:00</atom:updated>
  
      <description><![CDATA[A Connect integration guide aligned with Stripe’s Accounts v2 API: merchant, customer, and recipient configurations on one Account, customer_account vs Customer, and how Standard / Express / Custom maps onto the new model—with examples and links to official docs.]]></description>
      <content:encoded><![CDATA[<p>This is the <strong>Accounts v2</strong> companion to the <strong><a href="https://billyokeyo.dev/posts/integrating-to-stripe/">original Connect guide (Accounts v1)</a></strong>. Same <strong>platform concepts</strong>—Standard, Express, Custom, money flow, compliance—but the <strong>API shape</strong> is the one Stripe describes in <strong><a href="https://docs.stripe.com/connect/accounts-v2">Connect and the Accounts v2 API</a></strong>. Use the older post when you must stay on <strong>v1</strong> (<code>Account.create</code> with <code>type=express</code>, OAuth-only Standard flows, etc.). Use <strong>this</strong> post when you are designing around <strong>one <code>Account</code></strong>, <strong>configurations</strong>, and <strong><code>customer_account</code></strong>.</p>

<blockquote>
  <p class="prompt-tip"><strong>Heads-up:</strong> v2 uses <strong>different endpoints and JSON</strong> than classic <code>Accounts</code> CRUD. Always confirm <strong>API version</strong>, <strong>preview flags</strong>, and <strong>SDK support</strong> in <strong><a href="https://docs.stripe.com/connect/accounts-v2">Stripe’s documentation</a></strong> before shipping production code.</p>
</blockquote>

<h2 id="what-is-stripe-connect">What is Stripe Connect?</h2>

<p>Stripe Connect is for <strong>platforms</strong> that move money between <strong>buyers</strong>, <strong>sellers</strong>, and <strong>your platform</strong>. You connect <strong>connected accounts</strong> to your <strong>platform account</strong> so you can:</p>

<ul>
  <li>Collect payments from customers</li>
  <li>Pay out to sellers or service providers</li>
  <li>Take <strong>application fees</strong> where appropriate</li>
</ul>

<p>Stripe holds the <strong>payments</strong> rail; you own <strong>product and UX</strong> choices.</p>

<h2 id="two-ideas-at-once-style-standard--express--custom-and-shape-v2-configurations">Two ideas at once: “style” (Standard / Express / Custom) and “shape” (v2 configurations)</h2>

<p>The <strong><a href="https://billyokeyo.dev/posts/integrating-to-stripe/">original guide</a></strong> compares <strong>Standard</strong>, <strong>Express</strong>, and <strong>Custom</strong> as <strong>who owns onboarding, dashboards, and compliance</strong>.</p>

<p><strong>Accounts v2</strong> adds a separate axis: <strong>what capabilities</strong> a single <strong><code>Account</code></strong> has, expressed as <strong>configurations</strong>:</p>

<table>
  <thead>
    <tr>
      <th>Configuration (v2)</th>
      <th>Role in plain language</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><strong><code>merchant</code></strong></td>
      <td>Accept card payments, get paid out—what you usually wanted from a<strong>connected account</strong> selling on your platform.</td>
    </tr>
    <tr>
      <td><strong><code>customer</code></strong></td>
      <td>Be<strong>billed like a customer</strong> (subscriptions, invoices to your platform) using the <strong>same</strong> Account identity—often replacing a separate <strong>Customer</strong> object for that business.</td>
    </tr>
    <tr>
      <td><strong><code>recipient</code></strong></td>
      <td>Receive<strong>transfers</strong> (e.g. indirect charges), using the v2 <strong>transfer</strong> capabilities Stripe documents for recipients.</td>
    </tr>
  </tbody>
</table>

<p>You can assign <strong>one or more</strong> configurations to the <strong>same</strong> <code>Account</code>. That is the core promise of v2: <strong>one identity</strong>, <strong>multiple roles</strong>, <strong>less manual ID mapping</strong>.</p>

<p>The <strong>Standard / Express / Custom</strong> choice is still <strong>real</strong>: it describes <strong>OAuth vs Stripe-hosted onboarding vs fully custom UI</strong>. On v2 you implement those <strong>experiences</strong> while creating and updating <strong>Accounts</strong> through the <strong>v2</strong> surface (where supported).</p>

<h2 id="standard-vs-express-vs-custom-unchanged-product-trade-offs">Standard vs Express vs Custom (unchanged product trade-offs)</h2>

<table>
  <thead>
    <tr>
      <th>Feature / aspect</th>
      <th><strong>Standard</strong></th>
      <th><strong>Express</strong></th>
      <th><strong>Custom</strong></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><strong>Who owns the Stripe relationship</strong></td>
      <td>The user’s<strong>existing</strong> Stripe user; you connect via <strong>OAuth</strong>.</td>
      <td>You create<strong>connected accounts</strong>; Stripe hosts <strong>onboarding</strong> and a <strong>light</strong> dashboard.</td>
      <td>You own<strong>all</strong> UX; Stripe is invisible to end users.</td>
    </tr>
    <tr>
      <td><strong>KYC / onboarding</strong></td>
      <td>User uses<strong>Stripe Dashboard</strong>.</td>
      <td><strong>Stripe-hosted</strong> onboarding (Account Links, etc., per current docs).</td>
      <td><strong>You</strong> collect data and satisfy Stripe requirements via API.</td>
    </tr>
    <tr>
      <td><strong>Dashboard</strong></td>
      <td>Full<strong>Stripe</strong> dashboard for the user.</td>
      <td><strong>Express</strong> dashboard.</td>
      <td><strong>None</strong> unless you build it.</td>
    </tr>
    <tr>
      <td><strong>Best when</strong></td>
      <td>Sellers<strong>already</strong> have Stripe.</td>
      <td>You need<strong>speed</strong> and shared compliance.</td>
      <td>You need<strong>full</strong> branding and control.</td>
    </tr>
  </tbody>
</table>

<p>On <strong>v2</strong>, you still make these <strong>product</strong> choices—but you attach <strong>merchant</strong> / <strong>customer</strong> / <strong>recipient</strong> <strong>configurations</strong> to match what each connected business must do.</p>

<h2 id="architectural-overview">Architectural overview</h2>

<p>Fund flow is unchanged at a high level:</p>

<p><strong>What changes in v2</strong> is <strong>object modeling</strong>:</p>

<ul>
  <li>One <strong><code>Account</code></strong> can represent <strong>both</strong> “seller” and “buyer of your SaaS” if you add <strong><code>merchant</code></strong> and <strong><code>customer</code></strong> configurations.</li>
  <li>APIs that took <strong><code>customer</code></strong> may accept <strong><code>customer_account</code></strong> with an <strong>Account</strong> ID—see <strong><a href="https://docs.stripe.com/connect/use-accounts-as-customers">using Accounts as customers</a></strong>.</li>
</ul>

<h2 id="accounts-v2-primitives-before-code">Accounts v2 primitives (before code)</h2>

<p>Stripe’s v2 <strong><code>Account</code></strong> objects differ from v1’s flat <code>Account</code> create. You typically send:</p>

<ul>
  <li><strong><code>identity</code></strong> — country, entity type, business details.</li>
  <li><strong><code>configuration</code></strong> — nested blocks such as <strong><code>merchant</code></strong>, <strong><code>customer</code></strong>, <strong><code>recipient</code></strong>, each with <strong>capabilities</strong> you request (<code>card_payments</code>, balance / payout capabilities as named in current docs).</li>
  <li><strong><code>defaults</code></strong> — currency, locales, responsibilities (fees / losses collector), etc.</li>
  <li><strong><code>include</code></strong> — ask the API to return nested sections (e.g. <code>configuration.merchant</code>, <code>requirements</code>).</li>
</ul>

<p>Responses may <strong>omit</strong> fields unless you <strong><code>include</code></strong> them—see Stripe’s note on <strong><a href="https://docs.stripe.com/api-includable-response-values">includable response values</a></strong>.</p>

<p><strong>API version:</strong> v2 calls often require a specific <strong><code>Stripe-Version</code></strong> header (including <strong>preview</strong> versions while the API evolves). Set this from the <strong>exact</strong> value in <strong><a href="https://docs.stripe.com/connect/accounts-v2">Stripe’s Accounts v2 docs</a></strong> for your integration window.</p>

<h2 id="implementation-creating-an-account-on-v2-http-first">Implementation: creating an Account on v2 (HTTP-first)</h2>

<p>Official examples are <strong>REST + JSON</strong>. Below is <strong>illustrative</strong>—copy <strong>field names</strong>, <strong>capability keys</strong>, and <strong>version</strong> from the current docs, not from this blog alone.</p>

<h3 id="curl-canonical-pattern-from-stripe">cURL (canonical pattern from Stripe)</h3>

<p>Stripe documents <strong><code>POST /v2/core/accounts</code></strong> with a JSON body. Conceptually:</p>

<pre><code class="language-bash">curl -X POST https://api.stripe.com/v2/core/accounts \
  -H "Authorization: Bearer sk_test_..." \
  -H "Stripe-Version: &lt;version-from-stripe-docs&gt;" \
  -H "Content-Type: application/json" \
  --data '{
    "contact_email": "seller@example.com",
    "display_name": "Example Seller",
    "identity": {
      "country": "us",
      "entity_type": "company",
      "business_details": { "registered_name": "Example Co" }
    },
    "configuration": {
      "merchant": {
        "capabilities": {
          "card_payments": { "requested": true }
        }
      },
      "customer": {
        "capabilities": {
          "automatic_indirect_tax": { "requested": true }
        }
      }
    },
    "defaults": {
      "currency": "usd",
      "responsibilities": {
        "fees_collector": "stripe",
        "losses_collector": "stripe"
      },
      "locales": ["en-US"]
    },
    "include": [
      "configuration.customer",
      "configuration.merchant",
      "identity",
      "requirements"
    ]
  }'
</code></pre>

<p>This shows the <strong>mental model</strong>: <strong>one</strong> create, <strong>multiple</strong> configurations, <strong>explicit</strong> includes.</p>

<h3 id="python-generic-http-client">Python (generic HTTP client)</h3>

<p>Until your <strong><code>stripe</code></strong> SDK exposes stable helpers for every v2 path, <strong><code>httpx</code></strong> or <strong><code>requests</code></strong> keeps you aligned with the docs:</p>

<pre><code class="language-python">import os
import requests

def create_account_v2():
    r = requests.post(
        "https://api.stripe.com/v2/core/accounts",
        headers={
            "Authorization": f"Bearer {os.environ['STRIPE_SECRET_KEY']}",
            "Stripe-Version": "&lt;version-from-stripe-docs&gt;",
            "Content-Type": "application/json",
        },
        json={
            # ...same structure as the cURL example...
        },
        timeout=30,
    )
    r.raise_for_status()
    return r.json()
</code></pre>

<h3 id="php-laravel-style">PHP (Laravel-style)</h3>

<p>Use <strong>Guzzle</strong> or Laravel <strong><code>Http::withHeaders([...])-&gt;post(...)</code></strong> with the same URL, <strong><code>Stripe-Version</code></strong>, and JSON body. Keep <strong>secrets</strong> in <strong>config</strong>, not in source control.</p>

<h3 id="c-net">C# (.NET)</h3>

<p>Use <strong><code>HttpClient</code></strong> with <strong><code>StringContent(json, Encoding.UTF8, "application/json")</code></strong> and the same headers. Deserialize the JSON response into your own DTOs that track <strong><code>id</code></strong>, <strong><code>requirements</code></strong>, and <strong><code>configuration.*</code></strong> state.</p>

<blockquote>
  <p class="prompt-tip"><strong>OAuth / Standard accounts:</strong> Stripe currently directs platforms that authenticate with <strong>OAuth</strong> to connected accounts to <strong>continue using v1</strong> for that path. Treat <strong>Standard</strong> as <strong>documented in the <a href="https://billyokeyo.dev/posts/integrating-to-stripe/">v1 guide</a></strong> until your OAuth + v2 story is explicitly supported for your use case—see <strong><a href="https://docs.stripe.com/connect/accounts-v2">Accounts v2</a></strong> and <strong><a href="https://docs.stripe.com/stripe-apps/api-authentication/oauth">OAuth</a></strong>.</p>
</blockquote>

<h2 id="onboarding-links-express-style-flows">Onboarding links (Express-style flows)</h2>

<p>For <strong>Express-like</strong> experiences you still send users through <strong>Stripe-hosted onboarding</strong> where the product allows it. With a <strong>connected account ID</strong> returned from v2 (<code>acct_...</code>), <strong><code>Account Links</code></strong> (v1 resource) remain the usual tool for <strong><code>account_onboarding</code></strong>—the same pattern as the <strong><a href="https://billyokeyo.dev/posts/integrating-to-stripe/">v1 article</a></strong>, but the <strong><code>account</code></strong> value may come from a <strong>v2</strong> create. Verify compatibility for your <strong>API version</strong> in Stripe’s docs.</p>

<p><strong>Python (v1 Account Links API, account id from v2 create):</strong></p>

<pre><code class="language-python">import stripe
stripe.api_key = os.environ["STRIPE_SECRET_KEY"]

link = stripe.AccountLink.create(
    account=connected_account_id,
    refresh_url="https://yourapp.com/reauth",
    return_url="https://yourapp.com/complete",
    type="account_onboarding",
)
</code></pre>

<h2 id="custom-style-integrations-on-v2">Custom-style integrations on v2</h2>

<p><strong>Custom</strong> still means: <strong>you</strong> own KYC collection, ToS acceptance, and ongoing verification. On v2 you express that by:</p>

<ul>
  <li>Sending <strong>complete <code>identity</code></strong> data the API requires.</li>
  <li>Requesting <strong><code>merchant</code></strong> / <strong><code>recipient</code></strong> capabilities your product needs.</li>
  <li>Handling <strong><code>requirements</code></strong> and <strong>webhooks</strong> the same way you would for Custom on v1—only the <strong>payload shape</strong> differs.</li>
</ul>

<p>You may still use <strong><code>tos_acceptance</code></strong>-style fields where the v2 schema maps them; follow <strong>Stripe’s v2 reference</strong> for exact property names.</p>

<h2 id="using-accounts-as-customers-customer_account">Using Accounts as customers (<code>customer_account</code>)</h2>

<p>Where you used <strong><code>customer=cus_...</code></strong>, many flows accept <strong><code>customer_account=acct_...</code></strong> for an Account that has the <strong><code>customer</code></strong> configuration. Example pattern from Stripe (conceptual):</p>

<pre><code class="language-bash">curl https://api.stripe.com/v1/setup_intents \
  -u "sk_test_...:" \
  -H "Stripe-Version: &lt;version-from-stripe-docs&gt;" \
  -d customer_account=acct_123 \
  -d "payment_method_types[]=card" \
  -d confirm=true \
  -d usage=off_session
</code></pre>

<p>Details and supported objects live under <strong><a href="https://docs.stripe.com/connect/use-accounts-as-customers">using Accounts as customers</a></strong>.</p>

<h2 id="checking-balances">Checking balances</h2>

<p>For many <strong>Connect</strong> operations, <strong>connected account</strong> scoping is unchanged. <strong>Python:</strong></p>

<pre><code class="language-python">balance = stripe.Balance.retrieve(stripe_account=account_id)
</code></pre>

<p><strong>PHP:</strong></p>

<pre><code class="language-php">$balance = \Stripe\Balance::retrieve([], ['stripe_account' =&gt; $accountId]);
</code></pre>

<p><strong>C#:</strong></p>

<pre><code class="language-csharp">var balance = await stripe.Balance.GetAsync(
    new BalanceGetOptions(),
    new RequestOptions { StripeAccount = accountId }
);
</code></pre>

<p>Confirm in Stripe’s docs whether your <strong>v2</strong> account IDs behave identically for every <strong>Balance</strong> and <strong>v1</strong> helper you rely on during migration.</p>

<h2 id="compliance-responsibilities">Compliance responsibilities</h2>

<p>The <strong>Standard / Express / Custom</strong> compliance split from the <strong><a href="https://billyokeyo.dev/posts/integrating-to-stripe/">original article</a></strong> still applies <strong>who</strong> collects KYC and <strong>who</strong> owns disputes. <strong>v2</strong> can <strong>reduce duplicate</strong> identity collection when you <strong>add</strong> configurations to an <strong>existing</strong> Account instead of opening a second <strong>Customer</strong> record.</p>

<table>
  <thead>
    <tr>
      <th>Responsibility</th>
      <th>Standard</th>
      <th>Express</th>
      <th>Custom</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>KYC</td>
      <td>Stripe</td>
      <td>Mostly Stripe</td>
      <td>You</td>
    </tr>
    <tr>
      <td>Tax reporting</td>
      <td>Stripe-heavy</td>
      <td>Shared</td>
      <td>Often you</td>
    </tr>
    <tr>
      <td>PCI</td>
      <td>Stripe-hosted elements</td>
      <td>Shared</td>
      <td>Mostly you</td>
    </tr>
    <tr>
      <td>Disputes</td>
      <td>Stripe-heavy</td>
      <td>Shared</td>
      <td>Often you</td>
    </tr>
  </tbody>
</table>

<h2 id="choosing-a-path">Choosing a path</h2>

<table>
  <thead>
    <tr>
      <th>Scenario</th>
      <th>Style to favor</th>
      <th>v2 angle</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Sellers already on Stripe; OAuth</td>
      <td><strong>Standard</strong></td>
      <td>Often<strong>v1 OAuth</strong> until Stripe supports your OAuth + v2 plan</td>
    </tr>
    <tr>
      <td>Fast marketplace onboarding</td>
      <td><strong>Express</strong></td>
      <td><strong>v2</strong> <code>Account</code> + <strong><code>merchant</code></strong> + Account Links</td>
    </tr>
    <tr>
      <td>White-label, embedded finance</td>
      <td><strong>Custom</strong></td>
      <td><strong>v2</strong> full <strong><code>identity</code></strong> + capabilities + your UI</td>
    </tr>
    <tr>
      <td>Same business pays you<em>and</em> sells on your platform</td>
      <td><strong>Express</strong> or <strong>Custom</strong></td>
      <td>Same<strong><code>Account</code></strong>, <strong><code>merchant</code></strong> + <strong><code>customer</code></strong> configurations</td>
    </tr>
  </tbody>
</table>

<h2 id="strategic-considerations">Strategic considerations</h2>

<ul>
  <li><strong>Time-to-market:</strong> Standard (when OAuth fits) &lt; Express &lt; Custom.</li>
  <li><strong>API surface:</strong> v2 adds <strong>configuration</strong> discipline—plan for <strong>migration</strong> from v1, not an eternal split (Stripe <strong>discourages</strong> maintaining both versions simultaneously). - <a href="https://docs.stripe.com/connect/accounts-v2">Reference</a></li>
  <li><strong>SDKs:</strong> Expect to use <strong>HTTP</strong> for some <strong>v2</strong> paths until your language SDK is fully aligned.</li>
</ul>

<h2 id="final-thoughts">Final thoughts</h2>

<p><strong>Accounts v2</strong> does not erase <strong>Standard / Express / Custom</strong>—it <strong>repackages</strong> how you <strong>represent</strong> connected users in the API. Start from <strong><a href="https://docs.stripe.com/connect/accounts-v2">Connect and the Accounts v2 API</a></strong>, add <strong><a href="https://docs.stripe.com/connect/use-accounts-as-customers">using Accounts as customers</a></strong> when the same legal entity both <strong>sells</strong> and <strong>buys</strong> from your platform, and keep the <strong><a href="https://billyokeyo.dev/posts/integrating-to-stripe/">v1 Connect guide</a></strong> handy for <strong>OAuth</strong> flows and <strong>legacy</strong> snippets until you have fully moved.</p>

<p>Either way, you still trade off <strong>control</strong>, <strong>compliance</strong>, and <strong>complexity</strong>—only the <strong>object model</strong> got a long-overdue upgrade.</p>
]]></content:encoded>
      <author>billycartel360@gmail.com (Billy Okeyo)</author>
  
      <media:content url="https://billyokeyo.dev/assets/img/stripe-integration.jpg" medium="image" />
  
  
    
      <category>Payment Processing</category>
    
      <category>Software Development</category>
    
  
  
    
      <category>Stripe</category>
    
      <category>Payment Processing</category>
    
      <category>Software Development</category>
    
      <category>APIs</category>
    
      <category>Fintech</category>
    
      <category>Stripe Connect</category>
    
      <category>Accounts v2</category>
    
      <category>Integrating Stripe Laravel</category>
    
      <category>Integrating Stripe C#</category>
    
      <category>Integrating Stripe Python</category>
    
  
    </item>

  
  





  



  


    <item>
      <title>Contract Testing: Prevent Breaking Changes Before Production</title>
      <link>https://billyokeyo.dev/posts/contract-testing/</link>
      <guid isPermaLink="true">https://billyokeyo.dev/posts/contract-testing/</guid>
      <pubDate>Thu, 19 Mar 2026 00:00:00 +0000</pubDate>
  
      <atom:updated>2026-03-19T00:00:00+00:00</atom:updated>
  
      <description><![CDATA[Learn how to implement contract testing between services to catch breaking changes before they hit production. Works across any tech stack—examples in .NET and Angular.]]></description>
      <content:encoded><![CDATA[<blockquote>
  <p><em>“It worked locally. Tests passed. But production still broke.”</em></p>
</blockquote>

<p>If you’re building distributed systems with multiple services and frontends, you’ve likely encountered this (whether using <strong>.NET + Angular</strong>, <strong>Node.js + React</strong>, <strong>Python + Vue</strong>, or any combination):</p>

<ul>
  <li>A backend change gets deployed</li>
  <li>The frontend suddenly breaks</li>
  <li>No tests warned you</li>
</ul>

<p>The issue isn’t always logic.</p>

<p>It’s often a <strong>broken contract between systems</strong>.</p>

<h1 id="the-problem-silent-api-breakages">The Problem: Silent API Breakages</h1>

<p>In a typical setup:</p>

<ul>
  <li>Service Provider: An API or microservice</li>
  <li>Service Consumer: A frontend, app, or another service</li>
  <li>Communication: JSON over HTTP (or any protocol)</li>
</ul>

<p>Everything depends on one thing:</p>

<blockquote>
  <p>The consumer and provider agreeing on <strong>what data looks like</strong></p>
</blockquote>

<h2 id="a-real-example">A Real Example</h2>

<p>Let’s use a <strong>.NET API</strong> and <strong>Angular frontend</strong> as an example (though this applies to any tech stack).</p>

<h3 id="api-provider-initial-version">API Provider (Initial Version)</h3>

<pre><code class="language-csharp">public class UserDto
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
}
</code></pre>

<pre><code class="language-csharp">[HttpGet("{id}")]
public IActionResult GetUser(int id)
{
    return Ok(new UserDto
    {
        Id = 1,
        Name = "Billy",
        Email = "billy@example.com"
    });
}
</code></pre>

<h3 id="consumer-interface-angular-example">Consumer Interface (Angular Example)</h3>

<pre><code class="language-ts">export interface User {
  id: number;
  name: string;
  email: string;
}
</code></pre>

<p>Everything works perfectly.</p>

<h2 id="then-a-small-change-happens">Then a “Small” Change Happens</h2>

<pre><code class="language-csharp">public class UserDto
{
    public int Id { get; set; }
    public string FullName { get; set; } // renamed
    public string Email { get; set; }
}
</code></pre>

<h3 id="production-result">Production Result</h3>

<pre><code class="language-ts">user.name //  undefined
</code></pre>

<p>The UI breaks.</p>

<h2 id="why-didnt-traditional-tests-catch-this">Why Didn’t Traditional Tests Catch This?</h2>

<ul>
  <li>Unit tests → passed (backend logic is fine)</li>
  <li>Integration tests → passed (they used the old model)</li>
  <li>The API still returns valid JSON</li>
</ul>

<p>But the <strong>contract between systems changed</strong>—and traditional tests don’t verify that.</p>

<h1 id="what-is-contract-testing">What is Contract Testing?</h1>

<p>In Contract Testing, a contract is a formal specification of expected behavior and communication rules between two or more components, services or systems.</p>

<blockquote>
  <p><strong>Contract testing ensures that your service provider always matches what the consumer expects.</strong></p>
</blockquote>

<p>A <strong>contract</strong> defines:</p>

<ul>
  <li>Request format</li>
  <li>Response structure</li>
  <li>Required fields</li>
  <li>Data types</li>
</ul>

<h2 id="in-simple-terms">In Simple Terms</h2>

<blockquote>
  <p>The <strong>consumer</strong> (frontend, app, or service) defines expectations
The <strong>provider</strong> (API or service) must satisfy them</p>
</blockquote>

<h1 id="consumer-vs-provider">Consumer vs Provider</h1>

<h3 id="consumer">Consumer</h3>

<ul>
  <li>Calls the service/API</li>
  <li>Defines expected structure</li>
  <li>Examples: Angular frontend, React app, mobile app, another microservice</li>
</ul>

<h3 id="provider">Provider</h3>

<ul>
  <li>Returns the data</li>
  <li>Must not break expectations</li>
  <li>Examples: .NET API, Node.js backend, Python service, GraphQL endpoint</li>
</ul>

<h1 id="how-contract-testing-works">How Contract Testing Works</h1>

<p>Instead of relying only on integration tests:</p>

<ol>
  <li>Angular defines expectations</li>
  <li>A contract file is generated</li>
  <li>.NET verifies the contract</li>
</ol>

<h2 id="flow">Flow</h2>

<pre><code>Consumer Test (e.g., Angular)
      ↓
Generates Contract
      ↓
Saved as JSON/YAML
      ↓
Provider verifies against contract (e.g., .NET API)
</code></pre>

<h1 id="practical-example">Practical Example</h1>

<p><em>(.NET backend + Angular frontend as an example)</em></p>

<h2 id="step-1-define-expectations-in-consumer-angular-example">Step 1: Define Expectations in Consumer (Angular example)</h2>

<pre><code class="language-ts">const expectedUser = {
  id: 1,
  name: "Billy",
  email: "billy@example.com"
};

it("should fetch user correctly", async () =&gt; {
  const user = await userService.getUser(1);
  expect(user).toEqual(expectedUser);
});
</code></pre>

<h2 id="generated-contract-simplified">Generated Contract (Simplified)</h2>

<pre><code class="language-json">{
  "request": {
    "method": "GET",
    "path": "/api/users/1"
  },
  "response": {
    "body": {
      "id": 1,
      "name": "Billy",
      "email": "billy@example.com"
    }
  }
}
</code></pre>

<h2 id="step-2-verify-in-provider-net-api-example">Step 2: Verify in Provider (.NET API example)</h2>

<p>Install Pact:</p>

<pre><code class="language-bash">dotnet add package PactNet
</code></pre>

<h3 id="provider-test">Provider Test</h3>

<pre><code class="language-csharp">[Fact]
public void VerifyPact()
{
    var pactVerifier = new PactVerifier();

    pactVerifier
        .ServiceProvider("UserApi", "http://localhost:5000")
        .WithFileSource(new FileInfo("pacts/userapi-angular.json"))
        .Verify();
}
</code></pre>

<h2 id="if-provider-breaks-the-contract">If Provider Breaks the Contract</h2>

<pre><code class="language-csharp">public string FullName { get; set; }
</code></pre>

<ul>
  <li>
    <p>The test fails immediately</p>
  </li>
  <li>
    <p>You catch the issue before deployment</p>
  </li>
</ul>

<h1 id="where-contract-testing-fits">Where Contract Testing Fits</h1>

<pre><code>E2E Tests
(user journeys)

Integration Tests
(service interactions)

Contract Tests 
(API agreements)

Unit Tests
(business logic)
</code></pre>

<h1 id="why-this-matters-in-real-projects">Why This Matters in Real Projects</h1>

<h2 id="safer-refactoring">Safer Refactoring</h2>

<p>Change DTOs, schema, or API responses without fear. Contract tests verify nothing broke.</p>

<h2 id="independent-development">Independent Development</h2>

<p>Consumer and provider teams move faster. Changes are caught instantly, not in production.</p>

<h2 id="faster-debugging">Faster Debugging</h2>

<p>Failures clearly show what broke</p>

<h2 id="stronger-cicd-pipelines">Stronger CI/CD Pipelines</h2>

<pre><code>Consumer Build → Generate Contract
Provider Build → Verify Contract
Deploy → Only if both pass
</code></pre>

<p>This works with any tech stack.</p>

<h1 id="common-mistakes">Common Mistakes</h1>

<h3 id="over-specifying-data">Over-Specifying Data</h3>

<p>Bad:</p>

<pre><code class="language-json">"name": "Billy Okeyo"
</code></pre>

<p>Good:</p>

<pre><code class="language-json">"name": "string"
</code></pre>

<h3 id="testing-everything">Testing Everything</h3>

<p>Only validate fields your frontend actually uses</p>

<h3 id="ignoring-versioning">Ignoring Versioning</h3>

<p>Breaking contracts without versioning leads to production issues</p>

<h1 id="best-practices">Best Practices</h1>

<h3 id="keep-contracts-minimal">Keep Contracts Minimal</h3>

<p>Focus only on required fields</p>

<h3 id="version-your-api">Version Your API</h3>

<pre><code>/api/v1/users
/api/v2/users
</code></pre>

<h3 id="automate-in-cicd">Automate in CI/CD</h3>

<p>Contracts should be generated and verified automatically</p>

<h3 id="use-realistic-data">Use Realistic Data</h3>

<p>Avoid unrealistic mocks</p>

<h1 id="final-takeaway">Final Takeaway</h1>

<blockquote>
  <p>Unit tests verify logic
Integration tests verify systems
E2E tests verify user flows</p>

  <p><strong>Contract tests verify agreements</strong></p>
</blockquote>

<blockquote>
  <p>“Most production bugs aren’t failures… they’re misunderstandings between systems.”</p>
</blockquote>

<p>Contract testing eliminates those misunderstandings.</p>

]]></content:encoded>
      <author>billycartel360@gmail.com (Billy Okeyo)</author>
  
      <media:content url="https://billyokeyo.dev/assets/img/contract-testing.png" medium="image" />
  
  
    
      <category>Contract Testing</category>
    
      <category>API Testing</category>
    
      <category>Software Architecture</category>
    
  
  
    
      <category>Contract Testing</category>
    
      <category>API Testing</category>
    
      <category>Integration Testing</category>
    
      <category>Microservices</category>
    
      <category>Software Testing</category>
    
  
    </item>

  
  





  



  


    <item>
      <title>Why Your Django App Needs Redis and Celery in Production</title>
      <link>https://billyokeyo.dev/posts/why-your-django-app-needs-redis/</link>
      <guid isPermaLink="true">https://billyokeyo.dev/posts/why-your-django-app-needs-redis/</guid>
      <pubDate>Mon, 16 Mar 2026 00:00:00 +0000</pubDate>
  
      <atom:updated>2026-03-16T00:00:00+00:00</atom:updated>
  
      <description><![CDATA[Learn why integrating Redis and Celery into your Django application is essential for handling background tasks efficiently, improving performance, and scaling your app in production.]]></description>
      <content:encoded><![CDATA[<p>Django is an incredibly powerful framework for building web applications quickly. However, as your application grows, certain tasks begin to slow down request-response cycles.</p>

<p>Examples include:</p>

<ul>
  <li>Sending emails</li>
  <li>Generating reports</li>
  <li>Processing uploaded files</li>
  <li>Running background analytics</li>
  <li>Sending notifications</li>
</ul>

<p>Running these tasks during an HTTP request can make your application slow and unreliable.</p>

<p>This is where <strong>Celery and Redis</strong> come in.</p>

<p>Together they allow you to run background jobs asynchronously without blocking your main application.</p>

<hr />

<h2 id="the-problem-with-synchronous-tasks">The Problem with Synchronous Tasks</h2>

<p>Imagine a user submits a request that triggers an operation that takes <strong>10 seconds</strong>.</p>

<p>For example:</p>

<ul>
  <li>Generating a financial report</li>
  <li>Parsing a large document</li>
  <li>Sending multiple emails</li>
</ul>

<p>If your application processes this synchronously:</p>

<pre><code>User Request → Django → Long Task → Response
</code></pre>

<p>The user waits for the entire process to finish.</p>

<p>This leads to:</p>

<ul>
  <li>Slow responses</li>
  <li>Poor user experience</li>
  <li>Possible request timeouts</li>
</ul>

<hr />

<h2 id="introducing-celery">Introducing Celery</h2>

<p>Celery is a <strong>distributed task queue</strong> that allows you to run background jobs outside the request-response cycle.</p>

<p>Instead of executing tasks immediately, Django sends the job to a queue.</p>

<p>A worker then processes it asynchronously.</p>

<p>The flow becomes:</p>

<pre><code>User Request
    ↓
Django
    ↓
Queue Task
    ↓
Immediate Response
    ↓
Celery Worker
    ↓
Executes Job
</code></pre>

<p>This makes your application <strong>fast and scalable</strong>.</p>

<hr />

<h2 id="why-redis">Why Redis?</h2>

<p>Celery requires a <strong>message broker</strong> to manage task queues.</p>

<p>Redis is commonly used because it is:</p>

<ul>
  <li>Extremely fast</li>
  <li>Lightweight</li>
  <li>Easy to deploy</li>
  <li>Perfect for queues and caching</li>
</ul>

<p>Redis stores the tasks until workers pick them up.</p>

<hr />

<h2 id="example-sending-email-in-the-background">Example: Sending Email in the Background</h2>

<p>Instead of sending email directly in a Django view:</p>

<pre><code class="language-python">send_mail(
    "Welcome",
    "Thanks for signing up",
    "noreply@example.com",
    [user.email],
)
</code></pre>

<p>You create a Celery task:</p>

<pre><code class="language-python">from celery import shared_task
from django.core.mail import send_mail

@shared_task
def send_welcome_email(email):
    send_mail(
        "Welcome",
        "Thanks for signing up",
        "noreply@example.com",
        [email],
    )
</code></pre>

<p>Then call it asynchronously:</p>

<pre><code class="language-python">send_welcome_email.delay(user.email)
</code></pre>

<p>The user gets an immediate response while the email is processed in the background.</p>

<hr />

<h2 id="common-use-cases-for-celery">Common Use Cases for Celery</h2>

<p>Celery is useful for many production tasks:</p>

<h3 id="email-sending">Email sending</h3>

<ul>
  <li>Welcome emails</li>
  <li>Notifications</li>
  <li>Password resets</li>
</ul>

<h3 id="data-processing">Data processing</h3>

<ul>
  <li>Financial calculations</li>
  <li>AI processing</li>
  <li>Data pipelines</li>
</ul>

<h3 id="scheduled-tasks">Scheduled tasks</h3>

<ul>
  <li>Daily reports</li>
  <li>Cleaning expired sessions</li>
  <li>Updating analytics</li>
</ul>

<hr />

<h2 id="running-celery-in-production">Running Celery in Production</h2>

<p>A typical Django production stack might look like this:</p>

<pre><code>Users
  ↓
Nginx
  ↓
Gunicorn
  ↓
Django App
  ↓
Redis (Broker)
  ↓
Celery Workers
</code></pre>

<p>Each component plays a role:</p>

<ul>
  <li><strong>Nginx</strong> handles web traffic</li>
  <li><strong>Gunicorn</strong> runs Django</li>
  <li><strong>Redis</strong> manages task queues</li>
  <li><strong>Celery workers</strong> execute background jobs</li>
</ul>

<hr />

<h2 id="scaling-celery-workers">Scaling Celery Workers</h2>

<p>One of Celery’s biggest advantages is scalability.</p>

<p>If tasks increase, you simply add more workers.</p>

<pre><code>celery -A project worker --loglevel=info --concurrency=4
</code></pre>

<p>More workers mean faster task processing.</p>

<hr />

<h2 id="final-thoughts">Final Thoughts</h2>

<p>Celery and Redis are essential tools for running Django applications at scale.</p>

<p>They allow you to:</p>

<ul>
  <li>Improve response times</li>
  <li>Handle heavy workloads</li>
  <li>Build scalable architectures</li>
  <li>Run background processing reliably</li>
</ul>

<p>If your Django application handles tasks that take more than a few seconds, moving them to Celery is one of the best architectural decisions you can make.</p>
]]></content:encoded>
      <author>billycartel360@gmail.com (Billy Okeyo)</author>
  
      <media:content url="https://billyokeyo.dev/assets/img/django-redis.png" medium="image" />
  
  
    
      <category>Django</category>
    
      <category>Redis</category>
    
      <category>Celery</category>
    
      <category>Background Tasks</category>
    
  
  
    
      <category>Django</category>
    
      <category>Redis</category>
    
      <category>Celery</category>
    
      <category>Background Tasks</category>
    
      <category>Asynchronous Processing</category>
    
  
    </item>

  
  





  



  


    <item>
      <title>A Practical Guide to File Uploads (Images, Excel, CSV) in Angular + Django</title>
      <link>https://billyokeyo.dev/posts/image-uploads/</link>
      <guid isPermaLink="true">https://billyokeyo.dev/posts/image-uploads/</guid>
      <pubDate>Mon, 23 Feb 2026 00:00:00 +0000</pubDate>
  
      <atom:updated>2026-02-23T00:00:00+00:00</atom:updated>
  
      <description><![CDATA[A comprehensive guide to implementing file uploads for images, CSV, and Excel files using Angular on the frontend and Django with Django REST Framework on the backend, covering validation, security, and best practices.]]></description>
      <content:encoded><![CDATA[<p>File uploads are one of those features that look simple… until they aren’t.</p>

<p>Images need previewing. CSV files need parsing. Excel files need validation. Large files need handling. And suddenly your “simple upload” becomes a full feature.</p>

<p>In this guide, we’ll build a practical and production-ready file upload system using:</p>

<ul>
  <li>Angular (Frontend)</li>
  <li>Django + Django REST Framework (Backend)</li>
</ul>

<p>We’ll cover:</p>

<ol>
  <li>Image uploads with preview</li>
  <li>CSV uploads and parsing</li>
  <li>Excel uploads and processing</li>
  <li>Validation and security best practices</li>
</ol>

<hr />

<h1 id="backend-setup-django--drf">Backend Setup (Django + DRF)</h1>

<h2 id="1-install-dependencies">1. Install Dependencies</h2>

<pre><code class="language-bash">pip install djangorestframework pillow openpyxl pandas
</code></pre>

<ul>
  <li><code>pillow</code> → Image processing</li>
  <li><code>openpyxl</code> → Excel support</li>
  <li><code>pandas</code> → CSV &amp; Excel parsing</li>
</ul>

<hr />

<h2 id="2-configure-media-files">2. Configure Media Files</h2>

<h3 id="settingspy">settings.py</h3>

<pre><code class="language-python">MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
</code></pre>

<h3 id="urlspy-project-level">urls.py (project level)</h3>

<pre><code class="language-python">from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # your urls
]

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code></pre>

<hr />

<h1 id="part-1-image-upload">Part 1: Image Upload</h1>

<h2 id="django-model">Django Model</h2>

<pre><code class="language-python">from django.db import models

class Profile(models.Model):
    name = models.CharField(max_length=100)
    image = models.ImageField(upload_to='profiles/')
</code></pre>

<hr />

<h2 id="serializer">Serializer</h2>

<pre><code class="language-python">from rest_framework import serializers
from .models import Profile

class ProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile
        fields = '__all__'
</code></pre>

<hr />

<h2 id="view">View</h2>

<pre><code class="language-python">from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.parsers import MultiPartParser, FormParser
from rest_framework import status

class ProfileUploadView(APIView):
    parser_classes = [MultiPartParser, FormParser]

    def post(self, request):
        serializer = ProfileSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
</code></pre>

<hr />

<h1 id="angular-frontend-image-upload">Angular Frontend (Image Upload)</h1>

<h2 id="html">HTML</h2>

<pre><code class="language-html">&lt;input type="file" (change)="onFileSelected($event)" accept="image/*" /&gt;
&lt;img *ngIf="previewUrl" [src]="previewUrl" width="200" /&gt;
&lt;button (click)="upload()"&gt;Upload&lt;/button&gt;
</code></pre>

<hr />

<h2 id="component">Component</h2>

<pre><code class="language-typescript">selectedFile!: File;
previewUrl: string | ArrayBuffer | null = null;

onFileSelected(event: any) {
  this.selectedFile = event.target.files[0];

  const reader = new FileReader();
  reader.onload = () =&gt; {
    this.previewUrl = reader.result;
  };
  reader.readAsDataURL(this.selectedFile);
}

upload() {
  const formData = new FormData();
  formData.append('name', 'Billy');
  formData.append('image', this.selectedFile);

  this.http.post('http://localhost:8000/api/upload/', formData)
    .subscribe(res =&gt; console.log(res));
}
</code></pre>

<hr />

<h1 id="part-2-csv-upload-and-parsing">Part 2: CSV Upload and Parsing</h1>

<h2 id="django-view-for-csv">Django View for CSV</h2>

<pre><code class="language-python">import pandas as pd
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.parsers import MultiPartParser

class CSVUploadView(APIView):
    parser_classes = [MultiPartParser]

    def post(self, request):
        file = request.FILES['file']

        if not file.name.endswith('.csv'):
            return Response({'error': 'Invalid file type'}, status=400)

        df = pd.read_csv(file)

        # Example processing
        total_rows = len(df)
        columns = list(df.columns)

        return Response({
            'rows': total_rows,
            'columns': columns
        })
</code></pre>

<hr />

<h1 id="angular-csv-upload">Angular CSV Upload</h1>

<pre><code class="language-typescript">uploadCSV(file: File) {
  const formData = new FormData();
  formData.append('file', file);

  this.http.post('http://localhost:8000/api/upload-csv/', formData)
    .subscribe(res =&gt; console.log(res));
}
</code></pre>

<hr />

<h1 id="part-3-excel-upload-xlsx">Part 3: Excel Upload (.xlsx)</h1>

<h2 id="django-view-for-excel">Django View for Excel</h2>

<pre><code class="language-python">class ExcelUploadView(APIView):
    parser_classes = [MultiPartParser]

    def post(self, request):
        file = request.FILES['file']

        if not file.name.endswith('.xlsx'):
            return Response({'error': 'Invalid file type'}, status=400)

        df = pd.read_excel(file)

        summary = {
            'rows': len(df),
            'columns': list(df.columns)
        }

        return Response(summary)
</code></pre>

<hr />

<h1 id="validation--security-best-practices">Validation &amp; Security Best Practices</h1>

<h2 id="1-limit-file-size">1. Limit File Size</h2>

<p>In settings.py:</p>

<pre><code class="language-python">DATA_UPLOAD_MAX_MEMORY_SIZE = 5242880  # 5MB
</code></pre>

<hr />

<h2 id="2-validate-file-type-properly">2. Validate File Type Properly</h2>

<p>Don’t rely only on extension.</p>

<pre><code class="language-python">if file.content_type not in ['image/jpeg', 'image/png']:
    return Response({'error': 'Invalid image format'}, status=400)
</code></pre>

<hr />

<h2 id="3-rename-uploaded-files">3. Rename Uploaded Files</h2>

<pre><code class="language-python">import uuid

def upload_to(instance, filename):
    ext = filename.split('.')[-1]
    return f"uploads/{uuid.uuid4()}.{ext}"
</code></pre>

<hr />

<h2 id="4-handle-large-files-with-streaming">4. Handle Large Files with Streaming</h2>

<p>For very large CSV files, process in chunks:</p>

<pre><code class="language-python">for chunk in pd.read_csv(file, chunksize=1000):
    # process chunk
    pass
</code></pre>

<hr />

<h1 id="bonus-returning-processed-data">Bonus: Returning Processed Data</h1>

<p>Sometimes you don’t just upload — you process and return a result file.</p>

<p>Example: Generate processed CSV</p>

<pre><code class="language-python">from django.http import HttpResponse

response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="processed.csv"'
df.to_csv(response, index=False)
return response
</code></pre>

<h1 id="final-thoughts">Final Thoughts</h1>

<p>File uploads are not just about saving files.</p>

<p>They are about:</p>

<ul>
  <li>Validation</li>
  <li>Security</li>
  <li>User experience</li>
  <li>Scalability</li>
</ul>

<p>When done correctly, they become powerful data pipelines inside your application.</p>

<p>If you’re building admin systems, reporting tools, learning platforms, or fintech dashboards — mastering uploads is essential.</p>
]]></content:encoded>
      <author>billycartel360@gmail.com (Billy Okeyo)</author>
  
      <media:content url="https://billyokeyo.dev/assets/img/file-uploads.png" medium="image" />
  
  
    
      <category>Web Development</category>
    
      <category>Full Stack</category>
    
      <category>Django</category>
    
      <category>Angular</category>
    
  
  
    
      <category>File Uploads</category>
    
      <category>Angular</category>
    
      <category>Django</category>
    
      <category>REST Framework</category>
    
      <category>CSV</category>
    
      <category>Excel</category>
    
      <category>Images</category>
    
  
    </item>

  
  





  



  


    <item>
      <title>The Diderot Effect: A Subtle System Bug in How We Consume Technology</title>
      <link>https://billyokeyo.dev/posts/diderot-effect/</link>
      <guid isPermaLink="true">https://billyokeyo.dev/posts/diderot-effect/</guid>
      <pubDate>Fri, 09 Jan 2026 00:00:00 +0000</pubDate>
  
      <atom:updated>2026-01-09T00:00:00+00:00</atom:updated>
  
      <description><![CDATA[Explore the Diderot Effect and how it subtly influences our technology consumption habits, leading to cascading upgrades and shifting definitions of "enough."]]></description>
      <content:encoded><![CDATA[<p>At the beginning of year (<strong>2026</strong>), I took some time to reflect on my past behavior, not in terms of code quality, architectural decisions, or career milestones, but something far more mundane and quietly expensive: <strong>how I consume technology</strong>.</p>

<p>One pattern stood out immediately.</p>

<p>I bought a <strong>MacBook</strong>, and at the time, it felt sufficient. It solved the problem I had: performance, portability, and a solid development environment. From a purely functional standpoint, nothing else was required.</p>

<p>But that sense of “enough” didn’t persist.</p>

<p>Shortly after, I justified getting an <strong>iPhone</strong> partly for convenience, partly for the ecosystem. Once that was in place, the <strong>Apple Watch</strong> began to feel like a logical extension: notifications, health tracking, tighter integration. And somehow, even after all that, an <strong>Apple TV</strong> entered the setup  as if the system was still incomplete.</p>

<p>Individually, each purchase was defensible. Collectively, they formed a pattern I hadn’t consciously designed.</p>

<p>What struck me during this reflection was not the spending itself, but the realization that <strong>my definition of completeness kept shifting</strong>. Satisfaction behaved like a moving target, always one accessory away.</p>

<p>Later, I came across a concept that explained this behavior with surprising precision: <strong>The Diderot Effect</strong>.</p>

<h2 id="what-is-the-diderot-effect">What Is the Diderot Effect?</h2>

<p>The <strong>Diderot Effect</strong> describes a behavioral phenomenon where <strong>acquiring a new item triggers a cascade of related purchases</strong>, driven by the need for consistency rather than necessity.</p>

<p>The concept originates from <strong>Denis Diderot</strong>, an 18th-century philosopher who, after receiving a luxurious new robe, felt compelled to replace much of his existing furniture because it no longer “matched” the new standard he had introduced.</p>

<p>In modern terms, the Diderot Effect is essentially <strong>scope creep applied to consumption</strong>.</p>

<h2 id="why-the-diderot-effect-resonates-strongly-in-tech">Why the Diderot Effect Resonates Strongly in Tech</h2>

<p>Technology ecosystems are uniquely optimized to amplify this effect.</p>

<h3 id="1-ecosystem-lock-in-as-a-design-strategy">1. Ecosystem Lock-In as a Design Strategy</h3>

<p>Modern tech products are rarely designed as standalone components. They are built as <strong>interdependent systems</strong>:</p>

<ul>
  <li>Phone ↔ laptop ↔ watch ↔ TV</li>
  <li>Cloud services ↔ subscriptions ↔ hardware</li>
  <li>Accessories that unlock “full functionality”</li>
</ul>

<p>Once you introduce a single high-tier component into your stack, the rest of your setup begins to feel like technical debt.</p>

<h3 id="2-identity-driven-tooling">2. Identity-Driven Tooling</h3>

<p>In tech, tools are not just utilities they are signals. Owning certain devices, editors, keyboards, or setups subtly communicates:</p>

<ul>
  <li>Competence</li>
  <li>Professionalism</li>
  <li>“Seriousness” about the craft</li>
</ul>

<p>The internal logic becomes:</p>

<blockquote>
  <p><em>If I’m this kind of developer, my tools should reflect that.</em></p>
</blockquote>

<p>This is where the Diderot Effect stops being about objects and starts being about <strong>identity coherence</strong>.</p>

<h3 id="3-optimization-culture">3. Optimization Culture</h3>

<p>Engineers are trained to optimize systems. Unfortunately, that mindset often spills into consumption:</p>

<ul>
  <li>Latency → upgrade</li>
  <li>Minor friction → replace</li>
  <li>Marginal improvement → justify cost</li>
</ul>

<p>Not every inefficiency needs a hardware solution but the instinct is deeply ingrained.</p>

<h2 id="real-world-tech-examples-of-the-diderot-effect">Real-World Tech Examples of the Diderot Effect</h2>

<ul>
  <li>Buying a new laptop → external monitor → mechanical keyboard → standing desk</li>
  <li>Upgrading a phone → earbuds → watch → chargers in every room</li>
  <li>Improving a dev setup → paid tools → subscriptions → cloud services</li>
</ul>

<p>Each step feels incremental. The aggregate cost rarely does.</p>

<h2 id="the-hidden-costs-engineers-often-overlook">The Hidden Costs Engineers Often Overlook</h2>

<h3 id="1-financial-leakage-through-reasonable-decisions">1. Financial Leakage Through “Reasonable” Decisions</h3>

<p>Most Diderot-driven purchases pass basic rational checks. The problem isn’t irrationality it’s <strong>unbounded justification</strong>.</p>

<h3 id="2-perpetual-dissatisfaction">2. Perpetual Dissatisfaction</h3>

<p>When standards continuously shift upward, stability disappears. You’re always upgrading the environment instead of leveraging it.</p>

<h3 id="3-loss-of-intentional-system-design">3. Loss of Intentional System Design</h3>

<p>Your setup evolves reactively rather than architecturally.</p>

<h2 id="managing-the-diderot-effect-as-a-technical-thinker">Managing the Diderot Effect as a Technical Thinker</h2>

<p>The solution isn’t abstinence it’s <strong>intentional system design</strong>.</p>

<h3 id="1-introduce-decision-latency">1. Introduce Decision Latency</h3>

<p>Treat secondary purchases like production changes:</p>

<ul>
  <li>Add a delay (48 hours, a week, or a sprint)</li>
  <li>Re-evaluate the actual requirement</li>
</ul>

<p>Most impulses decay with time.</p>

<h3 id="2-define-system-boundaries">2. Define System Boundaries</h3>

<p>Before upgrading, explicitly define the scope:</p>

<blockquote>
  <p>“This purchase solves <em>this</em> problem. Nothing else changes.”</p>
</blockquote>

<p>Boundaries prevent cascade failures.</p>

<h3 id="3-separate-functional-debt-from-aesthetic-debt">3. Separate Functional Debt from Aesthetic Debt</h3>

<p>Ask:</p>

<ul>
  <li>Is this blocking productivity?</li>
  <li>Or does it simply look inferior relative to a new baseline?</li>
</ul>

<p>Most Diderot chains are triggered by aesthetics masquerading as inefficiency.</p>

<h3 id="4-budget-upgrades-as-projects-not-reactions">4. Budget Upgrades as Projects, Not Reactions</h3>

<p>Instead of ad-hoc improvements:</p>

<ul>
  <li>Plan upgrades quarterly or annually</li>
  <li>Allocate fixed budgets</li>
  <li>Close the project when scope is met</li>
</ul>

<p>No silent expansions.</p>

<h3 id="5-be-wary-of-identity-based-justifications">5. Be Wary of Identity-Based Justifications</h3>

<p>Phrases like:</p>

<ul>
  <li>“At my level, I should have…”</li>
  <li>“This setup doesn’t reflect where I am now…”</li>
</ul>

<p>These are signals that the Diderot Effect is driving the decision, not necessity.</p>

<h2 id="when-the-diderot-effect-can-be-used-intentionally">When the Diderot Effect Can Be Used Intentionally</h2>

<p>Not all cascades are bad.</p>

<p>Applied deliberately, the effect can reinforce positive systems:</p>

<ul>
  <li>Fitness → nutrition → sleep optimization</li>
  <li>Learning → better tools → deeper focus</li>
  <li>Workspace upgrades that genuinely reduce friction</li>
</ul>

<p>The difference lies in <strong>conscious orchestration</strong> versus unconscious drift.</p>

<h2 id="final-thoughts">Final Thoughts</h2>

<p>The Diderot Effect is not a failure of discipline, it’s a <strong>predictable system behavior</strong> triggered by introducing a higher standard into an existing environment.</p>

<p>In tech, where optimization and cohesion are prized, this effect is especially potent.</p>

<p>Reflecting on my own experience, from a single MacBook purchase to a fully integrated ecosystem  made one thing clear:
<strong>“Enough” must be explicitly defined, or it will keep moving.</strong></p>

<p>As engineers, we design systems for a living.
Our consumption habits deserve the same level of intentionality.</p>

]]></content:encoded>
      <author>billycartel360@gmail.com (Billy Okeyo)</author>
  
      <media:content url="https://billyokeyo.dev/assets/img/diderot-effect.jpg" medium="image" />
  
  
    
      <category>Personal Development</category>
    
      <category>Technology</category>
    
      <category>Behavioral Economics</category>
    
  
  
    
      <category>Diderot Effect</category>
    
      <category>Consumption</category>
    
      <category>Behavioral Economics</category>
    
      <category>Technology</category>
    
  
    </item>

  
  





  



  


    <item>
      <title>2025 in Review: A Year of Growth, Resilience, and Practical Engineering</title>
      <link>https://billyokeyo.dev/posts/year-review/</link>
      <guid isPermaLink="true">https://billyokeyo.dev/posts/year-review/</guid>
      <pubDate>Mon, 29 Dec 2025 00:00:00 +0000</pubDate>
  
      <atom:updated>2025-12-29T00:00:00+00:00</atom:updated>
  
      <description><![CDATA[Reflecting on the key engineering lessons, articles, and themes from 2025 — covering system design, testing strategies, performance optimizations, engineering culture, and real-world case studies.]]></description>
      <content:encoded><![CDATA[<p><em>Who would’ve thought I’d open my editor on the 29th of December not to debug production or chase a failing test—but to write this recap? Because apparently, I enjoy explaining bugs to the internet.</em></p>

<p>If you told me at the beginning of 2025 that I’d spend the year writing about <strong>scalable systems, testing strategies, outages, performance optimizations, and developer excuses</strong> I would’ve believed you.
If you also told me I’d still be debugging things that “worked yesterday,” I would’ve believed you even faster.</p>

<p>This article is a recap of everything I wrote this year: the lessons, the wins, the bugs, and the “how did this even pass code review?” moments. Think of it as a <strong>Spotify Wrapped</strong>, but for technical articles, minus the judgment (okay, maybe a little).</p>

<hr />

<h2 id="system-design--scalability--because-your-app-will-grow-whether-youre-ready-or-not"><strong>System Design &amp; Scalability — Because Your App <em>Will</em> Grow (Whether You’re Ready or Not)</strong></h2>

<p><strong>Summary:</strong>
This year, I spent a lot of time talking about <strong>scalable backend systems</strong> — not because every app needs to handle millions of users, but because <em>every app eventually meets its first “why is the server on fire?” moment</em>.</p>

<ul>
  <li><strong><a href="https://billyokeyo.dev/posts/building-scalable-backend-systems/">How to Build Scalable Backend Systems with Python, C#, PHP and Dart</a></strong>
A practical guide to designing systems that won’t collapse the moment your app gets featured on Twitter… or worse, WhatsApp groups.</li>
</ul>

<p><strong>Key lesson:</strong>
Scalability isn’t about overengineering — it’s about <em>not regretting your life choices later</em>.</p>

<hr />

<h2 id="testing--trust-issues-but-make-them-automated"><strong>Testing — Trust Issues, But Make Them Automated</strong></h2>

<p><strong>Summary:</strong>
Testing dominated a good part of the year, mainly because nothing builds trust issues faster than code that <em>looks correct</em> but isn’t.</p>

<p>This series walked through testing from the basics to full CI/CD integration — because “it works on my machine” is not a deployment strategy.</p>

<ul>
  <li><strong><a href="https://billyokeyo.dev/posts/unit-feature-integration-tests/">Unit, Integration, and End-to-End Tests — Part 1</a></strong>
Where we learn that tests are not the enemy — flaky tests are.</li>
  <li><strong><a href="https://billyokeyo.dev/posts/unit-feature-integration-tests/">Unit Testing in Depth — Part 2</a></strong>
Small tests, big confidence.</li>
  <li><strong><a href="https://billyokeyo.dev/posts/integration-testing/">Integration Testing in Depth — Part 3</a></strong>
When components finally talk to each other… and start arguing.</li>
  <li><strong><a href="https://billyokeyo.dev/posts/end-to-end-testing/">End-to-End Testing in Depth — Part 4</a></strong>
Testing your app the same way users break it.</li>
  <li><strong><a href="https://billyokeyo.dev/posts/testing-pyramid/">The Testing Pyramid &amp; CI/CD — Part 5</a></strong>
The moment you realize automation saves both time <em>and</em> sanity.</li>
</ul>

<p><strong>Key lesson:</strong>
Tests don’t slow you down — debugging production issues does.</p>

<hr />

<h2 id="performance--tooling--making-code-faster-without-sacrificing-sleep"><strong>Performance &amp; Tooling — Making Code Faster Without Sacrificing Sleep</strong></h2>

<p><strong>Summary:</strong>
Performance optimization showed up in different forms this year — from modern runtimes to build optimizations. Because sometimes the app isn’t slow… it’s just doing unnecessary work very enthusiastically.</p>

<ul>
  <li><strong><a href="https://billyokeyo.dev/posts/webassembly/">Diving into WebAssembly: What It Is and Why It Matters</a></strong>
For when JavaScript alone just isn’t fast enough.</li>
  <li><strong><a href="https://billyokeyo.dev/posts/tree-shaking-in-typescript/">Tree Shaking in TypeScript</a></strong>
Removing code you forgot existed but was still shipped to production.</li>
</ul>

<p><strong>Key lesson:</strong>
If users say your app is slow, they’re probably right. The logs just haven’t confessed yet.</p>

<hr />

<h2 id="engineering-culture--because-code-is-written-by-humans-flawed-ones"><strong>Engineering Culture — Because Code Is Written by Humans (Flawed Ones)</strong></h2>

<p><strong>Summary:</strong>
Not everything this year was serious architecture talk. Some articles leaned into the <em>very human side</em> of software development — where excuses are plentiful and accountability is… negotiable.</p>

<ul>
  <li><strong><a href="https://billyokeyo.dev/posts/developer-excuses-code-breaks/">Top 10 Developer Excuses When Code Breaks</a></strong>
A humorous breakdown of things we’ve all said — and what actually went wrong.</li>
</ul>

<p><strong>Key lesson:</strong>
If you’ve never blamed the cache, the network, or “some weird edge case,” are you even a developer?</p>

<hr />

<h2 id="industry-case-studies--learning-the-hard-way-so-you-dont-have-to"><strong>Industry Case Studies — Learning the Hard Way (So You Don’t Have To)</strong></h2>

<p><strong>Summary:</strong>
One of the most impactful pieces this year was breaking down a <strong>real-world outage</strong> — because nothing teaches engineering humility like watching large systems fail in creative ways.</p>

<ul>
  <li><strong><a href="https://billyokeyo.dev/posts/cloudflare-outage/">What Engineers Can Learn From the Cloudflare Outage</a></strong>
A reminder that one bad configuration can humble the biggest companies.</li>
</ul>

<p><strong>Key lesson:</strong>
Distributed systems don’t fail loudly — they fail <em>politely, globally, and at the worst possible time</em>.</p>

<hr />

<h2 id="what-2025-really-taught-me"><strong>What 2025 Really Taught Me</strong></h2>

<p>If I had to summarize the year in engineering truths:</p>

<ul>
  <li>Scalability matters <em>before</em> users complain.</li>
  <li>Tests are cheaper than apologies.</li>
  <li>Performance issues hide in plain sight.</li>
  <li>Systems fail — preparation determines whether you panic or recover.</li>
  <li>Developers are predictable creatures with unpredictable bugs.</li>
</ul>

<hr />

<h2 id="looking-ahead"><strong>Looking Ahead</strong></h2>

<p>In the next year, expect:</p>

<ul>
  <li>More real-world case studies</li>
  <li>Deeper dives into distributed systems and cloud patterns</li>
  <li>Practical articles you can actually apply on Monday morning</li>
</ul>

<p>Thank you for reading, sharing, and occasionally finding bugs in my examples (yes, I see you).</p>

<p>Here’s to another year of writing code, fixing mistakes, and pretending we knew what we were doing all along.</p>

]]></content:encoded>
      <author>billycartel360@gmail.com (Billy Okeyo)</author>
  
      <media:content url="https://billyokeyo.dev/assets/img/2025-review.png" medium="image" />
  
  
    
      <category>Engineering</category>
    
      <category>Year in Review</category>
    
  
  
    
      <category>Year in Review</category>
    
      <category>Engineering</category>
    
      <category>System Design</category>
    
      <category>Testing</category>
    
      <category>Performance</category>
    
      <category>Culture</category>
    
      <category>Case Studies</category>
    
  
    </item>

  
  





  



  


    <item>
      <title>What Engineers Can Learn From the Cloudflare Outage (November 2025)</title>
      <link>https://billyokeyo.dev/posts/cloudflare-outage/</link>
      <guid isPermaLink="true">https://billyokeyo.dev/posts/cloudflare-outage/</guid>
      <pubDate>Fri, 21 Nov 2025 00:00:00 +0000</pubDate>
  
      <atom:updated>2025-11-21T00:00:00+00:00</atom:updated>
  
      <description><![CDATA[Learn the key takeaways from the Cloudflare outage (November 2025), including the importance of configuration management, the dangers of hidden assumptions, and best practices for incident response.]]></description>
      <content:encoded><![CDATA[<p><em>How a single oversized configuration file brought down parts of the internet and why this matters for every engineering team.</em></p>

<p>On November 18, 2025, the internet shook a little.</p>

<p>Cloudflare, the massive networking and security platform powering millions of websites globally, experienced a major outage that resulted in widespread 5xx errors across the internet. For several hours, key services like CDN routing, Workers KV, Access authentication, and even Cloudflare’s own dashboard were degraded.</p>

<p>In their official <a href="https://blog.cloudflare.com/18-november-2025-outage/" target="_blank"> <strong>incident report</strong>, </a> Cloudflare broke down exactly what happened, and the root cause was surprisingly small and deceptively simple:</p>

<blockquote>
  <p><strong>A configuration file grew larger than expected, violated a hidden assumption in the proxy code, and triggered runtime panics across the global edge.</strong></p>
</blockquote>

<p>This incident is a powerful case study in modern distributed systems. Let’s break down what went wrong — and why engineers everywhere should take note.</p>

<h2 id="what-actually-happened-a-chain-reaction-from-one-oversized-file"><strong>What Actually Happened? A Chain Reaction From One Oversized File</strong></h2>

<p>The root cause began with a permissions change in Cloudflare’s <strong>ClickHouse database cluster</strong>, which led to duplicate rows in a dataset used by their Bot Management engine. That duplication caused the generated “feature file”, a config-like file that proxies rely on to double in size.</p>

<p>Here’s where assumptions came back to haunt them:</p>

<ul>
  <li>Cloudflare’s proxy engine expected a maximum of <strong>200 features</strong>.</li>
  <li>The new file exceeded that limit.</li>
  <li>An <code>.unwrap()</code> in their Rust-based FL2 proxy assumed the file would always be valid.</li>
  <li>That assumption failed — the code panicked — resulting in cascading 5xx failures.</li>
</ul>

<p>As Cloudflare noted in their report, this caused two types of breakage across their edge:</p>

<ol>
  <li><strong>FL2 proxies (new engine)</strong>: Panicked → produced 5xx errors</li>
  <li><strong>FL proxies (old engine)</strong>: Failed to process bot scores → defaulted to zero → broke logic in Access, rules, authentication, and security products</li>
</ol>

<p>To make things even more confusing, Cloudflare’s status page (hosted externally) briefly went offline too, creating a misleading early hypothesis that the outage was a <strong>massive DDoS attack</strong>.</p>

<p>It wasn’t.
It was configuration drift.</p>

<h2 id="why-this-seemingly-small-bug-became-a-big-internet-event"><strong>Why This Seemingly Small Bug Became a Big Internet Event</strong></h2>

<p>Config files have become “just another part of the deployment pipeline,” especially in cloud platforms where machine-generated metadata drives features. But Cloudflare’s outage shows:</p>

<ul>
  <li><strong>Config is not static</strong></li>
  <li><strong>Config can be corrupted</strong></li>
  <li><strong>Config needs validation just like code</strong></li>
</ul>

<p>Because this file was distributed globally across tens of thousands of Cloudflare servers, a single flawed generation step caused a worldwide issue within minutes.</p>

<p>Distributed systems amplify mistakes — both good ones and bad ones.</p>

<h2 id="key-engineering-lessons-we-should-all-learn"><strong>Key Engineering Lessons We Should All Learn</strong></h2>

<h3 id="1-never-rely-on-hidden-assumptions"><strong>1. Never rely on hidden assumptions</strong></h3>

<p>Cloudflare’s proxy code assumed the feature file would never exceed a certain size. That “should never happen” moment is often the birthplace of outages.</p>

<p><strong>Lesson:</strong>
Add explicit limits, schema checks, and sanity validations to <em>all</em> config ingestion paths.</p>

<hr />

<h3 id="2-configuration-is-part-of-your-software-supply-chain"><strong>2. Configuration is part of your software supply chain</strong></h3>

<p>The feature file was generated, replicated, and consumed automatically — no human intervention. That makes it just as risky as code.</p>

<p><strong>Lesson:</strong>
Treat configuration pipelines as first-class citizens: test them, validate them, gate them.</p>

<h3 id="3-build-for-graceful-degradation-not-hard-crashes"><strong>3. Build for graceful degradation, not hard crashes</strong></h3>

<p>A single <code>.unwrap()</code> took down parts of the internet.</p>

<p><strong>Lesson:</strong>
Fail softly.
If config is invalid, degrade safely, skip rules, or revert to defaults — don’t panic.</p>

<h3 id="4-feature-flags-and-kill-switches-are-essential"><strong>4. Feature flags and kill switches are essential</strong></h3>

<p>Cloudflare themselves acknowledged the need for a more robust kill-switch system in their follow-up plans.</p>

<p><strong>Lesson:</strong>
Every modern engineering team should have:</p>

<ul>
  <li>global feature kill switches</li>
  <li>fast configuration rollback</li>
  <li>manual override options</li>
</ul>

<h3 id="5-monitoring-needs-context-not-just-alarms"><strong>5. Monitoring needs context, not just alarms</strong></h3>

<p>Many engineers watching the outage thought it was an external attack. Alerting didn’t tell them <strong>where</strong> the failure was coming from, just that everything was “down.”</p>

<p><strong>Lesson:</strong>
Monitoring should distinguish between:</p>

<ul>
  <li>origin failure</li>
  <li>edge failure</li>
  <li>config failure</li>
  <li>auth failure</li>
  <li>internal propagation issues</li>
</ul>

<p>Context reduces misdiagnosis.</p>

<h3 id="6-observability-tools-must-be-lightweight-during-crises"><strong>6. Observability tools must be lightweight during crises</strong></h3>

<p>During recovery, Cloudflare reported that their debugging systems started consuming high CPU, which slowed other mission-critical services.</p>

<p><strong>Lesson:</strong>
Your troubleshooting tools <strong>must</strong> use minimal resources when the system is stressed.</p>

<h3 id="7-transparency-helps-the-whole-industry-learn"><strong>7. Transparency helps the whole industry learn</strong></h3>

<p>Cloudflare’s detailed post-mortem is a model for engineering culture. Their openness helps engineers worldwide understand real failure modes in large-scale systems.</p>

<p><strong>Lesson:</strong>
Share your failures.
They help others avoid the same mistakes.</p>

<hr />

<h2 id="the-bigger-picture-why-this-incident-matters"><strong>The Bigger Picture: Why This Incident Matters</strong></h2>

<p>Cloudflare’s outage wasn’t just a story about a config file. It was a reminder of how fragile the modern internet can be:</p>

<ul>
  <li>We automate everything</li>
  <li>We trust our pipelines</li>
  <li>We deploy continuously</li>
  <li>We assume schemas won’t change</li>
  <li>We rely on millions of machines making the same decision correctly</li>
</ul>

<p>But when the assumptions underneath those systems break, failures propagate at machine speed.</p>

<p>For engineers, SREs, DevOps teams, and platform architects, this incident underscores a fundamental truth:</p>

<blockquote>
  <p><strong>Your system is only as resilient as your least-validated assumption.</strong></p>
</blockquote>

<h2 id="final-thoughts"><strong>Final Thoughts</strong></h2>

<p>Cloudflare’s outage was a blip in the timeline of the internet, but the lessons are timeless.</p>

<p>Distributed systems will always fail, the question is how gracefully they fail, how quickly they recover, and how deeply the organization learns from the event.</p>

<p>Cloudflare’s transparency, analysis, and remediation steps set a strong example for engineering teams everywhere.</p>
]]></content:encoded>
      <author>billycartel360@gmail.com (Billy Okeyo)</author>
  
      <media:content url="https://billyokeyo.dev/assets/img/cloudflare-outage.jpg" medium="image" />
  
  
    
      <category>Engineering</category>
    
      <category>DevOps</category>
    
      <category>SRE</category>
    
      <category>Cloudflare</category>
    
      <category>Outages</category>
    
      <category>Distributed Systems</category>
    
  
  
    
      <category>Cloudflare</category>
    
      <category>Outages</category>
    
      <category>Distributed Systems</category>
    
      <category>Incident Response</category>
    
      <category>Engineering Best Practices</category>
    
  
    </item>

  </channel>
</rss>