<?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: Ayush Soni</title>
    <description>The latest articles on DEV Community by Ayush Soni (@ayushwing).</description>
    <link>https://dev.to/ayushwing</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%2F4210786%2F105aad99-2265-499a-8c6f-fa58f937f3cb.png</url>
      <title>DEV Community: Ayush Soni</title>
      <link>https://dev.to/ayushwing</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/ayushwing"/>
    <language>en</language>
    <item>
      <title>Cache stampedes: when one expiring key takes down the database</title>
      <dc:creator>Ayush Soni</dc:creator>
      <pubDate>Sat, 05 Dec 2026 12:43:12 +0000</pubDate>
      <link>https://dev.to/ayushwing/cache-stampedes-when-one-expiring-key-takes-down-the-database-10j8</link>
      <guid>https://dev.to/ayushwing/cache-stampedes-when-one-expiring-key-takes-down-the-database-10j8</guid>
      <description>&lt;p&gt;A cache with a 99.8% hit rate can still take your database down.&lt;/p&gt;

&lt;p&gt;The usual pattern is cache-aside: check the cache, and on a miss, load from the database and store the result with a TTL. It works beautifully until your most popular key expires. In the next few milliseconds, every request for that key misses, and every one of them runs the same database query. A thousand identical queries arrive at once for data that was in memory a moment ago.&lt;/p&gt;

&lt;p&gt;That's a &lt;strong&gt;cache stampede&lt;/strong&gt;, also called dogpiling or a thundering herd. It has an unpleasant property: the busier the key, the bigger the stampede, so it happens exactly when you have the most traffic. It's a well-understood problem with well-understood fixes, and they combine nicely.&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%2F34irld8svd1xlt1i879s.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%2F34irld8svd1xlt1i879s.png" alt="A thousand requests for the same key arrive in the same second. Unprotected, all thousand miss the cache and send the same query to the database, which falls over. With single-flight and stale values, the cache returns a stale value with a refresh flag, 999 requests are served immediately from the stale value, and one lock holder queries the database once and stores the fresh value." width="800" height="544"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;Same traffic, one database query instead of a thousand. &lt;a href="https://ayushwing.com/diagrams/cache-stampede.html" rel="noopener noreferrer"&gt;Explore the interactive diagram&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Three ways to start a stampede
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;A hot key expires.&lt;/strong&gt; The classic case: one popular product page, one homepage query, one config value.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Many keys expire together.&lt;/strong&gt; Everything cached at deploy time with &lt;code&gt;TTL = 3600&lt;/code&gt; expires at the same moment an hour later. No single key is hot, but the database sees the entire working set at once.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;The cache starts empty.&lt;/strong&gt; A cache node restarts, someone flushes it, or you shift traffic to a new region with a cold cache. Now &lt;em&gt;every&lt;/em&gt; key is missing.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The fixes below address these in different combinations.&lt;/p&gt;
&lt;h2&gt;
  
  
  Fix 1: add jitter to TTLs
&lt;/h2&gt;

&lt;p&gt;The cheapest fix, for case 2. Instead of a fixed TTL, add randomness:&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;Duration&lt;/span&gt; &lt;span class="n"&gt;ttl&lt;/span&gt; &lt;span class="o"&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;ofMinutes&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;60&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;plusSeconds&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;ThreadLocalRandom&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;current&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;nextInt&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="mi"&gt;600&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;redis&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;opsForValue&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;set&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;value&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;ttl&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;Keys cached together now expire over a ten-minute window instead of in the same second. It does nothing for a single hot key, but it removes synchronised expiry entirely, and it costs one line.&lt;/p&gt;

&lt;h2&gt;
  
  
  Fix 2: single-flight loading
&lt;/h2&gt;

&lt;p&gt;When a key is missing, &lt;strong&gt;only one caller loads it&lt;/strong&gt;; everyone else waits for that result instead of starting their own load.&lt;/p&gt;

&lt;p&gt;Within one service instance, a good cache library does this for you. Caffeine's &lt;code&gt;get(key, loader)&lt;/code&gt; runs the loader once per key, and concurrent callers for the same key block on that one computation:&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;LoadingCache&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="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Product&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;products&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Caffeine&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;newBuilder&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;maximumSize&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;100_000&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;expireAfterWrite&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;ofMinutes&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;10&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;build&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="n"&gt;productRepository&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;load&lt;/span&gt;&lt;span class="p"&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="p"&gt;;&lt;/span&gt;   &lt;span class="c1"&gt;// one load per key at a time, per instance&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Across instances, you need a shared lock, typically in Redis. The caller that wins the lock loads and writes the value; the others wait briefly and read the cache again:&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="kt"&gt;Boolean&lt;/span&gt; &lt;span class="n"&gt;won&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;redis&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;opsForValue&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;setIfAbsent&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"lock:"&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;instanceId&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;5&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;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;Boolean&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;TRUE&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;equals&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;won&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="nc"&gt;Product&lt;/span&gt; &lt;span class="n"&gt;fresh&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;productRepository&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;load&lt;/span&gt;&lt;span class="p"&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="n"&gt;redis&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;opsForValue&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;set&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;fresh&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nf"&gt;ttlWithJitter&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;fresh&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="nf"&gt;waitForValue&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;key&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="c1"&gt;// poll briefly for the winner's write&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="n"&gt;productRepository&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;load&lt;/span&gt;&lt;span class="p"&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="p"&gt;;&lt;/span&gt;  &lt;span class="c1"&gt;// last resort if the winner died&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The lock needs a timeout, because the winner can crash. Per-instance single-flight alone already cuts a stampede from "one query per request" to "one query per instance", which is often enough.&lt;/p&gt;

&lt;h2&gt;
  
  
  Fix 3: serve stale while one caller refreshes
&lt;/h2&gt;

&lt;p&gt;Waiting is better than stampeding, but it still adds latency to every request during the refresh. Usually there's a better answer: &lt;strong&gt;the old value is fine for a few more seconds.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Store two times with each value: a &lt;em&gt;soft&lt;/em&gt; expiry when it should be refreshed, and a &lt;em&gt;hard&lt;/em&gt; expiry when it must not be served any more. Between the two, return the stale value immediately, and let exactly one caller (the lock winner) refresh it in the background.&lt;/p&gt;

&lt;p&gt;Caffeine has this built in as &lt;code&gt;refreshAfterWrite&lt;/code&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="nc"&gt;LoadingCache&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="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Product&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;products&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Caffeine&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;newBuilder&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;refreshAfterWrite&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;ofMinutes&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;    &lt;span class="c1"&gt;// soft: after 5 min, the next read triggers a background reload&lt;/span&gt;
        &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;expireAfterWrite&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;ofMinutes&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;30&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;    &lt;span class="c1"&gt;// hard: never serve anything older than 30 min&lt;/span&gt;
        &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;build&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="n"&gt;productRepository&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;load&lt;/span&gt;&lt;span class="p"&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="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Callers never wait on a refresh, and the database sees one query per key per refresh interval, regardless of traffic. HTTP has the same idea as the &lt;code&gt;stale-while-revalidate&lt;/code&gt; directive on &lt;code&gt;Cache-Control&lt;/code&gt;, which lets CDNs do it for you.&lt;/p&gt;

&lt;p&gt;The question to ask the product owner: &lt;strong&gt;how stale is acceptable?&lt;/strong&gt; For a product description, minutes. For a price during a sale, seconds. For an account balance, don't cache it this way at all.&lt;/p&gt;

&lt;h2&gt;
  
  
  Fix 4: refresh early, probabilistically
&lt;/h2&gt;

&lt;p&gt;Single-flight needs a lock. There's an elegant lock-free alternative, published as "Optimal Probabilistic Cache Stampede Prevention" (Vattani, Chierichetti and Lowenstein, 2015) and often called XFetch: each reader, before the value expires, decides at random whether to refresh it early, with a probability that rises sharply as expiry approaches.&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;// delta: how long the last recomputation took; beta &amp;gt; 1 refreshes earlier (1.0 is a good default)&lt;/span&gt;
&lt;span class="kt"&gt;boolean&lt;/span&gt; &lt;span class="nf"&gt;shouldRefreshEarly&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;long&lt;/span&gt; &lt;span class="n"&gt;expiresAtMillis&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;long&lt;/span&gt; &lt;span class="n"&gt;deltaMillis&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;double&lt;/span&gt; &lt;span class="n"&gt;beta&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="kt"&gt;double&lt;/span&gt; &lt;span class="n"&gt;jitter&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="n"&gt;deltaMillis&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;beta&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="nc"&gt;Math&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;ThreadLocalRandom&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;current&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;nextDouble&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="nc"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;currentTimeMillis&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;jitter&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;=&lt;/span&gt; &lt;span class="n"&gt;expiresAtMillis&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;With many readers, one of them almost always refreshes shortly before expiry, so the key effectively never expires under load, and no coordination is needed. Expensive values (large &lt;code&gt;delta&lt;/code&gt;) start refreshing earlier, which is exactly what you want.&lt;/p&gt;

&lt;h2&gt;
  
  
  Fix 5: warm before you shift traffic
&lt;/h2&gt;

&lt;p&gt;For case 3, the cold cache, none of the above is enough: every key is missing at once. So don't let it happen to live traffic:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Pre-load&lt;/strong&gt; the hot set (the top N keys from yesterday's access logs) before a new cache node or region takes traffic.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Shift traffic gradually&lt;/strong&gt;, so the cache fills while load is still small.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Protect the database anyway&lt;/strong&gt;: a limit on concurrent database queries per instance (a bulkhead) turns an overload into slower responses instead of a dead database. Some requests will wait; none will take the database down.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Which ones you need
&lt;/h2&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Situation&lt;/th&gt;
&lt;th&gt;Fix&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Many keys cached at the same time&lt;/td&gt;
&lt;td&gt;TTL jitter&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;A few very hot keys&lt;/td&gt;
&lt;td&gt;Single-flight, plus stale-while-revalidate&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;You can't hold locks, or don't want to&lt;/td&gt;
&lt;td&gt;Probabilistic early refresh&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Data can't be stale at all&lt;/td&gt;
&lt;td&gt;Single-flight with a short wait; or don't cache it&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Cache restarts, flushes, new regions&lt;/td&gt;
&lt;td&gt;Warming, gradual traffic shift, database bulkhead&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;In practice, most systems want &lt;strong&gt;jitter everywhere, per-instance single-flight by default, and stale-while-revalidate for the hottest keys&lt;/strong&gt;. That combination handles the large majority of stampedes with very little code.&lt;/p&gt;

&lt;h2&gt;
  
  
  Takeaways
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;A high hit rate doesn't protect you when a &lt;strong&gt;hot key expires&lt;/strong&gt;; the misses all arrive at once.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Jitter TTLs&lt;/strong&gt; so keys don't expire together.&lt;/li&gt;
&lt;li&gt;Use &lt;strong&gt;single-flight&lt;/strong&gt; loading, so one caller loads and the rest wait or share its result.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Serve stale while refreshing&lt;/strong&gt; wherever slightly old data is acceptable, and agree how old is acceptable.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Warm caches&lt;/strong&gt; before shifting traffic, and put a &lt;strong&gt;concurrency limit&lt;/strong&gt; in front of the database as the last line of defence.&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;&lt;em&gt;Originally published at &lt;a href="https://ayushwing.com/blog/cache-stampede" rel="noopener noreferrer"&gt;ayushwing.com&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>caching</category>
      <category>redis</category>
      <category>performance</category>
      <category>distributedsystems</category>
    </item>
    <item>
      <title>Distributed locks are leases: why you need fencing tokens</title>
      <dc:creator>Ayush Soni</dc:creator>
      <pubDate>Thu, 03 Dec 2026 06:21:40 +0000</pubDate>
      <link>https://dev.to/ayushwing/distributed-locks-are-leases-why-you-need-fencing-tokens-jh8</link>
      <guid>https://dev.to/ayushwing/distributed-locks-are-leases-why-you-need-fencing-tokens-jh8</guid>
      <description>&lt;p&gt;Here's how a distributed lock ends up held by two processes at once, with no bug in the lock itself:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Worker 1 acquires the lock, with a 10-second lease so that a crashed holder can't block everyone forever.&lt;/li&gt;
&lt;li&gt;Worker 1 pauses. A long garbage-collection pause, a virtual machine being migrated, a process swapped to disk, a slow network call. Fifteen seconds pass.&lt;/li&gt;
&lt;li&gt;The lease expires. Worker 2 acquires the lock and starts its work.&lt;/li&gt;
&lt;li&gt;Worker 1 resumes. From its point of view, no time has passed: it holds the lock. It carries on writing.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Two writers, one "exclusive" resource. Martin Kleppmann laid this out clearly in his 2016 essay on distributed locking, and it applies to every lock with a timeout, whichever store implements it: Redis, ZooKeeper, etcd, a database row.&lt;/p&gt;

&lt;p&gt;The underlying point: &lt;strong&gt;a distributed lock with a timeout is a lease&lt;/strong&gt;, and a lease can end without its holder finding out in time. Checking "do I still hold the lock?" before writing doesn't help, because the pause can happen between the check and the write.&lt;/p&gt;

&lt;h2&gt;
  
  
  The fix: fencing tokens
&lt;/h2&gt;

&lt;p&gt;Every time the lock service grants the lock, it also hands out a &lt;strong&gt;number that only ever increases&lt;/strong&gt;: the fencing token. The holder includes the token with every write to the protected resource, and &lt;strong&gt;the resource rejects any write whose token is lower than the highest it has already accepted.&lt;/strong&gt;&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%2F54kix2h7vzojnrrvif1v.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%2F54kix2h7vzojnrrvif1v.png" alt="Worker 1 acquires the lock with token 33 and a 10-second lease, then pauses for 15 seconds. The lease expires and worker 2 acquires the lock with token 34 and writes to storage, which records 34 as the highest token. Worker 1 wakes up and writes with token 33; storage rejects it because 33 is lower than 34." width="800" height="538"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;The lock can't stop a paused holder. The resource can. &lt;a href="https://ayushwing.com/diagrams/fencing-tokens.html" rel="noopener noreferrer"&gt;Explore the interactive diagram&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;The important shift is &lt;strong&gt;where the check happens&lt;/strong&gt;. The lock service can't stop a paused process from waking up and writing; only the thing being written to can. So the resource does the final check, at the moment of the write, which is the only moment that matters.&lt;/p&gt;
&lt;h2&gt;
  
  
  Where the token comes from
