<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Venkatesan Ramar</title>
    <description>The latest articles on DEV Community by Venkatesan Ramar (@morpheus-vera).</description>
    <link>https://dev.to/morpheus-vera</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F3936242%2F5cebb340-ec45-4f77-b185-19f2c7d7a5e8.png</url>
      <title>DEV Community: Venkatesan Ramar</title>
      <link>https://dev.to/morpheus-vera</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/morpheus-vera"/>
    <language>en</language>
    <item>
      <title>Project Reactor Deep Dive: Schedulers, Context Propagation, and Error Handling</title>
      <dc:creator>Venkatesan Ramar</dc:creator>
      <pubDate>Sat, 14 Nov 2026 06:38:53 +0000</pubDate>
      <link>https://dev.to/morpheus-vera/project-reactor-deep-dive-schedulers-context-propagation-and-error-handling-1970</link>
      <guid>https://dev.to/morpheus-vera/project-reactor-deep-dive-schedulers-context-propagation-and-error-handling-1970</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;Reactive programming is not simply about composing asynchronous operations. Understanding execution boundaries, maintaining contextual information, and controlling failure propagation are what make a reactive application predictable and maintainable.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  1. Introduction: Beyond Mono and Flux
&lt;/h2&gt;

&lt;p&gt;Consider a Spring WebFlux payment service. A request arrives, the service loads customer information, calls an external payment gateway, and persists the transaction. The pipeline is a handful of chained operators, and in development it behaves exactly as expected.&lt;/p&gt;

&lt;p&gt;Production is less forgiving. A legacy client quietly blocks an event-loop thread, and throughput collapses under moderate load. A correlation ID that was present in the controller is &lt;code&gt;null&lt;/code&gt; in the log line three operators later. An exception you expected to be handled propagates straight to the client. A retry fires, and the customer is charged twice. When you finally open the stack trace, it points into Reactor internals and says nothing about your code.&lt;/p&gt;

&lt;p&gt;All of these symptoms trace back to three questions that reactive code forces you to answer explicitly:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Where does this work execute?&lt;/strong&gt; (Schedulers)&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;How does request-scoped state travel with the pipeline?&lt;/strong&gt; (Context)&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;What happens when something fails?&lt;/strong&gt; (Error handling, retry, timeout)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Reactor has solid mechanisms for each, but their semantics differ from what imperative Java trained us to expect. This article walks through them using a single running example, a payment processing service built on Java 21, Spring Boot 3.x, and Project Reactor.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. Understanding Reactor's Execution Model
&lt;/h2&gt;

&lt;p&gt;Before schedulers make sense, you need a clear model of how a Reactor pipeline actually runs.&lt;/p&gt;

&lt;p&gt;A &lt;code&gt;Mono&lt;/code&gt; or &lt;code&gt;Flux&lt;/code&gt; is a &lt;strong&gt;Publisher&lt;/strong&gt;. Calling an operator such as &lt;code&gt;map&lt;/code&gt; or &lt;code&gt;doOnNext&lt;/code&gt; does not process data. It wraps the upstream publisher in a new publisher that remembers what it should do. This is &lt;strong&gt;assembly time&lt;/strong&gt;, and it produces nothing but a description of the pipeline. Nothing executes until someone subscribes.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;Mono&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Mono&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;just&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Hello"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;map&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;value&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;value&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="s2"&gt;" Reactor"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;doOnNext&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;out&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nb"&gt;println&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Pipeline assembled"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;subscribe&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The output is &lt;code&gt;Pipeline assembled&lt;/code&gt; followed by &lt;code&gt;Hello Reactor&lt;/code&gt;. The &lt;code&gt;doOnNext&lt;/code&gt; callback ran only after &lt;code&gt;subscribe()&lt;/code&gt;. This laziness is why a pipeline can be built once and subscribed many times, and it is also the root of the retry behavior we'll examine later.&lt;/p&gt;

&lt;p&gt;At &lt;strong&gt;subscription time&lt;/strong&gt;, the flow reverses. The final &lt;code&gt;Subscriber&lt;/code&gt; subscribes to the last operator, which subscribes to the one before it, and so on up to the source. Each hop passes a &lt;code&gt;Subscription&lt;/code&gt; downstream through &lt;code&gt;onSubscribe&lt;/code&gt;. The subscriber then signals &lt;strong&gt;demand&lt;/strong&gt; with &lt;code&gt;request(n)&lt;/code&gt;, and only then does the source emit. Data flows downstream as &lt;code&gt;onNext&lt;/code&gt; signals, and the sequence ends with exactly one terminal signal: &lt;code&gt;onComplete&lt;/code&gt; or &lt;code&gt;onError&lt;/code&gt;. An error is terminal. After &lt;code&gt;onError&lt;/code&gt;, no further elements are emitted, which matters a great deal for how recovery operators behave.&lt;/p&gt;

&lt;p&gt;There are three different threads you might mean when you say "the thread this runs on":&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The thread where &lt;strong&gt;subscription&lt;/strong&gt; happens, which is the thread that calls &lt;code&gt;subscribe()&lt;/code&gt;, or where the subscription request is dispatched.&lt;/li&gt;
&lt;li&gt;The thread where the &lt;strong&gt;source emits&lt;/strong&gt;, which is often, but not always, the same.&lt;/li&gt;
&lt;li&gt;The thread where &lt;strong&gt;each downstream signal is delivered&lt;/strong&gt;, which can change at every scheduler boundary.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;By default Reactor is concurrency-agnostic. If nothing introduces a scheduler, signals are delivered on whichever thread subscribed or produced the data, such as a Netty event-loop thread in WebFlux. &lt;code&gt;subscribeOn&lt;/code&gt; and &lt;code&gt;publishOn&lt;/code&gt; are the operators that change this, and the distinction above is exactly the distinction between them.&lt;/p&gt;

&lt;h2&gt;
  
  
  3. Reactor Schedulers: Controlling Where Work Executes
&lt;/h2&gt;

&lt;h3&gt;
  
  
  3.1 Understanding Reactor Schedulers
&lt;/h3&gt;

&lt;p&gt;A &lt;code&gt;Scheduler&lt;/code&gt; abstracts a unit of execution, much like an &lt;code&gt;ExecutorService&lt;/code&gt;, with Reactor-specific features such as worker semantics and disposal. The built-in factory methods cover most needs:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Scheduler&lt;/th&gt;
&lt;th&gt;Purpose&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;Schedulers.immediate()&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Executes tasks on the current thread, with no switching&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;Schedulers.single()&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;One reusable dedicated thread, sequential execution&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;Schedulers.parallel()&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Fixed pool sized to the CPU core count, for CPU-bound work&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;Schedulers.boundedElastic()&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Bounded, growable pool for blocking or long-running work&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;Schedulers.fromExecutorService(...)&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Wraps an executor you supply&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;The choice follows the nature of the workload. &lt;strong&gt;CPU-bound&lt;/strong&gt; work, such as hashing, serialization, or computation, benefits from a pool sized to the number of cores, because more threads than cores only adds context switching. &lt;strong&gt;I/O-bound or blocking&lt;/strong&gt; work spends most of its time waiting, so it needs enough threads to keep other tasks moving while some are parked. &lt;code&gt;parallel()&lt;/code&gt; has exactly one worker per core, so a handful of blocking calls can occupy all of them and starve unrelated work.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;boundedElastic()&lt;/code&gt; exists for that second category. It creates threads on demand up to a cap (by default ten times the number of CPU cores), queues tasks beyond that, and reclaims idle threads after a time-to-live. The bound is deliberate: an unbounded elastic pool turns a slow dependency into an out-of-memory incident.&lt;/p&gt;

&lt;h3&gt;
  
  
  3.2 subscribeOn vs publishOn
&lt;/h3&gt;

&lt;p&gt;These two operators are the most frequently confused in Reactor, and the confusion usually comes from reading them as "run this operator on that thread".&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;code&gt;subscribeOn&lt;/code&gt;&lt;/strong&gt; controls the thread on which the &lt;em&gt;subscription&lt;/em&gt; is performed, which in practice determines where the source begins to produce its data. Its influence travels upstream:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;Mono&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Mono&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;fromCallable&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Thread&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;currentThread&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getName&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="s2"&gt;"Database result"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;subscribeOn&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Schedulers&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;boundedElastic&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The callable runs on a &lt;code&gt;boundedElastic&lt;/code&gt; thread, because the subscription (and therefore the call to the source) was moved there. Where the &lt;code&gt;subscribeOn&lt;/code&gt; appears in the chain does not matter for the source's execution; its effect is on the upstream side. Note also that some sources emit on threads they control themselves, such as an HTTP client's event loop, so &lt;code&gt;subscribeOn&lt;/code&gt; only affects the part that was actually scheduled by the subscriber.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;code&gt;publishOn&lt;/code&gt;&lt;/strong&gt; changes the thread used for &lt;em&gt;signals delivered downstream&lt;/em&gt; of its position:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;Mono&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;just&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Customer"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;map&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;validate&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;             &lt;span class="c1"&gt;// runs on the original thread&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;publishOn&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Schedulers&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;parallel&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;map&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;transform&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;            &lt;span class="c1"&gt;// runs on a parallel thread&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;subscribe&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;validate&lt;/code&gt; runs wherever the pipeline was subscribed or emitted. &lt;code&gt;transform&lt;/code&gt; runs on a &lt;code&gt;parallel&lt;/code&gt; worker. Because &lt;code&gt;publishOn&lt;/code&gt; introduces a queue and a handoff between threads, each boundary has a real cost, in both latency and memory behavior.&lt;/p&gt;

&lt;h3&gt;
  
  
  3.3 Common Scheduler Misconceptions
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Multiple &lt;code&gt;subscribeOn&lt;/code&gt; operators.&lt;/strong&gt; Only the one closest to the source determines where the source's subscription executes. Later ones are effectively redundant for that purpose, so stacking them does not give you any additional control, and it hints at confusion in the code.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Multiple &lt;code&gt;publishOn&lt;/code&gt; operators.&lt;/strong&gt; Each one is a new boundary. Everything after it runs on its scheduler until the next &lt;code&gt;publishOn&lt;/code&gt;. Sprinkling them throughout a pipeline "just in case" adds scheduling overhead and makes thread behavior harder to reason about.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;code&gt;parallel()&lt;/code&gt; is not for blocking I/O.&lt;/strong&gt; It has a fixed worker count equal to the core count. Blocking there does not just slow that one call, it removes capacity from every pipeline sharing the pool.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;code&gt;boundedElastic()&lt;/code&gt; is not a universal escape hatch.&lt;/strong&gt; It is the right place to isolate unavoidable blocking calls, but if most of your pipeline lands there, you have rebuilt a thread-per-request model with extra steps and lost the benefits of reactive I/O. Treat it as a quarantine zone, not a default.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Scheduler lifecycle.&lt;/strong&gt; The shared schedulers (&lt;code&gt;parallel()&lt;/code&gt;, &lt;code&gt;boundedElastic()&lt;/code&gt;, &lt;code&gt;single()&lt;/code&gt;) are managed for you. If you create your own with &lt;code&gt;Schedulers.newBoundedElastic(...)&lt;/code&gt; or &lt;code&gt;fromExecutorService(...)&lt;/code&gt;, you own its disposal. A leaked scheduler leaks threads.&lt;/p&gt;

&lt;p&gt;On Java 21 there is an interesting option: Reactor 3.6 and later can back &lt;code&gt;boundedElastic()&lt;/code&gt; with virtual threads, enabled by the &lt;code&gt;reactor.schedulers.defaultBoundedElasticOnVirtualThreads&lt;/code&gt; system property. This makes blocking isolation cheaper, but it does not make the blocking call itself any less blocking for the &lt;em&gt;caller's&lt;/em&gt; logical flow, so the architectural reasoning in this section still applies.&lt;/p&gt;

&lt;h3&gt;
  
  
  3.4 Practical Example: Isolating Blocking Dependencies
&lt;/h3&gt;

&lt;p&gt;Our payment service must consult a legacy fraud-check client that exposes only a synchronous API:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;Mono&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;FraudVerdict&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;verdict&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Mono&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;fromCallable&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;
        &lt;span class="n"&gt;legacyFraudClient&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;check&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;customerId&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;amount&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;subscribeOn&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Schedulers&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;boundedElastic&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The blocking call now executes on a &lt;code&gt;boundedElastic&lt;/code&gt; thread. The Netty event-loop thread that received the HTTP request is released immediately and can keep serving other connections. Every other call in the pipeline, such as the &lt;code&gt;WebClient&lt;/code&gt; request to the payment gateway, remains non-blocking and needs no scheduler at all.&lt;/p&gt;

&lt;p&gt;A crucial limitation must be stated plainly: &lt;strong&gt;schedulers control where work executes. They do not make blocking operations non-blocking.&lt;/strong&gt; A JDBC call on &lt;code&gt;boundedElastic&lt;/code&gt; is still a blocking JDBC call that occupies a thread for its duration. You have moved the cost somewhere it can be contained and measured, which is valuable, but you have not removed it. If that dependency is on your critical path at scale, the real fix is a non-blocking driver such as R2DBC or a different integration design.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Engineering takeaway:&lt;/strong&gt; scheduler selection is an architectural decision about isolation and capacity, not merely a performance optimization.&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Subscription flows UP                      Signals flow DOWN
(subscribeOn moves where this starts)      (publishOn moves where this continues)

 subscriber  -&amp;gt;  map  -&amp;gt;  publishOn  -&amp;gt;  map  -&amp;gt;  subscribeOn  -&amp;gt;  source
                           |                          |
                    downstream runs on         source starts on
                    scheduler B                scheduler A
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  4. Context Propagation: Managing State Across Asynchronous Boundaries
&lt;/h2&gt;

&lt;p&gt;In a classic Spring MVC application, one request is handled by one thread from start to finish. That makes &lt;code&gt;ThreadLocal&lt;/code&gt; a natural tool, and we use it constantly: correlation IDs, the &lt;code&gt;SecurityContext&lt;/code&gt;, tenant identifiers, logging MDC, transaction state.&lt;/p&gt;

&lt;p&gt;A reactive pipeline breaks the assumption underneath all of that. One request may begin on a Netty thread, continue on a &lt;code&gt;boundedElastic&lt;/code&gt; worker, and complete back on an event-loop thread, and a different request will interleave on the same threads. A value stored in a &lt;code&gt;ThreadLocal&lt;/code&gt; is attached to a thread, not to a request, so it either vanishes at a thread switch or, worse, leaks into an unrelated request.&lt;/p&gt;

&lt;h3&gt;
  
  
  4.1 Understanding Reactor Context
&lt;/h3&gt;

&lt;p&gt;Reactor's answer is the &lt;code&gt;Context&lt;/code&gt;, an immutable key-value structure associated with the &lt;strong&gt;subscriber&lt;/strong&gt; rather than any thread. It travels up the subscription chain, which means operators can read it regardless of which thread they execute on. Because it is immutable, writing to it creates a new &lt;code&gt;Context&lt;/code&gt;; that is what &lt;code&gt;contextWrite&lt;/code&gt; does.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;Mono&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Mono&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;deferContextual&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;ctx&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="kt"&gt;String&lt;/span&gt; &lt;span class="n"&gt;correlationId&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;ctx&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"correlationId"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nc"&gt;Mono&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;just&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;correlationId&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;contextWrite&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;ctx&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;ctx&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"correlationId"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"req-12345"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Position matters, and it is counterintuitive at first. Because context flows from the subscriber &lt;em&gt;upstream&lt;/em&gt;, a &lt;code&gt;contextWrite&lt;/code&gt; is visible to operators &lt;strong&gt;above&lt;/strong&gt; it in the chain, not below. The reader (&lt;code&gt;deferContextual&lt;/code&gt;) sits upstream of the writer here, so it sees the value. Reversing their order would leave the reader without the key.&lt;/p&gt;

&lt;h3&gt;
  
  
  4.2 Context Propagation Across Thread Switching
&lt;/h3&gt;

&lt;p&gt;The decisive property is that the context is unaffected by scheduler hops:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;Mono&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Mono&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;deferContextual&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;ctx&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;
        &lt;span class="nc"&gt;Mono&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;just&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;ctx&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"correlationId"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;publishOn&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Schedulers&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;parallel&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;map&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="s2"&gt;"Request: "&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;contextWrite&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;ctx&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;ctx&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"correlationId"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"req-12345"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The value read in &lt;code&gt;deferContextual&lt;/code&gt; is the same one that was written, even though downstream operators now run on a different thread. With a &lt;code&gt;ThreadLocal&lt;/code&gt;, the &lt;code&gt;map&lt;/code&gt; after &lt;code&gt;publishOn&lt;/code&gt; would be on a thread that never saw the value.&lt;/p&gt;

&lt;p&gt;In our payment service, the natural place to establish context is a &lt;code&gt;WebFilter&lt;/code&gt; at the edge:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Component&lt;/span&gt;
&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;CorrelationIdFilter&lt;/span&gt; &lt;span class="k"&gt;implements&lt;/span&gt; &lt;span class="nc"&gt;WebFilter&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="nd"&gt;@Override&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;Mono&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;Void&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;filter&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;ServerWebExchange&lt;/span&gt; &lt;span class="n"&gt;exchange&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;WebFilterChain&lt;/span&gt; &lt;span class="n"&gt;chain&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="kt"&gt;String&lt;/span&gt; &lt;span class="n"&gt;correlationId&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Optional&lt;/span&gt;
            &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;ofNullable&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;exchange&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getRequest&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getHeaders&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getFirst&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"X-Correlation-Id"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;orElseGet&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="no"&gt;UUID&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;randomUUID&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;toString&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;chain&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;filter&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;exchange&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;contextWrite&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;ctx&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;ctx&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"correlationId"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;correlationId&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Anything downstream in the same subscription, from the controller to the service to the gateway client, can now read &lt;code&gt;correlationId&lt;/code&gt; with &lt;code&gt;deferContextual&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  4.3 Integrating MDC and Observability
&lt;/h3&gt;

&lt;p&gt;Most of the Java ecosystem still reads from thread-locals: SLF4J's MDC, many tracing libraries, and security APIs. Reactor Context does not feed them automatically. MDC does not follow a thread switch unless something explicitly copies it.&lt;/p&gt;

&lt;p&gt;The modern bridge is the &lt;strong&gt;Micrometer Context Propagation&lt;/strong&gt; library. With &lt;code&gt;io.micrometer:context-propagation&lt;/code&gt; on the classpath, you register &lt;code&gt;ThreadLocalAccessor&lt;/code&gt;s for the thread-locals you care about, and Reactor can capture values into its &lt;code&gt;Context&lt;/code&gt; and restore them into thread-locals around operator execution. This is switched on with &lt;code&gt;Hooks.enableAutomaticContextPropagation()&lt;/code&gt; (available since Reactor 3.5.3), and the &lt;code&gt;contextCapture()&lt;/code&gt; operator marks where thread-local values should be captured into the context. Spring Boot 3.x's observation and tracing support builds on this machinery, which is how trace and span identifiers reach your log lines in a reactive stack.&lt;/p&gt;

&lt;p&gt;Two cautions. First, this restoration is a bridge for imperative libraries, and it carries a runtime cost, so you should not use it as a reason to keep storing request state in thread-locals. Second, be precise about what is configured. "MDC just works in WebFlux" is only true when the accessor registration and hooks are in place; without them it silently does not.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Practical takeaway:&lt;/strong&gt; use Reactor Context as the primary carrier of request-scoped state, and use the context propagation integrations only where you must bridge to thread-local-based libraries.&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;HTTP request
  -&amp;gt; CorrelationIdFilter: contextWrite(correlationId = "req-12345")
       |
       |   (Context travels with the SUBSCRIPTION, not the thread)
       v
  Controller -&amp;gt; Service -&amp;gt; publishOn(parallel) -&amp;gt; WebClient call
       ^              ^                 ^                ^
       reads ctx      reads ctx         different        reads ctx
                                        thread, same
                                        context
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  5. Reactive Error Handling: Understanding Failure Semantics
&lt;/h2&gt;

&lt;p&gt;The foundation is the terminal nature of errors. When a publisher signals &lt;code&gt;onError&lt;/code&gt;, that sequence is over. Error operators therefore do not "continue" the sequence; they &lt;strong&gt;replace&lt;/strong&gt; it, either with a fallback value, a different publisher, or a different error. Once you read the operators this way, their behavior becomes predictable.&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Operator&lt;/th&gt;
&lt;th&gt;Purpose&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;onErrorReturn&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Replace the error with a fallback value&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;onErrorResume&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Switch to an alternative publisher&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;onErrorMap&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Translate one exception into another&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;doOnError&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Observe the error as a side effect, without recovering&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;doFinally&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Run on completion, error, or cancellation&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;onErrorComplete&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Convert an error into a normal completion&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;h3&gt;
  
  
  5.1 Recovering with Fallback Values
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;inventoryClient&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getStock&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;productId&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;onErrorReturn&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is concise and, for some cases, entirely appropriate: a recommendation widget that shows nothing when the recommendation service is down is a perfectly reasonable degradation. The danger is in using it where a failure is &lt;em&gt;information&lt;/em&gt;. A stock count of zero that was really a network failure causes the system to behave as though the item is sold out, and the incident is invisible in the data. Fallbacks to constants should be reserved for cases where a wrong answer is cheap, and ideally the original error should still be logged or counted. You can also narrow what gets swallowed, for instance &lt;code&gt;onErrorReturn(WebClientRequestException.class, 0)&lt;/code&gt;, so that unexpected failures still propagate.&lt;/p&gt;

&lt;h3&gt;
  
  
  5.2 Switching to an Alternative Publisher
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;inventoryClient&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getStock&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;productId&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;onErrorResume&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;error&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;
        &lt;span class="n"&gt;cachedInventory&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getStock&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;productId&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;onErrorResume&lt;/code&gt; is the more expressive tool, because the fallback is itself a publisher and can be asynchronous, such as a cache lookup, a read replica, or a secondary provider. This is where degraded-service strategies live. Two points deserve attention. The fallback can itself fail, and unless it is handled, that failure replaces the original error and obscures it. And a fallback that returns stale data should be explicit about it, for example by marking the response as degraded, rather than pretending nothing happened.&lt;/p&gt;

&lt;h3&gt;
  
  
  5.3 Transforming Exceptions
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;paymentClient&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;process&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;payment&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;onErrorMap&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;error&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;
        &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;PaymentProcessingException&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Payment processing failed"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;error&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;onErrorMap&lt;/code&gt; is exception translation at a service boundary. The gateway client throws transport-level exceptions; your domain layer should not leak those upward, and your API layer should not have to understand them. Wrapping with the cause preserved lets a &lt;code&gt;@ControllerAdvice&lt;/code&gt; map &lt;code&gt;PaymentProcessingException&lt;/code&gt; to a stable HTTP response while the original exception stays available for diagnostics.&lt;/p&gt;

&lt;h3&gt;
  
  
  5.4 Observability Without Recovery
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;paymentClient&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;process&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;payment&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;doOnError&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;error&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;
        &lt;span class="n"&gt;log&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;error&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Payment processing failed"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;error&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;doOnError&lt;/code&gt; is a side-effect operator, nothing more. The error continues downstream unchanged. It is a frequent source of bugs for people who read it as "handle the error": the log line appears, and the request still fails. Use it for logging and metrics, and pair it with an actual recovery operator when recovery is what you want. For cleanup that must run however the pipeline ends, &lt;code&gt;doFinally&lt;/code&gt; receives a &lt;code&gt;SignalType&lt;/code&gt; (&lt;code&gt;ON_COMPLETE&lt;/code&gt;, &lt;code&gt;ON_ERROR&lt;/code&gt;, or &lt;code&gt;CANCEL&lt;/code&gt;), and the cancellation case is one that try/catch in imperative code never had to consider.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;payment gateway call
        |
     onError ----&amp;gt; onErrorMap (translate) ----&amp;gt; retry decision
                                                   |         |
                                              retryable   not retryable
                                                   |         |
                                          resubscribe     onErrorResume
                                                   |       (fallback)
                                                   v         |
                                            terminal outcome: success / failure / degraded
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  6. Retry, Timeout, and Resilience Patterns
&lt;/h2&gt;

&lt;p&gt;Error recovery is about what to do once. Resilience is about what to do when failures are transient and repeated. Both are easy to get dangerously wrong.&lt;/p&gt;

&lt;h3&gt;
  
  
  6.1 Retry Strategies
&lt;/h3&gt;