&lt;/h2&gt;

&lt;p&gt;You need a counter that increases with every grant:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;ZooKeeper&lt;/strong&gt;: the transaction id or the node's version number, or a sequential node, increases with every change.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;etcd&lt;/strong&gt;: the revision number of the lock key increases with every write.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;A database&lt;/strong&gt;: the lock is a row, and acquiring it increments a column in the same statement.
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="c1"&gt;-- acquire: succeeds only if the lease is free or expired; returns the new token&lt;/span&gt;
&lt;span class="k"&gt;UPDATE&lt;/span&gt; &lt;span class="n"&gt;locks&lt;/span&gt;
&lt;span class="k"&gt;SET&lt;/span&gt;    &lt;span class="n"&gt;holder&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="n"&gt;me&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;token&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;token&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;expires_at&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;now&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="kt"&gt;interval&lt;/span&gt; &lt;span class="s1"&gt;'10 seconds'&lt;/span&gt;
&lt;span class="k"&gt;WHERE&lt;/span&gt;  &lt;span class="n"&gt;name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s1"&gt;'invoice-run'&lt;/span&gt; &lt;span class="k"&gt;AND&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;holder&lt;/span&gt; &lt;span class="k"&gt;IS&lt;/span&gt; &lt;span class="kc"&gt;NULL&lt;/span&gt; &lt;span class="k"&gt;OR&lt;/span&gt; &lt;span class="n"&gt;expires_at&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="nb"&gt;now&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;RETURNING&lt;/span&gt; &lt;span class="n"&gt;token&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;A plain Redis &lt;code&gt;SET key value NX PX 10000&lt;/code&gt; gives you a lease but no ordered token. You can add one (an &lt;code&gt;INCR&lt;/code&gt; on a separate key in the same Lua script), but at that point consider whether a store with ordering built in is the better tool.&lt;/p&gt;
&lt;h2&gt;
  
  
  Where the check happens
&lt;/h2&gt;

&lt;p&gt;The resource has to remember the highest token it has accepted and compare. In a database, that's a conditional write:&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;UPDATE&lt;/span&gt; &lt;span class="n"&gt;invoice_runs&lt;/span&gt;
&lt;span class="k"&gt;SET&lt;/span&gt;    &lt;span class="n"&gt;status&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;last_token&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="n"&gt;token&lt;/span&gt;
&lt;span class="k"&gt;WHERE&lt;/span&gt;  &lt;span class="n"&gt;id&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt; &lt;span class="k"&gt;AND&lt;/span&gt; &lt;span class="n"&gt;last_token&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="n"&gt;token&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="c1"&gt;-- 0 rows updated: a newer lock holder has already written; stop&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For files or object storage, keep the last token alongside the data (in metadata, or a version field) and make the write conditional on it. Many object stores support conditional writes on a version or ETag, which you can build this on.&lt;/p&gt;

&lt;p&gt;If the resource &lt;strong&gt;can't&lt;/strong&gt; check tokens (a third-party API, an email being sent), a fencing token can't protect it. Then the operation itself has to be safe to do twice: an &lt;a href="https://ayushwing.com/blog/idempotency-keys" rel="noopener noreferrer"&gt;idempotency key&lt;/a&gt; the third party honours, or a record of "already sent" checked in the same transaction as the work.&lt;/p&gt;

&lt;h2&gt;
  
  
  Efficiency locks vs correctness locks
&lt;/h2&gt;

&lt;p&gt;Kleppmann's essay makes a distinction worth keeping:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Efficiency locks&lt;/strong&gt; stop two workers doing the same work twice, to save cost. If the lock occasionally fails, you waste some compute. A simple lease (one Redis key with a timeout) is fine.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Correctness locks&lt;/strong&gt; stop two workers corrupting data. If the lock fails, you get wrong data. These need fencing, or a design that doesn't depend on the lock at all.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Before choosing a lock implementation, decide which kind you have. Most arguments about locking algorithms are really disagreements about this.&lt;/p&gt;

&lt;h2&gt;
  
  
  Better still: don't need the lock
&lt;/h2&gt;

&lt;p&gt;Distributed locks are often a sign that the design could avoid them. Before adding one, check these:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Conditional writes.&lt;/strong&gt; "Update the order to SHIPPED only if it's PACKED" needs no lock; the database does the check atomically. (I wrote about this pattern in &lt;a href="https://ayushwing.com/blog/business-workflows-as-state-machines" rel="noopener noreferrer"&gt;Model business workflows as state machines&lt;/a&gt;.)&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;A single writer per key.&lt;/strong&gt; Partition the work so that only one consumer ever handles a given key. Kafka gives you this per partition: if every event for invoice 42 goes to the same partition, one consumer processes them in order, without a lock. During a consumer group rebalance, ownership moves, so writes still need to be idempotent.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Database row locks.&lt;/strong&gt; If the resource lives in the same database, &lt;code&gt;SELECT … FOR UPDATE&lt;/code&gt; inside a transaction is a lock with the right failure behaviour: if the holder dies, the transaction ends and the lock goes with it.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;A workflow engine.&lt;/strong&gt; For long-running "only one of these at a time" processes, a durable workflow keyed by the business id (one workflow per invoice run) gives you exclusivity and recovery without a separate lock. See &lt;a href="https://ayushwing.com/blog/durable-workflows-vs-queue-and-cron" rel="noopener noreferrer"&gt;Durable workflows vs. a queue and a cron job&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Checklist
&lt;/h2&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Question&lt;/th&gt;
&lt;th&gt;If yes&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Is the lock only to avoid duplicate work?&lt;/td&gt;
&lt;td&gt;A simple lease is enough&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Would two holders corrupt data?&lt;/td&gt;
&lt;td&gt;Fencing tokens, checked by the resource&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Can the resource check a token?&lt;/td&gt;
&lt;td&gt;Conditional write on the last token&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Can't it?&lt;/td&gt;
&lt;td&gt;Make the operation idempotent instead&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Is the resource in the same database?&lt;/td&gt;
&lt;td&gt;Use a row lock or a conditional update instead&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Can work be partitioned by key?&lt;/td&gt;
&lt;td&gt;Single writer per key, no lock&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;h2&gt;
  
  
  Takeaways
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;A distributed lock with a timeout is a &lt;strong&gt;lease&lt;/strong&gt;, and it can expire while the holder is &lt;strong&gt;paused&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;Checking the lock before writing doesn't help; the pause can come &lt;strong&gt;after&lt;/strong&gt; the check.&lt;/li&gt;
&lt;li&gt;Use &lt;strong&gt;fencing tokens&lt;/strong&gt;: increasing numbers per grant, checked &lt;strong&gt;by the resource&lt;/strong&gt; on every write.&lt;/li&gt;
&lt;li&gt;Know whether you need an &lt;strong&gt;efficiency&lt;/strong&gt; lock or a &lt;strong&gt;correctness&lt;/strong&gt; lock.&lt;/li&gt;
&lt;li&gt;Prefer designs that need &lt;strong&gt;no distributed lock&lt;/strong&gt;: conditional writes, single writers per key, row locks, workflows.&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;&lt;em&gt;Originally published at &lt;a href="https://ayushwing.com/blog/fencing-tokens" rel="noopener noreferrer"&gt;ayushwing.com&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>distributedsystems</category>
      <category>concurrency</category>
      <category>redis</category>
      <category>architecture</category>
    </item>
    <item>
      <title>Unique IDs at scale: auto-increment, UUIDv4, UUIDv7 and Snowflake</title>
      <dc:creator>Ayush Soni</dc:creator>
      <pubDate>Mon, 30 Nov 2026 08:58:42 +0000</pubDate>
      <link>https://dev.to/ayushwing/unique-ids-at-scale-auto-increment-uuidv4-uuidv7-and-snowflake-3jba</link>
      <guid>https://dev.to/ayushwing/unique-ids-at-scale-auto-increment-uuidv4-uuidv7-and-snowflake-3jba</guid>
      <description>&lt;p&gt;Choosing an ID format feels like a five-minute decision, and it usually gets five minutes. Then, a few years later, it turns out to have decided how fast your inserts are, whether you can split the database, what your URLs tell competitors, and how easy it is to find things during an incident.&lt;/p&gt;

&lt;p&gt;This is a solved problem: there are four well-understood answers, each with a clear sweet spot. Here's how to pick.&lt;/p&gt;

&lt;h2&gt;
  
  
  What we want from an ID
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Unique&lt;/strong&gt;, obviously, including across services and regions.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Generated without coordination&lt;/strong&gt;, so creating a record doesn't need a round trip to a central counter.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Index-friendly&lt;/strong&gt;: new IDs should land near each other in a B-tree index, not scattered randomly.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Roughly time-ordered&lt;/strong&gt;, which helps indexes and makes "what happened around then?" easy.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Compact&lt;/strong&gt; enough for your storage and your keys.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Safe to show&lt;/strong&gt; to users without leaking business information.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;No option is best at all six. That's why there are four options.&lt;/p&gt;

&lt;h2&gt;
  
  
  Option 1: database sequences (auto-increment)
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;BIGSERIAL&lt;/code&gt;, &lt;code&gt;AUTO_INCREMENT&lt;/code&gt;, &lt;code&gt;IDENTITY&lt;/code&gt;. The database hands out 1, 2, 3…&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Good:&lt;/strong&gt; compact (64 bits), perfectly ordered, ideal for indexes, and easy to read in a log.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bad:&lt;/strong&gt; the database is the coordinator, so you can't create an ID before talking to it, and two databases (after a split, or in two regions) produce clashing IDs. And they &lt;strong&gt;leak&lt;/strong&gt;: if a customer sees &lt;code&gt;order #109847&lt;/code&gt; at the end of March and &lt;code&gt;#104312&lt;/code&gt; at the start, they know you took about 5,500 orders that month. So does any competitor willing to buy from you twice.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Use it for:&lt;/strong&gt; internal keys inside a single database, never shown to users. That's still most tables in most systems, and it's a fine choice there.&lt;/p&gt;

&lt;h2&gt;
  
  
  Option 2: random UUIDs (UUIDv4)
&lt;/h2&gt;

&lt;p&gt;122 random bits. Any service can generate one, anywhere, with no coordination, and collisions are not a practical concern.&lt;/p&gt;

&lt;p&gt;The cost shows up in the database. Each new UUIDv4 lands at a &lt;strong&gt;random position in the primary key index&lt;/strong&gt;. On a large table, inserts touch pages all over the index instead of the same few "hot" pages at the end, which means more page splits, more cache misses and more disk I/O as the table grows. The bigger the table, the more you feel it. They're also 128 bits, twice the size of a &lt;code&gt;BIGINT&lt;/code&gt;, in every index and every foreign key.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Use it for:&lt;/strong&gt; identifiers that don't sit in a large B-tree index (idempotency keys, correlation IDs, tokens), or small tables where it doesn't matter.&lt;/p&gt;

&lt;h2&gt;
  
  
  Option 3: time-ordered UUIDs (UUIDv7)
&lt;/h2&gt;

&lt;p&gt;UUIDv7, standardised in RFC 9562 in 2024, keeps the UUID format but puts a &lt;strong&gt;millisecond timestamp in the first 48 bits&lt;/strong&gt; and fills the rest with random bits. You get the coordination-free generation of UUIDv4, and IDs created around the same time sort next to each other, so inserts go to the end of the index like a sequence.&lt;/p&gt;

&lt;p&gt;Generating one by hand is a few lines:&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;private&lt;/span&gt; &lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;SecureRandom&lt;/span&gt; &lt;span class="no"&gt;RANDOM&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;SecureRandom&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;static&lt;/span&gt; &lt;span class="no"&gt;UUID&lt;/span&gt; &lt;span class="nf"&gt;uuidV7&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="kt"&gt;long&lt;/span&gt; &lt;span class="n"&gt;millis&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;currentTimeMillis&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="kt"&gt;long&lt;/span&gt; &lt;span class="n"&gt;msb&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;millis&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="mi"&gt;16&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;                 &lt;span class="c1"&gt;// 48-bit Unix timestamp in milliseconds&lt;/span&gt;
             &lt;span class="o"&gt;|&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mh"&gt;0x7&lt;/span&gt;&lt;span class="no"&gt;L&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="mi"&gt;12&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;                   &lt;span class="c1"&gt;// version 7&lt;/span&gt;
             &lt;span class="o"&gt;|&lt;/span&gt; &lt;span class="no"&gt;RANDOM&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;nextInt&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="mi"&gt;12&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;       &lt;span class="c1"&gt;// 12 random bits&lt;/span&gt;
    &lt;span class="kt"&gt;long&lt;/span&gt; &lt;span class="n"&gt;lsb&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="no"&gt;RANDOM&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;nextLong&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;amp;&lt;/span&gt; &lt;span class="mh"&gt;0x3FFF_FFFF_FFFF_FFFF&lt;/span&gt;&lt;span class="no"&gt;L&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
             &lt;span class="o"&gt;|&lt;/span&gt; &lt;span class="mh"&gt;0x8000_0000_0000_0000&lt;/span&gt;&lt;span class="no"&gt;L&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;        &lt;span class="c1"&gt;// RFC variant bits&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="no"&gt;UUID&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;msb&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;lsb&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;In production, prefer a maintained library or your database's built-in generator if it has one; they handle details such as ordering within the same millisecond.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The trade-off:&lt;/strong&gt; the creation time is readable from the ID. That's usually fine, and occasionally useful in debugging. If the creation time is sensitive, don't expose the ID (see below).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Use it for:&lt;/strong&gt; primary keys in new systems with more than one writer. It's my default.&lt;/p&gt;

&lt;h2&gt;
  
  
  Option 4: Snowflake-style IDs
&lt;/h2&gt;

&lt;p&gt;Twitter published this design in 2010, and many systems use variations of it: a &lt;strong&gt;64-bit&lt;/strong&gt; integer made of a timestamp, a worker number and a per-worker sequence:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;| 41 bits: ms since a custom epoch | 10 bits: worker id | 12 bits: sequence |
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That's about 69 years of timestamps, 1,024 workers, and 4,096 IDs per millisecond per worker. You get time order and coordination-free generation in half the space of a UUID.&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;synchronized&lt;/span&gt; &lt;span class="kt"&gt;long&lt;/span&gt; &lt;span class="nf"&gt;nextId&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="kt"&gt;long&lt;/span&gt; &lt;span class="n"&gt;now&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;currentTimeMillis&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="no"&gt;EPOCH&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;now&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;lastMillis&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;throw&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;IllegalStateException&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Clock moved backwards; refusing to issue IDs"&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;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;now&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;lastMillis&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;sequence&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sequence&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt; &lt;span class="mh"&gt;0xFFF&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sequence&lt;/span&gt; &lt;span class="o"&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;span class="c1"&gt;// 4,096 used this millisecond: wait for the next&lt;/span&gt;
            &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;now&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;currentTimeMillis&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="no"&gt;EPOCH&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&lt;/span&gt; &lt;span class="n"&gt;lastMillis&lt;/span&gt;&lt;span class="p"&gt;)&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;onSpinWait&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;span class="k"&gt;else&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;sequence&lt;/span&gt; &lt;span class="o"&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;span class="n"&gt;lastMillis&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;now&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;now&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="mi"&gt;22&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;|&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;workerId&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="mi"&gt;12&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;|&lt;/span&gt; &lt;span class="n"&gt;sequence&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 space saving costs two operational problems that UUIDs don't have:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Worker IDs must be unique.&lt;/strong&gt; Two instances with the same worker ID can generate the same ID. You need a way to assign them: a lease in a coordination service, a database row each instance claims at startup, or the pod's ordinal in a stateful set.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Clocks go backwards.&lt;/strong&gt; NTP corrections and virtual machine migrations happen. The generator has to detect it and wait or refuse; it must never reuse a timestamp.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Use it for:&lt;/strong&gt; when IDs must be 64-bit integers: an existing &lt;code&gt;BIGINT&lt;/code&gt; schema, very large tables where 128-bit keys are too costly, or systems that need IDs to be sortable as numbers.&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%2Frb6r7s1sd3rtiqq4ta6r.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%2Frb6r7s1sd3rtiqq4ta6r.png" alt="A decision flow. If only one database writes the entity, use a database sequence, and if the ID is shown to users, expose an opaque public ID instead. If many writers create IDs and they must fit in 64 bits, use Snowflake-style IDs. Otherwise use UUIDv7." width="800" height="399"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;Two questions decide most cases. &lt;a href="https://ayushwing.com/diagrams/choose-an-id.html" rel="noopener noreferrer"&gt;Explore the interactive diagram&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  The rule that removes most of the dilemma
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;The ID in your database and the ID in your URL don't have to be the same thing.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Keep an efficient internal key (a sequence or UUIDv7) for joins and indexes, and give anything a user can see a separate, &lt;strong&gt;opaque public ID&lt;/strong&gt;: a random string, or an encoded form of the internal key that can't be reversed. Then you can choose the internal key purely for performance, and the public ID purely for privacy. You also stop users guessing neighbouring IDs, which makes some authorization bugs harder to exploit. (It doesn't replace the authorization check; I wrote about that in &lt;a href="https://ayushwing.com/blog/idor-object-level-authorization" rel="noopener noreferrer"&gt;IDOR: the most common API bug&lt;/a&gt;.)&lt;/p&gt;

&lt;h2&gt;
  
  
  Side by side
&lt;/h2&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;&lt;/th&gt;
&lt;th&gt;Sequence&lt;/th&gt;
&lt;th&gt;UUIDv4&lt;/th&gt;
&lt;th&gt;UUIDv7&lt;/th&gt;
&lt;th&gt;Snowflake-style&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Size&lt;/td&gt;
&lt;td&gt;64 bits&lt;/td&gt;
&lt;td&gt;128 bits&lt;/td&gt;
&lt;td&gt;128 bits&lt;/td&gt;
&lt;td&gt;64 bits&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Needs coordination&lt;/td&gt;
&lt;td&gt;Yes (the database)&lt;/td&gt;
&lt;td&gt;No&lt;/td&gt;
&lt;td&gt;No&lt;/td&gt;
&lt;td&gt;Worker IDs only&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Index-friendly inserts&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;td&gt;No&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Time-ordered&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;td&gt;No&lt;/td&gt;
&lt;td&gt;Roughly (ms)&lt;/td&gt;
&lt;td&gt;Roughly (ms)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Safe to show users&lt;/td&gt;
&lt;td&gt;No (leaks volume)&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;td&gt;Mostly (leaks time)&lt;/td&gt;
&lt;td&gt;Mostly (leaks time)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Operational risk&lt;/td&gt;
&lt;td&gt;Database is the bottleneck&lt;/td&gt;
&lt;td&gt;Index growth on big tables&lt;/td&gt;
&lt;td&gt;Low&lt;/td&gt;
&lt;td&gt;Clock and worker ID bugs&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;h2&gt;
  
  
  Takeaways
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Inside &lt;strong&gt;one database&lt;/strong&gt;, a sequence is still a great primary key. Just don't show it to users.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;UUIDv4 scatters inserts&lt;/strong&gt; across the index; it's fine for tokens and keys, poor for big tables.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;UUIDv7&lt;/strong&gt; gives coordination-free, time-ordered IDs. It's a sensible default for new systems.&lt;/li&gt;
&lt;li&gt;Use &lt;strong&gt;Snowflake-style&lt;/strong&gt; IDs when you need 64 bits, and budget for worker IDs and clock handling.&lt;/li&gt;
&lt;li&gt;Separate the &lt;strong&gt;internal key&lt;/strong&gt; from the &lt;strong&gt;public ID&lt;/strong&gt;, and most of the trade-offs disappear.&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;&lt;em&gt;Originally published at &lt;a href="https://ayushwing.com/blog/unique-ids-at-scale" rel="noopener noreferrer"&gt;ayushwing.com&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>distributedsystems</category>
      <category>database</category>
      <category>java</category>
      <category>architecture</category>
    </item>
    <item>
      <title>Tech debt as a portfolio: how to get it paid down</title>
      <dc:creator>Ayush Soni</dc:creator>
      <pubDate>Fri, 27 Nov 2026 17:44:03 +0000</pubDate>
      <link>https://dev.to/ayushwing/tech-debt-as-a-portfolio-how-to-get-it-paid-down-15p8</link>
      <guid>https://dev.to/ayushwing/tech-debt-as-a-portfolio-how-to-get-it-paid-down-15p8</guid>
      <description>&lt;p&gt;Every engineering team has tech debt, and almost every team has tried to get time to fix it with some version of: &lt;em&gt;"We need a refactor sprint."&lt;/em&gt; It rarely works. Not because leaders don't care about code quality, but because the request doesn't tell them what they're buying.&lt;/p&gt;

&lt;p&gt;The framing that works treats debt the way finance does: as a portfolio, where each item has a &lt;strong&gt;principal&lt;/strong&gt; and an &lt;strong&gt;interest rate&lt;/strong&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Principal and interest
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Principal&lt;/strong&gt; is what it would cost to fix: engineer-weeks, risk, coordination.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Interest&lt;/strong&gt; is what it costs you &lt;strong&gt;every week you don't&lt;/strong&gt;: slower delivery, incidents, on-call load, onboarding time, blocked features.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Ugly code with no interest — a messy module nobody touches — isn't urgent, however much it offends you. Clean-looking code with high interest — a configuration system that causes a production issue every month — is.&lt;/p&gt;

&lt;p&gt;The picture at the end of this post is a joke, but the iceberg is real: the debt you can see is rarely the debt that costs you most, and a shortcut taken once keeps charging interest every time someone works around it.&lt;/p&gt;

&lt;h2&gt;
  
  
  Classify what you have
&lt;/h2&gt;

&lt;p&gt;Not all debt is the same kind of problem:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Kind&lt;/th&gt;
&lt;th&gt;Example&lt;/th&gt;
&lt;th&gt;Typical interest&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Design debt&lt;/td&gt;
&lt;td&gt;Two services share a database table&lt;/td&gt;
&lt;td&gt;Every schema change needs two teams&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Code debt&lt;/td&gt;
&lt;td&gt;A 3,000-line class everyone fears to touch&lt;/td&gt;
&lt;td&gt;Slow changes, regressions&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Test debt&lt;/td&gt;
&lt;td&gt;No tests around billing&lt;/td&gt;
&lt;td&gt;Fear-driven releases, manual QA&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Operational debt&lt;/td&gt;
&lt;td&gt;Manual steps in deploys or migrations&lt;/td&gt;
&lt;td&gt;Toil, human error, slow recovery&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Dependency debt&lt;/td&gt;
&lt;td&gt;Framework or runtime versions near end of support&lt;/td&gt;
&lt;td&gt;Security exposure, a forced upgrade later at a worse time&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Knowledge debt&lt;/td&gt;
&lt;td&gt;One person understands the payment reconciliation job&lt;/td&gt;
&lt;td&gt;Risk concentrated in one calendar&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Unfinished migrations&lt;/td&gt;
&lt;td&gt;Old and new paths both live behind flags&lt;/td&gt;
&lt;td&gt;Double maintenance forever&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;h2&gt;
  
  
  Measure the interest
&lt;/h2&gt;

&lt;p&gt;You don't need precision; you need evidence. Good sources:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Lead time&lt;/strong&gt;: how long changes to this area take compared with others.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Incidents&lt;/strong&gt;: how many recent incidents involved this area.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Toil&lt;/strong&gt;: hours per week spent on manual work it causes.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Blocked work&lt;/strong&gt;: features on the roadmap that are slower or impossible because of it.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Developer surveys&lt;/strong&gt;: "which part of the codebase slows you down most?" is a surprisingly accurate signal.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;One concrete sentence beats a page of adjectives: &lt;em&gt;"Every release needs 2 engineer-days of manual config changes across 14 services, and 3 of the last 10 incidents were config mistakes."&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Keep a register
&lt;/h2&gt;

&lt;p&gt;A simple debt register — a table, not a tool — makes debt visible and comparable:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Item&lt;/th&gt;
&lt;th&gt;Kind&lt;/th&gt;
&lt;th&gt;Interest (evidence)&lt;/th&gt;
&lt;th&gt;Principal&lt;/th&gt;
&lt;th&gt;Next feature that touches it&lt;/th&gt;
&lt;th&gt;Owner&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Shared &lt;code&gt;orders&lt;/code&gt; table&lt;/td&gt;
&lt;td&gt;Design&lt;/td&gt;
&lt;td&gt;2 teams per schema change; 1 incident/quarter&lt;/td&gt;
&lt;td&gt;6 weeks&lt;/td&gt;
&lt;td&gt;Order history API&lt;/td&gt;
&lt;td&gt;Payments team&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Manual release config&lt;/td&gt;
&lt;td&gt;Operational&lt;/td&gt;
&lt;td&gt;2 eng-days per release&lt;/td&gt;
&lt;td&gt;2 weeks&lt;/td&gt;
&lt;td&gt;—&lt;/td&gt;
&lt;td&gt;Platform&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Billing tests&lt;/td&gt;
&lt;td&gt;Test&lt;/td&gt;
&lt;td&gt;1 regression/month&lt;/td&gt;
&lt;td&gt;3 weeks&lt;/td&gt;
&lt;td&gt;Tax changes in Q1&lt;/td&gt;
&lt;td&gt;Billing&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Review it quarterly, with product in the room. It turns "engineering complaining about code" into a shared list of business costs.&lt;/p&gt;

&lt;h2&gt;
  
  
  Pay down in the right order
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;High interest, low principal first.&lt;/strong&gt; Quick wins that remove recurring pain build trust for the bigger items.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Debt on the critical path of the roadmap next.&lt;/strong&gt; If the next three features all go through the same module, cleaning it is the fastest way to deliver them.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Leave the rest.&lt;/strong&gt; Low-interest debt can wait indefinitely. Some of it will disappear when the code is retired.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Bundle it with work people already want
&lt;/h2&gt;

&lt;p&gt;The most reliable way to get debt paid isn't a separate "debt sprint". It's &lt;strong&gt;bundling&lt;/strong&gt;: fix the debt in the area where a feature is being built, and estimate it as part of the feature.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;"Adding partial refunds to the wallet takes three weeks. Two of those weeks move the wallet to a proper ledger table. After that, the next four wallet features are days each instead of weeks."&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;That's a business case, not a request for permission. A standing allocation (many teams reserve 15–20% of capacity for engineering health) works well alongside it, for the items no feature will touch.&lt;/p&gt;

&lt;h2&gt;
  
  
  Stop creating it silently
&lt;/h2&gt;

&lt;p&gt;Some debt is a good decision: shipping a shortcut to meet a real deadline is often right. The problem is debt taken &lt;strong&gt;silently&lt;/strong&gt;. When you take a shortcut on purpose, add it to the register the same day, with the interest you expect and when you plan to pay it. Deliberate, recorded debt is a tool; forgotten debt is a trap.&lt;/p&gt;

&lt;h2&gt;
  
  
  Takeaways
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Describe debt by &lt;strong&gt;interest&lt;/strong&gt; (what it costs every week), not by how ugly the code is.&lt;/li&gt;
&lt;li&gt;Keep a &lt;strong&gt;register&lt;/strong&gt; with evidence, principal and owners; review it with product.&lt;/li&gt;
&lt;li&gt;Pay &lt;strong&gt;high-interest, low-principal&lt;/strong&gt; items first, then debt on the &lt;strong&gt;roadmap's critical path&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Bundle&lt;/strong&gt; paydown with features that touch the same code.&lt;/li&gt;
&lt;li&gt;When you take on debt deliberately, &lt;strong&gt;write it down that day&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;&lt;em&gt;Originally published at &lt;a href="https://ayushwing.com/blog/tech-debt-as-a-portfolio" rel="noopener noreferrer"&gt;ayushwing.com&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>techdebt</category>
      <category>engineeringmanagement</category>
      <category>career</category>
      <category>softwareengineering</category>
    </item>
    <item>
      <title>Self-serve platforms: turn your team from a queue into a product</title>
      <dc:creator>Ayush Soni</dc:creator>
      <pubDate>Wed, 25 Nov 2026 11:20:34 +0000</pubDate>
      <link>https://dev.to/ayushwing/self-serve-platforms-turn-your-team-from-a-queue-into-a-product-54l3</link>
      <guid>https://dev.to/ayushwing/self-serve-platforms-turn-your-team-from-a-queue-into-a-product-54l3</guid>
      <description>&lt;p&gt;Platform and infrastructure teams often end up as a queue. Other teams need an environment, a database, a migration, an access change; they file a ticket; someone on the platform team does it by hand. As the company grows, the queue grows faster than the team, and the platform team becomes the bottleneck for everyone — however hard it works.&lt;/p&gt;

&lt;p&gt;I've built self-serve tooling that let a team handle a multiple of its previous request volume without adding people. The tooling itself wasn't the hard part. Choosing what to automate, making it safe for non-experts, and proving it worked were.&lt;/p&gt;

&lt;h2&gt;
  
  
  1. Find the requests worth automating
&lt;/h2&gt;

&lt;p&gt;Export the last three months of tickets and group them. You're looking for requests that are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Frequent&lt;/strong&gt;: weekly or more.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Repetitive&lt;/strong&gt;: the same steps each time, with a few parameters.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Well understood&lt;/strong&gt;: you have a runbook, or could write one in an afternoon.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Waiting-heavy&lt;/strong&gt;: the requester waits days for a task that takes minutes of actual work.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The top two or three categories usually account for a large share of the queue. Start there. Don't automate the rare, gnarly requests first; they're where human judgment still pays.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. Turn the runbook into steps
&lt;/h2&gt;

&lt;p&gt;Before building any UI, turn the manual runbook into explicit steps, each with:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;A precondition check&lt;/strong&gt;: is it safe to start? (Quota available, target healthy, no conflicting operation running.)&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;An action&lt;/strong&gt;, made idempotent so it can be retried.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;A verification&lt;/strong&gt;: did it actually work?&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;A rollback&lt;/strong&gt;: how to undo it if a later step fails.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This is the core of the product. The interface — CLI, web form, API, chat command — is a thin layer on top, and you may end up offering more than one. For long-running, multi-step operations, a durable workflow engine is a natural backbone (see &lt;a href="https://ayushwing.com/blog/durable-workflows-vs-queue-and-cron" rel="noopener noreferrer"&gt;Durable workflows vs. a queue and a cron job&lt;/a&gt;).&lt;/p&gt;

&lt;h2&gt;
  
  
  3. Guardrails let non-experts press the button
&lt;/h2&gt;

&lt;p&gt;The reason requests come to experts is that experts know what &lt;em&gt;not&lt;/em&gt; to do. Self-serve needs that knowledge encoded:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Guardrail&lt;/th&gt;
&lt;th&gt;Example&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Validation&lt;/td&gt;
&lt;td&gt;Reject a request with an unsupported size or region before anything runs&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Pre-flight checks&lt;/td&gt;
&lt;td&gt;Refuse to start if the target is unhealthy or a conflicting job is running&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Dry run&lt;/td&gt;
&lt;td&gt;Show exactly what will change before it changes&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Limits&lt;/td&gt;
&lt;td&gt;Cap how much one request can do (number of resources, data volume)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Approvals for risky cases&lt;/td&gt;
&lt;td&gt;Routine requests run immediately; unusual ones route to a human&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Rollback&lt;/td&gt;
&lt;td&gt;One clear action to undo, available to the requester&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;The approval row matters most. You don't have to make &lt;strong&gt;every&lt;/strong&gt; case self-serve. Making the routine 80% instant, and routing the risky 20% to an expert with all the context already collected, is a huge improvement on 100% manual.&lt;/p&gt;

&lt;h2&gt;
  
  
  4. Status people can see without asking
&lt;/h2&gt;

&lt;p&gt;Half of the messages a platform team receives are "is my request done yet?". Every self-serve operation should have a status page (or command) showing: current step, what's done, what's next, and — if it failed — why, in plain language, with the next action. If the requester has to ask you to interpret an error, that error message is a bug.&lt;/p&gt;

&lt;h2&gt;
  
  
  5. Measure whether it worked
&lt;/h2&gt;

&lt;p&gt;Pick a few numbers and track them from before you start:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Self-serve rate&lt;/strong&gt;: % of requests of this type completed without a platform engineer touching them.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Lead time&lt;/strong&gt;: request to done, before vs. after.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Failure and rollback rate&lt;/strong&gt;: are guardrails catching problems, or are people stuck?&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Platform team time&lt;/strong&gt;: hours per week spent on this request type.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The self-serve rate is the honest one. A tool that still needs a Slack message to the platform team to work isn't self-serve; it's a ticket with a nicer form.&lt;/p&gt;

&lt;h2&gt;
  
  
  6. Treat it as a product
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Talk to users&lt;/strong&gt;: the teams filing requests know where the tool confuses them.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Write docs&lt;/strong&gt; for the requester's task ("how to get a new environment"), not for your internals.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Version and announce&lt;/strong&gt; changes, as you would for any API.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Retire&lt;/strong&gt; the old manual path, so there's one way to do it.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Takeaways
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Automate the &lt;strong&gt;frequent, repetitive, well-understood&lt;/strong&gt; requests first.&lt;/li&gt;
&lt;li&gt;Build each operation from &lt;strong&gt;precondition, action, verification, rollback&lt;/strong&gt; steps.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Guardrails and approvals&lt;/strong&gt; are what let non-experts run it safely.&lt;/li&gt;
&lt;li&gt;Give requesters &lt;strong&gt;visible status&lt;/strong&gt; and readable errors.&lt;/li&gt;
&lt;li&gt;Measure the &lt;strong&gt;self-serve rate&lt;/strong&gt;; it's the number that tells you whether you're still a queue.&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;&lt;em&gt;Originally published at &lt;a href="https://ayushwing.com/blog/self-serve-platforms" rel="noopener noreferrer"&gt;ayushwing.com&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>platformengineering</category>
      <category>devops</category>
      <category>devrel</category>
      <category>leadership</category>
    </item>
    <item>
      <title>Three small tools, three lessons</title>
      <dc:creator>Ayush Soni</dc:creator>
      <pubDate>Tue, 24 Nov 2026 17:14:48 +0000</pubDate>
      <link>https://dev.to/ayushwing/three-small-tools-three-lessons-29d9</link>
      <guid>https://dev.to/ayushwing/three-small-tools-three-lessons-29d9</guid>
      <description>&lt;p&gt;Not every project needs to be a platform. Some of the most useful lessons I've learned came from small tools built in an evening to solve one problem. Here are three from my GitHub, and the lesson each one taught me.&lt;/p&gt;

&lt;h2&gt;
  
  
  1. The vaccine-slot checker: ship the thin slice
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href="https://github.com/ayushwing/cowin-vaccine-availability" rel="noopener noreferrer"&gt;cowin-vaccine-availability&lt;/a&gt; · Java 11, Spring Boot 2.5 · 2021&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;During India's COVID-19 vaccination drive in 2021, booking a slot on the CoWIN portal was a race. Slots appeared and were gone within seconds, and there was no notification — you refreshed and hoped. The plan was simple: poll the public CoWIN API for my district and raise an alarm the moment a slot opened.&lt;/p&gt;

&lt;p&gt;The version in the repository is deliberately the first slice of that plan: a Spring Boot app with one service that calls the public &lt;code&gt;calendarByDistrict&lt;/code&gt; endpoint and returns the raw response through a REST endpoint.&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;UriComponentsBuilder&lt;/span&gt; &lt;span class="n"&gt;builder&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;UriComponentsBuilder&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;fromHttpUrl&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;cowinUri&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;queryParam&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"district_id"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;districtId&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;queryParam&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"date"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;date&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="nc"&gt;HttpEntity&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;Object&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;response&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;restTemplate&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;exchange&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="n"&gt;builder&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;toUriString&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="nc"&gt;HttpMethod&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;GET&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;entity&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;Object&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;class&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;It returns &lt;code&gt;Object&lt;/code&gt;, with a &lt;code&gt;// TODO: replace with object&lt;/code&gt; above it. That looks lazy, and in a production codebase it would be. But for a first slice it is the right call: before modelling a response, look at it — which fields are always present, how capacity is split by dose and age group, what an empty day looks like. Later, community Telegram bots did this at scale and better, and that was fine: the problem got solved.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The lesson:&lt;/strong&gt; build the thinnest slice that touches the real system, look at what comes back, then design. On large projects this is the difference between a migration plan built on assumptions and one built on what the data actually looks like.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. The WebSocket chat: anything free can disappear
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href="https://github.com/ayushwing/spark-websocket-chat" rel="noopener noreferrer"&gt;spark-websocket-chat&lt;/a&gt; · Java, Spark Java, Jetty WebSockets&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A group chat on the lightweight Spark Java framework, using Jetty's WebSocket support underneath. It kept every connected session in memory and broadcast each message to all open sessions, with the list of active users attached:&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="n"&gt;webSocketSession&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getAllActiveSession&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;stream&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="nc"&gt;Session&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;isOpen&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;forEach&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;s&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getRemote&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;sendString&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;JSONObject&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;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"response"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nf"&gt;wrapMessageInArticle&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;senderName&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;message&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;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"activeUsers"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;webSocketSession&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getAllActiveUsername&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;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="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;No database, no message log — privacy by design, because nothing was stored. Idle connections closed after 10 minutes (&lt;code&gt;webSocketIdleTimeoutMillis(10 * 60 * 1000)&lt;/code&gt;), and the README notes it handled more than 500 concurrent users. I set up a pipeline to deploy it to Heroku's free tier and put a live demo link in the README.&lt;/p&gt;

&lt;p&gt;Then, on November 28, 2022, Heroku discontinued free dynos. The link in the README now leads nowhere.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The lesson:&lt;/strong&gt; anything you don't pay for — a free tier, a vendor's goodwill, an unversioned internal API owned by another team — can change under you. Keep the deployment reproducible from the repository (here: build a fat JAR, run &lt;code&gt;java -jar&lt;/code&gt;) so moving is a chore, not a rewrite. In system design terms: know which dependencies you control, and have an exit plan for the ones you don't.&lt;/p&gt;

&lt;p&gt;There's a second, smaller lesson in that broadcast loop: it sends to every session one after another on the same thread. That's fine for hundreds of users; at thousands, one slow client delays everyone. A per-session send queue is the fix, and it's the same pattern you'll find inside any serious messaging system.&lt;/p&gt;

&lt;h2&gt;
  
  
  3. The 5-stream broadcaster: do the arithmetic first
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href="https://github.com/ayushwing/yt-multi-stream" rel="noopener noreferrer"&gt;yt-multi-stream&lt;/a&gt; · Docker Compose, ffmpeg&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The goal: stream five different local videos to five YouTube live streams at once from one machine. The setup is five identical containers, each running a small script that loops one video into ffmpeg and pushes it to YouTube's RTMP ingest with its own stream key:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nv"&gt;INPUT&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"/videos/${VIDEO_FILE}"&lt;/span&gt;
&lt;span class="nv"&gt;OUT&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"rtmp://a.rtmp.youtube.com/live2/${STREAM_KEY}"&lt;/span&gt;
&lt;span class="nv"&gt;VIDEO_BITRATE&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"${VIDEO_BITRATE:-13500k}"&lt;/span&gt;
&lt;span class="nv"&gt;PRESET&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"${PRESET:-ultrafast}"&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Everything is configured through environment variables, so one script serves all five containers, and &lt;code&gt;docker compose up -d&lt;/code&gt; starts the lot.&lt;/p&gt;

&lt;p&gt;The interesting part is the arithmetic. The defaults target 1440p at 13.5 Mbps per stream. Five streams need &lt;strong&gt;67.5 Mbps of sustained upload&lt;/strong&gt;, before audio and overhead. Most home and many office connections can't do that. &lt;code&gt;ultrafast&lt;/code&gt; keeps CPU per stream low, so the first thing that breaks isn't the machine — it's the network, and YouTube reports it as buffering. The README's advice is accordingly blunt: lower the bitrate, lower the resolution, or run fewer streams.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The lesson:&lt;/strong&gt; before scaling out, multiply. Requests per second × payload size, consumers × partitions, streams × bitrate. A one-line calculation tells you which resource runs out first, and it's often not the one you were planning to add more of.&lt;/p&gt;

&lt;h2&gt;
  
  
  What the three have in common
&lt;/h2&gt;

&lt;p&gt;None of these projects is big. Each one met a real constraint — an API I didn't control, a platform that changed its terms, a network with a ceiling — and each constraint is one that large systems meet too, just with more zeros. Small tools are a cheap place to learn expensive lessons.&lt;/p&gt;




&lt;p&gt;&lt;em&gt;Originally published at &lt;a href="https://ayushwing.com/blog/three-small-tools" rel="noopener noreferrer"&gt;ayushwing.com&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>java</category>
      <category>sideprojects</category>
      <category>websockets</category>
      <category>docker</category>
    </item>
    <item>
      <title>Zero-downtime schema and data migrations with expand–contract</title>
      <dc:creator>Ayush Soni</dc:creator>
      <pubDate>Sun, 22 Nov 2026 17:15:50 +0000</pubDate>
      <link>https://dev.to/ayushwing/zero-downtime-schema-and-data-migrations-with-expand-contract-5673</link>
      <guid>https://dev.to/ayushwing/zero-downtime-schema-and-data-migrations-with-expand-contract-5673</guid>
      <description>&lt;p&gt;Most risky changes to a running system aren't code changes. They're changes to data: renaming a column, splitting a table, moving an entity to a new service, moving a whole dataset to new infrastructure. The application code that depends on the data is deployed continuously; the data has to stay correct the entire time.&lt;/p&gt;

&lt;p&gt;The pattern that makes this safe is &lt;strong&gt;expand–contract&lt;/strong&gt; (also called parallel change). It replaces one big, irreversible step with several small, reversible ones. Renaming a single column becomes about five deploys. That's the point.&lt;/p&gt;

&lt;h2&gt;
  
  
  The running example
&lt;/h2&gt;

&lt;p&gt;We want to replace &lt;code&gt;customers.phone&lt;/code&gt; (free text, inconsistent formats) with &lt;code&gt;customers.phone_e164&lt;/code&gt; (normalised, validated). The table is large and written to constantly. A downtime window is not an option.&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%2F36x1wrht0vyetm613wmy.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%2F36x1wrht0vyetm613wmy.png" alt="Five phases: expand, dual-write, backfill and verify, switch reads, contract. Each of the first four can be rolled back by a flag; only contract is one-way." width="800" height="372"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;Everything before "contract" is reversible. &lt;a href="https://ayushwing.com/diagrams/expand-contract.html" rel="noopener noreferrer"&gt;Explore the interactive diagram&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Phase 1: Expand
&lt;/h2&gt;

&lt;p&gt;Add the new column, nullable, with no default that would rewrite the table:&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;ALTER&lt;/span&gt; &lt;span class="k"&gt;TABLE&lt;/span&gt; &lt;span class="n"&gt;customers&lt;/span&gt; &lt;span class="k"&gt;ADD&lt;/span&gt; &lt;span class="k"&gt;COLUMN&lt;/span&gt; &lt;span class="n"&gt;phone_e164&lt;/span&gt; &lt;span class="kt"&gt;TEXT&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Nothing reads or writes it yet. Deploying this is boring by design. On Postgres, adding a nullable column without a volatile default is a metadata-only change; on other engines, check whether the operation rewrites the table, and use an online schema-change tool if it does.&lt;/p&gt;

&lt;h2&gt;
  
  
  Phase 2: Dual-write
&lt;/h2&gt;

&lt;p&gt;Change the application so every write sets &lt;strong&gt;both&lt;/strong&gt; columns:&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="n"&gt;customer&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;setPhone&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;rawPhone&lt;/span&gt;&lt;span class="p"&gt;)&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="nf"&gt;setPhoneE164&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;PhoneNumbers&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;toE164&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;rawPhone&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;orElse&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;null&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;Reads still use the old column. From this deploy onwards, every new or updated row is correct in both places. Put dual-writing behind a flag so you can turn it off without a deploy.&lt;/p&gt;