&lt;p&gt;&lt;code&gt;retry(n)&lt;/code&gt; resubscribes immediately, up to &lt;code&gt;n&lt;/code&gt; times. That is rarely what you want against a struggling dependency, because it adds load at the precise moment the dependency is least able to bear it. &lt;code&gt;retryWhen&lt;/code&gt; with a &lt;code&gt;Retry&lt;/code&gt; spec gives you control:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;paymentClient&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;fetchStatus&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;paymentId&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;retryWhen&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="nc"&gt;Retry&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;backoff&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Duration&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;ofMillis&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;200&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;maxBackoff&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Duration&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;ofSeconds&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;filter&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;isTransientFailure&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This retries at most three times with exponential backoff starting at 200 ms and capped at two seconds. &lt;code&gt;Retry.backoff&lt;/code&gt; applies jitter by default (a factor of 0.5), which spreads retries from many clients over time rather than letting them synchronize. The &lt;code&gt;filter&lt;/code&gt; is what makes this safe: a 503 or a connection reset is worth retrying, while a 400 or a validation failure will fail identically every time. One behavior to know: when retries are exhausted, Reactor by default throws a &lt;code&gt;Retry.RetryExhaustedException&lt;/code&gt; wrapping the last failure. If downstream code expects the original exception, configure &lt;code&gt;onRetryExhaustedThrow&lt;/code&gt; to propagate it.&lt;/p&gt;

&lt;h3&gt;
  
  
  6.2 Timeout Management
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;paymentClient&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;fetchStatus&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;paymentId&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;timeout&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Duration&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;ofSeconds&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If no signal arrives within the window, the pipeline fails with a &lt;code&gt;TimeoutException&lt;/code&gt;. Two details matter in practice.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Placement.&lt;/strong&gt; A &lt;code&gt;timeout&lt;/code&gt; placed &lt;em&gt;before&lt;/em&gt; &lt;code&gt;retryWhen&lt;/code&gt; bounds each attempt. Placed &lt;em&gt;after&lt;/em&gt; it, it bounds the total time across all attempts. These are different guarantees, and you usually want both: a short per-attempt timeout and a longer overall deadline.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;A timeout is not cancellation of remote work.&lt;/strong&gt; When the timeout fires, Reactor cancels the upstream subscription, which with &lt;code&gt;WebClient&lt;/code&gt; closes the connection or abandons the exchange. That stops &lt;em&gt;your side&lt;/em&gt; from waiting. It does not guarantee the remote service has stopped processing, and for a payment request it may well have completed. This is the single most important thing to understand about timeouts on side-effecting calls.&lt;/p&gt;