&lt;h2&gt;
  
  
  Phase 3: Backfill, then verify
&lt;/h2&gt;

&lt;p&gt;Now fix the old rows — in &lt;strong&gt;small batches&lt;/strong&gt;, never one giant &lt;code&gt;UPDATE&lt;/code&gt;:&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;UPDATE&lt;/span&gt; &lt;span class="n"&gt;customers&lt;/span&gt;
&lt;span class="k"&gt;SET&lt;/span&gt;    &lt;span class="n"&gt;phone_e164&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;normalise_e164&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;phone&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;WHERE&lt;/span&gt;  &lt;span class="n"&gt;id&lt;/span&gt; &lt;span class="k"&gt;IN&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="k"&gt;SELECT&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt; &lt;span class="k"&gt;FROM&lt;/span&gt; &lt;span class="n"&gt;customers&lt;/span&gt;
    &lt;span class="k"&gt;WHERE&lt;/span&gt;  &lt;span class="n"&gt;phone_e164&lt;/span&gt; &lt;span class="k"&gt;IS&lt;/span&gt; &lt;span class="kc"&gt;NULL&lt;/span&gt; &lt;span class="k"&gt;AND&lt;/span&gt; &lt;span class="n"&gt;phone&lt;/span&gt; &lt;span class="k"&gt;IS&lt;/span&gt; &lt;span class="k"&gt;NOT&lt;/span&gt; &lt;span class="kc"&gt;NULL&lt;/span&gt;
    &lt;span class="k"&gt;ORDER&lt;/span&gt;  &lt;span class="k"&gt;BY&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;
    &lt;span class="k"&gt;LIMIT&lt;/span&gt;  &lt;span class="mi"&gt;5000&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;Run it in a loop with a short pause between batches, watching replication lag and database load. A single huge update holds locks for a long time, bloats the table and can push replicas minutes behind.&lt;/p&gt;