&lt;h3&gt;
  
  
  6.3 Common Failure Scenarios
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Retry storms.&lt;/strong&gt; If every client in every service retries three times, a dependency under stress receives a multiple of its normal load. Limits, backoff, and jitter are mitigations, and circuit breakers (for example Resilience4j's Reactor integration) are the structural answer.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Retrying non-idempotent operations.&lt;/strong&gt; This is the dangerous one, and it follows directly from the execution model in section 2: &lt;strong&gt;a retry resubscribes to the upstream publisher, and if that publisher performs a side effect, the effect happens again.&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Dangerous: a retry re-executes the charge&lt;/span&gt;
&lt;span class="n"&gt;paymentClient&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;charge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;retryWhen&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Retry&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;backoff&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Duration&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;ofMillis&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;200&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If the first charge succeeded but the response was lost to a timeout, the retry charges the customer a second time. The fix is not in Reactor but in the design: send an &lt;strong&gt;idempotency key&lt;/strong&gt; with the request so the gateway can recognize a duplicate, and keep transaction boundaries clear so a retry does not repeat a partially committed unit of work.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;Mono&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;PaymentResult&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;charge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;PaymentRequest&lt;/span&gt; &lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nc"&gt;Mono&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;deferContextual&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;ctx&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="kt"&gt;String&lt;/span&gt; &lt;span class="n"&gt;idempotencyKey&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;idempotencyKey&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;   &lt;span class="c1"&gt;// stable across retries&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;paymentClient&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;charge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;idempotencyKey&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;timeout&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Duration&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;ofSeconds&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;                          &lt;span class="c1"&gt;// per attempt&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;retryWhen&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Retry&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;backoff&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Duration&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;ofMillis&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;200&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;filter&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;isTransientFailure&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;onErrorMap&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;e&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;PaymentProcessingException&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Payment processing failed"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The key is generated once, outside the retry scope, so every attempt carries the same one.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Fallback failures and cascades.&lt;/strong&gt; A fallback that calls another remote service is another dependency that can fail, and chained fallbacks across microservices can propagate load backward through the call graph. Timeouts at every boundary are what keep a slow dependency from becoming a slow system.&lt;/p&gt;

&lt;h2&gt;
  
  
  7. Debugging and Testing Reactive Pipelines
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Debugging
&lt;/h3&gt;

&lt;p&gt;A reactive stack trace usually shows Reactor internals and the scheduler thread, because the code that &lt;em&gt;assembled&lt;/em&gt; the pipeline is long gone from the call stack when an error occurs. There are several tools to recover that information:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;checkpoint("description")&lt;/code&gt;&lt;/strong&gt; adds a lightweight marker, so when an error flows through it, the trace includes where it passed. It is cheap enough to use at meaningful stages, such as after the gateway call.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;Hooks.onOperatorDebug()&lt;/code&gt;&lt;/strong&gt; captures an assembly-time stack for every operator. It is very informative and very expensive, which makes it suitable for local debugging but not for production.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;ReactorDebugAgent.init()&lt;/code&gt;&lt;/strong&gt; from &lt;code&gt;reactor-tools&lt;/code&gt; provides assembly tracing via bytecode instrumentation without the runtime overhead of the hook, and is the better choice when you need it in a deployed environment.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;BlockHound&lt;/strong&gt; detects blocking calls on non-blocking threads and is excellent in tests and CI for catching the problem from section 1 before production.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Beyond tracing, learn to read thread names: &lt;code&gt;reactor-http-nio-*&lt;/code&gt; means you are on an event-loop thread and must not block, while &lt;code&gt;boundedElastic-*&lt;/code&gt; or &lt;code&gt;parallel-*&lt;/code&gt; tell you which scheduler you are on. Watch for scheduler saturation, which shows up as growing latency and queued tasks on &lt;code&gt;boundedElastic&lt;/code&gt; while CPU stays idle. Distributed tracing connects the picture across services, which is where the context propagation work in section 4 pays off.&lt;/p&gt;

&lt;h3&gt;
  
  
  Testing
&lt;/h3&gt;

&lt;p&gt;&lt;code&gt;StepVerifier&lt;/code&gt; subscribes to a publisher and lets you assert on each signal:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;StepVerifier&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;create&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="nc"&gt;Mono&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;just&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Reactor"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;map&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;toUpperCase&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;expectNext&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"REACTOR"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;verifyComplete&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The same tool covers the harder cases. Error paths use &lt;code&gt;expectError(PaymentProcessingException.class)&lt;/code&gt; or &lt;code&gt;expectErrorSatisfies(...)&lt;/code&gt;. Retry and timeout tests use &lt;code&gt;StepVerifier.withVirtualTime(...)&lt;/code&gt;, which controls a virtual clock so a three-second timeout does not make your test wait three seconds. Context-dependent code can be given an initial context through &lt;code&gt;StepVerifierOptions.create().withInitialContext(...)&lt;/code&gt;. Cancellation can be asserted with &lt;code&gt;thenCancel()&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;For more advanced scenarios, &lt;code&gt;TestPublisher&lt;/code&gt; lets you emit signals manually and simulate misbehaving sources, while &lt;code&gt;PublisherProbe&lt;/code&gt; wraps a fallback publisher so you can assert whether it was subscribed, which is exactly what you need to verify that &lt;code&gt;onErrorResume&lt;/code&gt; actually switched to the cache.&lt;/p&gt;

&lt;h2&gt;
  
  
  8. Common Mistakes and Production Anti-Patterns
&lt;/h2&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Anti-pattern&lt;/th&gt;
&lt;th&gt;Consequence&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Blocking on event-loop threads&lt;/td&gt;
&lt;td&gt;Reduced throughput and request starvation&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Using &lt;code&gt;parallel()&lt;/code&gt; for blocking I/O&lt;/td&gt;
&lt;td&gt;Scheduler starvation across unrelated pipelines&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Treating Context as &lt;code&gt;ThreadLocal&lt;/code&gt;
&lt;/td&gt;
&lt;td&gt;Wrong placement of &lt;code&gt;contextWrite&lt;/code&gt;, missing values&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Unbounded or unfiltered retries&lt;/td&gt;
&lt;td&gt;Retry storms and cascading failures&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Swallowing errors with constant fallbacks&lt;/td&gt;
&lt;td&gt;Hidden operational problems and wrong data&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Excessive &lt;code&gt;publishOn&lt;/code&gt; switching&lt;/td&gt;
&lt;td&gt;Extra scheduling overhead and harder reasoning&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Missing timeout boundaries&lt;/td&gt;
&lt;td&gt;Requests that hang and exhaust resources&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Retrying non-idempotent operations&lt;/td&gt;
&lt;td&gt;Duplicate side effects, such as double charges&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Assuming a timeout stops remote work&lt;/td&gt;
&lt;td&gt;Remote operation completes after the caller gave up&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Most of these share a cause: carrying imperative assumptions into a model where threads, state, and failures behave differently.&lt;/p&gt;

&lt;h2&gt;
  
  
  9. Final Thoughts
&lt;/h2&gt;

&lt;p&gt;Three principles carry most of what matters:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Schedulers control execution boundaries.&lt;/strong&gt; They decide where work runs, they do not make blocking calls non-blocking, and choosing one is an architectural decision about isolation.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Reactor Context preserves subscriber-associated information.&lt;/strong&gt; It follows the subscription, not the thread, and bridging to thread-local libraries should be a deliberate integration rather than an assumption.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Error operators define how failures propagate and recover.&lt;/strong&gt; Errors are terminal signals, recovery replaces the sequence, and retries resubscribe, so every retry is a question about idempotency.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Writing reactive code is relatively easy. Building predictable reactive systems requires understanding where execution happens, how context travels, and what happens when things fail.&lt;/p&gt;




</description>
      <category>java</category>
      <category>spring</category>
      <category>backenddevelopment</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Reactive Spring Applications: Architecture, Trade-offs, and Production Realities</title>
      <dc:creator>Venkatesan Ramar</dc:creator>
      <pubDate>Wed, 21 Oct 2026 02:07:44 +0000</pubDate>
      <link>https://dev.to/morpheus-vera/reactive-spring-applications-architecture-trade-offs-and-production-realities-4pj9</link>
      <guid>https://dev.to/morpheus-vera/reactive-spring-applications-architecture-trade-offs-and-production-realities-4pj9</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;This article covers fundamentals of Spring WebFlux, blocking dependencies, backpressure and resilience.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Imagine a backend service receiving thousands of concurrent requests. Each request performs a small amount of computation but spends most of its lifetime waiting for a database query, a remote API, or another microservice to respond. The service is not necessarily CPU-bound. Its resources are tied up waiting for work to complete.&lt;/p&gt;

&lt;p&gt;A traditional Spring MVC application handles requests using a &lt;em&gt;thread-per-request model&lt;/em&gt;. This is straightforward and works well for many workloads, but concurrency can become expensive when large numbers of threads remain occupied by blocking I/O. Threads consume memory and scheduling resources, and increasing the thread pool indefinitely is not a sustainable way to handle growing concurrency.&lt;/p&gt;

&lt;p&gt;Spring WebFlux approaches this problem differently. Instead of requiring a dedicated application thread to remain occupied while every I/O operation completes, it uses non-blocking I/O and reactive composition to allow execution to progress when results become available.&lt;/p&gt;

&lt;p&gt;That sounds like an obvious improvement, but there is an important distinction: &lt;strong&gt;non-blocking execution can improve resource efficiency without necessarily making an individual request faster&lt;/strong&gt;. A database query still takes as long as the database needs. A remote service still introduces network latency. Reactive programming changes how the application manages waiting, composes asynchronous work, and responds to demand.&lt;/p&gt;

&lt;p&gt;Understanding that distinction is essential to deciding whether reactive Spring is the right architectural choice.&lt;/p&gt;

&lt;h2&gt;
  
  
  1. Why Reactive Spring Exists
&lt;/h2&gt;

&lt;p&gt;The conventional thread-per-request model is attractive because its execution flow closely resembles the business process. A controller calls a service, the service queries a database, and the result is returned to the caller. When a method performs blocking I/O, however, the executing thread waits until that operation completes.&lt;/p&gt;

&lt;p&gt;At modest concurrency, this is rarely a problem. As concurrent requests increase, more threads may spend their time waiting rather than doing useful work. Increasing the thread pool can help up to a point, but it also increases resource consumption and scheduling overhead. The actual bottleneck may eventually move to the database connection pool or a downstream service rather than the application threads themselves.&lt;/p&gt;

&lt;p&gt;Spring WebFlux is designed for workloads where many concurrent operations spend significant time waiting on I/O. Its non-blocking execution model allows a relatively small number of event-loop threads to coordinate a much larger number of in-flight requests, provided the application and its dependencies do not block those threads.&lt;/p&gt;

&lt;p&gt;Reactive programming also introduces Reactive Streams backpressure, which provides a mechanism for consumers to signal how much data they are ready to receive. This becomes useful when producers can generate data faster than downstream consumers can process it.&lt;/p&gt;

&lt;p&gt;Neither capability guarantees lower latency or higher throughput in every application. A CPU-intensive service may benefit little from non-blocking I/O, while a conventional CRUD service using blocking JPA calls may gain complexity without removing its primary bottleneck.&lt;/p&gt;

&lt;p&gt;The architectural question is therefore not whether reactive programming is more modern. It is whether the workload benefits from &lt;strong&gt;non-blocking concurrency, asynchronous composition, or controlled data flow enough to justify the associated complexity&lt;/strong&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. Reactive Foundations: Mono, Flux, and Reactive Streams
&lt;/h2&gt;

&lt;p&gt;Project Reactor, the reactive library commonly used with Spring WebFlux, provides two fundamental publisher types: &lt;code&gt;Mono&lt;/code&gt; and &lt;code&gt;Flux&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;A &lt;code&gt;Mono&amp;lt;T&amp;gt;&lt;/code&gt; represents an asynchronous computation that can produce zero or one value, followed by completion, or terminate with an error. A &lt;code&gt;Flux&amp;lt;T&amp;gt;&lt;/code&gt; represents a sequence that can produce zero to many values, followed by completion or an error. These types describe the shape of the result; they do not, by themselves, guarantee that the underlying work is asynchronous or non-blocking.&lt;/p&gt;

&lt;p&gt;Consider a reactive repository:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;Mono&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Customer&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;customer&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
    &lt;span class="n"&gt;customerRepository&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;findById&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;customerId&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="nc"&gt;Flux&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Order&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;orders&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
    &lt;span class="n"&gt;orderRepository&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;findByCustomerId&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;customerId&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The first publisher represents an optional customer result. The second represents a stream of orders associated with that customer.&lt;/p&gt;

&lt;p&gt;Reactive Streams defines the interaction between publishers, subscribers, and demand. A subscriber can request a certain number of elements, allowing a compliant publisher to regulate how much data it emits. This is the foundation of backpressure, although its effectiveness depends on how the entire pipeline and its external dependencies handle demand.&lt;/p&gt;

&lt;p&gt;Another important characteristic is that Reactor pipelines are generally lazy. Declaring a publisher does not necessarily execute the work it describes. Execution is initiated when something subscribes to the publisher, or when a framework component such as WebFlux subscribes as part of handling an HTTP request.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;Mono&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Customer&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;customer&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
    &lt;span class="n"&gt;customerRepository&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;findById&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;customerId&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;map&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;enrichCustomer&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This declares a pipeline. In a typical WebFlux controller, returning the &lt;code&gt;Mono&lt;/code&gt; allows the framework to manage subscription and response handling. Application code generally should not introduce arbitrary manual subscriptions inside request processing, because doing so can detach work from the request lifecycle and make error propagation and cancellation harder to manage.&lt;/p&gt;

&lt;p&gt;The important point is that &lt;code&gt;Mono&lt;/code&gt; and &lt;code&gt;Flux&lt;/code&gt; are not simply replacements for ordinary Java return types. They represent computations whose execution, completion, failure, and demand are managed through a reactive protocol.&lt;/p&gt;

&lt;h2&gt;
  
  
  3. How Spring WebFlux Executes Requests
&lt;/h2&gt;

&lt;p&gt;WebFlux commonly uses an event-loop-based execution model, particularly with Reactor Netty. A small number of event-loop threads process network activity and advance reactive pipelines as I/O operations complete. When a properly non-blocking operation is waiting for network data, the thread can process other work instead of remaining blocked on that operation.&lt;/p&gt;

&lt;p&gt;A simplified request lifecycle looks like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Incoming HTTP Request
         |
         v
   WebFlux Handler
         |
         v
   Reactive Pipeline
         |
         +---- Non-blocking I/O
         |          |
         |          v
         |    Thread is available
         |    for other work
         |          |
         |          v
         |    I/O completion signal
         |          |
         +----------+
                    |
                    v
             HTTP Response
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The key benefit is not that one thread performs every operation. It is that the application avoids occupying threads while waiting for supported non-blocking I/O.&lt;/p&gt;

&lt;p&gt;This is also why blocking operations are particularly dangerous on event-loop threads. If a handler calls a synchronous database driver or waits on a blocking SDK, the event-loop thread cannot progress other work assigned to it until that call returns. A single blocking dependency can therefore undermine the concurrency model the application was designed to exploit.&lt;/p&gt;

&lt;p&gt;Reactor provides &lt;code&gt;publishOn&lt;/code&gt; and &lt;code&gt;subscribeOn&lt;/code&gt; to influence execution context. &lt;code&gt;publishOn&lt;/code&gt; changes the scheduler used for subsequent downstream operators, while &lt;code&gt;subscribeOn&lt;/code&gt; influences where subscription and upstream execution begin. Their exact effects depend on the pipeline and source.&lt;/p&gt;

&lt;p&gt;Neither operator transforms a blocking API into a non-blocking API. Scheduling a blocking call on an event loop still blocks that event loop. Moving it to a dedicated scheduler can isolate the impact, but the operation remains blocking and still consumes a thread while it waits.&lt;/p&gt;

&lt;p&gt;That distinction should guide design reviews: &lt;strong&gt;thread switching is an execution decision, not a substitute for understanding the blocking behavior of dependencies&lt;/strong&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  4. Building a Reactive Request Flow
&lt;/h2&gt;

&lt;p&gt;Consider an Order Summary API that retrieves an order and then uses the order's customer identifier to retrieve customer details. The second request depends on the first, so the pipeline should express that dependency explicitly.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;Mono&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;OrderSummary&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;getOrderSummary&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;String&lt;/span&gt; &lt;span class="n"&gt;orderId&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;orderClient&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getOrder&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;orderId&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;flatMap&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;order&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;
            &lt;span class="n"&gt;customerClient&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getCustomer&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;order&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;customerId&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
                &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;map&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;customer&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;
                    &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;OrderSummary&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;order&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;customer&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
                &lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;flatMap&lt;/code&gt; operator composes the asynchronous customer lookup after the order response becomes available. The customer request is not started until the order provides the required customer identifier. The resulting &lt;code&gt;Mono&amp;lt;OrderSummary&amp;gt;&lt;/code&gt; represents the complete operation.&lt;/p&gt;

&lt;p&gt;This is more than a different syntax for nested callbacks. The dependency is visible in the pipeline, and failures from either request can propagate through the composed result.&lt;/p&gt;

&lt;p&gt;Now consider a product view that requires inventory and pricing information. If the two calls are independent, they can be composed without waiting for one to finish before starting the other:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;Mono&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;ProductView&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;getProductView&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;String&lt;/span&gt; &lt;span class="n"&gt;productId&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nc"&gt;Mono&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;zip&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="n"&gt;inventoryClient&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getInventory&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;productId&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="n"&gt;pricingClient&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getPrice&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;productId&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;map&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;tuple&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;
        &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;ProductView&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;tuple&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getT1&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;tuple&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getT2&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When the returned publisher is subscribed to, both source publishers can progress independently. The combined result becomes available when both have produced their required values. This can reduce the time spent waiting sequentially, but only when the calls are genuinely independent and the underlying clients support asynchronous execution.&lt;/p&gt;

&lt;p&gt;Reactive composition does not remove the need to define failure behavior. If either call fails, the combined publisher normally fails unless the pipeline explicitly handles that failure. If pricing is optional, for example, the application might choose a fallback value rather than fail the entire response.&lt;/p&gt;

&lt;p&gt;Timeouts and cancellation matter for the same reason. A request that has already exceeded its useful deadline should not continue consuming downstream capacity unnecessarily. At the same time, cancellation of a reactive publisher does not guarantee that every external operation can be forcibly stopped. The client, protocol, and downstream service must support the relevant cancellation semantics.&lt;/p&gt;

&lt;p&gt;The design objective is to make dependencies, concurrency, and failure behavior explicit—not merely to express ordinary business logic with reactive operators.&lt;/p&gt;

&lt;h2&gt;
  
  
  5. The Hidden Complexity: Blocking Dependencies and Data Access
&lt;/h2&gt;

&lt;p&gt;The largest architectural mistake in reactive applications is adopting WebFlux at the HTTP layer while leaving the rest of the application predominantly blocking.&lt;/p&gt;

&lt;p&gt;Consider a service that uses WebFlux controllers but relies on Spring Data JPA and JDBC for persistence. These technologies are built around blocking database access. Wrapping a repository call in a &lt;code&gt;Mono&lt;/code&gt; does not change the behavior of the JDBC driver or turn the database interaction into non-blocking I/O.&lt;/p&gt;

&lt;p&gt;For a genuinely reactive persistence path, Spring Data R2DBC provides database access through Reactive Streams-based APIs and supported reactive drivers. That can allow database operations to participate in a non-blocking pipeline, but it does not automatically guarantee better performance. Database capacity, connection limits, query efficiency, transaction behavior, and downstream contention still determine the practical outcome.&lt;/p&gt;

&lt;p&gt;The same issue arises with third-party SDKs, legacy clients, filesystem operations, and libraries that expose only synchronous APIs. Sometimes replacing these dependencies is not feasible. In that case, blocking work can be isolated on an appropriate scheduler:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;Mono&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Data&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;data&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
    &lt;span class="nc"&gt;Mono&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;fromCallable&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;legacyClient&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;fetchData&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;subscribeOn&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Schedulers&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;boundedElastic&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This schedules the callable on Reactor's bounded-elastic scheduler, which is intended for blocking work. It protects event-loop threads from directly executing the blocking call, but it does not eliminate the cost of waiting or create unlimited capacity. Scheduler saturation, queueing, and downstream limits still need to be considered.&lt;/p&gt;

&lt;p&gt;The escape hatch is useful when blocking work is unavoidable. It is not a strong reason to make an entire application reactive while retaining blocking persistence and most of its existing execution model.&lt;/p&gt;

&lt;p&gt;Connection pools introduce another constraint. Non-blocking execution can support many concurrent in-flight requests, but the database cannot necessarily execute thousands of queries concurrently. If the connection pool has limited capacity, additional requests may queue for connections. Increasing application concurrency without managing database capacity can move the bottleneck rather than remove it.&lt;/p&gt;

&lt;p&gt;This is why Spring MVC can be the more appropriate choice for conventional applications built around blocking JPA/JDBC access. A coherent blocking architecture is often easier to understand and operate than a partially reactive one.&lt;/p&gt;

&lt;h2&gt;
  
  
  6. Backpressure, Errors, and Resilience
&lt;/h2&gt;

&lt;p&gt;Reactive Streams backpressure provides a mechanism for consumers to communicate demand to publishers. This can help control data flow in streaming pipelines, particularly when the producer and consumer can coordinate how many elements are requested and emitted.&lt;/p&gt;

&lt;p&gt;However, backpressure is not an automatic, end-to-end guarantee across every system in an application. A database, HTTP client, message broker, or external API may have its own buffering and flow-control behavior. If a producer cannot slow down, the application must decide whether to buffer, drop, reject, or fail work. Unbounded buffering simply converts a throughput mismatch into a memory problem.&lt;/p&gt;

&lt;p&gt;Resilience also requires deliberate error and timeout policies. Consider a downstream status lookup:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;paymentClient&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;fetchStatus&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;paymentId&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;timeout&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Duration&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;ofSeconds&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;retryWhen&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="nc"&gt;Retry&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;backoff&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Duration&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;ofMillis&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;filter&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;isTransientFailure&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This example applies a two-second timeout and retries selected transient failures with backoff, allowing up to two retries under the configured policy. The exact overall deadline depends on the timeout's placement and the time consumed by retries, so production code should define the intended request deadline explicitly.&lt;/p&gt;

&lt;p&gt;Retries are not inherently safe. If a request triggers a side effect and the client times out before receiving the response, the operation might already have succeeded remotely. Retrying it can duplicate that effect unless the operation is idempotent or protected by an idempotency mechanism. During an outage, aggressive retries can also amplify load on an already struggling dependency.&lt;/p&gt;

&lt;p&gt;Cancellation, circuit breakers, and bulkheads address related concerns. Cancellation can stop unnecessary downstream work when supported. Circuit breakers can prevent repeated calls to a failing dependency, while bulkheads limit how much capacity one dependency or workload can consume.&lt;/p&gt;

&lt;p&gt;Reactive programming provides tools for composing these policies, but it does not choose the correct policies for the business. Those decisions still depend on deadlines, retry safety, downstream capacity, and the consequences of partial failure.&lt;/p&gt;

&lt;h2&gt;
  
  
  7. Reactive Spring vs. Spring MVC with Virtual Threads
&lt;/h2&gt;

&lt;p&gt;Java 21 introduced virtual threads, giving Spring MVC applications another way to handle high concurrency while retaining an imperative programming model. Virtual threads are lightweight threads managed by the JVM, making it practical to support many concurrent blocking tasks without the same platform-thread cost associated with traditional thread-per-request designs.&lt;/p&gt;

&lt;p&gt;This changes the decision between WebFlux and Spring MVC. Reactive programming is no longer the only option worth considering when a service needs to support many concurrent I/O-bound requests.&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Consideration&lt;/th&gt;
&lt;th&gt;Spring WebFlux&lt;/th&gt;
&lt;th&gt;Spring MVC with Virtual Threads&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Programming model&lt;/td&gt;
&lt;td&gt;Reactive composition&lt;/td&gt;
&lt;td&gt;Imperative, blocking-friendly&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Concurrency approach&lt;/td&gt;
&lt;td&gt;Non-blocking I/O&lt;/td&gt;
&lt;td&gt;Lightweight virtual threads&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Backpressure&lt;/td&gt;
&lt;td&gt;Reactive Streams support&lt;/td&gt;
&lt;td&gt;Requires other mechanisms where applicable&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;JDBC/JPA integration&lt;/td&gt;
&lt;td&gt;Blocking calls require careful isolation&lt;/td&gt;
&lt;td&gt;Natural fit for blocking APIs&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Streaming&lt;/td&gt;
&lt;td&gt;Strong fit for reactive streaming&lt;/td&gt;
&lt;td&gt;Depends on API and workload&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Complexity&lt;/td&gt;
&lt;td&gt;Higher learning and debugging cost&lt;/td&gt;
&lt;td&gt;Often simpler for conventional business workflows&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Virtual threads reduce the cost of blocking threads; they do not make blocking I/O non-blocking. Nor do they remove database connection limits, downstream bottlenecks, or the need to manage concurrency. A service can create many virtual threads while still overwhelming a database with too many concurrent queries.&lt;/p&gt;

&lt;p&gt;WebFlux remains attractive when the application benefits from non-blocking clients, streaming, reactive composition, or explicit demand management. Spring MVC with virtual threads can be a better fit when the application is primarily request-response business logic built around blocking libraries and the team values a straightforward imperative flow.&lt;/p&gt;

&lt;p&gt;Neither option is universally superior. The decision should reflect the dependency stack, workload characteristics, operational requirements, and the team's ability to debug and maintain the chosen model.&lt;/p&gt;

&lt;h2&gt;
  
  
  8. Production Observability and Testing
&lt;/h2&gt;

&lt;p&gt;Reactive code that passes unit tests can still fail under contention, slow downstream responses, scheduler saturation, or connection-pool exhaustion. Production validation must therefore cover more than successful responses.&lt;/p&gt;

&lt;p&gt;Track latency, throughput, error rates, timeout rates, and connection-pool saturation. For WebFlux applications, investigate blocked event-loop threads and scheduler saturation. Distributed traces should preserve request context across asynchronous boundaries so that a slow dependency can be identified without reconstructing the entire execution path from logs.&lt;/p&gt;

&lt;p&gt;Reactor's &lt;code&gt;StepVerifier&lt;/code&gt; can test publisher behavior, including emitted values, completion, errors, and time-dependent behavior when configured appropriately. Those tests are useful for validating reactive logic, but they do not replace integration tests against real databases, brokers, and network clients. The integration layer should validate the behavior that unit tests intentionally simulate.&lt;/p&gt;

&lt;p&gt;Load tests are equally important. Benchmark with realistic downstream latency, representative concurrency, meaningful payload sizes, and realistic resource limits. Compare the same workload and infrastructure when evaluating WebFlux against MVC or virtual threads. Synthetic benchmarks that exclude the actual bottleneck can make an architectural choice appear better without demonstrating a production benefit.&lt;/p&gt;

&lt;p&gt;The outcome to measure is not the number of reactive operators or the number of requests a test can generate. It is whether the chosen architecture improves the service's resource efficiency, throughput, latency distribution, or resilience under the workload it actually serves.&lt;/p&gt;

&lt;h2&gt;
  
  
  9. A Practical Decision Framework
&lt;/h2&gt;

&lt;p&gt;Before adopting reactive Spring, ask whether the workload is predominantly I/O-bound, whether its important dependencies support non-blocking access, and whether streaming or backpressure solves a real problem. Evaluate whether the team can operate and debug reactive pipelines effectively, and compare the design with Spring MVC using virtual threads where appropriate. Finally, use representative load tests to demonstrate a measurable improvement before accepting the additional complexity.&lt;/p&gt;

&lt;p&gt;Reactive programming is valuable when its execution model matches the workload and the surrounding infrastructure supports it. It is not a universal performance upgrade, and &lt;code&gt;Mono&lt;/code&gt; and &lt;code&gt;Flux&lt;/code&gt; are not evidence of a scalable architecture by themselves.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Choose reactive programming because the workload benefits from non-blocking composition and flow control—not because &lt;code&gt;Mono&lt;/code&gt; and &lt;code&gt;Flux&lt;/code&gt; look more modern than imperative Java.&lt;/strong&gt;&lt;/p&gt;

</description>
      <category>spring</category>
      <category>backend</category>
      <category>tutorial</category>
      <category>discuss</category>
    </item>
    <item>
      <title>Consistency Boundaries in Distributed Systems: Locks, Outbox and Inbox Patterns</title>
      <dc:creator>Venkatesan Ramar</dc:creator>
      <pubDate>Thu, 24 Sep 2026 08:50:42 +0000</pubDate>
      <link>https://dev.to/morpheus-vera/consistency-boundaries-in-distributed-systems-locks-outbox-and-inbox-patterns-2n4d</link>
      <guid>https://dev.to/morpheus-vera/consistency-boundaries-in-distributed-systems-locks-outbox-and-inbox-patterns-2n4d</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;While covering '&lt;a href="https://dev.to/morpheus-vera/distributed-locking-in-practice-guarantees-failure-scenarios-and-better-alternatives-14-3plb"&gt;Distributed Locking in Practice&lt;/a&gt;', few questions came to mind and that led me to write this article.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;A distributed system can be perfectly correct inside each individual component and still produce an incorrect result across components.&lt;/p&gt;

&lt;p&gt;That is where many reliability problems begin.&lt;/p&gt;

&lt;p&gt;A database transaction can be atomic. A message broker can durably store messages. A consumer can correctly process a message. Yet the overall business operation can still fail because these components do not share the same transaction boundary. The problem is rarely that one component failed to perform its own job. More often, the failure occurs in the gap between two components that operate independently.&lt;/p&gt;

&lt;p&gt;The same principle appears in another form when multiple service instances concurrently modify the same business resource. Each service may execute its own code correctly, but the combined result can still violate a business invariant because there was no mechanism coordinating their access to the shared state.&lt;/p&gt;

&lt;p&gt;This leads to an architectural question that is easy to phrase incorrectly:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Can we say distributed locking ensures consistency and reliability through coordination between relational database systems, while Outbox/Inbox patterns solve reliability between relational databases and asynchronous messaging systems such as RabbitMQ or Kafka?&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The short answer is: &lt;strong&gt;almost, but that distinction is too narrow.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The more useful distinction is not &lt;em&gt;database-to-database&lt;/em&gt; versus &lt;em&gt;database-to-message-broker&lt;/em&gt;. The important question is &lt;strong&gt;which consistency boundary needs protection and what kind of failure can occur across that boundary&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Distributed locking coordinates &lt;strong&gt;concurrent ownership of shared resources&lt;/strong&gt;. The Outbox pattern coordinates the transition from &lt;strong&gt;committed transactional state to asynchronous messaging&lt;/strong&gt;. The Inbox pattern coordinates the transition from &lt;strong&gt;asynchronous message delivery to transactional business processing&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Once we look at the patterns through that lens, their differences—and their intersections—become much clearer.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;1. Start With the Consistency Problem&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Consider a payment service running across several application instances.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;              Payment Service
        ┌──────────┼──────────┐
        │          │          │
        ▼          ▼          ▼
     Instance A Instance B Instance C
        │          │          │
        └──────────┼──────────┘
                   │
                   ▼
              PostgreSQL
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Suppose two instances receive requests that modify the same payment at approximately the same time. Each instance reads the current state and attempts to perform the business operation independently.&lt;/p&gt;

&lt;p&gt;The problem here is &lt;strong&gt;concurrent ownership&lt;/strong&gt;. Multiple actors are attempting to make decisions about the same shared resource without coordinating those decisions.&lt;/p&gt;

&lt;p&gt;A distributed lock can be one way of solving that problem.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Instance A ──┐
             │
             ▼
       Distributed Lock
             │
             ▼
       Shared Resource
             ▲
             │
Instance B ──┘
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The lock introduces an explicit ownership decision. One instance obtains permission to enter the critical section, while other instances must wait, retry, or perform some alternative action.&lt;/p&gt;

&lt;p&gt;The question being answered is:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Who is allowed to perform this operation?&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;However, that guarantee has an important limitation: &lt;strong&gt;a lock coordinates ownership; it does not physically stop a process from continuing to execute.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Suppose &lt;code&gt;Instance A&lt;/code&gt; acquires a lock and then becomes stalled because of a long garbage collection pause, a process suspension, a network problem, or some other failure. If the lock uses a lease, the lease may eventually expire and Instance B may acquire a new lease.&lt;/p&gt;

&lt;p&gt;The dangerous situation is then:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Time ──────────────────────────────────────────────►

Instance A     Acquire Lock
                   │
                   │     Process pauses
                   │          ──────────
                   │                    │
                   │              Lease expires
                   │                    │
Instance B                            Acquire Lock
                                      │
                                      ▼
                                Modify Resource
                   │
                   │
             Instance A resumes
                   │
                   ▼
             Modify Resource
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There are now two processes that believe they can act.&lt;/p&gt;

&lt;p&gt;The lock service may correctly believe that B is the current owner. A, however, may still be executing code from its earlier ownership period. This means that &lt;strong&gt;a lock alone is insufficient when stale owners can still reach the protected resource&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;The usual safeguard is a &lt;strong&gt;fencing token&lt;/strong&gt;: every successful ownership acquisition receives a monotonically increasing token, and the protected resource rejects operations carrying an older token.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Instance A → Lock Service → Token 41
Instance B → Lock Service → Token 42

Resource accepts:
    Token 42

Resource rejects:
    Token 41
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The lock establishes &lt;strong&gt;ownership&lt;/strong&gt;. The fencing token establishes &lt;strong&gt;authority at the resource&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;This distinction is critical because it defines the actual correctness boundary. If correctness depends on preventing stale owners from modifying state, the resource itself must enforce that rule; simply trusting the lock holder to stop executing is not enough.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;2. The Database-to-Broker Problem&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Consider an Order Service that confirms an order.&lt;/p&gt;

&lt;p&gt;The business operation requires two outcomes. The order must be marked as confirmed in the database, and an &lt;code&gt;OrderConfirmed&lt;/code&gt; event must eventually reach downstream services.&lt;/p&gt;

&lt;p&gt;A naive implementation might look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Database Transaction
        │
        ├── Update Order
        │
        └── Commit
                │
                ▼
          Publish Event
                │
                ▼
             RabbitMQ
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;At first glance, this seems reasonable. The order is updated and committed, and then the application publishes the event.&lt;/p&gt;

&lt;p&gt;The problem is that the database transaction and the message publication do not share the same atomic boundary.&lt;/p&gt;

&lt;p&gt;Consider what happens if the application crashes immediately after the database commits.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Update Order
     │
     ▼
Commit Database
     │
     X
 Application crashes
     │
     X
Publish Event
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The database now contains:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Order = CONFIRMED
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But the &lt;code&gt;OrderConfirmed&lt;/code&gt; event was never published.&lt;/p&gt;

&lt;p&gt;Inventory never receives the event.&lt;br&gt;
Payment never receives the event.&lt;br&gt;
Shipping never receives the event.&lt;/p&gt;

&lt;p&gt;The database is internally consistent. The broker is internally consistent. Yet the distributed business workflow is inconsistent because a committed state transition was never propagated to the systems that depend on it.&lt;/p&gt;

&lt;p&gt;This is not a concurrency problem. No two services were competing for ownership of the order.&lt;/p&gt;

&lt;p&gt;It is a &lt;strong&gt;reliable state propagation problem&lt;/strong&gt;.&lt;/p&gt;



&lt;p&gt;&lt;strong&gt;3. This Is Where Outbox Enters&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The Outbox pattern addresses this problem by moving the durable record of the event into the same database transaction as the business state change.&lt;/p&gt;

&lt;p&gt;The architecture becomes:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;                Database Transaction
              ┌──────────────────────┐
              │ Update Order         │
              │                      │
              │ Insert Outbox Event  │
              └──────────────────────┘
                         │
                       Commit
                         │
                         ▼
                  Outbox Publisher
                         │
                         ▼
                      RabbitMQ
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The important change is that the business state and the intention to publish the event are committed together.&lt;/p&gt;

&lt;p&gt;If the application crashes after the transaction commits, the Outbox record remains in the database. A separate publisher can discover the pending event and retry publication later.&lt;/p&gt;

&lt;p&gt;The Outbox pattern therefore gives us a much stronger guarantee:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;If the business transaction commits, the intent to publish the corresponding event is durably recorded.&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Notice what the Outbox does &lt;strong&gt;not&lt;/strong&gt; guarantee.&lt;/p&gt;

&lt;p&gt;It does not magically make PostgreSQL and RabbitMQ one distributed transaction. There can still be a delay between the database commit and the actual message publication. The event may also be published more than once if the publisher crashes at the wrong point.&lt;/p&gt;

&lt;p&gt;What the pattern does is move the critical guarantee into a transactional boundary that the database can actually enforce.&lt;/p&gt;

&lt;p&gt;Instead of trying to atomically coordinate two independent systems, we make the database transaction contain everything that must be committed together.&lt;/p&gt;

&lt;p&gt;That is the architectural insight behind Outbox.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;4. Inbox Solves the Other Side&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The Outbox solves the producer-side problem. The consumer has a different failure scenario.&lt;/p&gt;

&lt;p&gt;Suppose RabbitMQ successfully delivers &lt;code&gt;OrderConfirmed&lt;/code&gt; to the Inventory Service.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;RabbitMQ
    │
    ▼
Inventory Service
    │
    ▼
Update Database
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The Inventory Service processes the message and successfully commits its database transaction.&lt;/p&gt;

&lt;p&gt;But before the consumer acknowledges the message, the application crashes.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;RabbitMQ
    │
    ▼
Consumer
    │
    ▼
Database Commit
    │
    X
Crash before ACK
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;From the broker's perspective, the message was never successfully acknowledged.&lt;/p&gt;

&lt;p&gt;The broker therefore redelivers it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;RabbitMQ
    │
    ├──── OrderConfirmed ────► Consumer
    │
    └──── OrderConfirmed ────► Consumer
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The consumer now has to deal with duplicate delivery.&lt;/p&gt;

&lt;p&gt;Without protection, the Inventory Service might reserve the same inventory twice. This is where the Inbox pattern becomes useful.&lt;/p&gt;

&lt;p&gt;The consumer records the identity of the message as part of its own transactional state.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Message
   │
   ▼
Inbox
   │
   ├── Already processed?
   │       │
   │       ├── Yes → Ignore
   │       │
   │       └── No
   │
   ▼
Business Transaction
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The Inbox therefore gives the consumer durable knowledge of which messages have already been processed.&lt;/p&gt;

&lt;p&gt;The important guarantee is not that the broker will deliver the message exactly once. The broker may still deliver it multiple times.&lt;/p&gt;

&lt;p&gt;Instead, the consumer makes duplicate delivery safe by ensuring that the same message does not produce the same business effect repeatedly.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;5. Three Patterns, Three Questions&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;At this point, the distinction becomes much clearer.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F60f6fzpn5sbqqqsjtn2g.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F60f6fzpn5sbqqqsjtn2g.png" alt=" " width="800" height="533"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Distributed locking, Outbox, and Inbox are all associated with reliability in distributed systems, but they protect different parts of the workflow.&lt;/p&gt;

&lt;p&gt;A distributed lock is concerned with &lt;strong&gt;concurrent ownership&lt;/strong&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Multiple Actors
      │
      ▼
Shared Resource
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The question it answers is:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Who is allowed to act?&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The Outbox pattern is concerned with &lt;strong&gt;state propagation&lt;/strong&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Transactional State
      │
      ▼
Asynchronous Event
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The question it answers is:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;How do I reliably propagate a committed state transition to another system?&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The Inbox pattern is concerned with &lt;strong&gt;event consumption&lt;/strong&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Asynchronous Event
      │
      ▼
Transactional Processing
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The question it answers is:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;How do I safely process an asynchronously delivered event despite duplicate delivery and failures?&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;These are different problems.&lt;/p&gt;

&lt;p&gt;They can occur in the same business workflow, but solving one does not automatically solve the others.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;6. Why "Between Relational Database Systems" Is Too Narrow&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This is the part of the original statement that needs the most correction.&lt;/p&gt;

&lt;p&gt;Distributed locking is not fundamentally about coordinating &lt;strong&gt;relational database systems&lt;/strong&gt;.&lt;br&gt;
It is about coordinating &lt;strong&gt;distributed actors that need controlled access to a shared resource&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;The resource may be stored in a relational database, but that is only one possibility.&lt;/p&gt;

&lt;p&gt;For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Application A ──┐
                │
Application B ──┼── Distributed Lock
                │
Application C ──┘
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The protected resource could be:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;a database record&lt;/li&gt;
&lt;li&gt;an inventory allocation&lt;/li&gt;
&lt;li&gt;a scheduled job&lt;/li&gt;
&lt;li&gt;a shared file&lt;/li&gt;
&lt;li&gt;an external API&lt;/li&gt;
&lt;li&gt;a cache rebuild&lt;/li&gt;
&lt;li&gt;a distributed resource&lt;/li&gt;
&lt;li&gt;a cluster responsibility&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The database might not participate in the locking mechanism at all.&lt;/p&gt;

&lt;p&gt;Imagine three application instances running a scheduled reconciliation job. Only one instance should execute the job at a time.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Instance A ──┐
Instance B ──┼── Scheduler Lock
Instance C ──┘
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There is no need for three databases. There may not even be a database involved in the critical operation. The problem remains one of distributed ownership.&lt;/p&gt;

&lt;p&gt;This is why a more precise definition is:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Distributed locking is a coordination mechanism for controlling concurrent ownership of a shared resource across distributed processes.&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;It can contribute to consistency, but it does not automatically guarantee consistency by itself.&lt;/p&gt;

&lt;p&gt;A lock can tell an application &lt;strong&gt;who currently owns the lease&lt;/strong&gt;. It cannot, by itself, guarantee that an old owner has stopped executing, that the network is healthy, or that the protected resource will reject stale operations.&lt;/p&gt;

&lt;p&gt;That is why production-grade designs need to consider the failure model of the lock itself.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;7. Distributed Locking Can Still Protect Database Consistency&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Although distributed locking is not specifically a database-to-database coordination mechanism, it can certainly be used to protect database consistency.&lt;/p&gt;

&lt;p&gt;Consider inventory.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Inventory = 1

Instance A ──► Reserve
Instance B ──► Reserve
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If both instances read the same inventory state and independently perform the reservation, the system can produce an invalid result.&lt;/p&gt;

&lt;p&gt;A distributed lock can serialize the critical section.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Instance A
     │
     ▼
Acquire Lock
     │
     ▼
Read Inventory
     │
     ▼
Reserve
     │
     ▼
Release Lock
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Instance B waits until ownership becomes available. The lock therefore contributes to consistency by controlling concurrent access.&lt;/p&gt;

&lt;p&gt;But there are several safeguards to consider.&lt;/p&gt;

&lt;p&gt;First, the lock should normally have &lt;strong&gt;bounded ownership&lt;/strong&gt; rather than remaining held forever. A lease or timeout prevents a crashed process from holding ownership indefinitely.&lt;/p&gt;

&lt;p&gt;Second, lease expiry must not be interpreted as proof that the previous process has stopped. A paused or partitioned process may resume after its lease has expired.&lt;/p&gt;

&lt;p&gt;Third, if stale execution can corrupt the resource, the design should use &lt;strong&gt;fencing tokens&lt;/strong&gt; or an equivalent resource-side mechanism so that an older owner cannot successfully perform operations after a newer owner has taken over.&lt;/p&gt;

&lt;p&gt;Fourth, the critical operation should be designed so that failure during lock acquisition, renewal, or release does not silently violate the business invariant. Releasing a lock is not a substitute for committing correct business state, and failing to acquire a lock should normally result in a controlled retry or rejection rather than proceeding without coordination.&lt;/p&gt;

&lt;p&gt;These safeguards can be summarized as:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;                 Distributed Lock
                        │
              ┌─────────┴─────────┐
              │                   │
           Lease             Ownership Token
              │                   │
              ▼                   ▼
       Bounded ownership     Fencing / Validation
                                  │
                                  ▼
                         Protected Resource
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The database itself may provide a simpler alternative.&lt;/p&gt;

&lt;p&gt;For example, optimistic concurrency can detect conflicting inventory updates:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;UPDATE inventory 
  SET quantity = quantity - 1, 
      version = version + 1
  WHERE product_id = ?
    AND version = ?
    AND quantity &amp;gt; 0;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The database detects conflicting updates, and the application retries when necessary.&lt;/p&gt;

&lt;p&gt;Depending on the workload, optimistic concurrency may be simpler and more scalable than introducing a distributed coordination service.&lt;/p&gt;

&lt;p&gt;The architectural lesson is important:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;A distributed lock is one mechanism for preserving consistency when correctness depends on exclusive or coordinated ownership.&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;It is not a universal consistency mechanism, and a lock should not be introduced when a simpler invariant-enforcement mechanism already exists.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;8. Outbox Is About a Different Consistency Boundary&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Return to the Order Service.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;       Order Service
            │
      ┌─────┴─────┐
      │           │
      ▼           ▼
   Database     RabbitMQ
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The database and RabbitMQ have different transactional semantics.&lt;/p&gt;

&lt;p&gt;The database transaction can atomically modify relational state.&lt;br&gt;
The broker can durably accept a message.&lt;/p&gt;

&lt;p&gt;But there is no single local transaction that automatically encompasses both operations. That creates a consistency boundary.&lt;/p&gt;

&lt;p&gt;The Outbox pattern explicitly manages that boundary.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Database Transaction
        │
        ├── Business State
        │
        └── Outbox Event
                │
              Commit
                │
                ▼
        Asynchronous Publish
                │
                ▼
             Broker
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The pattern effectively says:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;I cannot make these two systems participate in one atomic local transaction, so I will make the database the durable source of truth for the publication intent.&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The publisher can then retry until the event reaches the broker. This is fundamentally different from distributed locking. &lt;/p&gt;

&lt;p&gt;The Outbox does not decide who is allowed to modify a resource. It ensures that a state transition that has already been committed is not silently lost when it needs to become an asynchronous event.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;9. Inbox Protects the Consumer Boundary&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The consumer faces the inverse problem.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;      RabbitMQ / Kafka
              │
              ▼
        Consumer Service
              │
              ▼
           Database
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The message broker owns delivery.&lt;br&gt;
The consumer owns business processing. &lt;/p&gt;

&lt;p&gt;Both can fail independently.&lt;/p&gt;

&lt;p&gt;The message can be delivered successfully.&lt;br&gt;
The database transaction can commit successfully.&lt;br&gt;
The consumer can then crash before acknowledging the message.&lt;br&gt;
The broker may redeliver it.&lt;/p&gt;

&lt;p&gt;The Inbox pattern gives the consumer a durable mechanism for recognizing that the message has already been processed.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Message ID
    │
    ▼
Inbox Record
    │
    ▼
Business Update
    │
    ▼
Commit
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The message receipt and business processing can be incorporated into the consumer's transactional boundary.&lt;/p&gt;

&lt;p&gt;Again, the pattern does not turn Kafka or RabbitMQ into a relational database. It does not eliminate duplicate delivery at the broker level. It manages the boundary between asynchronous delivery and transactional business processing.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;10. Where the Patterns Intersect&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Real systems frequently use all three patterns in the same business workflow.&lt;/p&gt;

&lt;p&gt;Consider an order processing system.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;              Order Service
                   │
             DB Transaction
              │          │
              │          └── Outbox
              │
              ▼
             Order
                   │
                   ▼
              Message Broker
                   │
                   ▼
          Inventory Service
                   │
                 Inbox
                   │
                   ▼
          Inventory Database
                   │
             Distributed
                Lock
                   │
                   ▼
          Reserve Inventory
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Each pattern has a different responsibility.&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;Outbox&lt;/strong&gt; makes the Order → Event transition reliable. If the order transaction commits, the event publication intent is durably stored.&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;Inbox&lt;/strong&gt; makes the Event → Inventory processing resilient to duplicate delivery. If the broker delivers the event more than once, the consumer can recognize the duplicate.&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;Distributed Lock&lt;/strong&gt; coordinates concurrent access to inventory if the business requirement genuinely requires exclusive ownership.&lt;/p&gt;

&lt;p&gt;The last point contains an important qualification: &lt;strong&gt;the lock is necessary only if the inventory invariant actually requires serialized ownership and cannot be enforced more simply at the resource itself.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The patterns therefore complement one another.&lt;/p&gt;

&lt;p&gt;Removing the &lt;strong&gt;Outbox&lt;/strong&gt; can reintroduce the database-to-broker &lt;strong&gt;dual-write problem&lt;/strong&gt;.&lt;br&gt;
Removing the &lt;strong&gt;Inbox&lt;/strong&gt; can reintroduce &lt;strong&gt;duplicate-processing problems&lt;/strong&gt;.&lt;br&gt;
Removing the &lt;strong&gt;lock&lt;/strong&gt; may reintroduce &lt;strong&gt;concurrent ownership problems&lt;/strong&gt; if the underlying business operation cannot tolerate them.&lt;/p&gt;

&lt;p&gt;The patterns intersect because the same business workflow crosses multiple consistency boundaries.&lt;/p&gt;

&lt;p&gt;They do not overlap because they solve the same problem.&lt;/p&gt;



&lt;p&gt;&lt;strong&gt;11. A More Precise Architectural Model&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A useful way to reason about these patterns is to identify the consistency boundary being crossed or protected.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;┌──────────────────────────────────────────────────────────────┐
│                     Distributed System                       │
│                                                              │
│   Concurrent Ownership                                       │
│          │                                                   │
│          ▼                                                   │
│   ┌───────────────┐                                          │
│   │ Distributed   │                                          │
│   │     Lock      │                                          │
│   └───────────────┘                                          │
│          │                                                   │
│          │  Lease + Fencing when stale owners are possible  │
│          ▼                                                   │
│   Protected Resource                                         │
│                                                              │
│   Transactional State                                        │
│          │                                                   │
│          ▼                                                   │
│   ┌───────────────┐                                          │
│   │    Outbox     │                                          │
│   └───────────────┘                                          │
│          │                                                   │
│          ▼                                                   │
│   Asynchronous Messaging                                     │
│          │                                                   │
│          ▼                                                   │
│   ┌───────────────┐                                          │
│   │    Inbox      │                                          │
│   └───────────────┘                                          │
│          │                                                   │
│          ▼                                                   │
│   Consumer Transaction                                       │
│                                                              │
└──────────────────────────────────────────────────────────────┘
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The important addition here is that a distributed lock may need &lt;strong&gt;additional safeguards at the protected resource&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;The lock service answers the ownership question, but correctness may depend on the resource validating that ownership.&lt;/p&gt;

&lt;p&gt;This is especially important in systems where a process can pause, become partitioned, or continue executing after its lease has expired.&lt;/p&gt;

&lt;p&gt;The resulting model is:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Lock
 │
 ├── Lease ─────────────► Bound ownership duration
 │
 └── Fencing Token ────► Prevent stale ownership
                              │
                              ▼
                       Resource Validation
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is a stronger architectural model than treating "lock acquired" as equivalent to "this process is guaranteed to be the only process that can ever act."&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;12. The Three Failure Models&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Another way to distinguish the patterns is to examine the failure each one is designed to address.&lt;/p&gt;

&lt;p&gt;With distributed locking, the central problem is concurrent access.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Two Instances
      │
      ▼
Concurrent Access
      │
      ▼
Incorrect Shared State
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But distributed locking introduces its own failure modes. A process can fail while holding the lock, a lease can expire while the process is still executing, or network uncertainty can cause different participants to have different views of ownership.&lt;/p&gt;

&lt;p&gt;Therefore, when stale execution matters, the protection cannot end at the lock service.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Lock Service
     │
     ▼
Ownership Granted
     │
     ▼
Protected Resource
     │
     ▼
Validate Current Authority
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is where leases, fencing tokens, and resource-side validation become safeguards rather than optional implementation details.&lt;/p&gt;

&lt;p&gt;With Outbox, the central problem is a failure between committing business state and publishing the corresponding event.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Database Commit
      │
      X
Application Crash
      │
      X
Event Not Published
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The system needs a durable representation of the publication intent.&lt;/p&gt;

&lt;p&gt;With Inbox, the central problem is a failure between processing a message and acknowledging its successful consumption.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Message Delivered
      │
      ▼
Business Transaction
      │
      X
Crash Before ACK
      │
      ▼
Message Redelivered
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The system needs a durable record that allows the consumer to recognize duplicate delivery. These failure models are fundamentally different.&lt;/p&gt;

&lt;p&gt;That is why the patterns should not be treated as interchangeable reliability mechanisms.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;13. The More Important Architectural Question&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This leads to a better question than:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;"Should I use Distributed Locking or Outbox/Inbox?"&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Instead, ask:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;"Where is my consistency boundary, and what can fail independently on either side of it?"&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ul&gt;
&lt;li&gt;If multiple actors can concurrently modify the same resource, you have an &lt;strong&gt;ownership and coordination problem&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;If a database transaction must reliably result in an asynchronous event, you have a &lt;strong&gt;publication problem&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;If an asynchronous event must safely affect transactional state despite retries and duplicate delivery, you have a &lt;strong&gt;processing problem&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For ownership problems, there is a second question:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;"What prevents a stale owner from modifying the resource after its ownership has expired?"&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;If the answer is simply "the process should stop," the design may not be strong enough for a correctness-critical operation.&lt;/p&gt;

&lt;p&gt;A stronger design uses a lease to bound ownership and, where necessary, a fencing mechanism that the protected resource itself can enforce.&lt;/p&gt;

&lt;p&gt;Those problems can exist within the same business workflow.&lt;/p&gt;

&lt;p&gt;For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Order Transaction
       │
       ▼
     Outbox
       │
       ▼
   Message Broker
       │
       ▼
     Inbox
       │
       ▼
Inventory Processing
       │
       ▼
Distributed Coordination
       │
       ▼
Resource-side Validation
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There is no contradiction in using all three.&lt;/p&gt;

&lt;p&gt;Each one protects a different boundary.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;14. The Refined Statement&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;So, can we say:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;"Distributed locking ensures consistency and reliability through coordination between relational database systems, whereas Outbox/Inbox solves reliability between relational databases and asynchronous messaging systems such as RabbitMQ/Kafka"?&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;It is directionally correct, but the terminology should be refined.&lt;/p&gt;

&lt;p&gt;A more precise statement is:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Distributed locking coordinates concurrent ownership of shared resources across distributed processes, while the Outbox and Inbox patterns provide reliable state propagation between transactional application state and asynchronous messaging systems.&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;An even more architectural formulation is:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Distributed locking protects consistency within a shared ownership boundary. Outbox protects the transition from committed transactional state to asynchronous messaging. Inbox protects the transition from asynchronous message delivery to transactional processing.&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;There is one further qualification worth keeping in mind:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;A distributed lock provides an ownership mechanism, not an unconditional correctness guarantee. When lease expiry or stale execution is possible, correctness-critical resources may require fencing or equivalent resource-side validation.&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This formulation is stronger because it does not tie the concepts to specific technologies.&lt;/p&gt;

&lt;p&gt;The database behind an Outbox could be PostgreSQL, MySQL, or another transactional datastore.&lt;/p&gt;

&lt;p&gt;The messaging infrastructure could be Kafka, RabbitMQ, or another asynchronous broker.&lt;/p&gt;

&lt;p&gt;Likewise, distributed locking could coordinate access to a database, a file, an external system, a scheduler, or another shared resource.&lt;/p&gt;

&lt;p&gt;The underlying architectural problem remains the same regardless of the technology.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;15. The Bigger Lesson&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Distributed systems rarely fail because one component cannot perform its own job.&lt;/p&gt;

&lt;p&gt;The database can commit.&lt;br&gt;
The broker can durably store messages.&lt;br&gt;
The consumer can process events.&lt;/p&gt;

&lt;p&gt;The difficult failures appear &lt;strong&gt;between them&lt;/strong&gt;. The same principle applies to distributed ownership.&lt;/p&gt;

&lt;p&gt;A lock service can correctly grant ownership, yet the owner may subsequently pause, lose connectivity, or continue executing after its lease expires.&lt;/p&gt;

&lt;p&gt;That is why a correctness-critical design must distinguish &lt;strong&gt;ownership&lt;/strong&gt; from &lt;strong&gt;authority&lt;/strong&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;        Ownership
            │
            ▼
      Distributed Lock
            │
            ▼
     Lease / Token
            │
            ▼
   Resource-side Validation
            │
            ▼
       Safe Operation
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For messaging, the corresponding boundaries look different:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Transactional State
        │
        ▼
      Outbox
        │
        ▼
Asynchronous Message
        │
        ▼
      Inbox
        │
        ▼
Transactional State
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Distributed locking, Outbox, and Inbox are therefore not three competing reliability patterns.&lt;/p&gt;

&lt;p&gt;They are mechanisms for three different classes of consistency boundary.&lt;/p&gt;

&lt;p&gt;They answer three different questions:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Who is allowed to act?&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;How does committed state reliably become an event?&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;How does an event safely become committed state?&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;And for lock-based designs, there is an additional correctness question:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;What prevents an old owner from acting after it is no longer authorized?&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Once those questions are separated, choosing the appropriate pattern becomes considerably easier.&lt;/p&gt;

&lt;p&gt;The important architectural habit is therefore not memorizing which pattern goes with which technology. It is identifying &lt;strong&gt;the consistency boundary, the failure mode associated with that boundary, the guarantee actually required, and the simplest mechanism capable of preserving the business invariant&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;That is ultimately what good distributed-system design is about: &lt;em&gt;not eliminating failures, but ensuring that failures at one boundary do not silently violate the guarantees expected at another&lt;/em&gt;.&lt;/p&gt;

</description>
      <category>distributedsystems</category>
      <category>microservices</category>
      <category>tutorial</category>
      <category>discuss</category>
    </item>
    <item>
      <title>Distributed Locking in Practice: Guarantees, Failure Scenarios and Better Alternatives (4/4)</title>
      <dc:creator>Venkatesan Ramar</dc:creator>
      <pubDate>Wed, 19 Aug 2026 08:05:19 +0000</pubDate>
      <link>https://dev.to/morpheus-vera/distributed-locking-in-practice-guarantees-failure-scenarios-and-better-alternatives-44-2am1</link>
      <guid>https://dev.to/morpheus-vera/distributed-locking-in-practice-guarantees-failure-scenarios-and-better-alternatives-44-2am1</guid>
      <description>&lt;p&gt;&lt;strong&gt;22. The Best Distributed Lock Is Often No Lock at All&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;By now, we've explored distributed locks, leases, fencing tokens, leader election, and consensus.&lt;/p&gt;

&lt;p&gt;Each of these mechanisms exists to solve a specific coordination problem in distributed systems, where multiple machines must agree on who is allowed to do what and when.&lt;/p&gt;

&lt;p&gt;A natural conclusion from studying all of them might be that building reliable distributed systems requires increasingly sophisticated coordination mechanisms.&lt;/p&gt;

&lt;p&gt;However, in practice, experienced engineers often arrive at the opposite conclusion after working with these systems at scale. Before introducing any form of distributed coordination, they tend to step back and ask a more fundamental question:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Can we re-design the system so that coordination isn't necessary in the first place?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This question is important because every coordination mechanism introduces real cost into the system.&lt;/p&gt;

&lt;p&gt;It adds additional network communication between services. It increases the number of failure scenarios that must be handled correctly. It introduces operational complexity that must be monitored, debugged, and maintained. It often increases latency, since coordination typically requires waiting for agreement or confirmation.&lt;/p&gt;

&lt;p&gt;Because of these costs, the most reliable distributed systems are not necessarily the ones with the strongest or most complex coordination mechanisms.&lt;/p&gt;

&lt;p&gt;Instead, they are often the systems that minimize coordination as much as possible while still preserving correctness.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;23. Let the Database Protect Its Own Data&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Suppose an application allows users to register with an email address.&lt;/p&gt;

&lt;p&gt;A straightforward but naive approach might introduce a distributed lock to prevent duplicate registrations. The flow would look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Acquire Distributed Lock
        |
        v
Check Email Exists
        |
        v
Insert Customer
        |
        v
Release Lock
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this design, the distributed lock ensures that two application instances do not attempt to create the same customer at the same time.&lt;/p&gt;

&lt;p&gt;While this approach works in principle, it is often unnecessary in practice. Relational databases already provide strong guarantees about data integrity, including uniqueness constraints. Instead of coordinating at the application level, we can express the business rule directly in the database schema.&lt;/p&gt;

&lt;p&gt;A unique constraint makes the intent explicit and enforces it reliably:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt; &lt;span class="k"&gt;UNIQUE&lt;/span&gt; &lt;span class="k"&gt;INDEX&lt;/span&gt; &lt;span class="n"&gt;uk_customer_email&lt;/span&gt;
&lt;span class="k"&gt;ON&lt;/span&gt; &lt;span class="n"&gt;customer&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;email&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With this constraint in place, every application instance can simply attempt the insert operation without any external coordination.&lt;/p&gt;

&lt;p&gt;The flow becomes much simpler:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Insert Customer
        |
        |
Unique Constraint
        |
  Success/Reject
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There is no distributed lock.&lt;br&gt;
There is no coordination service.&lt;br&gt;
There is no lease management.&lt;/p&gt;

&lt;p&gt;The database already owns the data, and therefore it is the most appropriate place to enforce rules about that data.&lt;/p&gt;

&lt;p&gt;Whenever correctness depends entirely on the state of a single database, delegating enforcement to the database itself is usually the simplest and most reliable solution.&lt;/p&gt;



&lt;p&gt;&lt;strong&gt;24. Optimistic Concurrency Instead of Ownership&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Some coordination problems arise because multiple application instances attempt to modify the same record at the same time.&lt;/p&gt;

&lt;p&gt;At first glance, this seems to require a distributed lock to ensure exclusive access.&lt;/p&gt;

&lt;p&gt;However, that assumption is not always correct.&lt;/p&gt;

&lt;p&gt;Consider an inventory record:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Product
--------
Quantity = 25
Version = 8
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now imagine two application instances reading and updating this record concurrently.&lt;/p&gt;

&lt;p&gt;Both instances start from the same version:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Application A

Version 8
-------------------

Application B

Version 8
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Application A performs an update first, and the database successfully applies the change:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Version = 9&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;When Application B attempts to apply its update, it is still working with the outdated version 8. The database detects this mismatch and rejects the update.&lt;/p&gt;

&lt;p&gt;At this point, the application can retry the operation using the latest state from the database.&lt;/p&gt;

&lt;p&gt;No distributed lock was required at any point in this process.&lt;br&gt;
No application had to wait for exclusive ownership of the record.&lt;/p&gt;

&lt;p&gt;Instead of preventing concurrent work, optimistic concurrency allows concurrent operations to proceed and resolves conflicts only when they actually occur. This approach is particularly effective when conflicts are relatively rare.&lt;/p&gt;

&lt;p&gt;It provides high throughput because operations are not blocked unnecessarily. It minimizes coordination overhead between services. It also offers a simple recovery model, where failed updates are retried with fresh state.&lt;/p&gt;

&lt;p&gt;This combination of properties is why &lt;em&gt;optimistic concurrency&lt;/em&gt; is widely used in modern backend systems.&lt;/p&gt;



&lt;p&gt;&lt;strong&gt;25. Idempotency Eliminates Many Locking Problems&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Consider a scenario where a payment request is received more than once.&lt;/p&gt;

&lt;p&gt;This can happen for many reasons in distributed systems.&lt;/p&gt;

&lt;p&gt;A client might retry after a timeout, even though the first request already succeeded.&lt;/p&gt;

&lt;p&gt;A message broker might deliver the same event more than once.&lt;br&gt;
A network failure might occur after the operation completes but before the response is acknowledged.&lt;/p&gt;

&lt;p&gt;One possible solution is to use a distributed lock to ensure the payment is only processed once:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Acquire Lock
      |
Charge Customer
      |
Release Lock
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;However, there is another approach that avoids coordination entirely by changing the nature of the operation itself.&lt;/p&gt;

&lt;p&gt;In this design, every request includes an idempotency key that uniquely identifies the operation:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Payment Request

Idempotency Key
PAY-48291
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Before processing the payment, the system checks whether this key has already been used.&lt;/p&gt;

&lt;p&gt;The flow becomes:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Receive Request
       |
Already Processed?
       |
   +---+---+
   |       |
 Yes       No
  |         |
Return     Process
Result     Payment
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If the request has already been processed, the system simply returns the previous result. If not, it proceeds with the payment and records the key. This makes &lt;em&gt;duplicate requests safe by design&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Instead of coordinating ownership between multiple application instances, the system ensures that repeating the same operation does not change the outcome.&lt;/p&gt;

&lt;p&gt;This approach is often more robust than distributed locking because retries are not edge cases in distributed systems—they are expected behavior.&lt;/p&gt;

&lt;p&gt;Reliable systems are designed with retries in mind. They do not merely try to prevent them; they make them safe.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;26. Partition Ownership Instead of Global Coordination&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Consider a payment platform that processes millions of transactions every day.&lt;/p&gt;

&lt;p&gt;If every payment required a distributed lock, the system would quickly become a bottleneck due to the overhead of coordination.&lt;/p&gt;

&lt;p&gt;A more scalable approach is to partition the work.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Payments A-H
      |
      v
Consumer A
-------------------

Payments I-P
      |
      v
Consumer B
-------------------

Payments Q-Z
      |
      v
Consumer C
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this model, each consumer is responsible for a specific subset of the workload. Each partition has a clear owner, and that ownership is determined by the partitioning strategy rather than dynamic locking.&lt;/p&gt;

&lt;p&gt;As a result, applications no longer compete for individual operations. Instead, they operate independently within their assigned partitions. This pattern is commonly used in message brokers and stream processing systems.&lt;/p&gt;

&lt;p&gt;Rather than coordinating every single operation globally, the system only coordinates partition ownership. This significantly reduces synchronization overhead and improves scalability.&lt;/p&gt;

&lt;p&gt;Partitioning is one of the most effective techniques for reducing the need for distributed coordination in large systems.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;27. Sharding Reduces Shared Ownership&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A similar idea applies to data storage systems.&lt;/p&gt;

&lt;p&gt;Instead of storing all data in a single shared database, the data can be divided into shards.&lt;/p&gt;

&lt;p&gt;For example, customer data might be partitioned alphabetically:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Customers A-M
       |
       v
Database A
-------------------

Customers N-Z
       |
       v
Database B
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Each shard is responsible for a subset of the data and operates independently.&lt;/p&gt;

&lt;p&gt;Most requests only interact with a single shard, which means there is no need for global coordination across the entire dataset. Applications only need to coordinate within the boundaries of a single shard, not across all shards.&lt;/p&gt;

&lt;p&gt;By reducing the amount of shared ownership, sharding naturally reduces the need for distributed locking and other global coordination mechanisms.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;28. Sometimes Coordination Isn't Necessary&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Not all distributed problems require strict exclusivity or ownership. In some cases, concurrent operations can safely proceed without coordination at all.&lt;/p&gt;

&lt;p&gt;For example, consider a distributed counter that is updated by multiple application instances.&lt;/p&gt;

&lt;p&gt;Instead of preventing concurrent updates, the system can use a data structure designed to merge updates safely. In this model, multiple instances can update the counter at the same time without conflict.&lt;/p&gt;

&lt;p&gt;The applications are not competing for control; they are contributing to a shared result. Some distributed data structures are specifically designed to support this kind of behavior.&lt;/p&gt;

&lt;p&gt;Their goal is not to prevent concurrent updates, but to ensure that all updates eventually converge to a consistent final state. While the details of these structures are beyond the scope of this discussion, they highlight an important principle in distributed system design.&lt;/p&gt;

&lt;p&gt;Coordination should only be introduced when it is truly required for correctness.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;29. Choosing the Simplest Correct Solution&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;As distributed systems grow in complexity, a clear pattern emerges.&lt;/p&gt;

&lt;p&gt;Different problems require different coordination strategies, and not all of them require distributed locking.&lt;/p&gt;

&lt;p&gt;Using a distributed lock simply because multiple machines are involved often leads to unnecessary complexity and reduced scalability.&lt;/p&gt;

&lt;p&gt;A better approach is to choose the simplest mechanism that still guarantees correctness.&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Engineering Problem&lt;/th&gt;
&lt;th&gt;Recommended Approach&lt;/th&gt;
&lt;th&gt;Why It's a Better Choice&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Prevent duplicate customer registration&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;Database Unique Constraint&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;The database is the source of truth and can enforce uniqueness atomically without external coordination.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Concurrent updates to the same record&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;Optimistic Locking&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Detects write conflicts efficiently while allowing high concurrency and minimal coordination.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Duplicate payment or API requests&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;Idempotency&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Makes retries safe by ensuring repeated requests produce the same outcome.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;One instance should execute scheduled jobs&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;Leader Election&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Elects a single coordinator while allowing automatic failover if the leader becomes unavailable.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Exclusive access to a shared resource&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;Lease + Fencing Tokens&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Provides temporary ownership and prevents stale owners from modifying shared state after lease expiration.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Maintain consistent cluster configuration or metadata&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;Consensus&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Ensures all healthy nodes agree on a single, consistent view of shared state despite failures.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Process high-volume event streams or queues&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;Partition Ownership&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Assigns exclusive ownership of partitions to consumers, eliminating the need for global locking.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Distribute ownership of large datasets&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;Sharding&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Reduces shared ownership by partitioning data, minimizing the need for cross-node coordination.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Merge concurrent updates safely without coordination&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;Conflict-Free Data Structures (CRDTs)&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Allows concurrent updates to converge automatically, avoiding locks for specific classes of problems.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;One important observation is that distributed locking appears only once in this table.&lt;/p&gt;

&lt;p&gt;This is intentional.&lt;/p&gt;

&lt;p&gt;Most real-world problems are better solved using mechanisms that are specifically designed for those problems, rather than relying on a general-purpose locking abstraction.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;30. Common Misconceptions&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;There are several misconceptions that frequently appear when discussing distributed locking in system design.&lt;/p&gt;

&lt;p&gt;One common belief is that distributed locks guarantee correctness. In reality, this is not always true. Correctness depends not only on acquiring the lock, but also on how the protected resource validates ownership. Without mechanisms like fencing tokens, stale lock holders may still be able to modify shared state incorrectly.&lt;/p&gt;

&lt;p&gt;Another misconception is that lease expiration implies the original owner has stopped working. In practice, this is not guaranteed. The application may still be running but temporarily unable to renew the lease due to garbage collection pauses, CPU starvation, or network delays. Distributed systems must reason in terms of timeouts and uncertainty, not absolute state.&lt;/p&gt;

&lt;p&gt;It is also often assumed that leader election replaces consensus. This is not the case. Leader election determines which node is responsible for coordination, while consensus determines what the system agrees upon. These are fundamentally different problems that operate at different layers of the system.&lt;/p&gt;

&lt;p&gt;Finally, there is a belief that every distributed system requires distributed locking. In reality, many systems do not. Techniques such as unique constraints, optimistic concurrency, idempotent operations, and partition ownership often provide simpler and more scalable solutions.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Final Thoughts&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We began this discussion with a simple question: how can multiple application instances ensure that only one of them performs a particular operation?&lt;/p&gt;

&lt;p&gt;At first, distributed locking seems like a complete solution. It enforces exclusivity across machines, giving the impression that once a lock is acquired, all other contenders are safely excluded.&lt;/p&gt;

&lt;p&gt;However, each approach introduces trade-offs that matter in real systems.&lt;/p&gt;

&lt;p&gt;Permanent locks can become stale if the holder crashes, leaving the system blocked indefinitely.&lt;/p&gt;

&lt;p&gt;Leases reduce this risk by introducing time-bounded ownership, but they also allow ownership to expire mid-operation, even when work is still valid. Even with leases, stale ownership can still cause incorrect writes unless the system can distinguish between current and outdated owners.&lt;/p&gt;

&lt;p&gt;Fencing tokens address this by enforcing monotonic ordering, ensuring only the latest owner can modify shared state and preventing delayed operations from corrupting data.&lt;/p&gt;

&lt;p&gt;At a higher level, leader election coordinates long-running responsibilities by ensuring a single active coordinator, while consensus protocols allow multiple nodes to agree on a single consistent state despite failures.&lt;/p&gt;

&lt;p&gt;Together, these mechanisms highlight a core truth about distributed systems:&lt;/p&gt;

&lt;p&gt;Distributed locking is not really about locking—it is about coordination under partial and unreliable information, where no node has a complete or up-to-date view of the system.&lt;/p&gt;

&lt;p&gt;In practice, machines pause, networks delay or drop messages, and failures often look identical to transient slowness. This makes correctness fundamentally harder to reason about.&lt;/p&gt;

&lt;p&gt;As a result, correctness is not achieved by removing uncertainty, but by designing systems that remain correct despite it.&lt;/p&gt;

&lt;p&gt;The key lesson is simple:&lt;/p&gt;

&lt;p&gt;Before introducing distributed locking, first ask whether the problem can be solved without adding coordination at all, since coordination is often the main source of complexity and fragility.&lt;/p&gt;

&lt;p&gt;The most resilient distributed systems are not those with the most advanced locking mechanisms, but those that minimize coordination while still preserving correctness under all expected failure modes.&lt;/p&gt;




&lt;p&gt;Assisted AI to paraphrase. &lt;/p&gt;

</description>
      <category>distributedsystems</category>
      <category>database</category>
      <category>systemdesign</category>
      <category>discuss</category>
    </item>
    <item>
      <title>Distributed Locking in Practice: Guarantees, Failure Scenarios and Better Alternatives (3/4)</title>
      <dc:creator>Venkatesan Ramar</dc:creator>
      <pubDate>Wed, 19 Aug 2026 07:22:08 +0000</pubDate>
      <link>https://dev.to/morpheus-vera/distributed-locking-in-practice-guarantees-failure-scenarios-and-better-alternatives-34-494m</link>
      <guid>https://dev.to/morpheus-vera/distributed-locking-in-practice-guarantees-failure-scenarios-and-better-alternatives-34-494m</guid>
      <description>&lt;p&gt;&lt;strong&gt;15. Distributed Locking Is Only One Coordination Pattern&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;By this point, we've established an important progression in how distributed systems handle coordination.&lt;/p&gt;

&lt;p&gt;A distributed lock is designed to solve a very specific problem: coordinating ownership of a resource across multiple machines. It ensures that only one node can act on a shared resource at a time.&lt;/p&gt;

&lt;p&gt;As systems evolved, we introduced leases to handle a different failure mode—abandoned locks caused by crashed or unreachable nodes. Leases ensure that ownership is temporary and automatically expires if not renewed. We then added fencing tokens to address a more subtle issue: stale owners. Even if a node believes it still holds a lock, a higher-numbered token can prevent it from making unsafe updates.&lt;/p&gt;

&lt;p&gt;This naturally leads to a broader question.&lt;/p&gt;

&lt;p&gt;If distributed locking has become this sophisticated, why do modern distributed systems still rely on concepts such as leader election and consensus?&lt;/p&gt;

&lt;p&gt;The answer lies in a key realization: exclusive ownership is not always the problem we're trying to solve.&lt;/p&gt;

&lt;p&gt;In many systems, the goal is not to have multiple machines competing for the same resource. Instead, the goal is much simpler: ensure that one machine coordinates the rest.&lt;/p&gt;

&lt;p&gt;That difference shifts the entire coordination model.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;16. From Ownership to Leadership&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Consider a cluster of application instances responsible for scheduling background jobs.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;          +-------------+
          | Instance A  |
          +-------------+

          +-------------+
          | Instance B  |
          +-------------+

          +-------------+
          | Instance C  |
          +-------------+
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Each instance runs the same code. Every minute, all of them check whether invoices should be generated.&lt;/p&gt;

&lt;p&gt;If all instances execute the scheduler independently, duplicate invoices become inevitable.&lt;/p&gt;

&lt;p&gt;A straightforward solution is to use a distributed lock. Before running the scheduler, each instance attempts to acquire the lock. The winner proceeds, and the others wait.&lt;/p&gt;

&lt;p&gt;This works correctly, but it introduces a repeating pattern of contention.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Minute 1

Acquire Lock
↓
Generate Jobs
↓
Release Lock
-------------------

Minute 2

Acquire Lock
↓
Generate Jobs
↓
Release Lock
-------------------

Minute 3

Acquire Lock
↓
Generate Jobs
↓
Release Lock
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Every execution cycle requires coordination. Every minute, the system competes again for the same ownership.&lt;/p&gt;

&lt;p&gt;But the real requirement is simpler: only one instance should be responsible for scheduling. That responsibility does not change frequently.&lt;/p&gt;

&lt;p&gt;Continuously competing for it introduces unnecessary overhead.&lt;/p&gt;

&lt;p&gt;This is where leader election becomes a better fit.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Leadership Is Long-Lived Ownership&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Instead of competing for every operation, the cluster elects a single instance to act as the coordinator.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;          +-------------+
          | Instance A  |
          +-------------+
                 │
                 │
          Leader Elected
                 │
                 ▼
          +-------------+
          | Leader      |
          | Instance A  |
          +-------------+

          +-------------+
          | Instance B  |
          +-------------+

          +-------------+
          | Instance C  |
          +-------------+
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once elected, the leader takes responsibility for shared tasks such as:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;scheduling background jobs&lt;/li&gt;
&lt;li&gt;coordinating cluster state&lt;/li&gt;
&lt;li&gt;assigning work to nodes&lt;/li&gt;
&lt;li&gt;monitoring cluster health&lt;/li&gt;
&lt;li&gt;managing shared configuration&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The other instances continue serving requests, but they no longer compete for leadership unless a failure occurs.&lt;/p&gt;

&lt;p&gt;This changes the coordination model fundamentally.&lt;/p&gt;

&lt;p&gt;Instead of repeatedly asking:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;"Who owns this operation right now?"&lt;br&gt;
the system asks:&lt;br&gt;
"Who is currently the leader of the cluster?"&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Leadership becomes a long-lived role rather than a short-lived lock acquisition.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;17. Leaders Can Fail Too&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Leader election does not remove failure scenarios. It simply changes how the system responds to them.&lt;/p&gt;

&lt;p&gt;Suppose Instance A is currently the leader.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;         Leader

      Instance A
           │
           │
      Coordinates Cluster
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;While performing its responsibilities, Instance A crashes unexpectedly.&lt;/p&gt;

&lt;p&gt;At that moment, the cluster loses its coordinator. No other node is actively managing scheduling or coordination.&lt;/p&gt;

&lt;p&gt;To recover, the system must elect a new leader.&lt;/p&gt;

&lt;p&gt;This process is called &lt;strong&gt;leader election&lt;/strong&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Before Failure

Leader
Instance A
---------------------
After Failure

Leader
Instance B

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Unlike distributed locking, leader election is not triggered for every operation. It only occurs when leadership is lost.&lt;/p&gt;

&lt;p&gt;Most of the time, the leader continues operating without interruption, making it a relatively stable coordination role.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Leadership Is Also Temporary&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;A natural question arises at this point: how does the system know the leader has actually failed?&lt;/p&gt;

&lt;p&gt;The honest answer is that it does not know with certainty.&lt;/p&gt;

&lt;p&gt;The same uncertainty we saw earlier still applies.&lt;/p&gt;

&lt;p&gt;The leader may have crashed.&lt;br&gt;
The network may be partitioned.&lt;br&gt;
The process may be paused.&lt;br&gt;
The machine may be overloaded.&lt;/p&gt;

&lt;p&gt;From the perspective of other nodes, all they can observe is that communication has stopped.&lt;/p&gt;

&lt;p&gt;Because of this uncertainty, leader election relies on the same foundational mechanisms we have already discussed:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;temporary ownership&lt;/li&gt;
&lt;li&gt;heartbeats&lt;/li&gt;
&lt;li&gt;leases&lt;/li&gt;
&lt;li&gt;timeouts&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The problem has not disappeared. It has simply shifted from protecting a resource to protecting the leadership role itself.&lt;/p&gt;



&lt;p&gt;&lt;strong&gt;18. Why Leader Election Is Not Consensus&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Engineers often encounter leader election and consensus together, but they solve different problems.&lt;/p&gt;

&lt;p&gt;Leader election answers a narrow question:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Which node should coordinate the cluster?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Consensus answers a broader one:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;How do multiple nodes agree on shared state despite failures?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Consider a cluster of three nodes maintaining configuration data.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;          Node A

          Node B

          Node C
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now imagine a configuration change is introduced. Every node must eventually agree on the same final state.&lt;/p&gt;

&lt;p&gt;If one node applies the change while another rejects it, the cluster becomes inconsistent.&lt;/p&gt;

&lt;p&gt;Leader election alone cannot solve this. It only determines who proposes or coordinates the change. It does not guarantee agreement.&lt;/p&gt;

&lt;p&gt;Consensus is what ensures that all nodes converge on the same decision.&lt;/p&gt;

&lt;p&gt;This distinction is subtle but critical.&lt;/p&gt;

&lt;p&gt;Leadership assigns responsibility.&lt;br&gt;
Consensus ensures agreement.&lt;/p&gt;



&lt;p&gt;&lt;strong&gt;19. Coordination Requires Agreement&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;To make this more concrete, consider a distributed storage system with three nodes maintaining metadata.&lt;/p&gt;

&lt;p&gt;The leader decides that a new storage node should join the cluster.&lt;/p&gt;

&lt;p&gt;If the update is not applied consistently across all nodes, the system becomes fragmented.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Node A

Storage 1
Storage 2
Storage 3
------------------

Node B

Storage 1
Storage 2
Storage 3
------------------

Node C

Storage 1
Storage 2
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Even though a leader exists, the cluster is now inconsistent. One node has a different view of membership than the others.&lt;/p&gt;

&lt;p&gt;This demonstrates an important principle: leadership alone is not enough.&lt;/p&gt;

&lt;p&gt;Consensus mechanisms exist to ensure that all healthy nodes eventually agree on the same state.&lt;/p&gt;

&lt;p&gt;The exact algorithms behind this—such as Paxos or Raft—are complex and deserve their own discussion.&lt;/p&gt;

&lt;p&gt;For now, the key architectural insight is:&lt;/p&gt;

&lt;p&gt;Leader election determines &lt;strong&gt;who coordinates&lt;/strong&gt;.&lt;br&gt;
Consensus determines &lt;strong&gt;what everyone agrees on&lt;/strong&gt;.&lt;/p&gt;



&lt;p&gt;&lt;strong&gt;20. Where Modern Coordination Systems Fit&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Modern distributed coordination systems often combine all of these concepts into a single platform.&lt;/p&gt;

&lt;p&gt;They typically provide:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;temporary ownership through leases&lt;/li&gt;
&lt;li&gt;fencing via monotonic tokens&lt;/li&gt;
&lt;li&gt;leader election&lt;/li&gt;
&lt;li&gt;consensus mechanisms&lt;/li&gt;
&lt;li&gt;failure detection&lt;/li&gt;
&lt;li&gt;cluster membership management&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Instead of requiring every application to implement these primitives independently, the coordination system provides them as shared infrastructure.&lt;/p&gt;

&lt;p&gt;From an application perspective, the architecture becomes much simpler:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Application
      │
      ▼
Coordination Platform
      │
      ├── Leases
      ├── Leader Election
      ├── Cluster Membership
      ├── Consensus
      └── Coordination Metadata
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The application focuses on business logic, while the platform handles correctness under failure conditions.&lt;/p&gt;

&lt;p&gt;An important observation here is that the specific technology—whether ZooKeeper, etcd, Consul, or another system—is often less important than understanding the underlying coordination problem.&lt;/p&gt;

&lt;p&gt;Choosing a tool before understanding the problem often leads to unnecessary complexity.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;21. Choosing the Right Coordination Primitive&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Throughout this article, we have explored several coordination mechanisms. While they are often discussed together, each one solves a distinct problem.&lt;/p&gt;

&lt;p&gt;Understanding these differences makes system design significantly clearer.&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Engineering Problem&lt;/th&gt;
&lt;th&gt;Coordination Primitive&lt;/th&gt;
&lt;th&gt;Primary Guarantee&lt;/th&gt;
&lt;th&gt;Typical Use Cases&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Ensure only one node performs a critical operation&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;Distributed Lock / Lease&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Temporary exclusive ownership&lt;/td&gt;
&lt;td&gt;Scheduled jobs, file processing, cache refresh, resource ownership&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Prevent stale owners from modifying shared state&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;Fencing Tokens&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Rejects operations from older owners&lt;/td&gt;
&lt;td&gt;Inventory updates, payment processing, distributed storage, metadata updates&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Ensure one active coordinator exists&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;Leader Election&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Single active leader for cluster-wide coordination&lt;/td&gt;
&lt;td&gt;Job schedulers, controllers, coordinators, cluster management&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Keep multiple nodes in agreement&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;Consensus&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Consistent cluster state despite failures&lt;/td&gt;
&lt;td&gt;Cluster membership, configuration management, metadata, distributed coordination&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Recover ownership automatically after failures&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;Leases&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Ownership expires unless renewed&lt;/td&gt;
&lt;td&gt;Long-running tasks, distributed locks, leadership management&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Detect failed coordinators and trigger recovery&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;Heartbeats + Timeouts&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Failure detection based on liveness&lt;/td&gt;
&lt;td&gt;Leader monitoring, cluster health, node membership&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;This table reflects the progression we have followed throughout the article.&lt;/p&gt;

&lt;p&gt;We began with distributed locks for shared resource coordination.&lt;br&gt;
We then addressed their limitations with leases.&lt;br&gt;
We fixed stale ownership with fencing tokens.&lt;br&gt;
We improved coordination efficiency with leader election.&lt;br&gt;
Finally, we ensured correctness across nodes with consensus.&lt;/p&gt;

&lt;p&gt;Each mechanism builds on the limitations of the previous one. None replaces the others. Instead, they form a layered toolkit for building reliable distributed systems.&lt;/p&gt;

&lt;p&gt;The final question in this series naturally follows from here:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Do we actually need distributed locking at all?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In many real-world systems, correctness is achieved through alternative approaches such as optimistic concurrency, idempotent operations, database constraints, partition ownership, or queue-based processing. Understanding when to use these alternatives is often more valuable than implementing a distributed lock itself.&lt;/p&gt;




</description>
      <category>distributedsystems</category>
      <category>database</category>
      <category>systemdesign</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Distributed Locking in Practice: Guarantees, Failure Scenarios and Better Alternatives (2/4)</title>
      <dc:creator>Venkatesan Ramar</dc:creator>
      <pubDate>Tue, 18 Aug 2026 09:48:00 +0000</pubDate>
      <link>https://dev.to/morpheus-vera/distributed-locking-in-practice-guarantees-failure-scenarios-and-better-alternatives-24-809</link>
      <guid>https://dev.to/morpheus-vera/distributed-locking-in-practice-guarantees-failure-scenarios-and-better-alternatives-24-809</guid>
      <description>&lt;p&gt;In this article, we'll explore the mechanisms to solve the coordination problem. &lt;/p&gt;




&lt;p&gt;&lt;strong&gt;8. Introducing Leases&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;To address the problem of permanent ownership, distributed systems typically replace it with temporary ownership.&lt;/p&gt;

&lt;p&gt;This concept is known as a &lt;em&gt;lease&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Instead of granting indefinite control over a resource, the coordination service assigns ownership for a limited period of time.&lt;/p&gt;

&lt;p&gt;Rather than stating, “You own this resource until you explicitly release it,” the system instead says, “You own this resource for the next 30 seconds.”&lt;/p&gt;

&lt;p&gt;This changes the interaction model significantly.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Acquire Lease
       |
       v
Execute Work
       |
       v
Renew Lease
       |
       v
Continue Processing
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As long as the application remains healthy, it periodically renews the lease to maintain ownership. If the application crashes or becomes unresponsive, it can no longer renew the lease. Once the lease duration expires, ownership is automatically revoked.&lt;/p&gt;

&lt;p&gt;At that point, another application becomes eligible to acquire the lease and continue the work.&lt;/p&gt;

&lt;p&gt;Leases solve a critical problem in distributed systems: &lt;em&gt;they prevent abandoned locks from blocking progress indefinitely&lt;/em&gt;. The system can recover automatically without manual intervention.&lt;/p&gt;

&lt;p&gt;However, while leases improve availability, they also introduce a new class of subtle and more complex problems.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Leases Depend on Time&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;To understand the next challenge, assume the lease duration is thirty seconds.&lt;/p&gt;

&lt;p&gt;Application A successfully acquires the lease.&lt;/p&gt;

&lt;p&gt;Lease Granted&lt;/p&gt;

&lt;p&gt;Duration = 30 seconds&lt;/p&gt;

&lt;p&gt;After twenty seconds, the JVM begins a long Full Garbage Collection cycle. This pause lasts forty seconds, significantly longer than the lease duration.&lt;/p&gt;

&lt;p&gt;The timeline now becomes problematic.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Lease Granted
      |
      |
Processing
      |
      |
GC Pause (40 sec)
      |
      |
Lease Expires
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;While Application A is paused, the lease expires. During this time, another application requests access to the same resource.&lt;/p&gt;

&lt;p&gt;The coordination service observes that the previous lease has expired and therefore grants ownership to Application B.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Application A             Application B

Lease Holder
      |
GC Pause
                           Acquire Lease
                                |
                          Lease Granted
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After the garbage collection completes, Application A resumes execution. From its perspective, it simply continues where it left off, still believing it owns the resource.&lt;/p&gt;

&lt;p&gt;At the same time, Application B also believes it legitimately owns the resource because it was granted a valid lease by the coordination service.&lt;/p&gt;

&lt;p&gt;Neither application is behaving incorrectly. Both are operating based on information that was valid at different points in time.&lt;/p&gt;

&lt;p&gt;However, the system now has two active owners for the same resource.&lt;/p&gt;

&lt;p&gt;This situation is significantly more dangerous than an abandoned lock because both participants are actively performing work under the assumption of exclusive ownership.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;9. Split Brain Without a Network Partition&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Many engineers associate split-brain scenarios exclusively with network partitions, where parts of the system become isolated from each other.&lt;/p&gt;

&lt;p&gt;However, as the previous example demonstrates, split-brain conditions can occur even without a network failure.&lt;/p&gt;

&lt;p&gt;Application A still believes it holds a valid lease, while Application B has legitimately acquired a newer lease from the coordination service.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;        Coordination Service

          Lease Expired
                |
      +---------+---------+
      |                   |
      v                   v
Application A      Application B
Believes           Believes
It Owns            It Owns
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Both applications continue processing independently.&lt;/p&gt;

&lt;p&gt;Importantly, the coordination service is behaving correctly. It expired the old lease and issued a new one based on its rules. Application A is also behaving correctly, because it has not yet observed that its lease has expired. Application B is also correct, because it received a valid lease.&lt;/p&gt;

&lt;p&gt;The problem is not incorrect behavior by any single component. The problem is that ownership information has become stale and inconsistent across the system.&lt;/p&gt;

&lt;p&gt;This leads to a crucial realization in distributed systems design: acquiring a lease does not guarantee continuous or permanent ownership. Ownership is not a static property; it can change while an application is temporarily unable to observe that change.&lt;/p&gt;

&lt;p&gt;Leases solve one important problem by eliminating abandoned locks, but they introduce another, more subtle challenge.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;How do we ensure that an application does not continue performing work after it has lost ownership?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Answering this question leads directly to one of the most important concepts in distributed coordination: &lt;em&gt;fencing tokens&lt;/em&gt;.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;10. Why Leases Alone Cannot Protect Your Data&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The previous section ended with an uncomfortable situation.&lt;/p&gt;

&lt;p&gt;Application A acquired a lease, but the JVM paused long enough for that lease to expire. During that time, Application B legitimately acquired a new lease. When Application A eventually resumed, both applications believed they owned the same resource.&lt;/p&gt;

&lt;p&gt;This leads to a natural question: why doesn't the coordination service simply reject any further requests from Application A once its lease has expired?&lt;/p&gt;

&lt;p&gt;The answer is simple, but important. The coordination service has no control over what Application A does after it acquires the lease. Once ownership is granted, the application runs independently and continues performing work on its own.&lt;/p&gt;

&lt;p&gt;It cannot intercept every database update, file write, API call, or business operation that the application performs.&lt;/p&gt;

&lt;p&gt;To make this concrete, consider a payment processing service:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;            Coordination Service
                    |
             Lease Granted
                    |
                    v
             Payment Service
                    |
                    v
             Banking System
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After the lease is granted, the payment service communicates directly with the banking system. At this point, the coordination service is no longer in the execution path.&lt;/p&gt;

&lt;p&gt;If the lease expires while the payment service is paused, nothing prevents it from continuing to submit payment requests after it resumes. The coordination service may know the lease has expired, but the banking system does not.&lt;/p&gt;

&lt;p&gt;This reveals a key insight: a distributed lock controls ownership, but it does not automatically control every operation performed by the owner.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Ownership and Authority Are Different&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;To understand the problem more clearly, consider a warehouse system that reserves inventory.&lt;/p&gt;

&lt;p&gt;Application A acquires a lease and begins processing. While it is still working, the lease expires. At that point, Application B becomes the new owner.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;       Lease Owner

     Application A
            ↓
     Lease Expires
            ↓
     Application B
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now imagine Application A resumes execution. Even though it is no longer the owner, it still holds references to in-memory objects, still has an open database connection, and still has network access.&lt;/p&gt;

&lt;p&gt;Nothing physically prevents it from continuing to update inventory.&lt;/p&gt;

&lt;p&gt;The coordination service cannot reach back in time and undo or block operations that are already in progress.&lt;/p&gt;

&lt;p&gt;So while ownership has changed, the authority to modify the shared resource has not been automatically revoked in the running application.&lt;/p&gt;

&lt;p&gt;This is why leases alone cannot guarantee correctness in distributed systems.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;11. The Missing Piece&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Let’s revisit the inventory example in more detail.&lt;/p&gt;

&lt;p&gt;The inventory contains a single remaining item. Application A acquires a lease and begins processing. A few seconds later, it pauses unexpectedly. During this pause, the lease expires.&lt;/p&gt;

&lt;p&gt;Application B then acquires a new lease and successfully reserves the inventory item.&lt;/p&gt;

&lt;p&gt;Several seconds later, Application A resumes and also attempts to reserve the same item.&lt;/p&gt;

&lt;p&gt;At this point, the inventory becomes inconsistent.&lt;/p&gt;

&lt;p&gt;What is important here is that neither application violated the lease protocol. The coordination service behaved correctly. Both applications followed the rules as designed.&lt;/p&gt;

&lt;p&gt;The problem is that the shared resource had no way to distinguish between the current owner and a previous owner that resumed late.&lt;/p&gt;

&lt;p&gt;Both requests looked valid.&lt;/p&gt;

&lt;p&gt;The missing capability is not another lock or another lease mechanism. The missing capability is a way to determine which owner is newer.&lt;/p&gt;

&lt;p&gt;This is exactly the problem that &lt;em&gt;fencing tokens&lt;/em&gt; solve.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;12. Introducing Fencing Tokens&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Instead of only granting a lease, the coordination service also issues a monotonically increasing number along with it.&lt;/p&gt;

&lt;p&gt;This number is called a &lt;strong&gt;fencing token&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Each time a new lease is granted, the token increases. Every new owner receives a strictly larger value than the previous one.&lt;/p&gt;

&lt;p&gt;The sequence might look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Application A
Lease Granted
Token = 101
--------------------
Application B
Lease Granted
Token = 102
--------------------
Application C
Lease Granted
Token = 103
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The fencing token represents the freshness of ownership. A larger token always means a more recent owner.&lt;/p&gt;

&lt;p&gt;Unlike timestamps, fencing tokens do not depend on clock synchronization. They are simply increasing numbers generated by the coordination system.&lt;/p&gt;

&lt;p&gt;This small addition fundamentally changes how safety is enforced in distributed systems.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Why Increasing Numbers Matter&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Now consider what happens when Application A pauses after receiving token 101. While it is paused, Application B acquires a lease and receives token 102.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Time

Application A
Acquire Lease
Token 101
      |
      |
GC Pause
      |
      |
Resume
-------------------------

Application B

Acquire Lease
Token 102
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Both applications continue running independently.&lt;/p&gt;

&lt;p&gt;Without fencing tokens, both would appear equally valid when they attempt to modify the shared resource.&lt;/p&gt;

&lt;p&gt;With fencing tokens, every operation now carries proof of ownership.&lt;/p&gt;

&lt;p&gt;Application A sends a request like this:&lt;/p&gt;

&lt;p&gt;Reserve Inventory&lt;/p&gt;

&lt;p&gt;Token = 101&lt;/p&gt;

&lt;p&gt;Application B sends:&lt;/p&gt;

&lt;p&gt;Reserve Inventory&lt;/p&gt;

&lt;p&gt;Token = 102&lt;/p&gt;

&lt;p&gt;The resource can now immediately determine which request belongs to the most recent owner.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;13. The Resource Must Enforce the Token&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This is the point where many explanations stop, and also where many real-world systems fail.&lt;/p&gt;

&lt;p&gt;The coordination service generates fencing tokens, but it does not enforce them. The responsibility of validation belongs entirely to the protected resource.&lt;/p&gt;

&lt;p&gt;For example, imagine the inventory database keeps track of the highest token it has seen so far.&lt;/p&gt;

&lt;p&gt;Initially, the state might be:&lt;/p&gt;

&lt;p&gt;Highest Token = 101&lt;/p&gt;

&lt;p&gt;When Application B submits its request with token 102, the database compares it with the stored value. Since 102 is greater, the request is accepted, and the state is updated:&lt;/p&gt;

&lt;p&gt;Highest Token = 102&lt;/p&gt;

&lt;p&gt;Later, Application A resumes and submits a request with token 101. The database performs the same comparison:&lt;/p&gt;

&lt;p&gt;101 &amp;lt; 102&lt;/p&gt;

&lt;p&gt;Since the incoming token is older than the current highest token, the request is rejected.&lt;/p&gt;

&lt;p&gt;This prevents the stale owner from modifying the shared resource.&lt;/p&gt;

&lt;p&gt;The key insight is that correctness is enforced by the resource itself, not by the coordination service and not by the lease mechanism.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Why the Coordination Service Cannot Do This&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;At first glance, it might seem simpler if the coordination service itself rejected stale operations.&lt;/p&gt;

&lt;p&gt;However, this is not possible in practice.&lt;/p&gt;

&lt;p&gt;The coordination service only participates during lease acquisition. After that point, all business operations happen directly between the application and the resource.&lt;/p&gt;

&lt;p&gt;Consider this flow:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Application
      |
Acquire Lease
      |
Coordination Service

Application
      |
      |
      v
Database
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once the lease is granted, every subsequent operation bypasses the coordination service entirely. Because of this, only the database (or the protected resource) can determine whether a request is stale.&lt;/p&gt;

&lt;p&gt;This is why fencing tokens must accompany every operation that modifies shared state.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;14. Where Fencing Tokens Are Useful&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Fencing tokens are useful anywhere multiple distributed processes can modify a shared resource.&lt;/p&gt;

&lt;p&gt;Common examples include:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;updating inventory systems&lt;/li&gt;
&lt;li&gt;processing payment batches&lt;/li&gt;
&lt;li&gt;writing to shared storage systems&lt;/li&gt;
&lt;li&gt;updating distributed metadata stores&lt;/li&gt;
&lt;li&gt;controlling scheduled or background jobs&lt;/li&gt;
&lt;li&gt;modifying cluster configuration or leadership state&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The underlying technology does not matter. What matters is that multiple actors can attempt to modify the same resource, and correctness depends on ensuring only the newest owner succeeds.&lt;/p&gt;

&lt;p&gt;Whenever a system must distinguish between stale and current ownership, fencing tokens provide a reliable solution.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Fencing Tokens Are Not a Replacement for Leases&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;It is important to understand that leases and fencing tokens solve different problems.&lt;/p&gt;

&lt;p&gt;Leases answer the question:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;"Who currently owns the resource?"&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Fencing tokens answer a different question:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;"Is this request coming from the most recent owner?"&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;A system that uses leases without fencing tokens can still suffer from stale writes. A system that uses fencing tokens without leases has no mechanism for transferring ownership in the first place.&lt;/p&gt;

&lt;p&gt;In practice, robust distributed systems use both together.&lt;/p&gt;

&lt;p&gt;The lease establishes temporary ownership.&lt;/p&gt;

&lt;p&gt;The fencing token allows the resource to verify that ownership before accepting any operation.&lt;/p&gt;

&lt;p&gt;This separation of concerns is a key idea behind production systems like ZooKeeper and etcd, which must remain correct even in the presence of failures, pauses, and network partitions.&lt;/p&gt;




</description>
      <category>distributedsystems</category>
      <category>database</category>
      <category>systemdesign</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Distributed Locking in Practice: Guarantees, Failure Scenarios and Better Alternatives (1/4)</title>
      <dc:creator>Venkatesan Ramar</dc:creator>
      <pubDate>Mon, 17 Aug 2026 05:41:00 +0000</pubDate>
      <link>https://dev.to/morpheus-vera/distributed-locking-in-practice-guarantees-failure-scenarios-and-better-alternatives-14-3plb</link>
      <guid>https://dev.to/morpheus-vera/distributed-locking-in-practice-guarantees-failure-scenarios-and-better-alternatives-14-3plb</guid>
      <description>&lt;p&gt;Distributed systems solve many problems by dividing work across multiple machines. The same characteristic also introduces an entirely new class of problems.&lt;/p&gt;

&lt;p&gt;Machines must coordinate.&lt;/p&gt;

&lt;p&gt;Unlike threads running inside a single JVM, independent services have no shared memory, no common execution context, and no built-in synchronization mechanism. Every instance makes decisions based on the information available to it at that moment. When several instances attempt to perform the same business operation simultaneously, coordination becomes significantly more difficult than it first appears.&lt;/p&gt;

&lt;p&gt;Distributed locking is often introduced as the solution to this problem.&lt;/p&gt;

&lt;p&gt;It certainly plays an important role.&lt;br&gt;
It is also one of the most misunderstood concepts in distributed systems.&lt;/p&gt;

&lt;p&gt;Many discussions focus on implementing distributed locks using a particular technology. Much less attention is given to understanding what distributed locking actually guarantees, what it cannot guarantee, and why many production systems solve coordination problems without using distributed locks at all.&lt;/p&gt;

&lt;p&gt;This article explores distributed locking from an engineering perspective.&lt;/p&gt;

&lt;p&gt;Rather than starting with technologies, we'll begin with the coordination problem itself.&lt;/p&gt;

&lt;p&gt;As the discussion progresses, each solution will naturally expose its own limitations. Those limitations lead us toward leases, split-brain scenarios, fencing tokens, leader election, consensus, and finally the situations where a distributed lock is not the right solution.&lt;/p&gt;

&lt;p&gt;Because distributed locking is ultimately not about acquiring a lock.&lt;/p&gt;

&lt;p&gt;It is about keeping distributed systems correct while machines fail, networks become unreliable, and time itself becomes uncertain.&lt;/p&gt;



&lt;p&gt;&lt;strong&gt;1. The Coordination Problem&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Imagine an e-commerce platform during a flash sale. Only one unit of a limited-edition product remains in inventory. Two customers place an order at nearly the same time.&lt;/p&gt;

&lt;p&gt;The application is deployed across multiple instances.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;                Inventory = 1

          +----------------------+
          |                      |
          v                      v
     Application A          Application B
          |                      |
          |                      |
     Reserve Item           Reserve Item
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Both application instances receive the request almost simultaneously.&lt;/p&gt;

&lt;p&gt;Both read the inventory.&lt;br&gt;
Both conclude that one unit is available.&lt;br&gt;
Both attempt to reserve it.&lt;/p&gt;

&lt;p&gt;The inventory now becomes negative.&lt;/p&gt;

&lt;p&gt;No service crashed.&lt;br&gt;
No exception occurred.&lt;br&gt;
The database remained healthy.&lt;/p&gt;

&lt;p&gt;Every component behaved exactly as designed.&lt;/p&gt;

&lt;p&gt;The failure was not caused by incorrect code. It was caused by the &lt;em&gt;absence of coordination&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Both applications made independent decisions about the same business resource.&lt;/p&gt;

&lt;p&gt;This problem appears in many business systems.&lt;/p&gt;

&lt;p&gt;Examples include processing the same payment twice, generating duplicate invoices, executing the same scheduled job on multiple servers, refreshing the same cache simultaneously, and assigning the same delivery request to multiple drivers.&lt;/p&gt;

&lt;p&gt;Although these scenarios appear unrelated, they all share the same underlying problem.&lt;/p&gt;

&lt;p&gt;Multiple independent machines need to agree that only one of them should perform a particular operation. That is &lt;strong&gt;coordination problem&lt;/strong&gt;.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Coordination Is Different From Concurrency&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Concurrency is a familiar concept for most Java developers.&lt;/p&gt;

&lt;p&gt;Two threads execute simultaneously inside the same JVM. They share memory, they share execution context, and they rely on built-in synchronization primitives provided by the language and runtime. Because of this shared environment, coordination is relatively straightforward: threads can directly block, signal, and enforce mutual exclusion using well-defined mechanisms.&lt;/p&gt;

&lt;p&gt;Distributed systems operate under entirely different conditions.&lt;/p&gt;

&lt;p&gt;Application instances do not share memory. They cannot directly observe each other's state. Communication happens over a network, which introduces latency, partial failures, and uncertainty. Messages may be delayed, reordered, or lost. Machines may fail independently without affecting others. As a result, every instance has only a partial and potentially outdated view of the overall system.&lt;/p&gt;

&lt;p&gt;Imagine three application instances running in different environments.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  +-------------+    +-------------+    +-------------+
  | Application |    | Application |    | Application |
  |      A      |    |      B      |    |      C      |
  +-------------+    +-------------+    +-------------+
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Each instance executes independently, making decisions based solely on local information. None of them can infer the state of the others unless explicit communication occurs. This lack of shared state fundamentally changes how synchronization must be designed in distributed systems.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;2. Why Traditional Locks Stop Working&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Most Java developers are comfortable solving concurrency problems using synchronization primitives such as synchronized blocks or explicit locks.&lt;/p&gt;

&lt;p&gt;Consider a simple example of protecting a critical section in a single JVM.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;InventoryService&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;

    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;Object&lt;/span&gt; &lt;span class="n"&gt;lock&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Object&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;

    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;reserve&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;productId&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;

        &lt;span class="kd"&gt;synchronized&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;lock&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="c1"&gt;// Reserve inventory&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="o"&gt;}&lt;/span&gt;

&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Inside a single JVM, this approach works exactly as expected. Only one thread can enter the critical section at a time, and the JVM enforces mutual exclusion reliably. The lock effectively serializes access to shared in-memory state.&lt;/p&gt;

&lt;p&gt;The problem becomes apparent when the same application is deployed across multiple instances.&lt;/p&gt;

&lt;p&gt;Suppose the service runs on two different servers.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;          JVM A                     JVM B

     synchronized(lock)      synchronized(lock)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Each JVM maintains its own memory space. Each instance creates its own independent lock object. There is no shared state between them, and neither JVM is aware of the other’s existence. As a result, both threads can enter their respective synchronized blocks simultaneously without any coordination.&lt;/p&gt;

&lt;p&gt;The synchronization mechanism has not failed. It has simply been applied outside its intended scope. It only guarantees mutual exclusion within a single process, not across multiple processes.&lt;/p&gt;

&lt;p&gt;The same limitation applies to other in-memory primitives such as &lt;code&gt;ReentrantLock&lt;/code&gt;, &lt;code&gt;Semaphore&lt;/code&gt;, and &lt;code&gt;ReadWriteLock&lt;/code&gt;. All of them assume a shared memory model, which distributed systems fundamentally do not provide.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;What About Database Locks?&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;A natural question arises at this point: if multiple application instances share the same database, can the database itself act as a coordination mechanism?&lt;/p&gt;

&lt;p&gt;The answer is nuanced.&lt;/p&gt;

&lt;p&gt;In some cases, it works well. In others, it is appropriate but limited. In many cases, it is not suitable at all.&lt;/p&gt;

&lt;p&gt;Consider a scenario where two applications attempt to update the same customer record. A relational database can enforce row-level locking, ensuring that only one transaction modifies the row at a time.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Application A
       |
Row Locked
       |
Application B Waits
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This works effectively because the resource being protected—the database row—already exists within the database’s control domain. The database is naturally responsible for managing consistency of its own data, so using its locking mechanism aligns with its design.&lt;/p&gt;

&lt;p&gt;Now consider a different scenario: a scheduled reconciliation job that must run only once per night. The job performs multiple external operations such as downloading files, calling third-party services, generating reports, and uploading results.&lt;/p&gt;

&lt;p&gt;None of these operations map cleanly to a single database row. There is no single database entity that represents the job’s execution state in a way that the database can meaningfully lock. The resource requiring coordination exists outside the database’s transactional boundary.&lt;/p&gt;

&lt;p&gt;This highlights an important distinction. Database locks are highly effective for protecting database state, but they are not a general-purpose coordination mechanism for distributed workflows that span multiple systems and external dependencies.&lt;/p&gt;

&lt;p&gt;Recognizing this boundary prevents overusing database locking as a distributed coordination strategy.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;3. What Problem Are We Actually Solving?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;At this point, it is easy to assume that the solution is simply a lock that works across machines. However, this intuition only partially captures the real problem.&lt;/p&gt;

&lt;p&gt;The actual goal is &lt;strong&gt;not the lock&lt;/strong&gt; itself. The goal is ensuring that &lt;strong&gt;only one application instance performs a specific business responsibility at a given time&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;This distinction is subtle but critical.&lt;/p&gt;

&lt;p&gt;Consider an application responsible for generating monthly customer statements. If three instances of the application start simultaneously, each instance may attempt to perform the same job independently.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Instance A
             |
             |
        Generate Statements

        Instance B
             |
             |
        Generate Statements

        Instance C
             |
             |
        Generate Statements
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If all three proceed, the system produces duplicate work and potentially inconsistent results. However, the business requirement is not about locking—it is about ensuring exclusivity of execution.&lt;/p&gt;

&lt;p&gt;Only one instance should perform the task.&lt;/p&gt;

&lt;p&gt;This requirement is fundamentally about ownership rather than synchronization. The system needs a way to assign temporary responsibility for a task to a single participant.&lt;/p&gt;

&lt;p&gt;This pattern appears repeatedly in distributed systems. One instance may need to refresh a shared cache, process a payment batch, act as a leader, execute scheduled tasks, or migrate shared data. In all cases, the requirement is consistent: a single owner must perform a specific responsibility for a defined period of time.&lt;/p&gt;

&lt;p&gt;Distributed locking is one possible mechanism to achieve this outcome, but it is not the outcome itself.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;4. The First Distributed Lock&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;To address coordination across multiple machines, a shared coordination service is often introduced. Before performing a critical operation, each application instance requests permission from this service.&lt;/p&gt;

&lt;p&gt;The interaction typically follows a simple pattern.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Application
      |
Acquire Lock
      |
      v
Coordination Service
      |
Lock Granted
      |
      v
Execute Work
      |
Release Lock
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;From a conceptual standpoint, this resembles traditional synchronization. One participant acquires exclusive access, others wait or retry, and only a single instance proceeds with execution.&lt;/p&gt;

&lt;p&gt;At first glance, this appears to solve the problem effectively. The coordination service replaces shared memory, and mutual exclusion is enforced across distributed instances. The business requirement of single execution is satisfied.&lt;/p&gt;

&lt;p&gt;If distributed systems were perfectly reliable, this model would be sufficient and straightforward.&lt;/p&gt;

&lt;p&gt;However, real-world systems introduce complexity that does not exist in single-process environments. Time becomes unreliable. Machines can fail unexpectedly. Network communication can be delayed or interrupted. Processes may pause due to garbage collection or crash entirely.&lt;/p&gt;

&lt;p&gt;These factors introduce uncertainty into the system. A lock that was granted moments ago may no longer represent a valid or safe assumption about system state.&lt;/p&gt;

&lt;p&gt;As a result, the problem evolves.&lt;/p&gt;

&lt;p&gt;It is no longer sufficient to ask, “Who holds the lock?”&lt;/p&gt;

&lt;p&gt;The more important question becomes, “Is the current lock holder still alive and capable of safely completing the work?”&lt;/p&gt;

&lt;p&gt;This shift in perspective fundamentally changes how distributed locking must be designed and evaluated. It also explains why acquiring a distributed lock is only the beginning of the problem, not its solution.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;5. Failure Changes Everything&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;At the end of the previous section, we arrived at a seemingly simple solution.&lt;/p&gt;

&lt;p&gt;Every application instance requests a distributed lock before performing a critical operation.&lt;/p&gt;

&lt;p&gt;Only one instance receives the lock, while all other instances are forced to wait until it becomes available again.&lt;/p&gt;

&lt;p&gt;From a business perspective, this appears to satisfy the requirement because only one application performs the work at any given time.&lt;/p&gt;

&lt;p&gt;If distributed systems behaved like a single JVM, this would be sufficient. In a single process, synchronization primitives provide strong guarantees about mutual exclusion and ownership.&lt;/p&gt;

&lt;p&gt;However, distributed systems do not behave like a single JVM.&lt;/p&gt;

&lt;p&gt;The difficulty begins the moment we acknowledge a simple reality: machines fail.&lt;/p&gt;

&lt;p&gt;More importantly, machines sometimes appear to fail even when they are still running correctly. This distinction fundamentally changes how distributed coordination must be designed.&lt;/p&gt;




&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;When a Machine Stops Responding&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Let’s assume an application successfully acquires a distributed lock.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Application A
      |
Acquire Lock
      |
Lock Granted
      |
Processing...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;At this point, everything appears normal. The system has successfully established exclusive access, and the application begins performing its critical work.&lt;/p&gt;

&lt;p&gt;A few seconds later, the application stops responding.&lt;/p&gt;

&lt;p&gt;This immediately raises an important question: &lt;em&gt;should another application be allowed to acquire the lock?&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;At first glance, the answer seems obvious. If the application is not responding, it feels reasonable that another instance should take over and continue the work.&lt;/p&gt;

&lt;p&gt;However, distributed systems rarely provide clarity about why a machine stopped responding. There are many possible explanations, and from the outside, they often look identical.&lt;/p&gt;

&lt;p&gt;The application may have crashed unexpectedly due to a runtime error or fatal exception. The operating system itself may have restarted the machine as part of maintenance or recovery. The network connection may have been interrupted, isolating the machine even though it is still running. The machine may simply be overloaded, causing extreme delays in processing requests. In some cases, the process may still be alive and functioning correctly, but temporarily unable to communicate with the rest of the system.&lt;/p&gt;

&lt;p&gt;From the perspective of other machines, all of these scenarios produce the same observable behavior: &lt;em&gt;the application becomes silent&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;This silence is deceptively simple, yet extremely difficult to interpret correctly in a distributed environment.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Failure Is Often Uncertainty&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;One of the most important differences between concurrent programming and distributed systems is that failures are rarely definitive in distributed environments.&lt;/p&gt;

&lt;p&gt;Inside a single JVM, the behavior is clear and deterministic. A thread either holds a lock or it does not. A method either completes successfully or it throws an exception. The system has complete visibility into execution state.&lt;/p&gt;

&lt;p&gt;Distributed systems, however, operate with incomplete and delayed information.&lt;/p&gt;

&lt;p&gt;Imagine three application instances interacting in a network.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;               +-------------+
               | Instance A  |
               +-------------+
                      |
          Communication Lost
                      X
        +-------------+-------------+
        |                           |
        v                           v
 +-------------+             +-------------+
 | Instance B  |             | Instance C  |
 +-------------+             +-------------+
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this scenario, Instances B and C stop receiving messages from Instance A. From their perspective, communication has simply ceased.&lt;/p&gt;

&lt;p&gt;There are several possible explanations for this condition. Instance A may have crashed entirely. The network between the instances may have failed or become partitioned. Instance A may still be running but temporarily paused or overloaded. Alternatively, messages may simply be delayed in transit due to congestion or resource constraints.&lt;/p&gt;

&lt;p&gt;The key challenge is that the remaining instances cannot immediately distinguish between these possibilities. They only observe the absence of communication, not its cause.&lt;/p&gt;

&lt;p&gt;This uncertainty is not an edge case in distributed systems; it is the default operating condition. As a result, engineering decisions must often be made without complete or reliable information.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;6. Time Introduces New Problems&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Now consider a different scenario. Application A successfully acquires a distributed lock and begins processing a large batch of financial transactions.&lt;/p&gt;

&lt;p&gt;Initially, everything proceeds as expected. The system is stable, and the application is actively performing work.&lt;/p&gt;

&lt;p&gt;However, after a short period, the JVM triggers a Full Garbage Collection cycle. During this process, the application is paused while memory is being reclaimed and reorganized.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Acquire Lock
      |
      v
Begin Processing
      |
      v
Full GC Pause
      |
      |
      |
      v
Resume Processing
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;From the perspective of the application itself, nothing unusual has occurred. Execution has simply been paused temporarily and will resume once garbage collection completes.&lt;/p&gt;

&lt;p&gt;From the perspective of the rest of the system, however, the situation looks very different. During the pause, the application is unable to respond to requests, send heartbeats, or communicate its state. For several seconds, it appears completely unresponsive.&lt;/p&gt;

&lt;p&gt;Importantly, the application is not dead. It is still running. It is simply not making progress.&lt;/p&gt;

&lt;p&gt;Distributed systems struggle with this distinction because external observers cannot easily determine whether a system is paused or permanently failed.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;A Pause Can Look Like a Failure&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This ambiguity often surprises engineers who are new to distributed systems.&lt;/p&gt;

&lt;p&gt;A useful analogy is waiting for a colleague to respond to an important message. If several minutes pass without a reply, multiple interpretations become possible. The colleague may be busy with other work. Their phone may be turned off or disconnected. They may have lost internet connectivity. In the worst case, they may no longer be available at all.&lt;/p&gt;

&lt;p&gt;Without additional context, all of these explanations remain equally plausible.&lt;/p&gt;

&lt;p&gt;Distributed systems face the same problem at scale. A temporary pause caused by garbage collection, heavy CPU contention, thread starvation, or resource exhaustion can appear identical to a complete system failure.&lt;/p&gt;

&lt;p&gt;Because of this ambiguity, distributed systems cannot rely on perfect failure detection. There is no reliable mechanism that can always distinguish between a slow system and a dead one.&lt;/p&gt;

&lt;p&gt;Instead, systems must make decisions based on incomplete and sometimes misleading information.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;7. Locks Cannot Last Forever&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;To understand why distributed locking is fundamentally different from local locking, consider what would happen if a coordination service granted locks indefinitely.&lt;/p&gt;

&lt;p&gt;In that model, the interaction would look familiar:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Acquire Lock
      |
      v
     Work
      |
      v
Release Lock
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This mirrors traditional synchronization inside a single JVM, where a thread holds a lock until it explicitly releases it.&lt;/p&gt;

&lt;p&gt;Now revisit a failure scenario. Application A acquires the lock and begins processing. Shortly afterward, the machine hosting the application crashes unexpectedly.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Application A
      |
Acquire Lock
      |
Machine Crash
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Because the application crashes, it never reaches the step where it releases the lock.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Release Lock&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;As a result, the lock remains permanently held. No other application can acquire it, and every other instance is forced to wait indefinitely.&lt;/p&gt;

&lt;p&gt;The system effectively stops making progress.&lt;/p&gt;

&lt;p&gt;This illustrates a critical problem: in distributed systems, permanent ownership is dangerous because failures are not rare exceptions—they are expected events.&lt;/p&gt;

&lt;p&gt;To maintain availability, the system must be able to recover from abandoned locks automatically.&lt;/p&gt;




&lt;p&gt;Assisted AI to paraphrase. &lt;/p&gt;

</description>
      <category>distributedsystems</category>
      <category>database</category>
      <category>systemdesign</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Building Reliable Event-Driven Systems: Event Schemas, Versioning, Contract Testing and Events vs Commands (5/5)</title>
      <dc:creator>Venkatesan Ramar</dc:creator>
      <pubDate>Wed, 22 Jul 2026 08:50:00 +0000</pubDate>
      <link>https://dev.to/morpheus-vera/building-reliable-event-driven-systems-event-schemas-versioning-contract-testing-and-events-vs-47ed</link>
      <guid>https://dev.to/morpheus-vera/building-reliable-event-driven-systems-event-schemas-versioning-contract-testing-and-events-vs-47ed</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;In this final article, we're going to explore &lt;strong&gt;Production practices&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;




&lt;p&gt;&lt;strong&gt;22. Events Are Delivered, Not Guaranteed&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A common misconception in event-driven architecture is that publishing an event guarantees it will be processed exactly once.&lt;/p&gt;

&lt;p&gt;Production systems rarely provide that guarantee.&lt;/p&gt;

&lt;p&gt;Events may be:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;delivered multiple times&lt;/li&gt;
&lt;li&gt;delayed&lt;/li&gt;
&lt;li&gt;delivered out of order&lt;/li&gt;
&lt;li&gt;temporarily unavailable&lt;/li&gt;
&lt;li&gt;replayed long after publication&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Reliable systems are not built on ideal conditions. They assume these scenarios will occur.&lt;/p&gt;

&lt;p&gt;As a result, designing resilient consumers is just as important as designing reliable producers.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Duplicate Delivery Is Normal&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Consider the following workflow.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;OrderConfirmed
       |
       v
Inventory Service
       |
Inventory Reserved
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The Inventory Service processes the event successfully. Before acknowledging completion, it crashes.&lt;/p&gt;

&lt;p&gt;After recovery, the event is delivered again.&lt;/p&gt;

&lt;p&gt;From the messaging system’s perspective, this is correct behavior. From the application’s perspective, the same business event has arrived twice.&lt;/p&gt;

&lt;p&gt;Without safeguards, inventory may be reserved twice.&lt;/p&gt;

&lt;p&gt;Duplicate delivery is not an edge case. It is expected behavior in distributed systems.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;23. Idempotency Makes Event Processing Safe&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Idempotency ensures that executing the same operation multiple times produces the same result.&lt;/p&gt;

&lt;p&gt;For event consumers, this means processing the same event repeatedly should not create duplicate business outcomes.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Using Event Identifiers&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Each event should include an &lt;code&gt;eventId&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Consumers track processed events:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Processed Events
----------------
E-1001
E-1002
E-1003
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When a new event arrives, say: eventId = E-1002&lt;/p&gt;

&lt;p&gt;The consumer checks if it has already processed it.&lt;/p&gt;

&lt;p&gt;If yes, ignore it&lt;br&gt;
If no, process it&lt;/p&gt;

&lt;p&gt;Flow:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Receive Event
      |
      v
Already Processed?
      |
 +----+----+
 |         |
Yes        No
 |          |
Ignore   Process Event
            |
            v
      Record eventId
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This approach ensures correctness even with duplicate delivery.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Idempotency Belongs to Business Logic&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Infrastructure can reduce duplicates but cannot eliminate them.&lt;/p&gt;

&lt;p&gt;Idempotency must be enforced at the application level.&lt;/p&gt;

&lt;p&gt;Example: a payment service must never charge a customer twice for the same event.&lt;/p&gt;

&lt;p&gt;This guarantee belongs to business logic, not messaging infrastructure.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;24. Ordering Cannot Always Be Assumed&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Developers often assume events arrive in the order they were published.&lt;/p&gt;

&lt;p&gt;In reality, delivery order can change due to:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;network latency&lt;/li&gt;
&lt;li&gt;retries&lt;/li&gt;
&lt;li&gt;parallel processing&lt;/li&gt;
&lt;li&gt;independent consumers&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Expected sequence:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;OrderCreated
      |
OrderConfirmed
      |
OrderShipped
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A consumer might observe:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;OrderConfirmed
      |
OrderCreated
      |
OrderShipped
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The producer behaved correctly. The delivery order changed.&lt;/p&gt;

&lt;p&gt;Consumers should not rely on strict ordering unless explicitly guaranteed.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Design Consumers to Tolerate Reordering&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Consumers should validate state before processing.&lt;/p&gt;

&lt;p&gt;Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Receive `OrderShipped`
         |
   Order Exists?
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If required state is missing:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;retry later&lt;/li&gt;
&lt;li&gt;delay processing&lt;/li&gt;
&lt;li&gt;move the event for later handling&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This approach handles temporary inconsistencies without assuming perfect ordering.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;25. Correlation Makes Distributed Systems Understandable&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A single user action can trigger multiple events across services.&lt;/p&gt;

&lt;p&gt;Consider a sample flow:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Create Order
      |
OrderConfirmed
      |
InventoryReserved
      |
PaymentCompleted
      |
ShipmentCreated
      |
InvoiceGenerated
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Without correlation, these events appear unrelated. But, with a shared identifier like &lt;em&gt;REQ-98451&lt;/em&gt; the entire workflow becomes traceable.&lt;/p&gt;

&lt;p&gt;Correlation improves observability without affecting business logic.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;26. Events Become Part of Your Audit Trail&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Events naturally capture business history.&lt;/p&gt;

&lt;p&gt;Example lifecycle:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;OrderCreated
      |
OrderConfirmed
      |
PaymentCompleted
      |
ShipmentCreated
      |
OrderDelivered
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This sequence provides a complete record of what happened. Because events represent completed facts, they should never be modified.&lt;/p&gt;

&lt;p&gt;History must remain immutable.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;27. Observability Should Include Events&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Traditional systems usually track:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;request latency&lt;/li&gt;
&lt;li&gt;response time&lt;/li&gt;
&lt;li&gt;database queries&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Event-driven systems require additional metrics:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;published events&lt;/li&gt;
&lt;li&gt;consumed events&lt;/li&gt;
&lt;li&gt;failed processing&lt;/li&gt;
&lt;li&gt;retry count&lt;/li&gt;
&lt;li&gt;duplicate events&lt;/li&gt;
&lt;li&gt;processing latency&lt;/li&gt;
&lt;li&gt;dead-letter events&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Without these, failures may go unnoticed until business issues appear.&lt;/p&gt;

&lt;p&gt;Observability must include event flows, not just services.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Tracing Event Flows&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Distributed tracing becomes more effective with correlation identifiers.&lt;/p&gt;

&lt;p&gt;Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Customer Request
        |
Order Service
        |
Inventory Service
        |
Payment Service
        |
Shipping Service
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Tracing allows engineers to follow a complete business workflow instead of isolated logs.&lt;/p&gt;

&lt;p&gt;This significantly improves debugging and incident analysis.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;28. A Practical Checklist&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Reliable event-driven systems consistently follow these practices.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Design&lt;/strong&gt;&lt;br&gt;
✓ Events represent business facts&lt;br&gt;
✓ Events expose business concepts, not internal models&lt;br&gt;
✓ Payloads contain meaningful business data&lt;br&gt;
✓ Technical metadata is separated from business data&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Evolution&lt;/strong&gt;&lt;br&gt;
✓ Schemas evolve carefully&lt;br&gt;
✓ Breaking changes are avoided&lt;br&gt;
✓ Optional fields are preferred over removal&lt;br&gt;
✓ Compatibility is continuously validated&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Reliability&lt;/strong&gt;&lt;br&gt;
✓ Consumers are idempotent&lt;br&gt;
✓ Duplicate delivery is expected&lt;br&gt;
✓ Ordering is not assumed&lt;br&gt;
✓ Correlation identifiers are included&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Operations&lt;/strong&gt;&lt;br&gt;
✓ Contracts are validated automatically&lt;br&gt;
✓ Event processing is observable&lt;br&gt;
✓ Historical events remain immutable&lt;br&gt;
✓ Producers and consumers evolve independently&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Final Thoughts&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Event-driven architecture is often described as a &lt;em&gt;messaging pattern&lt;/em&gt;. In practice, it is a &lt;em&gt;contract-driven architecture&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Messaging transports events. Contracts enable independent evolution.&lt;/p&gt;

&lt;p&gt;Reliable systems are not defined by tools or frameworks. They are defined by disciplined practices:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;designing events as business contracts&lt;/li&gt;
&lt;li&gt;evolving schemas safely&lt;/li&gt;
&lt;li&gt;validating contracts continuously&lt;/li&gt;
&lt;li&gt;building resilient consumers&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;These principles apply regardless of technology.&lt;/p&gt;

&lt;p&gt;When applied consistently, events become more than messages. They become stable, long-lived contracts that support scalable and maintainable distributed systems.&lt;/p&gt;




&lt;p&gt;Assisted AI to paraphrase.&lt;/p&gt;

</description>
      <category>eventdriven</category>
      <category>distributedsystems</category>
      <category>systemdesign</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Building Reliable Event-Driven Systems: Event Schemas, Versioning, Contract Testing and Events vs Commands (4/5)</title>
      <dc:creator>Venkatesan Ramar</dc:creator>
      <pubDate>Mon, 20 Jul 2026 09:00:00 +0000</pubDate>
      <link>https://dev.to/morpheus-vera/building-reliable-event-driven-systems-event-schemas-versioning-contract-testing-and-events-vs-7fo</link>
      <guid>https://dev.to/morpheus-vera/building-reliable-event-driven-systems-event-schemas-versioning-contract-testing-and-events-vs-7fo</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;In this article, we're going to explore &lt;strong&gt;Contract Testing&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;em&gt;Contract testing&lt;/em&gt; ensures that event contracts remain stable as systems evolve. Producers receive immediate feedback when changes affect consumers, and consumers gain confidence in the data they process.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;16. Why Contract Testing Matters&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Events act as public contracts, and those contracts evolve as systems grow. The key question is how a producer can verify that a schema change does not break its consumers.&lt;/p&gt;

&lt;p&gt;Many teams rely on integration testing for this purpose. While useful, integration tests only confirm that systems can communicate. They do not guarantee that all consumers still understand the event contract.&lt;/p&gt;

&lt;p&gt;Consider an Order Service publishing an &lt;code&gt;OrderConfirmed&lt;/code&gt; event consumed by multiple services:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;                  OrderConfirmed
                         |
      +------------------+-------------------+
      |                  |                   |
      v                  v                   v
 Inventory          Billing          Notification
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If the producer renames a field:&lt;br&gt;
&lt;code&gt;{&lt;br&gt;
    "customerId": "CUS-501"&lt;br&gt;
}&lt;/code&gt;&lt;br&gt;
to:&lt;br&gt;
&lt;code&gt;{&lt;br&gt;
    "accountId": "CUS-501"&lt;br&gt;
}&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;everything may still appear correct. The code compiles, tests pass, and deployment succeeds. However, the Billing Service may &lt;strong&gt;fail at runtime&lt;/strong&gt; because it still expects &lt;code&gt;customerId&lt;/code&gt;. The producer had &lt;em&gt;no visibility into this dependency&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;The issue is not deployment failure but &lt;strong&gt;contract violation&lt;/strong&gt;. Contract testing exists to detect such issues before they reach production.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Integration Tests Cannot Protect Unknown Consumers&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Integration tests typically validate interactions between known systems:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Order Service
      |
      v
Inventory Service
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this setup, both systems are controlled and predictable. Event-driven systems differ because consumers are loosely coupled and may not be known to the producer.&lt;/p&gt;

&lt;p&gt;A new Analytics Service might start consuming &lt;code&gt;OrderConfirmed&lt;/code&gt; months later. The producer cannot manually validate every consumer. Contract testing addresses this by validating expectations rather than communication.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;17. Consumer-Driven Contracts&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Traditional API testing starts with the producer defining the contract. Consumers adapt to it. Consumer-driven contract testing reverses this approach.&lt;/p&gt;

&lt;p&gt;Consumers define their expectations, and producers verify that they continue to meet them. This model works well in event-driven systems where consumers evolve independently.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Thinking From the Consumer's Perspective&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Different consumers often require different subsets of data. For example, the Billing Service may need:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"orderId"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"ORD-1001"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"customerId"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"CUS-501"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"totalAmount"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mf"&gt;249.99&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The Notification Service may require:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"orderId"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"ORD-1001"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"customerId"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"CUS-501"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"customerEmail"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"alice@example.com"&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The producer does not need to understand each consumer’s logic. It only needs to satisfy their declared contracts. This encourages careful evolution and explicit documentation of expectations.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;A Contract Is More Than Field Names&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Contracts define more than structure. They also capture meaning and constraints.&lt;/p&gt;

&lt;p&gt;For example:&lt;br&gt;
&lt;code&gt;{&lt;br&gt;
    "orderId": "ORD-1001",&lt;br&gt;
    "totalAmount": 249.99&lt;br&gt;
}&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;A robust contract may specify:&lt;br&gt;
&lt;code&gt;orderId&lt;/code&gt; must exist and not be empty&lt;br&gt;
&lt;code&gt;totalAmount&lt;/code&gt; must be numeric&lt;br&gt;
&lt;code&gt;totalAmount&lt;/code&gt; must be greater than zero&lt;/p&gt;

&lt;p&gt;These rules ensure data integrity and provide stronger guarantees for both producers and consumers.&lt;/p&gt;



&lt;p&gt;&lt;strong&gt;18. Contract Testing in Practice&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Consider an Order Service publishing:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"eventType"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"OrderConfirmed"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"eventVersion"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"1.0"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"payload"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
        &lt;/span&gt;&lt;span class="nl"&gt;"orderId"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"ORD-1001"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
        &lt;/span&gt;&lt;span class="nl"&gt;"customerId"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"CUS-501"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
        &lt;/span&gt;&lt;span class="nl"&gt;"currency"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"USD"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
        &lt;/span&gt;&lt;span class="nl"&gt;"totalAmount"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mf"&gt;249.99&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Consumers depend on different fields:&lt;br&gt;
&lt;strong&gt;Billing&lt;/strong&gt;: orderId, customerId, totalAmount&lt;br&gt;
&lt;strong&gt;Inventory&lt;/strong&gt;: orderId&lt;br&gt;
&lt;strong&gt;Notification&lt;/strong&gt;: customerId&lt;/p&gt;

&lt;p&gt;If the producer changes the schema:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"payload"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
        &lt;/span&gt;&lt;span class="nl"&gt;"orderId"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"ORD-1001"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
        &lt;/span&gt;&lt;span class="nl"&gt;"accountId"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"CUS-501"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
        &lt;/span&gt;&lt;span class="nl"&gt;"currency"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"USD"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
        &lt;/span&gt;&lt;span class="nl"&gt;"totalAmount"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mf"&gt;249.99&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;the system may still compile and deploy. However, &lt;em&gt;contract validation fails&lt;/em&gt; because &lt;em&gt;consumer expectations are no longer met&lt;/em&gt;. The issue is detected before release, preventing runtime failures.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;The Development Workflow&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Contract testing integrates into the delivery pipeline:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Consumer Defines Contract
          |
          v
Producer Validates Contract
          |
          v
   Build Succeeds
          |
          v
       Deploy
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Every schema change is validated during the build process, ensuring compatibility before deployment.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;19. Using JSON Schema to Describe Events&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;JSON Schema provides a structured way to define event contracts. It acts as an executable specification shared by producers and consumers.&lt;/p&gt;

&lt;p&gt;Consider a sample schema:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"type"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"object"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"required"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="s2"&gt;"orderId"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="s2"&gt;"customerId"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="s2"&gt;"totalAmount"&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"properties"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"orderId"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
      &lt;/span&gt;&lt;span class="nl"&gt;"type"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"string"&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"customerId"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
      &lt;/span&gt;&lt;span class="nl"&gt;"type"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"string"&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"totalAmount"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
      &lt;/span&gt;&lt;span class="nl"&gt;"type"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"number"&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This schema defines required fields, types, and structure. Additional constraints can include string lengths, numeric ranges, formats, and enumerations. Unlike static documentation, &lt;em&gt;schemas can be validated automatically&lt;/em&gt;.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Validation During Publishing&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Producers can validate events before publishing:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;OrderConfirmedEvent&lt;/span&gt; &lt;span class="n"&gt;event&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;...&lt;/span&gt;

&lt;span class="n"&gt;validator&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;validate&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;event&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

&lt;span class="n"&gt;eventPublisher&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;publish&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;event&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Invalid events are rejected early, preventing faulty data from entering the system.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Validation During Consumption&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Consumers can also validate incoming events:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;OrderConfirmedEvent&lt;/span&gt; &lt;span class="n"&gt;event&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;...&lt;/span&gt;

&lt;span class="n"&gt;validator&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;validate&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;event&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

&lt;span class="n"&gt;process&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;event&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This ensures that only valid data reaches business logic, improving reliability.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;20. Schema Registries and Centralized Contracts&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;As systems scale, managing schemas across multiple repositories becomes difficult. Teams may define similar events differently, leading to inconsistencies.&lt;/p&gt;

&lt;p&gt;A centralized schema repository addresses this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;              Event Schemas
                    |
       +------------+------------+
       |                         |
       v                         v
 Producers                  Consumers
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This repository becomes the single source of truth. Producers publish against registered schemas, and consumers validate against them.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Why Centralized Schemas Help&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Centralized schema management improves consistency and visibility. Contracts become discoverable, version history is preserved, and compatibility rules can be enforced automatically.&lt;/p&gt;

&lt;p&gt;Teams spend less time interpreting payloads and more time building features. The contract becomes a shared organizational asset rather than an isolated implementation detail.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;21. Common Contract Testing Mistakes&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Several common issues arise when adopting contract testing.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Treating Documentation as the Contract&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Documentation often becomes outdated as implementations change. Consumers may rely on incorrect assumptions. Executable contracts remain synchronized with the system and provide reliable validation.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Testing Only Happy Paths&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Contracts should cover more than valid scenarios. They should include:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;missing required fields&lt;/li&gt;
&lt;li&gt;invalid data types&lt;/li&gt;
&lt;li&gt;unexpected values&lt;/li&gt;
&lt;li&gt;optional fields&lt;/li&gt;
&lt;li&gt;deprecated fields&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This ensures consumers handle both valid and invalid inputs correctly.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Ignoring Backward Compatibility&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Passing current contracts does not guarantee future compatibility. Schema evolution must be validated alongside contract correctness to avoid breaking existing consumers.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Assuming Producers Own the Contract&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Although producers publish events, contracts are shared responsibilities. Both producers and consumers must maintain and validate them.&lt;/p&gt;




&lt;p&gt;Reliable event-driven systems depend on well-defined, continuously validated contracts. &lt;/p&gt;

&lt;p&gt;In the next part, we will explore production practices like idempotency, event ordering, duplicate handling, correlation and  observability.&lt;/p&gt;

</description>
      <category>eventdriven</category>
      <category>distributedsystems</category>
      <category>systemdesign</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Building Reliable Event-Driven Systems: Event Schemas, Versioning, Contract Testing and Events vs Commands (3/5)</title>
      <dc:creator>Venkatesan Ramar</dc:creator>
      <pubDate>Fri, 17 Jul 2026 09:27:53 +0000</pubDate>
      <link>https://dev.to/morpheus-vera/building-reliable-event-driven-systems-event-schemas-versioning-contract-testing-and-events-vs-l6o</link>
      <guid>https://dev.to/morpheus-vera/building-reliable-event-driven-systems-event-schemas-versioning-contract-testing-and-events-vs-l6o</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;In this article, we're going to explore &lt;strong&gt;Event Schema evolution with Event versioning&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;




&lt;p&gt;&lt;strong&gt;10. Event Schemas Will Eventually Change&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;No event schema stays the same forever. As businesses grow, regulations shift, products gain new features, and processes become more complex, the data shared between services must evolve as well. This evolution is not optional—it is a natural consequence of a system adapting to changing requirements.&lt;/p&gt;

&lt;p&gt;Many teams initially assume they can simply update an event whenever needed. This assumption may hold when there is only one producer and one consumer, but real-world systems rarely remain that simple. Over time, multiple consumers emerge, each with its own responsibilities and release cycles.&lt;/p&gt;

&lt;p&gt;A typical system often looks like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;                  OrderConfirmed
                         |
      +------------------+-------------------+
      |                  |                   |
      v                  v                   v
 Inventory          Billing          Notification
      |
      v
 Analytics
      |
      v
 Customer Insights
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Each consumer evolves independently. Some services may deploy updates weekly, while others might release changes quarterly. In some cases, consumers may even belong to external teams with entirely different priorities and timelines. Because of this, producers cannot assume that all consumers will upgrade simultaneously.&lt;/p&gt;

&lt;p&gt;Schema evolution, therefore, is not just about modifying data structures. It is fundamentally about maintaining compatibility across independently evolving systems.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Compatibility Is More Important Than Version Numbers&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;When discussing schema evolution, teams often focus immediately on versioning. While versioning is useful, compatibility is far more critical. Without compatibility, versioning alone cannot prevent system breakage.&lt;/p&gt;

&lt;p&gt;Consider the following event:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"orderId"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"ORD-1001"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"customerId"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"CUS-501"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"totalAmount"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mf"&gt;249.99&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now imagine a new requirement introduces currency. One approach might replace the existing field entirely:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"orderId"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"ORD-1001"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"customerId"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"CUS-501"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"amount"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
      &lt;/span&gt;&lt;span class="nl"&gt;"value"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mf"&gt;249.99&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
      &lt;/span&gt;&lt;span class="nl"&gt;"currency"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"USD"&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Although the data model has improved, this change breaks every existing consumer that depends on the original structure. The producer has evolved, but the contract has not been preserved.&lt;/p&gt;

&lt;p&gt;The goal of schema evolution is to allow both producers and consumers to evolve independently without causing disruptions.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;11. Backward and Forward Compatibility&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Compatibility is often described using formal definitions, but a practical understanding is more useful when designing real systems.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Backward Compatibility&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Backward compatibility ensures that existing consumers continue to function when producers introduce newer versions of events. This is one of the most important principles in event-driven systems.&lt;/p&gt;

&lt;p&gt;Consider Version 1 of an event:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"orderId"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"ORD-1001"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"customerId"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"CUS-501"&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now Version 2 introduces an additional field:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"orderId"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"ORD-1001"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"customerId"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"CUS-501"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"currency"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"USD"&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Older consumers can safely ignore the new field, allowing them to continue operating without modification. This makes adding optional fields one of the safest ways to evolve a schema. In contrast, removing fields is far more risky because it can break existing consumers.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Forward Compatibility&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Forward compatibility addresses the opposite scenario, where newer consumers must handle older events produced by systems that have not yet been upgraded.&lt;/p&gt;

&lt;p&gt;For example, a new consumer might expect:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"orderId"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"..."&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"customerId"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"..."&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"currency"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"USD"&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;However, older producers may still emit:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"orderId"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"..."&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"customerId"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"..."&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this case, consumers must be designed to handle missing fields gracefully. They might use default values, leave fields empty, or apply fallback logic. This approach ensures that consumers remain resilient even when the system evolves asynchronously.&lt;/p&gt;

&lt;p&gt;Consumers should never assume that every field will always be present, as distributed systems rarely evolve in perfect synchronization.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Compatibility Is a Team Discipline&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Most compatibility issues arise not from technical limitations but from &lt;em&gt;incorrect assumptions&lt;/em&gt;. A common example is the belief that all consumers have already upgraded to the latest version.&lt;/p&gt;

&lt;p&gt;In practice, this assumption is rarely valid. Independent deployment is one of the key advantages of microservices, and compatibility is what preserves that independence. Without it, teams become tightly coupled, and deployments require coordination, defeating the purpose of a distributed architecture.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;12. Safe Schema Evolution&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Schema evolution&lt;/em&gt; is ultimately about maintaining trust between producers and consumers. Producers must continue evolving to meet business needs, while consumers must retain the freedom to upgrade on their own timelines.&lt;/p&gt;

&lt;p&gt;Not all schema changes carry the same level of risk. Some changes are generally safe and can be introduced with minimal impact, while others are inherently breaking and require careful planning.&lt;/p&gt;

&lt;p&gt;Understanding the difference between these types of changes is essential for preventing production failures.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Adding Optional Fields&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Adding optional fields is usually &lt;em&gt;a safe way to evolve a schema&lt;/em&gt;. It allows new functionality to be introduced without disrupting existing consumers.&lt;/p&gt;

&lt;p&gt;For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"orderId"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"ORD-1001"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"customerId"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"CUS-501"&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;can evolve into:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"orderId"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"ORD-1001"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"customerId"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"CUS-501"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"currency"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"USD"&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Older consumers will ignore the new field, while newer consumers can take advantage of it. This approach supports gradual adoption and minimizes risk.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Removing Fields&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Removing fields is significantly &lt;em&gt;more dangerous&lt;/em&gt;. If any consumer depends on a field, its removal will cause failures.&lt;/p&gt;

&lt;p&gt;For instance, if a Billing service relies on:&lt;br&gt;
&lt;code&gt;{&lt;br&gt;
  "totalAmount": 249.99&lt;br&gt;
}&lt;/code&gt;&lt;br&gt;
and that field is removed, the service will break. Because it is often difficult to know all consumers of an event, it is safest to assume that every published field is in use somewhere.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Renaming Fields&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Renaming fields may appear harmless, but it effectively behaves like removing one field and adding another. This makes it &lt;em&gt;a breaking change&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;For example:&lt;br&gt;
&lt;code&gt;{&lt;br&gt;
   "customerId": "CUS-501"&lt;br&gt;
}&lt;/code&gt;&lt;br&gt;
changing to:&lt;br&gt;
&lt;code&gt;{&lt;br&gt;
   "accountId": "CUS-501"&lt;br&gt;
}&lt;/code&gt;&lt;br&gt;
will cause existing consumers to fail because they no longer recognize the expected field. Renaming should therefore be treated with the same caution as removing fields.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Changing Data Types&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Changing the data type of a field can also introduce &lt;em&gt;subtle but serious issues&lt;/em&gt;. Even if serialization succeeds, consumers may fail when processing the data.&lt;/p&gt;

&lt;p&gt;For example:&lt;br&gt;
&lt;code&gt;{&lt;br&gt;
   "quantity": 5&lt;br&gt;
}&lt;/code&gt;&lt;br&gt;
becoming:&lt;br&gt;
&lt;code&gt;{&lt;br&gt;
   "quantity": "5"&lt;br&gt;
}&lt;/code&gt;&lt;br&gt;
may not immediately cause errors during transmission, but it can break downstream logic that expects a numeric value. Type changes should be treated as breaking changes and handled carefully.&lt;/p&gt;



&lt;p&gt;&lt;strong&gt;13. Versioning Strategies&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;There are situations where compatibility alone is not sufficient, and the contract must change in a way that cannot be made backward-compatible. In such cases, versioning becomes necessary.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Version Inside the Event&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;One approach is to include version information directly within the event metadata:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
   &lt;/span&gt;&lt;span class="nl"&gt;"eventType"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"OrderConfirmed"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
   &lt;/span&gt;&lt;span class="nl"&gt;"eventVersion"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"2.0"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
   &lt;/span&gt;&lt;span class="nl"&gt;"payload"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
      &lt;/span&gt;&lt;span class="err"&gt;...&lt;/span&gt;&lt;span class="w"&gt;
   &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This allows consumers to adjust their behavior based on the version while keeping the event name consistent. It provides flexibility but requires consumers to handle multiple versions within their logic.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Different Event Types&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Another approach is to define separate event types for each version:&lt;br&gt;
&lt;code&gt;OrderConfirmedV1&lt;br&gt;
OrderConfirmedV2&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;In this model, consumers &lt;em&gt;subscribe only to the versions&lt;/em&gt; they support. The producer may need to &lt;em&gt;maintain multiple versions during the transition period&lt;/em&gt;, but this approach &lt;em&gt;simplifies consumer logic by avoiding conditional handling&lt;/em&gt; within a single event type.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Which Strategy Is Better?&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;There is no universally correct choice between these strategies. Embedding versions keeps naming simpler, while separate event types make changes more explicit.&lt;/p&gt;

&lt;p&gt;The most important factor is consistency. Teams should adopt a standard approach across services to reduce confusion and operational complexity.&lt;/p&gt;



&lt;p&gt;&lt;strong&gt;14. Avoid Breaking Changes Whenever Possible&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Breaking changes introduce tight coupling between services by forcing coordinated deployments. Instead of allowing independent evolution, they create dependencies that can slow down development and increase risk.&lt;/p&gt;

&lt;p&gt;Consider the following structure:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Producer
    |
    +-----------------------------+
    |      |      |      |        |
    v      v      v      v        v
Service Service Service Service Service
   A       B       C       D       E
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If the producer removes a field, every consumer must update before the change can be safely deployed. Deployment order becomes critical, and the independence of services is lost.&lt;/p&gt;

&lt;p&gt;Even a single breaking change can undermine the benefits of an event-driven architecture.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Deprecation Is Usually Better Than Removal&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;When a field becomes obsolete, it is better to deprecate it rather than remove it immediately.&lt;br&gt;
&lt;code&gt;{&lt;br&gt;
    "legacyField": "..."&lt;br&gt;
}&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Keeping the field while marking it as deprecated allows consumers time to migrate at their own pace. Once all consumers have transitioned away from the field, it can be safely removed.&lt;/p&gt;

&lt;p&gt;This gradual approach &lt;em&gt;reduces disruption and maintains system stability&lt;/em&gt;.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;15. Common Versioning Mistakes&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Certain mistakes appear frequently when teams manage schema evolution.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Treating Events Like Internal DTOs&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Internal data transfer objects (DTOs) often change rapidly as implementation details evolve. Public event contracts, however, should be treated with much greater care.&lt;/p&gt;

&lt;p&gt;They represent agreements between services and should not be modified casually.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Releasing Breaking Changes Without Visibility&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Producers often lack visibility into who consumes their events. Making breaking changes without understanding downstream dependencies introduces significant risk.&lt;/p&gt;

&lt;p&gt;Contract testing can help address this issue by providing insight into how events are used.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Versioning Every Small Change&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Some teams create new versions for every minor change:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;OrderConfirmedV2&lt;br&gt;
OrderConfirmedV3&lt;br&gt;
OrderConfirmedV4&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;In many cases, this is unnecessary. Adding optional fields often preserves compatibility without requiring a new version. Excessive versioning can make systems harder to maintain and understand.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Forgetting That Old Events Continue to Exist&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Events are often stored for long periods and may be replayed for analytics, auditing, or recovery purposes. Schema evolution must account for both new and historical events.&lt;/p&gt;

&lt;p&gt;Even if the schema changes, historical data remains unchanged. Systems must be able to handle both.&lt;/p&gt;




&lt;p&gt;In the next section, we will explore contract testing and how it helps validate these assumptions before changes reach production.&lt;/p&gt;

</description>
      <category>eventdriven</category>
      <category>distributedsystems</category>
      <category>systemdesign</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Building Reliable Event-Driven Systems: Event Schemas, Versioning, Contract Testing and Events vs Commands (2/5)</title>
      <dc:creator>Venkatesan Ramar</dc:creator>
      <pubDate>Wed, 15 Jul 2026 05:41:00 +0000</pubDate>
      <link>https://dev.to/morpheus-vera/building-reliable-event-driven-systems-event-schemas-versioning-contract-testing-and-events-vs-28oa</link>
      <guid>https://dev.to/morpheus-vera/building-reliable-event-driven-systems-event-schemas-versioning-contract-testing-and-events-vs-28oa</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;In this article, we're going to explore &lt;strong&gt;&lt;em&gt;Event Schemas&lt;/em&gt;&lt;/strong&gt;. &lt;/p&gt;
&lt;/blockquote&gt;




&lt;p&gt;&lt;strong&gt;5. Designing Event Schemas That Age Well&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Once a team adopts event-driven architecture, the event schema quickly becomes one of the most critical design artifacts in the system. Unlike an internal Java class that is used within a single codebase, an event schema is consumed by multiple independent services. These services may be developed, deployed, and maintained by different teams, often evolving at different speeds. As a result, every field included in an event effectively becomes part of a contract that consumers may rely on.&lt;/p&gt;

&lt;p&gt;Changing that contract later is rarely as simple as modifying a Java object. While internal models can evolve freely, event schemas must remain stable over time. Good schemas are designed to evolve gracefully, allowing systems to grow without breaking existing consumers. Poorly designed schemas, on the other hand, tend to accumulate compatibility issues that become increasingly difficult to manage.&lt;/p&gt;

&lt;p&gt;At the core of this challenge is a simple but powerful question:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Is the event describing a business fact or exposing the producer's implementation?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Events Should Represent Business Concepts&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Consider an Order Service that has just confirmed an order. One way to represent this event is by focusing on the business outcome:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"orderId"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"ORD-1001"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"customerId"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"CUS-501"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"status"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"CONFIRMED"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"totalAmount"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mf"&gt;249.99&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Another approach might expose internal structures:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"id"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"ORD-1001"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"customerEntity"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
      &lt;/span&gt;&lt;span class="err"&gt;...&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"orderAggregate"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
      &lt;/span&gt;&lt;span class="err"&gt;...&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"hibernateVersion"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;12&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Although both events may contain similar information, only the first represents a stable business contract. The second leaks internal implementation details that consumers should not depend on. Over time, such exposure creates tight coupling and makes evolution difficult.&lt;/p&gt;

&lt;p&gt;A useful guideline is:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Design events for consumers, not for producers.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The producer already understands its internal model. Consumers only need clear, meaningful business information.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Don't Serialize Your Domain Model&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;A common mistake is publishing JPA entities directly as events. For example:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;eventPublisher.publish(orderEntity);&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;This approach may seem convenient because it avoids creating additional classes. However, it tightly couples consumers to the producer’s internal structure. Any change in the domain model can unintentionally break consumers.&lt;/p&gt;

&lt;p&gt;Consider an initial model:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Order&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;Customer&lt;/span&gt; &lt;span class="n"&gt;customer&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Later, the model evolves:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Order&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;CustomerAccount&lt;/span&gt; &lt;span class="n"&gt;customerAccount&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;From a business perspective, nothing has changed. However, the event payload has changed, potentially breaking consumers. This happens because the event contract was tied directly to the internal model.&lt;/p&gt;

&lt;p&gt;A better approach is to define dedicated event models:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="n"&gt;record&lt;/span&gt; &lt;span class="nf"&gt;OrderConfirmedEvent&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;
    &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;orderId&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt;
    &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;customerId&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt;
    &lt;span class="nc"&gt;BigDecimal&lt;/span&gt; &lt;span class="n"&gt;totalAmount&lt;/span&gt;
&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This separation ensures that the event contract remains stable even as the internal model evolves. Both can change independently without affecting each other.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;6. Designing Event Payloads&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Every event answers a specific business question. The schema should provide enough information for consumers to understand that answer clearly, without exposing unnecessary implementation details. Striking this balance is one of the most important design decisions in event-driven systems.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Include Business Information&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Consider a minimal event:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"orderId"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"ORD-1001"&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;While technically valid, it is not very useful. Consumers will likely need additional information, forcing them to make extra API calls:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;OrderConfirmed Event
         |
         v
Inventory Service
         |
         v
GET /orders/ORD-1001
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If multiple consumers follow this pattern, a single event can trigger multiple network requests. This increases system load and introduces unnecessary coupling between services.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Avoid Including Everything&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;At the other extreme, some events include too much information:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"order"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
        &lt;/span&gt;&lt;span class="err"&gt;...&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"customer"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
        &lt;/span&gt;&lt;span class="err"&gt;...&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"payment"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
        &lt;/span&gt;&lt;span class="err"&gt;...&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"inventory"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
        &lt;/span&gt;&lt;span class="err"&gt;...&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"shipment"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
        &lt;/span&gt;&lt;span class="err"&gt;...&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Large payloads can lead to higher network usage, increased serialization costs, and tighter coupling between services. They also make schema evolution more difficult, as changes in one part of the payload may affect multiple consumers.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Design Around Business Needs&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;A practical approach is to ask:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;What information should every consumer reasonably expect to receive?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;For an &lt;code&gt;OrderConfirmed&lt;/code&gt; event, a balanced payload might look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"orderId"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"ORD-1001"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"customerId"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"CUS-501"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"orderDate"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"2026-07-01T10:15:30Z"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"currency"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"USD"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"totalAmount"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mf"&gt;249.99&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This provides essential business context without overwhelming consumers. Those who need additional details can fetch them independently, while others remain unaffected.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;7. Event Metadata Matters&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;While developers often focus on the payload, metadata plays an equally important role in production systems. Metadata provides critical context that helps systems understand how to process and trace events.&lt;/p&gt;

&lt;p&gt;It enables systems to determine when an event occurred, where it originated, how it should be tracked, and whether it has already been processed. Without this information, operating and debugging event-driven systems becomes significantly more challenging.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Business Data vs Technical Metadata&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Business data should reside in the payload, while technical details belong in metadata. For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"eventId"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"8c1e6d12"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"eventType"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"OrderConfirmed"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"eventVersion"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"1.0"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"occurredAt"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"2026-07-01T10:15:30Z"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"correlationId"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"REQ-98451"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"payload"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
      &lt;/span&gt;&lt;span class="nl"&gt;"orderId"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"ORD-1001"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
      &lt;/span&gt;&lt;span class="nl"&gt;"customerId"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"CUS-501"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
      &lt;/span&gt;&lt;span class="nl"&gt;"totalAmount"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mf"&gt;249.99&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This separation improves clarity and makes it easier to evolve both business data and technical metadata independently.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Event Identifier&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Every event should include a unique identifier: &lt;code&gt;eventId&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;This identifier is essential for de-duplication, ensuring idempotent processing, enabling tracing, and supporting auditing. It also simplifies handling scenarios where events may be delivered multiple times.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Correlation Identifier&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In distributed systems, workflows often span multiple services:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Create Order
      |
Reserve Inventory
      |
Process Payment
      |
Create Shipment
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Each step may produce additional events. A correlation identifier links these events together:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Correlation ID&lt;br&gt;
REQ-98451&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;This makes it much easier to trace workflows and debug issues in production environments.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Event Timestamp&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Events should record when the business action occurred, not when the event was received. These timestamps can differ due to network delays, retries, or temporary failures. Keeping business time separate from delivery time ensures accurate interpretation of events.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;8. Naming Events Consistently&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Naming may seem like a minor detail, but it becomes increasingly important as systems grow. Large organizations may produce hundreds of event types, and consistency helps maintain clarity and usability across teams.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Prefer Past-Tense Business Events&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Effective event names describe completed business actions:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;CustomerRegistered&lt;br&gt;
OrderConfirmed&lt;br&gt;
InventoryReserved&lt;br&gt;
PaymentCompleted&lt;br&gt;
ShipmentCreated&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;These names clearly communicate what has happened, making them easy for consumers to understand.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Avoid CRUD-Oriented Events&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Generic names such as:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;OrderUpdated&lt;br&gt;
CustomerModified&lt;br&gt;
ProductChanged&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;lack clarity. They do not explain what changed or why, forcing consumers to inspect the payload for meaning. Event names should convey intent directly.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Keep Names Business-Oriented&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Avoid technical or implementation-focused names:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;DatabaseUpdated&lt;br&gt;
RowInserted&lt;br&gt;
EntitySaved&lt;br&gt;
JpaEntityUpdated&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;These describe internal processes rather than business outcomes. Consumers care about what happened in the business domain, not how it was implemented.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;9. Common Schema Design Mistakes&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Despite differences in technology, many event-driven systems encounter similar design issues. Recognizing these common mistakes can help teams avoid long-term problems.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Publishing Internal Objects&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Internal models change frequently, while public contracts should remain stable. Mixing the two leads to fragile systems. Keeping them separate ensures better maintainability.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Making Events Too Generic&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;An event like: &lt;code&gt;OrderUpdated&lt;/code&gt; can represent many different actions, making it difficult for consumers to interpret. More specific events provide clearer intent:&lt;br&gt;
&lt;code&gt;OrderConfirmed&lt;br&gt;
OrderCancelled&lt;br&gt;
OrderRefunded&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;This clarity simplifies consumer logic and improves overall system understanding.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Missing Metadata&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Without essential metadata such as event identifiers, timestamps, and correlation IDs, troubleshooting becomes significantly harder. Operational concerns should be considered from the beginning of event design.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Designing for Today's Consumers&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Many producers design events based only on current consumers, overlooking future needs. A better approach is:&lt;/p&gt;

&lt;p&gt;Design events as though the next consumer has not been written yet.&lt;/p&gt;

&lt;p&gt;This mindset encourages more flexible and future-proof designs.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Practical Rule of Thumb&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Well-designed schemas remain clear and understandable long after they are introduced. They focus on business facts rather than implementation details, separate metadata from payload data, and provide sufficient context without unnecessary complexity.&lt;/p&gt;




&lt;p&gt;In the next part, we will explore schema evolution, event versioning, backward compatibility, and strategies that allow producers and consumers to evolve independently without disrupting production systems.&lt;/p&gt;

&lt;p&gt;Assisted AI to paraphrase the content. &lt;/p&gt;

</description>
      <category>eventdriven</category>
      <category>distributedsystems</category>
      <category>systemdesign</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Building Reliable Event-Driven Systems: Event Schemas, Versioning, Contract Testing and Events vs Commands (1/5)</title>
      <dc:creator>Venkatesan Ramar</dc:creator>
      <pubDate>Tue, 14 Jul 2026 05:00:00 +0000</pubDate>
      <link>https://dev.to/morpheus-vera/building-reliable-event-driven-systems-event-schemas-versioning-contract-testing-and-events-vs-37eg</link>
      <guid>https://dev.to/morpheus-vera/building-reliable-event-driven-systems-event-schemas-versioning-contract-testing-and-events-vs-37eg</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;As part-1 of a multi-part series, in this article we'll explore why and where event-driven systems fail and foundational concepts. &lt;/p&gt;
&lt;/blockquote&gt;




&lt;p&gt;Distributed systems have become considerably easier to build than they were a decade ago. Modern frameworks allow us to publish events with only a few lines of code, cloud platforms provide fully managed messaging services, and frameworks like Spring Boot makes asynchronous communication feel almost effortless. Because of this, many teams successfully adopt event-driven architectures. Unfortunately, publishing events is usually the easiest part of the journey. &lt;/p&gt;

&lt;p&gt;Designing events that remain reliable for years is considerably more difficult. Most production problems in event-driven systems are rarely caused by the messaging infrastructure itself. Instead, they originate from architectural questions such as: &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;What information an event should contain?&lt;/em&gt;&lt;br&gt;
&lt;em&gt;Whether an event schema can evolve without breaking existing consumers?&lt;/em&gt; &lt;br&gt;
&lt;em&gt;How new services safely consume old events?&lt;/em&gt; &lt;br&gt;
&lt;em&gt;When a service should publish an event instead of sending a command?&lt;/em&gt; &lt;br&gt;
&lt;em&gt;How producers can know they haven't broken downstream consumers?&lt;/em&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;These questions determine whether an event-driven system remains maintainable as more services, teams, and business capabilities are added. &lt;/p&gt;

&lt;p&gt;This article explores the practices that make event-driven systems resilient over time. We focus on the contracts that services exchange with each other. In event-driven architecture, events become public APIs, and unlike REST APIs, those APIs are usually consumed by systems the producer does not directly control. It makes compatibility one of the most important design concerns.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;1. Event-Driven Architecture Is Really About Contracts&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Many developers describe event-driven architecture as services communicating through events. That description is correct, but it is also incomplete. Events are more than messages moving between services—every published event represents a contract.&lt;/p&gt;

&lt;p&gt;Suppose an Order Service publishes the following event.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"orderId"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"ORD-1001"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"customerId"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"CUS-501"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"status"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"CONFIRMED"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"totalAmount"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mf"&gt;249.99&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Several services subscribe to it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;                 OrderConfirmed
                        |
        +---------------+---------------+
        |               |               |
        v               v               v
 Inventory Service  Billing Service  Notification Service
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The producer may know about three consumers today. Six months later, another team builds additional services such as Analytics, Recommendation, and Customer Loyalty. The producer does not need to change; the consumers simply subscribe. This loose coupling is one of the biggest strengths of event-driven systems, but it is also one of their biggest challenges.&lt;/p&gt;

&lt;p&gt;The producer no longer knows who depends on the event, which makes changing the event significantly more complicated than changing an internal Java object.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Events Are Public APIs&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Most teams treat REST APIs very carefully. Before removing a field, they consider existing clients, API versions, backward compatibility, and migration plans. Events deserve exactly the same level of discipline.&lt;/p&gt;

&lt;p&gt;Once an event is published, it becomes part of the public interface of the service. Removing a field from an event can break downstream systems just as easily as removing a field from a REST response. The difference is that consumers are often invisible. A REST API usually has documented clients, while an event may have consumers owned by completely different teams, some of which may not even exist when the producer is originally developed.&lt;/p&gt;

&lt;p&gt;Thinking of events as contracts fundamentally changes how they should be designed.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;2. Why Event Design Matters More Than Event Publishing&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Publishing an event is a technical task, but designing an event is an architectural task. Many event-driven projects begin with something like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Order&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;

    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;Long&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;Customer&lt;/span&gt; &lt;span class="n"&gt;customer&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;OrderItem&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;items&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;Address&lt;/span&gt; &lt;span class="n"&gt;shippingAddress&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The easiest approach is to serialize the entire object and publish it.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;eventPublisher.publish(order);&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;It works—until the domain model changes. A field gets renamed, an object is restructured, or a new relationship is introduced. Every consumer now receives a different payload. The producer evolved, but the contract changed accidentally.&lt;/p&gt;

&lt;p&gt;This is one of the most common mistakes in event-driven systems. Events should not expose internal domain models; they should communicate business facts. Those are two very different things.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;An Event Describes Something That Already Happened&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;A useful mental model is that a command asks for something to happen, while an event states that something already happened. For example:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;OrderConfirmed&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;This is a business fact. It cannot be rejected because it has already occurred. Similarly:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;PaymentCompleted&lt;br&gt;
InventoryReserved&lt;br&gt;
ShipmentCreated&lt;br&gt;
CustomerRegistered&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;All describe completed business actions. &lt;/p&gt;

&lt;p&gt;Consumers should be able to trust that these events represent facts. This makes event names extremely important. Good names communicate completed business outcomes, while poor names often expose implementation details. Compare the following examples:&lt;/p&gt;

&lt;p&gt;Good: &lt;code&gt;OrderConfirmed&lt;/code&gt;&lt;br&gt;
Poor: &lt;code&gt;UpdateOrderStatus&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;The first describes something that happened, while the second sounds like an &lt;em&gt;internal method call&lt;/em&gt;. This distinction becomes increasingly important as systems grow.&lt;/p&gt;



&lt;p&gt;&lt;strong&gt;3. Events Are Immutable&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;One characteristic separates events from many other forms of communication: events are immutable. Once published, an event represents history, and history cannot be rewritten.&lt;/p&gt;

&lt;p&gt;Imagine the following event:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"orderId"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"ORD-1001"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"status"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"CONFIRMED"&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Tomorrow, the customer cancels the order. The producer should not update the previous event. Instead, it publishes a new one:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"orderId"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"ORD-1001"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"status"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"CANCELLED"&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The event stream now tells a complete story:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;OrderCreated
      |
OrderConfirmed
      |
OrderCancelled
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Consumers joining later can reconstruct what happened. This is one of the reasons event-driven systems are valuable—events become an immutable business history. Changing previously published events destroys that history.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Events Represent Facts, Not State&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Another common misunderstanding is treating events as snapshots of current state. Consider this event:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"orderId"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"ORD-1001"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"status"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"PROCESSING"&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;Does it mean the order is currently processing, or that the order entered processing&lt;/em&gt;? These are different meanings.&lt;/p&gt;

&lt;p&gt;A better event would be: &lt;code&gt;OrderProcessingStarted&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;The name clearly communicates a business fact. Consumers no longer need to interpret the payload because the event itself explains what happened. As event catalogs grow, this principle becomes increasingly important. Well-designed event names reduce ambiguity, while poorly named events force consumers to infer business meaning.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;4. Events and Commands Are Not the Same&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This is one of the most misunderstood topics in event-driven architecture. Many teams use commands and events interchangeably, which creates tightly coupled systems. Understanding the difference changes how services communicate.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Commands Express Intent&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;A command represents a request where the sender expects another service to perform an action. &lt;/p&gt;

&lt;p&gt;For example:&lt;br&gt;
&lt;code&gt;ReserveInventory&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;The sender is asking, “Please reserve inventory.” The receiving service can accept it, reject it, validate it, or return an error. &lt;/p&gt;

&lt;p&gt;Commands imply responsibility—someone is expected to do something.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Events Express Facts&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;An event communicates that something has already happened. &lt;/p&gt;

&lt;p&gt;For example:&lt;br&gt;
&lt;code&gt;InventoryReserved&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;The reservation has already completed. Consumers cannot reject it; they simply react. This difference may appear subtle, but architecturally it is enormous. Commands influence behavior, while events communicate history.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Visualizing the Difference&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Command&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Order Service
      |
Reserve Inventory
      |
      v
Inventory Service
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The Order Service knows exactly who should process the request, making the communication directed.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Event&lt;/strong&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;InventoryReserved
        |
   +----+----+---------+
   |         |         |
   v         v         v
Billing   Shipping   Analytics
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The Inventory Service simply publishes a business fact. It does not know who reacts, and it does not need to. That is the essence of loose coupling.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;A Practical Rule of Thumb&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;One guideline that helps during system design reviews is simple: use a &lt;strong&gt;command&lt;/strong&gt; when &lt;em&gt;one specific service is responsible for performing an action&lt;/em&gt;, and use an &lt;strong&gt;event&lt;/strong&gt; when &lt;em&gt;informing any interested service that a business fact has already occurred&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;This distinction keeps responsibilities clear and prevents event-driven systems from gradually turning into distributed RPC systems disguised as messaging.&lt;/p&gt;




&lt;p&gt;In the next part, we will build on these foundations by designing event schemas that survive years of system evolution.&lt;/p&gt;

&lt;p&gt;Assisted AI to paraphrase. &lt;/p&gt;

</description>
      <category>eventdriven</category>
      <category>distributedsystems</category>
      <category>systemdesign</category>
      <category>tutorial</category>
    </item>
  </channel>
</rss>