&lt;p&gt;Then &lt;strong&gt;verify&lt;/strong&gt; before you trust it:&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;SELECT&lt;/span&gt; &lt;span class="nb"&gt;count&lt;/span&gt;&lt;span class="cm"&gt;(*) FROM customers
WHERE  phone IS NOT NULL
AND    phone_e164 IS DISTINCT FROM normalise_e164(phone);
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The answer should be zero, or a known list of values that genuinely can't be normalised — which is a product decision, not a migration detail. Verification is the step teams skip, and it's the one that catches the bug in your normalisation function before customers do.&lt;/p&gt;

&lt;h2&gt;
  
  
  Phase 4: Switch reads
&lt;/h2&gt;

&lt;p&gt;Flip reads to the new column, behind a flag, ideally gradually (a percentage of traffic, or one service at a time). Keep dual-writing. If anything looks wrong, flip the flag back: the old column is still complete and current.&lt;/p&gt;

&lt;p&gt;For high-stakes data, run a &lt;strong&gt;shadow read&lt;/strong&gt; first: read both columns, serve the old one, and log any mismatch. A week of zero mismatches is a strong signal.&lt;/p&gt;

&lt;h2&gt;
  
  
  Phase 5: Contract
&lt;/h2&gt;

&lt;p&gt;Only when reads have used the new column for a while with no issues:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Stop writing the old column (deploy).&lt;/li&gt;
&lt;li&gt;Remove the old column from the code entirely (deploy).&lt;/li&gt;
&lt;li&gt;Drop it from the database (migration).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This is the only one-way step, which is why it comes last and why it's split up. And actually do it: half-finished migrations, where both columns live forever and nobody remembers which is the truth, are a very common kind of tech debt.&lt;/p&gt;

&lt;h2&gt;
  
  
  The same shape, bigger
&lt;/h2&gt;

&lt;p&gt;Expand–contract scales from a column to a whole system:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Change&lt;/th&gt;
&lt;th&gt;Expand&lt;/th&gt;
&lt;th&gt;Dual-write&lt;/th&gt;
&lt;th&gt;Backfill + verify&lt;/th&gt;
&lt;th&gt;Switch reads&lt;/th&gt;
&lt;th&gt;Contract&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Rename a column&lt;/td&gt;
&lt;td&gt;New column&lt;/td&gt;
&lt;td&gt;Write both&lt;/td&gt;
&lt;td&gt;Batch update&lt;/td&gt;
&lt;td&gt;Read new&lt;/td&gt;
&lt;td&gt;Drop old&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Split a table&lt;/td&gt;
&lt;td&gt;New table&lt;/td&gt;
&lt;td&gt;Write both&lt;/td&gt;
&lt;td&gt;Copy rows&lt;/td&gt;
&lt;td&gt;Read new table&lt;/td&gt;
&lt;td&gt;Drop old columns&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Move an entity to a new service&lt;/td&gt;
&lt;td&gt;New service + store&lt;/td&gt;
&lt;td&gt;Write via both&lt;/td&gt;
&lt;td&gt;Copy history&lt;/td&gt;
&lt;td&gt;Route reads to new service&lt;/td&gt;
&lt;td&gt;Retire old code path&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Move data to new infrastructure&lt;/td&gt;
&lt;td&gt;Provision target&lt;/td&gt;
&lt;td&gt;Replicate / sync&lt;/td&gt;
&lt;td&gt;Bulk copy + checksums&lt;/td&gt;
&lt;td&gt;Cut over traffic&lt;/td&gt;
&lt;td&gt;Decommission source&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;The bigger the change, the more the phases benefit from &lt;strong&gt;automation&lt;/strong&gt;: each phase becomes a step with a precondition check, an action, a verification and a rollback. That's the point where a durable workflow engine starts paying for itself — see &lt;a href="https://ayushwing.com/blog/durable-workflows-vs-queue-and-cron" rel="noopener noreferrer"&gt;Durable workflows vs. a queue and a cron job&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Takeaways
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Split a risky data change into &lt;strong&gt;expand, dual-write, backfill + verify, switch reads, contract&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;Backfill in &lt;strong&gt;small batches&lt;/strong&gt;, and &lt;strong&gt;verify with a query&lt;/strong&gt; before switching reads.&lt;/li&gt;
&lt;li&gt;Keep every phase except the last &lt;strong&gt;reversible with a flag&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;Finish the contract phase — otherwise the migration becomes permanent debt.&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;&lt;em&gt;Originally published at &lt;a href="https://ayushwing.com/blog/expand-contract-migrations" rel="noopener noreferrer"&gt;ayushwing.com&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>database</category>
      <category>migrations</category>
      <category>devops</category>
      <category>architecture</category>
    </item>
    <item>
      <title>Design it: a personalised email platform at 20M emails a day</title>
      <dc:creator>Ayush Soni</dc:creator>
      <pubDate>Fri, 20 Nov 2026 11:11:31 +0000</pubDate>
      <link>https://dev.to/ayushwing/design-it-a-personalised-email-platform-at-20m-emails-a-day-4jf4</link>
      <guid>https://dev.to/ayushwing/design-it-a-personalised-email-platform-at-20m-emails-a-day-4jf4</guid>
      <description>&lt;p&gt;At a travel company, I worked on redesigning a monolithic email system into services. The APIs we built powered around &lt;strong&gt;20 million personalised emails a day&lt;/strong&gt;, both transactional and promotional, each one shaped by what the customer had searched for and booked.&lt;/p&gt;

&lt;p&gt;This post is the design I'd draw today for that kind of system, worked through the way I'd present it in a design review. It isn't a description of that company's internals; it's the generalised version, with the lessons built in.&lt;/p&gt;

&lt;h2&gt;
  
  
  Requirements
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Functional&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Transactional email&lt;/strong&gt;, triggered by events: booking confirmed, payment failed, trip tomorrow. Must arrive within seconds.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Promotional email&lt;/strong&gt;, triggered by campaigns: a deal for an audience of millions. Must arrive within hours, and must respect each customer's preferences.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Personalisation&lt;/strong&gt;: content based on search and booking history ("hotels in Goa, since you looked last week").&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Compliance&lt;/strong&gt;: unsubscribes are honoured immediately, and promotional email only goes to people who agreed to it.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Non-functional&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;20M emails a day is about 230 a second &lt;strong&gt;on average&lt;/strong&gt;. Averages are misleading here: campaigns go out in bursts. If 10M promotional emails go out in a two-hour window, that's roughly &lt;strong&gt;1,400 a second&lt;/strong&gt; for two hours, on top of transactional traffic. Design for the burst.&lt;/li&gt;
&lt;li&gt;Transactional latency must not depend on what campaigns are running.&lt;/li&gt;
&lt;li&gt;No email is sent twice, even when something retries.&lt;/li&gt;
&lt;li&gt;The email provider has its own rate limits. Exceeding them, or sending to dead addresses, damages &lt;strong&gt;deliverability&lt;/strong&gt;: the inbox providers start sending your mail to spam.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  The design
&lt;/h2&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%2F7d2mi39m4qp74rtww6p1.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%2F7d2mi39m4qp74rtww6p1.png" alt="Booking events and campaign runs both enter an eligibility step that checks consent, frequency caps and the suppression list. Eligible messages are rendered from a template plus a precomputed user profile, then split into a transactional lane that never waits and a rate-limited promotional lane, both sending through the email provider. Bounces and complaints come back through webhooks and update the suppression list." width="799" height="469"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;Decide, personalise, send in two lanes, and close the loop. &lt;a href="https://ayushwing.com/diagrams/email-platform.html" rel="noopener noreferrer"&gt;Explore the interactive diagram&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  1. Two kinds of trigger, one pipeline
&lt;/h3&gt;

&lt;p&gt;Transactional emails start from &lt;strong&gt;events&lt;/strong&gt;: the booking service publishes &lt;code&gt;BookingConfirmed&lt;/code&gt; to Kafka, and the email platform consumes it. The booking service doesn't call the email service directly; if email is slow or down, bookings still work. (Publish those events with an &lt;a href="https://ayushwing.com/blog/transactional-outbox" rel="noopener noreferrer"&gt;outbox&lt;/a&gt;, or you'll occasionally lose one.)&lt;/p&gt;

&lt;p&gt;Promotional emails start from a &lt;strong&gt;campaign run&lt;/strong&gt;: a scheduled job resolves an audience (a query over customer data) into a stream of "send campaign X to user Y" requests.&lt;/p&gt;

&lt;p&gt;Both become the same internal message, a &lt;strong&gt;send request&lt;/strong&gt;: who, which template, why, and a priority. Everything downstream handles one shape.&lt;/p&gt;

&lt;h3&gt;
  
  
  2. Decide before you render
&lt;/h3&gt;

&lt;p&gt;The cheapest email is the one you don't build. Before any personalisation, the eligibility step answers:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Consent&lt;/strong&gt;: has this person agreed to this category of email? (Transactional mail about their own booking doesn't need marketing consent; promotions do.)&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Suppression&lt;/strong&gt;: have they unsubscribed, hard-bounced or complained?&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Frequency caps&lt;/strong&gt;: have we already sent them three promotions this week?&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Quiet hours&lt;/strong&gt;: is it 3am where they live? Then schedule it for later.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Doing this first matters for cost. At campaign scale, a significant share of an audience is often filtered out here. Every one of those is a render, a provider call and a quota slot you didn't spend.&lt;/p&gt;

&lt;h3&gt;
  
  
  3. Personalisation is a lookup, not a query
&lt;/h3&gt;

&lt;p&gt;The naive version renders each email by querying the analytics store: "what did this user search for recently?" At 1,400 renders a second, against a warehouse built for large scans, that falls over.&lt;/p&gt;

&lt;p&gt;Instead, &lt;strong&gt;precompute&lt;/strong&gt; a profile per user: recent destinations, last search, loyalty tier, preferred language. A batch job writes it to a key-value store, and events keep the hottest fields fresh. Rendering then becomes &lt;code&gt;template + one key lookup&lt;/code&gt;, which is fast and predictable.&lt;/p&gt;

&lt;p&gt;The trade-off is freshness: a profile computed overnight doesn't know about a search from five minutes ago. For promotions that's fine. For anything triggered by a recent action, put the fresh data &lt;strong&gt;in the event itself&lt;/strong&gt; (the booking event carries the booking) instead of looking it up.&lt;/p&gt;

&lt;h3&gt;
  
  
  4. Two send lanes, never one
&lt;/h3&gt;

&lt;p&gt;This is the most important decision in the design. Transactional and promotional email get &lt;strong&gt;separate queues, separate workers and separate provider quotas&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;With one shared queue, a 10-million-recipient campaign at 9am puts every booking confirmation behind it. The customer at the airport wondering whether their booking went through doesn't care that the queue is "working as designed".&lt;/p&gt;

&lt;p&gt;With two lanes:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The &lt;strong&gt;transactional lane&lt;/strong&gt; is small, always has spare capacity, and is scaled for latency.&lt;/li&gt;
&lt;li&gt;The &lt;strong&gt;promotional lane&lt;/strong&gt; is large, deliberately rate-limited to the provider's quota and a warm-up curve, and is scaled for throughput. When it's busy, it's just slower; nothing important waits.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Many email providers also let you send transactional and promotional mail from separate IP addresses or sub-accounts, so a campaign's spam complaints don't hurt the reputation of your password-reset emails. Use that.&lt;/p&gt;

&lt;h3&gt;
  
  
  5. Exactly one email, even with retries
&lt;/h3&gt;

&lt;p&gt;Workers crash, provider calls time out, Kafka redelivers. Each of those can turn into a second copy of the same email, and customers notice duplicates.&lt;/p&gt;

&lt;p&gt;Give every send request a deterministic &lt;strong&gt;message key&lt;/strong&gt;, for example &lt;code&gt;hash(userId, template, bookingId)&lt;/code&gt; for a booking confirmation or &lt;code&gt;hash(userId, campaignId)&lt;/code&gt; for a promotion. Before sending, the worker records the key with a unique constraint; if the key already exists, it skips. Pass the same key to the provider as an idempotency key if it supports one. This is the same pattern as &lt;a href="https://ayushwing.com/blog/idempotency-keys" rel="noopener noreferrer"&gt;idempotency keys for payments&lt;/a&gt;, and it matters for the same reason: retrying must be safe.&lt;/p&gt;

&lt;h3&gt;
  
  
  6. Close the loop
&lt;/h3&gt;

&lt;p&gt;The provider tells you what happened through webhooks: delivered, opened, bounced, marked as spam, unsubscribed. Two of these must change behaviour &lt;strong&gt;automatically&lt;/strong&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A &lt;strong&gt;hard bounce&lt;/strong&gt; (the address doesn't exist) goes on the suppression list. Repeatedly sending to dead addresses is one of the fastest ways to damage deliverability.&lt;/li&gt;
&lt;li&gt;A &lt;strong&gt;spam complaint&lt;/strong&gt; suppresses that person from promotional email immediately.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The rest (deliveries, opens, clicks) feed analytics, and back into the next profile computation.&lt;/p&gt;

&lt;h2&gt;
  
  
  Failure modes, and what happens
&lt;/h2&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Failure&lt;/th&gt;
&lt;th&gt;Effect&lt;/th&gt;
&lt;th&gt;Design response&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Provider is down&lt;/td&gt;
&lt;td&gt;Sends fail&lt;/td&gt;
&lt;td&gt;Requests stay in the queue; retry with backoff; transactional lane alerts within minutes&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Provider rate-limits you&lt;/td&gt;
&lt;td&gt;429 responses&lt;/td&gt;
&lt;td&gt;The promotional lane slows down; transactional quota is separate&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Campaign audience is wrong&lt;/td&gt;
&lt;td&gt;Wrong people emailed&lt;/td&gt;
&lt;td&gt;Dry run first: count and sample the audience before the real run; kill switch per campaign&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Worker crashes mid-batch&lt;/td&gt;
&lt;td&gt;Redelivery&lt;/td&gt;
&lt;td&gt;Message key prevents duplicates&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Profile store is stale&lt;/td&gt;
&lt;td&gt;Less relevant content&lt;/td&gt;
&lt;td&gt;Acceptable for promotions; transactional data travels in the event&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Template bug&lt;/td&gt;
&lt;td&gt;Broken emails at scale&lt;/td&gt;
&lt;td&gt;Render a sample to a seed list first; validate templates in CI&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;h2&gt;
  
  
  What I'd measure
&lt;/h2&gt;

&lt;p&gt;A funnel per campaign and per template: &lt;strong&gt;requested → eligible → rendered → sent → delivered → opened&lt;/strong&gt;, plus bounces and complaints. A sudden drop between two stages tells you where the problem is. For transactional email, also measure &lt;strong&gt;time from event to send&lt;/strong&gt;, and alert on that rather than on queue length.&lt;/p&gt;

&lt;h2&gt;
  
  
  Takeaways
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Separate transactional and promotional email&lt;/strong&gt; completely: queues, workers and provider quotas.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Decide before you render.&lt;/strong&gt; Consent, caps and suppression are cheap; rendering isn't.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Precompute personalisation&lt;/strong&gt; so rendering is a lookup. Put fresh data in the triggering event.&lt;/li&gt;
&lt;li&gt;Give every email a &lt;strong&gt;deterministic message key&lt;/strong&gt;, so retries can't send twice.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Feed bounces and complaints back&lt;/strong&gt; into suppression automatically. Deliverability is a feature.&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;&lt;em&gt;Originally published at &lt;a href="https://ayushwing.com/blog/design-email-platform" rel="noopener noreferrer"&gt;ayushwing.com&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>systemdesign</category>
      <category>architecture</category>
      <category>distributedsystems</category>
      <category>kafka</category>
    </item>
    <item>
      <title>YT Studio AI: wiring Vision, NLP and LLMs into a creator tool</title>
      <dc:creator>Ayush Soni</dc:creator>
      <pubDate>Thu, 19 Nov 2026 10:11:57 +0000</pubDate>
      <link>https://dev.to/ayushwing/yt-studio-ai-wiring-vision-nlp-and-llms-into-a-creator-tool-55jn</link>
      <guid>https://dev.to/ayushwing/yt-studio-ai-wiring-vision-nlp-and-llms-into-a-creator-tool-55jn</guid>
      <description>&lt;p&gt;Creators spend hours on a video and minutes on its thumbnail and title — the two things that decide whether anyone clicks. I wanted a tool that answers, before upload: &lt;em&gt;is this thumbnail readable on a phone? Does the title match what's in the picture? How does it compare with what's working for similar channels?&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/ayushwing/yt-studio-ai" rel="noopener noreferrer"&gt;YT Studio AI&lt;/a&gt; is that tool: a full-stack app with a thumbnail analyzer, title and description analysis, video analysis, competitor research, an A/B workshop for thumbnail variants, a combined "content score", and YouTube Analytics through OAuth.&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%2F30sn7lv5j74iojoq9pyw.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%2F30sn7lv5j74iojoq9pyw.png" alt="YT Studio AI dashboard showing project stats, competitor benchmarks, top tags and recent activity." width="800" height="500"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;The project dashboard.&lt;/em&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Architecture
&lt;/h2&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Layer&lt;/th&gt;
&lt;th&gt;Choice&lt;/th&gt;
&lt;th&gt;Why&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Frontend&lt;/td&gt;
&lt;td&gt;React 18, Vite, Tailwind, Zustand, Recharts&lt;/td&gt;
&lt;td&gt;Fast to build dashboards; small state store&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Backend&lt;/td&gt;
&lt;td&gt;Java 21, Spring Boot 3, WebClient&lt;/td&gt;
&lt;td&gt;Many slow external calls; non-blocking HTTP client&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Storage&lt;/td&gt;
&lt;td&gt;PostgreSQL 16, 12 tables, JSONB columns&lt;/td&gt;
&lt;td&gt;Relational for projects and history, JSONB for API responses whose shape I don't control&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;External&lt;/td&gt;
&lt;td&gt;Google Vision, Natural Language, Video Intelligence; YouTube Data and Analytics; Gemini or Claude&lt;/td&gt;
&lt;td&gt;Specialised tools for facts, an LLM for judgment&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;JSONB earns its place here. Vision and NLP responses are large, nested and change between API versions. Storing them as JSONB next to a few typed columns (scores, timestamps, foreign keys) means a new field from Google needs no schema migration.&lt;/p&gt;
&lt;h2&gt;
  
  
  Facts first, opinions second
&lt;/h2&gt;

&lt;p&gt;The tempting design is to send the thumbnail straight to a multimodal LLM and ask "is this good?". You get fluent answers, but nothing anchors them: scores drift between runs, and a confident reason may describe something that isn't in the picture.&lt;/p&gt;

&lt;p&gt;So the app splits the job:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Deterministic APIs extract facts.&lt;/strong&gt; Google Vision returns labels, detected text (OCR), faces, dominant colours and safe-search ratings; I compute the percentage of dark pixels myself. These are repeatable — the same image yields the same facts.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;The LLM reasons over the facts.&lt;/strong&gt; The prompt carries those facts, plus the creator's own history (past thumbnails analysed in this project) and competitor videos they've collected.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;The LLM must answer in a fixed JSON shape.&lt;/strong&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Respond ONLY in this exact JSON structure (no text before or after):
{
  "overall_score": 0-100,
  "scores": {
    "visibility":      { "score": 0-100, "reasoning": "..." },
    "emotion":         { "score": 0-100, "reasoning": "..." },
    "text_clarity":    { "score": 0-100, "reasoning": "..." },
    "color_impact":    { "score": 0-100, "reasoning": "..." },
    "mobile_friendly": { "score": 0-100, "reasoning": "..." },
    "content_relevance": { "score": 0-100, "reasoning": "..." }
  },
  "strengths": [...], "weaknesses": [...],
  "action_items": [{ "priority": "high|medium|low", "action": "...", "expected_impact": "..." }],
  "competitor_comparison": "...", "trend_vs_history": "...", "audience_fit": "..."
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Structured output turned the LLM from a chat partner into a component: the backend parses scores into columns, the UI renders them as charts, and the A/B workshop compares variants field by field.&lt;/p&gt;
&lt;h2&gt;
  
  
  One interface, two providers
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;AiProviderService&lt;/code&gt; owns every prompt and delegates the actual API call:&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;private&lt;/span&gt; &lt;span class="nc"&gt;AiInsight&lt;/span&gt; &lt;span class="nf"&gt;callAi&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;prompt&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;analysisType&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;Long&lt;/span&gt; &lt;span class="n"&gt;analysisId&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                         &lt;span class="kt"&gt;Long&lt;/span&gt; &lt;span class="n"&gt;projectId&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;Map&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="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;Object&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;contextData&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;apiKeyService&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;hasKey&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"gemini"&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;geminiService&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;callGemini&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;prompt&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;analysisType&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;analysisId&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;projectId&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;contextData&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;else&lt;/span&gt; &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;apiKeyService&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;hasKey&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"anthropic"&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;claudeService&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;callClaude&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;prompt&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;analysisType&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;analysisId&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;projectId&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;contextData&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;throw&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;RuntimeException&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"No AI provider configured. Please add a Gemini or Anthropic API key in Settings."&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;Gemini comes first because its free tier makes the tool usable at zero cost; Claude is there for users who prefer it. Keeping prompts in one place and providers behind a thin call keeps each provider class small — it only knows how to send a prompt and parse a reply — and every stored insight records which model produced it.&lt;/p&gt;

&lt;h2&gt;
  
  
  Users' API keys, encrypted
&lt;/h2&gt;

&lt;p&gt;Users paste their own Google and AI keys in Settings. They are stored encrypted with AES-256 in GCM mode: a fresh 12-byte random IV per value, a 128-bit authentication tag, and the IV stored alongside the ciphertext. GCM matters here: it doesn't just hide the key, it detects tampering — a modified ciphertext fails to decrypt instead of decrypting to garbage.&lt;/p&gt;

&lt;h2&gt;
  
  
  What I'd do differently
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Provider fallback, not just provider choice.&lt;/strong&gt; Today the app picks whichever key exists. If Gemini returns a 429 or a 5xx, the request fails even when a Claude key is configured. A fallback chain with a circuit breaker per provider would fix that.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Validate the JSON, then retry once.&lt;/strong&gt; Models occasionally wrap JSON in prose. Parse strictly against a schema and, on failure, retry once with the error message in the prompt.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;A real key-derivation step.&lt;/strong&gt; The AES key is a SHA-256 hash of a configured secret. For a self-hosted tool that's acceptable; for a hosted version I'd use a key-management service and envelope encryption.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Takeaways
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Let deterministic tools produce facts and let the model produce judgment — results get repeatable.&lt;/li&gt;
&lt;li&gt;Force structured output; it turns LLM responses into data your app can use.&lt;/li&gt;
&lt;li&gt;Put providers behind one interface early; models change faster than your code.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The full app — backend, frontend, Docker setup and screenshots — is on &lt;a href="https://github.com/ayushwing/yt-studio-ai" rel="noopener noreferrer"&gt;GitHub&lt;/a&gt;.&lt;/p&gt;




&lt;p&gt;&lt;em&gt;Originally published at &lt;a href="https://ayushwing.com/blog/yt-studio-ai" rel="noopener noreferrer"&gt;ayushwing.com&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>ai</category>
      <category>java</category>
      <category>springboot</category>
      <category>llm</category>
    </item>
    <item>
      <title>Model business workflows as state machines</title>
      <dc:creator>Ayush Soni</dc:creator>
      <pubDate>Wed, 18 Nov 2026 08:54:52 +0000</pubDate>
      <link>https://dev.to/ayushwing/model-business-workflows-as-state-machines-2opa</link>
      <guid>https://dev.to/ayushwing/model-business-workflows-as-state-machines-2opa</guid>
      <description>&lt;p&gt;Orders, refunds, subscriptions, tenants, support tickets, deployments — most business entities move through a lifecycle. And a whole category of production bugs comes from that lifecycle being implicit:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A cancelled order gets shipped because the cancel and the ship request arrived 50 ms apart.&lt;/li&gt;
&lt;li&gt;A refund is issued twice because two retries both saw &lt;code&gt;status = 'PAID'&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;An account stuck in &lt;code&gt;PROVISIONING&lt;/code&gt; for a week because a step failed and nothing defined what happens next.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In each case, the states existed only as a string column, and any code path could set any value. The fix is to make the state machine explicit, and to enforce it where concurrency actually happens: in the database.&lt;/p&gt;

&lt;h2&gt;
  
  
  Step 1: name the states and transitions
&lt;/h2&gt;

&lt;p&gt;Write them down in one place. For an order:&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%2Fdo8hr634jxnezl3ojgab.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%2Fdo8hr634jxnezl3ojgab.png" alt="Order states: CREATED to PAID to PACKED to SHIPPED to DELIVERED. CREATED and PAID can move to CANCELLED. PAID can move to REFUND_PENDING then REFUNDED." width="800" height="348"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;Every arrow is an allowed transition; anything else is a bug. &lt;a href="https://ayushwing.com/diagrams/order-state-machine.html" rel="noopener noreferrer"&gt;Explore the interactive diagram&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;In Java, an enum with its allowed transitions keeps the rules next to the states:&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="k"&gt;enum&lt;/span&gt; &lt;span class="nc"&gt;OrderStatus&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="no"&gt;CREATED&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="no"&gt;PAID&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="no"&gt;PACKED&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="no"&gt;SHIPPED&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="no"&gt;DELIVERED&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="no"&gt;CANCELLED&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="no"&gt;REFUND_PENDING&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="no"&gt;REFUNDED&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="kt"&gt;Map&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;OrderStatus&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;Set&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;OrderStatus&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt; &lt;span class="no"&gt;ALLOWED&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kt"&gt;Map&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;of&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="no"&gt;CREATED&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;        &lt;span class="kt"&gt;Set&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;of&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="no"&gt;PAID&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="no"&gt;CANCELLED&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="no"&gt;PAID&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;           &lt;span class="kt"&gt;Set&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;of&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="no"&gt;PACKED&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="no"&gt;CANCELLED&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="no"&gt;REFUND_PENDING&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="no"&gt;PACKED&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;         &lt;span class="kt"&gt;Set&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;of&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="no"&gt;SHIPPED&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="no"&gt;SHIPPED&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;        &lt;span class="kt"&gt;Set&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;of&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="no"&gt;DELIVERED&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="no"&gt;REFUND_PENDING&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;Set&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;of&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="no"&gt;REFUNDED&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="no"&gt;PAID&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;   &lt;span class="c1"&gt;// refund rejected -&amp;gt; back to PAID&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;boolean&lt;/span&gt; &lt;span class="nf"&gt;canMoveTo&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;OrderStatus&lt;/span&gt; &lt;span class="n"&gt;next&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="no"&gt;ALLOWED&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getOrDefault&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;Set&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;of&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;contains&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;next&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;&lt;code&gt;DELIVERED&lt;/code&gt;, &lt;code&gt;CANCELLED&lt;/code&gt; and &lt;code&gt;REFUNDED&lt;/code&gt; have no outgoing transitions: they're terminal. Writing that down is itself useful — it's the conversation with product ("can a delivered order be cancelled?") that usually never happened.&lt;/p&gt;

&lt;h2&gt;
  
  
  Step 2: enforce transitions with a conditional write
&lt;/h2&gt;

&lt;p&gt;Checking &lt;code&gt;canMoveTo&lt;/code&gt; in memory isn't enough. Two requests can each load the order as &lt;code&gt;PAID&lt;/code&gt;, each decide the transition is valid, and each write their new state. The last write wins, and one of them silently overwrote the other.&lt;/p&gt;

&lt;p&gt;Make the database do the check, atomically:&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;UPDATE&lt;/span&gt; &lt;span class="n"&gt;orders&lt;/span&gt;
&lt;span class="k"&gt;SET&lt;/span&gt;    &lt;span class="n"&gt;status&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s1"&gt;'CANCELLED'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;version&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;version&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;updated_at&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;now&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;WHERE&lt;/span&gt;  &lt;span class="n"&gt;id&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;
&lt;span class="k"&gt;AND&lt;/span&gt;    &lt;span class="n"&gt;status&lt;/span&gt; &lt;span class="k"&gt;IN&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'CREATED'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'PAID'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;      &lt;span class="c1"&gt;-- the allowed "from" states&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If the update touches &lt;strong&gt;one row&lt;/strong&gt;, you won the transition. If it touches &lt;strong&gt;zero&lt;/strong&gt;, someone else moved the order first — reload and decide what to tell the caller ("this order has already shipped"). No locks held across network calls, no race.&lt;/p&gt;

&lt;p&gt;The same idea works on stores without SQL. In DynamoDB it's a &lt;code&gt;ConditionExpression&lt;/code&gt; on the update; in a document store it's a compare-and-set on a version field. The principle is identical: &lt;strong&gt;the write states what it expects the current state to be&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="nd"&gt;@Transactional&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;cancel&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;long&lt;/span&gt; &lt;span class="n"&gt;orderId&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;reason&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;actor&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;updated&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;jdbc&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;update&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"""
        UPDATE orders SET status = 'CANCELLED', version = version + 1
        WHERE id = ? AND status IN ('CREATED', 'PAID')
        """&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="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;updated&lt;/span&gt; &lt;span class="o"&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;span class="k"&gt;throw&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;IllegalTransitionException&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="nc"&gt;OrderStatus&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;CANCELLED&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;transitions&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;record&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="nc"&gt;OrderStatus&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;CANCELLED&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;reason&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;actor&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;h2&gt;
  
  
  Step 3: record every transition
&lt;/h2&gt;

&lt;p&gt;Keep an append-only history next to the current state:&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;TABLE&lt;/span&gt; &lt;span class="n"&gt;order_transitions&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="n"&gt;order_id&lt;/span&gt;    &lt;span class="kt"&gt;BIGINT&lt;/span&gt;      &lt;span class="k"&gt;NOT&lt;/span&gt; &lt;span class="kc"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;from_status&lt;/span&gt; &lt;span class="kt"&gt;TEXT&lt;/span&gt;        &lt;span class="k"&gt;NOT&lt;/span&gt; &lt;span class="kc"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;to_status&lt;/span&gt;   &lt;span class="kt"&gt;TEXT&lt;/span&gt;        &lt;span class="k"&gt;NOT&lt;/span&gt; &lt;span class="kc"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;actor&lt;/span&gt;       &lt;span class="kt"&gt;TEXT&lt;/span&gt;        &lt;span class="k"&gt;NOT&lt;/span&gt; &lt;span class="kc"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;     &lt;span class="c1"&gt;-- user, service, or job that caused it&lt;/span&gt;
    &lt;span class="n"&gt;reason&lt;/span&gt;      &lt;span class="kt"&gt;TEXT&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;at&lt;/span&gt;          &lt;span class="kt"&gt;TIMESTAMPTZ&lt;/span&gt; &lt;span class="k"&gt;NOT&lt;/span&gt; &lt;span class="kc"&gt;NULL&lt;/span&gt; &lt;span class="k"&gt;DEFAULT&lt;/span&gt; &lt;span class="nb"&gt;now&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;Written in the same transaction as the state change, it answers the questions support and finance actually ask — &lt;em&gt;who cancelled this, and when?&lt;/em&gt; — and it's invaluable when debugging how an entity reached a strange state.&lt;/p&gt;

&lt;h2&gt;
  
  
  Step 4: make failure states first-class
&lt;/h2&gt;

&lt;p&gt;Long-running lifecycles (provisioning, migrations, onboarding) need explicit failure states with an exit:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;PROVISIONING_FAILED&lt;/code&gt; → &lt;code&gt;PROVISIONING&lt;/code&gt; (retry) or → &lt;code&gt;DEPROVISIONING&lt;/code&gt; (clean up).&lt;/li&gt;
&lt;li&gt;A job that &lt;strong&gt;times out&lt;/strong&gt; of a state moves to a failure state instead of sitting there forever. A periodic sweep that finds entities older than X in a transient state is a cheap, effective safety net.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;An entity "stuck" in a state with no defined way out is a design gap, not an operations problem.&lt;/p&gt;

&lt;h2&gt;
  
  
  Where the state machine lives
&lt;/h2&gt;

&lt;p&gt;Keep the rules in &lt;strong&gt;one&lt;/strong&gt; place — an enum, a small domain class, or a library — and route every status change through it. If you find &lt;code&gt;order.setStatus(...)&lt;/code&gt; scattered across controllers, jobs and consumers, that's the refactor to do first.&lt;/p&gt;

&lt;p&gt;For lifecycles with many steps, timers and external calls, the state machine often becomes the backbone of a workflow; at that point a durable workflow engine may fit better (see &lt;a href="https://ayushwing.com/blog/durable-workflows-vs-queue-and-cron" rel="noopener noreferrer"&gt;Durable workflows vs. a queue and a cron job&lt;/a&gt;). The two combine well: the workflow drives the steps, and the entity's state machine guarantees that no other code path can move it illegally in the meantime.&lt;/p&gt;

&lt;h2&gt;
  
  
  Takeaways
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Write down every &lt;strong&gt;state&lt;/strong&gt; and every &lt;strong&gt;allowed transition&lt;/strong&gt;; agree on terminal states with product.&lt;/li&gt;
&lt;li&gt;Enforce transitions with a &lt;strong&gt;conditional write&lt;/strong&gt; that names the expected current state.&lt;/li&gt;
&lt;li&gt;Keep an &lt;strong&gt;append-only transition history&lt;/strong&gt;, written in the same transaction.&lt;/li&gt;
&lt;li&gt;Give every transient state a &lt;strong&gt;timeout&lt;/strong&gt; and every failure state a &lt;strong&gt;way out&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;&lt;em&gt;Originally published at &lt;a href="https://ayushwing.com/blog/business-workflows-as-state-machines" rel="noopener noreferrer"&gt;ayushwing.com&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>architecture</category>
      <category>java</category>
      <category>database</category>
      <category>ddd</category>
    </item>
    <item>
      <title>Debugging production: a method, not a hunch</title>
      <dc:creator>Ayush Soni</dc:creator>
      <pubDate>Sat, 14 Nov 2026 04:16:36 +0000</pubDate>
      <link>https://dev.to/ayushwing/debugging-production-a-method-not-a-hunch-34k4</link>
      <guid>https://dev.to/ayushwing/debugging-production-a-method-not-a-hunch-34k4</guid>
      <description>&lt;p&gt;Production incidents reward method over brilliance. The fastest way to a fix is rarely knowing every corner of the system; it's not skipping steps. When an alert fires, the instinct is to open the logs and start reading. That instinct costs hours.&lt;/p&gt;

&lt;p&gt;Here's the method I use.&lt;/p&gt;

&lt;h2&gt;
  
  
  1. Stop the bleeding first
&lt;/h2&gt;

&lt;p&gt;Your first job is to reduce user impact, not to understand the problem. Understanding can happen after users are fine.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Roll back&lt;/strong&gt; the last deploy if the timing fits, even if you're "pretty sure" it isn't the cause. A rollback that doesn't help is cheap information.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Fail over&lt;/strong&gt; to another region or replica.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Disable&lt;/strong&gt; the feature flag behind the new code path.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Shed load&lt;/strong&gt;: rate-limit the noisy client, pause the batch job, scale out.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Declare the incident, name one person to coordinate and one to communicate, and post updates on a fixed rhythm. A quiet incident channel makes everyone else start their own investigation in parallel.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. Build a timeline
&lt;/h2&gt;

&lt;p&gt;"It's slow" isn't a starting point; "p99 latency on checkout went from 300 ms to 12 s at 09:02 UTC" is. Pin down:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;When&lt;/strong&gt; exactly it started (and whether it was a step or a ramp).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;What&lt;/strong&gt; is affected: which endpoints, error codes, regions, customers.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;What isn't&lt;/strong&gt; affected. Healthy neighbours are as informative as broken ones.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;A step change usually means something changed. A slow ramp usually means something filled up: a disk, a queue, a connection pool, a cache that's slowly expiring.&lt;/p&gt;

&lt;h2&gt;
  
  
  3. Ask "what changed?"
&lt;/h2&gt;

&lt;p&gt;Most incidents are caused by a change. Check, in roughly this order:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Change&lt;/th&gt;
&lt;th&gt;Where to look&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Code deploys&lt;/td&gt;
&lt;td&gt;Deploy log, around the start time&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Configuration and feature flags&lt;/td&gt;
&lt;td&gt;Flag history, config repo&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Infrastructure&lt;/td&gt;
&lt;td&gt;Scaling events, node replacements, certificate renewals, DNS changes&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Traffic&lt;/td&gt;
&lt;td&gt;Volume, shape, a new client, a bot&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Dependencies&lt;/td&gt;
&lt;td&gt;Status pages, error rates on outbound calls&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Data&lt;/td&gt;
&lt;td&gt;A new tenant, a huge record, a backfill job running&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;A shared, searchable change log across all of these is one of the highest-value investments a platform team can make. Without it, step 3 becomes a poll of the whole engineering department.&lt;/p&gt;

&lt;h2&gt;
  
  
  4. Form a hypothesis you can test quickly
&lt;/h2&gt;

&lt;p&gt;"Something's wrong with the database" isn't testable. "Connection pool exhaustion on the order service since the 09:00 deploy, which raised the default timeout" is: check pool metrics and the diff in five minutes.&lt;/p&gt;

&lt;p&gt;Write the hypothesis in the incident channel before you test it. It keeps the team aligned, stops three people testing the same idea, and makes the timeline easy to write afterwards. When a hypothesis is disproved, say so and move on — don't keep half-believing it.&lt;/p&gt;

&lt;h2&gt;
  
  
  5. Narrow by halves
&lt;/h2&gt;

&lt;p&gt;When there's no obvious change, bisect the problem space:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;One &lt;strong&gt;region&lt;/strong&gt; or all of them?&lt;/li&gt;
&lt;li&gt;One &lt;strong&gt;endpoint&lt;/strong&gt; or all of them?&lt;/li&gt;
&lt;li&gt;One &lt;strong&gt;customer&lt;/strong&gt; or all of them? (A single tenant with unusual data is behind more incidents than people expect.)&lt;/li&gt;
&lt;li&gt;One &lt;strong&gt;host or pod&lt;/strong&gt; or all of them? (One bad node behind a load balancer looks like a small, random error rate.)&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Before or after&lt;/strong&gt; a dependency? Traces answer this directly: where does the time go?&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Each question halves the search space. Five good questions narrow almost anything.&lt;/p&gt;

&lt;p&gt;This is where observability earns its cost: structured logs with a trace ID, traces across service boundaries (including message queues), and metrics you can slice by endpoint, tenant and host. If you can't slice, you can't bisect. (I packaged my defaults for this into a &lt;a href="https://ayushwing.com/blog/spring-boot-starter-observability" rel="noopener noreferrer"&gt;Spring Boot starter&lt;/a&gt;.)&lt;/p&gt;

&lt;h2&gt;
  
  
  6. Write it down
&lt;/h2&gt;

&lt;p&gt;After the incident, write a short, blameless review:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Timeline&lt;/strong&gt; — from first symptom to recovery, with timestamps.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Impact&lt;/strong&gt; — who was affected, for how long, how badly.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Cause&lt;/strong&gt; — the technical chain of events, as far as you know it.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Detection&lt;/strong&gt; — how did we find out, and could we have found out sooner?&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Follow-ups&lt;/strong&gt; — a small number of concrete actions with owners: a missing alert, a guardrail, a runbook step.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The detection question is often the most valuable. "The customer told us" is a finding in itself.&lt;/p&gt;

&lt;h2&gt;
  
  
  Habits that make the method faster
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Dashboards built for questions&lt;/strong&gt;, not decoration: the four golden signals (latency, traffic, errors, saturation) per service, sliceable by endpoint.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Runbooks&lt;/strong&gt; for the alerts you have, with the first three things to check.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Practice&lt;/strong&gt;: game days where you break something on purpose in a safe environment and run the method.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Takeaways
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Mitigate before you investigate.&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;Build a precise &lt;strong&gt;timeline&lt;/strong&gt;, then ask &lt;strong&gt;what changed&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;Work from &lt;strong&gt;testable hypotheses&lt;/strong&gt;, said out loud.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Bisect&lt;/strong&gt; by region, endpoint, tenant, host and dependency.&lt;/li&gt;
&lt;li&gt;Finish with a &lt;strong&gt;blameless review&lt;/strong&gt; that improves detection, not just the fix.&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;&lt;em&gt;Originally published at &lt;a href="https://ayushwing.com/blog/debugging-production" rel="noopener noreferrer"&gt;ayushwing.com&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>debugging</category>
      <category>sre</category>
      <category>incidents</category>
      <category>observability</category>
    </item>
    <item>
      <title>One dependency for logs, traces and metrics: writing a Spring Boot starter</title>
      <dc:creator>Ayush Soni</dc:creator>
      <pubDate>Wed, 11 Nov 2026 09:07:51 +0000</pubDate>
      <link>https://dev.to/ayushwing/one-dependency-for-logs-traces-and-metrics-writing-a-spring-boot-starter-2fgg</link>
      <guid>https://dev.to/ayushwing/one-dependency-for-logs-traces-and-metrics-writing-a-spring-boot-starter-2fgg</guid>
      <description>&lt;p&gt;The worst time to discover that your services log differently is during an incident. It happens easily: each service is set up by a different person at a different time, so you end up with different field names, trace IDs in some services but not others, and a correlation ID that stops at the first hop. In a platform with several services I've worked on, the answer was a shared module for logging, auth and tracing; this starter is that idea rebuilt in the open.&lt;/p&gt;

&lt;p&gt;The fix isn't a wiki page of conventions. It's making the right setup the default by putting it in a dependency. That's what &lt;a href="https://github.com/ayushwing/spring-boot-starter-observability" rel="noopener noreferrer"&gt;spring-boot-starter-observability&lt;/a&gt; does: add one dependency to a Spring Boot 3 app and you get:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Structured JSON logs&lt;/strong&gt; with &lt;code&gt;traceId&lt;/code&gt;, &lt;code&gt;spanId&lt;/code&gt;, &lt;code&gt;requestId&lt;/code&gt; and &lt;code&gt;correlationId&lt;/code&gt; on every line.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;OpenTelemetry tracing&lt;/strong&gt;: a server span per HTTP request, spans across Kafka producers and consumers using the W3C &lt;code&gt;traceparent&lt;/code&gt; header, and &lt;code&gt;@Traced&lt;/code&gt; for any method.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Micrometer metrics&lt;/strong&gt;: JVM metrics plus &lt;code&gt;@Timed&lt;/code&gt; and &lt;code&gt;@Counted&lt;/code&gt; on any method, and a health indicator.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Correlation IDs&lt;/strong&gt; that cross service boundaries via &lt;code&gt;X-Correlation-Id&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  What a starter actually is
&lt;/h2&gt;

&lt;p&gt;A Spring Boot starter is two small ideas:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;A list of auto-configuration classes in &lt;code&gt;META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports&lt;/code&gt;, which Spring Boot loads at startup.&lt;/li&gt;
&lt;li&gt;Those classes create beans &lt;strong&gt;only when it makes sense&lt;/strong&gt;, using &lt;code&gt;@Conditional...&lt;/code&gt; annotations.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The project is split the way the Spring team splits its own starters:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Module&lt;/th&gt;
&lt;th&gt;Role&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;starter-core&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Annotations (&lt;code&gt;@Traced&lt;/code&gt;) and constants; no auto-configuration&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;starter-autoconfigure&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Logging, tracing and metrics auto-configuration&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;starter-sample&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;A product API that shows everything working&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;h2&gt;
  
  
  Rule 1: every bean backs off
&lt;/h2&gt;

&lt;p&gt;The most important annotation in a starter is &lt;code&gt;@ConditionalOnMissingBean&lt;/code&gt;. If the application defines its own &lt;code&gt;SpanExporter&lt;/code&gt; or &lt;code&gt;SdkTracerProvider&lt;/code&gt;, the starter's version quietly steps aside:&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;@AutoConfiguration&lt;/span&gt;
&lt;span class="nd"&gt;@ConditionalOnClass&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nc"&gt;OpenTelemetrySdk&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;class&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;OtlpGrpcSpanExporter&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;class&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="nd"&gt;@ConditionalOnProperty&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;prefix&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"observability.tracing"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"enabled"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                       &lt;span class="n"&gt;havingValue&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"true"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;matchIfMissing&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;ObservabilityTracingAutoConfiguration&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="nd"&gt;@Bean&lt;/span&gt;
    &lt;span class="nd"&gt;@ConditionalOnMissingBean&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;SpanExporter&lt;/span&gt; &lt;span class="nf"&gt;otlpGrpcSpanExporter&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;ObservabilityProperties&lt;/span&gt; &lt;span class="n"&gt;properties&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;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Each piece is also gated on the classpath and on a property. Kafka tracing only appears when Kafka's interceptor classes are present &lt;strong&gt;and&lt;/strong&gt; a &lt;code&gt;Tracer&lt;/code&gt; bean exists; the servlet filter and MVC interceptor only appear in servlet web applications. A starter that forces beans on you gets ripped out within a quarter.&lt;/p&gt;

&lt;h2&gt;
  
  
  Rule 2: observability never stops the app
&lt;/h2&gt;

&lt;p&gt;If the trace collector is down, your service should still serve traffic. If the exporter can't even be built — a malformed endpoint, say — the auto-configuration catches the failure, logs a warning and returns a no-op exporter:&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="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;catch&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Exception&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="n"&gt;log&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;warn&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Failed to initialize OTLP span exporter (endpoint: {}). "&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt;
             &lt;span class="s2"&gt;"Traces will not be exported: {}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;tracingProps&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getEndpoint&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;e&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getMessage&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="nc"&gt;SpanExporter&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;composite&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;// no-op: the app starts, spans are discarded&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 collector is simply unreachable at runtime, the OpenTelemetry SDK exports in the background and drops what it can't send. Either way, requests keep flowing.&lt;/p&gt;

&lt;h2&gt;
  
  
  Logs that carry the trace
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;RequestContextFilter&lt;/code&gt; runs once per request and fills the SLF4J MDC, so every log line written while handling the request carries the same identifiers:&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="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;request&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getHeader&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="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;correlationId&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="k"&gt;null&lt;/span&gt; &lt;span class="o"&gt;||&lt;/span&gt; &lt;span class="n"&gt;correlationId&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;isBlank&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="n"&gt;correlationId&lt;/span&gt; &lt;span class="o"&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="no"&gt;MDC&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="n"&gt;response&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;setHeader&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="n"&gt;correlationId&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;Everything is cleared in a &lt;code&gt;finally&lt;/code&gt; block — without that, values leak into the next request that reuses the pooled thread, which produces some of the most confusing logs you'll ever read.&lt;/p&gt;

&lt;p&gt;The filter is configurable with properties (&lt;code&gt;include-headers&lt;/code&gt;, &lt;code&gt;header-filter&lt;/code&gt;, &lt;code&gt;custom-fields&lt;/code&gt;) so a team can, for example, add &lt;code&gt;tenantId&lt;/code&gt; to every line without writing code.&lt;/p&gt;

&lt;h2&gt;
  
  
  Tracing across Kafka
&lt;/h2&gt;

&lt;p&gt;HTTP has standard instrumentation in most stacks; message queues are where traces usually break. The producer interceptor writes a W3C header onto each record:&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;// version-traceId-spanId-traceFlags&lt;/span&gt;
&lt;span class="kt"&gt;String&lt;/span&gt; &lt;span class="n"&gt;traceparent&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"00-"&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;traceId&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="s2"&gt;"-"&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;spanId&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="s2"&gt;"-"&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;traceFlags&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;record&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;headers&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;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"traceparent"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;traceparent&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getBytes&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;StandardCharsets&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;UTF_8&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 consumer interceptor reads it back and starts a child span, so a trace that begins with an HTTP request continues through the topic into the consumer. In Jaeger you see one trace across both services instead of two unrelated ones.&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%2F2n31ybnacof4ok5igv4p.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%2F2n31ybnacof4ok5igv4p.png" alt="An HTTP request passes through the request-context filter and tracing interceptor; Kafka messages pass through producer and consumer interceptors; all emit JSON logs, OpenTelemetry spans and Micrometer metrics." width="800" height="784"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;Entry points on the left, the three signals on the right. &lt;a href="https://ayushwing.com/diagrams/observability-starter.html" rel="noopener noreferrer"&gt;Explore the interactive diagram&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Three gaps I found reviewing my own starter
&lt;/h2&gt;

&lt;p&gt;I re-read the code as if it were someone else's pull request. Three findings:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;HTTP spans don't continue the caller's trace.&lt;/strong&gt; The tracing interceptor starts the server span with &lt;code&gt;setParent(Context.current())&lt;/code&gt;, but nothing extracts an incoming &lt;code&gt;traceparent&lt;/code&gt; header first. Kafka hops are linked; HTTP hops start a new trace. The fix is to run the OpenTelemetry &lt;code&gt;TextMapPropagator&lt;/code&gt; over the request headers before starting the span.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Two different trace IDs.&lt;/strong&gt; The log filter takes its &lt;code&gt;traceId&lt;/code&gt; from an &lt;code&gt;X-Trace-Id&lt;/code&gt; header (or falls back to the request ID), while spans have OpenTelemetry's own trace ID. Logs and traces should share one ID; the filter should read it from the current span.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;http.route&lt;/code&gt; uses the raw URI.&lt;/strong&gt; &lt;code&gt;/products/123&lt;/code&gt; and &lt;code&gt;/products/456&lt;/code&gt; become different routes, which explodes metric cardinality. It should use Spring's matched pattern (&lt;code&gt;/products/{id}&lt;/code&gt;).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;None of these show up in a demo. All three show up in production, during the incident you built the starter for. Fixes are the next commits.&lt;/p&gt;

&lt;h2&gt;
  
  
  Takeaways
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Put conventions in a dependency, not a document.&lt;/li&gt;
&lt;li&gt;In a starter, &lt;code&gt;@ConditionalOnMissingBean&lt;/code&gt; is a feature: let teams override anything.&lt;/li&gt;
&lt;li&gt;Observability failures must degrade to "no data", never to "no service".&lt;/li&gt;
&lt;li&gt;Trace propagation is only as good as its weakest hop — test every protocol your services speak.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Code, tests and the sample app are on &lt;a href="https://github.com/ayushwing/spring-boot-starter-observability" rel="noopener noreferrer"&gt;GitHub&lt;/a&gt;.&lt;/p&gt;




&lt;p&gt;&lt;em&gt;Originally published at &lt;a href="https://ayushwing.com/blog/spring-boot-starter-observability" rel="noopener noreferrer"&gt;ayushwing.com&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>springboot</category>
      <category>observability</category>
      <category>opentelemetry</category>
      <category>java</category>
    </item>
  </channel>
</rss>
