<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Prachi Patil on Medium]]></title>
        <description><![CDATA[Stories by Prachi Patil on Medium]]></description>
        <link>https://medium.com/@prachy.p?source=rss-9368d6ebb0a1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*fJ60tYfiFpD32NW_.</url>
            <title>Stories by Prachi Patil on Medium</title>
            <link>https://medium.com/@prachy.p?source=rss-9368d6ebb0a1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 20:26:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@prachy.p/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Searchable Only When Durable: Designing a Failure-Aware Order Pipeline]]></title>
            <link>https://medium.com/@prachy.p/searchable-only-when-durable-designing-a-failure-aware-order-pipeline-d4cba8190dc8?source=rss-9368d6ebb0a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4cba8190dc8</guid>
            <category><![CDATA[reliability-engineering]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[cloud-architecture]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <dc:creator><![CDATA[Prachi Patil]]></dc:creator>
            <pubDate>Sat, 26 Sep 2026 17:08:40 GMT</pubDate>
            <atom:updated>2026-09-26T17:08:40.168Z</atom:updated>
            <content:encoded><![CDATA[<p>A search system often needs two very different things:</p><ul><li>fast lookup across a small set of attributes</li><li>access to the complete document once a result is found</li></ul><p>In our order platform, we separated those responsibilities.</p><p><strong>Elasticsearch handled discovery. Blob storage held the complete order JSON.</strong></p><p>The read flow was simple:</p><p><strong>Search → identify the order → fetch the full document.</strong></p><h3>Architecture: Read Path</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5v68Srt9fQa-vSv-cx31HA.png" /><figcaption>Elasticsearch finds the order; Blob storage returns the complete document.</figcaption></figure><p>This separation worked well, but it created one important architectural invariant:</p><blockquote><strong><em>If an order is searchable, its complete document must already be retrievable.</em></strong></blockquote><blockquote>Everything else in the design followed from that decision.</blockquote><h4>Decision 1: Persist Before You Index</h4><p>Consider this state:</p><pre>Elasticsearch ✅<br>Blob          ❌</pre><p>The user can find the order, but fetching the complete order fails.</p><p>The reverse is safer:</p><pre>Blob          ✅<br>Elasticsearch ❌</pre><p>The order is temporarily not searchable, but we haven’t exposed an incomplete record.</p><p>So our write ordering became:</p><p><strong>Blob first → Elasticsearch second</strong></p><p>This wasn’t just sequencing in the code. It was our consistency boundary.</p><h4>Decision 2: Batch Without Breaking the Invariant</h4><p>The simplest implementation would be:</p><pre>Order 1 → Blob → Elasticsearch<br>Order 2 → Blob → Elasticsearch<br>Order 3 → Blob → Elasticsearch<br>...</pre><p>Correct, but expensive at high throughput.</p><p>Each order introduces another set of remote calls.</p><p>Instead, we process orders in small batches of five.</p><p>Blob writes execute in parallel, and only when the Blob stage succeeds do we send the batch to Elasticsearch using a bulk operation.</p><h4>Architecture: Normal Write Path</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uArHoi3QqlyE7RvRo92M4g.png" /><figcaption>Parallel Blob writes reduce latency; Elasticsearch bulk indexing reduces network round trips.</figcaption></figure><p>The important part is that batching changed the implementation, but <strong>not the invariant</strong>.</p><p>An order still never becomes searchable before its complete document exists.</p><h4>What If One Blob Write Fails?</h4><p>Suppose a batch looks like this:</p><pre>O1 ✅<br>O2 ✅<br>O3 ❌<br>O4 ✅<br>O5 ✅</pre><p>We don’t index the four successful orders and leave O3 behind.</p><p>The failed Blob operation first goes through local retries.</p><p>If it succeeds, the batch continues to Elasticsearch.</p><p>If it still fails, the <strong>entire batch moves into recovery</strong>.</p><p>That means O1, O2, O4 and O5 may be written again.</p><p>We accepted that because both Blob and Elasticsearch writes are <strong>idempotent</strong>.</p><p>Because the writes are idempotent, reprocessing previously successful orders is safe.That gave us a useful trade-off:</p><blockquote><em>A little extra I/O in exchange for a much simpler recovery model.</em></blockquote><h3>Local Retry Is Not Enough for a Regional Failure</h3><p>Retries work well when the problem is temporary.</p><p>They don’t help much when the regional dependency itself is unhealthy.</p><pre>Write → Fail → Retry → Fail → Retry → Fail</pre><p>At that point we are repeatedly calling the same failing system.</p><p>So after Blob retries are exhausted, we move the failed batch to a <strong>recovery Blob in another region</strong>.</p><p>That matters because the failed work is now outside the same failure domain as the primary Blob.</p><p>A poller checks the recovery Blob every five minutes.</p><p>When it finds work:</p><pre>Remote Recovery Blob<br>        ↓<br>      Poller<br>        ↓<br>  Blob Retry Queue<br>        ↓<br>Parallel Blob Writes</pre><p>Once the batch is picked up and added to the retry queue, the corresponding recovery record is removed from the remote Blob.</p><p>The recovery Blob is therefore not the retry processor.</p><p>It is a <strong>durable handoff point</strong>.</p><h3>Elasticsearch Failure Has Its Own Recovery Path</h3><p>Elasticsearch is different.</p><p>By the time we reach Elasticsearch, Blob has already succeeded.</p><p>So if Elasticsearch indexing fails, there is no reason to rewrite Blob.</p><p>The system first performs the normal Elasticsearch bulk retry.</p><p>If those retries are exhausted:</p><pre>Elasticsearch Bulk<br>        ↓<br>    Local Retry<br>        ↓<br>Remote ES Retry Blob<br>        ↓<br>      Poller<br>        ↓<br>   ES Retry Queue<br>        ↓<br>Elasticsearch Bulk</pre><p>The recovery starts from <strong>Elasticsearch</strong>, not from the beginning of the pipeline.</p><p>That distinction is important.</p><blockquote><strong><em>Recover from the failed stage, not from the start of the workflow.</em></strong></blockquote><h3>Architecture: Complete Failure and Recovery Flow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UgEEoZfqNROqOelPWHbFYQ.png" /><figcaption>Blob failures re-enter the Blob stage. Elasticsearch failures re-enter only the indexing stage.</figcaption></figure><h3>Why We Didn’t Try to Make This a Distributed Transaction</h3><p>Blob and Elasticsearch are independent systems with different responsibilities.</p><p>Trying to make them behave like one transactional database would introduce significantly more coordination and operational complexity.</p><p>Instead, the design relies on a few explicit guarantees:</p><p>ConcernDecisionSearch correctnessBlob before ElasticsearchThroughputParallel Blob writes + Elasticsearch bulkSafe replayIdempotent writesShort-lived failureLocal retriesRegional Blob failureCross-region durable recoveryElasticsearch failureIndependent ES recovery path</p><p>The goal wasn’t to guarantee that every operation succeeds on the first attempt.</p><p>The goal was to guarantee that <strong>failure does not violate the user-facing contract</strong>.</p><h3>The Trade-off We Chose</h3><p>A single order failing can cause a five-order batch to be replayed.</p><p>That means some successful writes happen more than once.</p><p>We accepted that cost because:</p><ul><li>the batch is small</li><li>writes are idempotent</li><li>bulk operations reduce normal-path overhead</li><li>recovery stays easy to reason about</li><li>an incomplete order is never exposed through search</li></ul><p>This is a trade-off I increasingly value in distributed systems:</p><blockquote><strong><em>Operational simplicity can be more valuable than eliminating every redundant write.</em></strong></blockquote><h3>The Takeaway</h3><p>The most important part of this architecture wasn’t the retry count or the API used to write Blob.</p><p>It was defining the invariant first:</p><blockquote><strong><em>Searchable only when durable.</em></strong></blockquote><p>From that one decision, the rest of the architecture became easier to reason about:</p><p><strong>Persist before indexing.<br>Batch for throughput.<br>Use idempotency for replay.<br>Move failed work outside the failure domain.<br>Resume recovery from the stage that actually failed.</strong></p><p>Retries are an implementation mechanism.</p><p><strong>Recoverability is an architectural property.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4cba8190dc8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When a Health Check Became the Outage]]></title>
            <link>https://medium.com/@prachy.p/when-a-health-check-became-the-outage-eef577e95a48?source=rss-9368d6ebb0a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/eef577e95a48</guid>
            <category><![CDATA[production]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[design]]></category>
            <dc:creator><![CDATA[Prachi Patil]]></dc:creator>
            <pubDate>Wed, 23 Sep 2026 16:00:54 GMT</pubDate>
            <atom:updated>2026-09-23T16:00:54.210Z</atom:updated>
            <content:encoded><![CDATA[<p>We usually think of health checks as harmless.</p><p>They run in the background, verify that a dependency is reachable, and help the system recover when something goes wrong.</p><p>In one production incident, our health check became part of the failure itself.</p><h3>The Setup</h3><p>Our application used a startup probe to verify database connectivity.</p><p>The probe executed a query similar to:</p><pre>WHERE someField LIKE &#39;%1%&#39;</pre><p>The logic was straightforward:</p><p><strong>If the query succeeds, the database is reachable. </strong>For a long time, this worked without any visible problem.</p><p>Then the data grew.</p><h3>What Changed at Scale</h3><p>Our database was partitioned by customerId.</p><p>That meant queries containing the partition key could be routed directly to a specific partition.</p><p>But this probe query did not include customerId.</p><p>So the database had to execute it across multiple partitions.</p><p>At the same time, the query used a leading wildcard:</p><pre>LIKE &#39;%1%&#39;</pre><p>That made the search more expensive because the database had to inspect a much larger amount of data.</p><p>Individually, neither detail looked dramatic.</p><p>Together, at production scale, they became expensive.</p><h3>The Failure</h3><p>The startup probe was effectively doing this:</p><p><strong>Startup Probe → Leading-Wildcard Search → Cross-Partition Scan → High CPU</strong></p><p>As these queries executed, CPU usage on the database nodes increased sharply.</p><p>Eventually, some database nodes became unhealthy.</p><p>That created the next part of the failure:</p><p><strong>DB Nodes Unhealthy → Database Connectivity Fails → Application Pods Crash</strong></p><p>The system entered a bad feedback loop.</p><p>The application was checking whether the database was healthy, while the health check itself was contributing additional load to an already stressed database.</p><h3>The Real Mistake</h3><p>The mistake was not simply using LIKE.</p><p>The bigger mistake was using a <strong>business-data query as a connectivity check</strong>.</p><p>A startup probe should answer a very narrow question:</p><blockquote><em>Can my application reach the database?</em></blockquote><p>Our probe was effectively asking:</p><blockquote><em>Can my database execute a distributed search across a large production dataset?</em></blockquote><p>Those are very different operations.</p><h3>What We Learned</h3><p>Health checks should be designed differently from normal application queries.</p><p>They should be:</p><ul><li>lightweight</li><li>predictable</li><li>cheap to execute repeatedly</li><li>independent of production data growth</li><li>partition-aware when a data lookup is unavoidable</li></ul><p>The most important question is not just:</p><p><strong>Does this query work?</strong></p><p>It is:</p><p><strong>How expensive will this query become when the system is under stress?</strong></p><p>Because health checks, retries, and recovery paths often run more frequently exactly when the system is already unhealthy.</p><h3>Final Thought</h3><p>The most dangerous production issues are not always caused by obviously bad code.</p><p>Sometimes they come from small decisions that looked completely reasonable when the system was smaller.</p><p>In our case, a query written to prove that the database was healthy eventually became one of the reasons it was not.</p><p><strong>A health check should observe the system, not become part of the workload that takes it down.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eef577e95a48" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[40 Searchable Fields. 900 Stored. Where Our Elasticsearch Design Went Wrong]]></title>
            <link>https://medium.com/@prachy.p/when-elasticsearch-became-more-than-a-search-index-a8713f91ef79?source=rss-9368d6ebb0a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8713f91ef79</guid>
            <category><![CDATA[search-engines]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[design]]></category>
            <dc:creator><![CDATA[Prachi Patil]]></dc:creator>
            <pubDate>Mon, 14 Sep 2026 10:52:15 GMT</pubDate>
            <atom:updated>2026-10-01T19:22:57.285Z</atom:updated>
            <content:encoded><![CDATA[<p>Sometimes a design works perfectly well at the beginning — until the data model starts growing.</p><p>That is what happened with one of our <strong>Search APIs backed by Elasticsearch</strong>.</p><p>The requirement was simple:</p><blockquote><strong><em>Search for an order using a set of attributes and return the complete order.</em></strong></blockquote><blockquote>Using Elasticsearch seemed like a natural choice.</blockquote><p>But over time, we realized we were asking Elasticsearch to do much more than search.</p><h3>40 Searchable Fields. 900 Fields Stored.</h3><p>Initially, the order document was relatively small.</p><p>As new business requirements and consumers were added, the order model kept evolving.</p><p>Eventually, each Elasticsearch document contained roughly:</p><p><strong>800–900 attributes.</strong></p><p>But only around:</p><p><strong>40 attributes were actually searchable.</strong></p><p>The remaining fields were primarily stored because the Search API needed them to construct the complete order response.</p><p>So our Elasticsearch document effectively looked like:</p><pre>Order Document<br>│<br>├── ~40 searchable attributes<br>│<br>└── ~800+ additional attributes<br>        ↓<br>   Stored mainly for<br>   response generation</pre><p>That difference became important at scale.</p><h4>The Cost Started Showing Up in the Shards</h4><p>We were retaining years of historical order data.</p><p>As the number of orders increased and the order document became larger, the Elasticsearch index grew significantly.</p><p>Our cluster had:</p><p><strong>60 primary shards + 1 replica</strong></p><p>and shard sizes had grown to approximately:</p><p><strong>250 GB per shard.</strong></p><p>At that point, Elasticsearch wasn’t just maintaining a search index.</p><p>It was maintaining a very large copy of our complete order data.</p><p>And large shards come with operational costs — more data to store and replicate, and heavier shard recovery, relocation, and rebalancing.</p><p>The convenience of returning everything directly from Elasticsearch had slowly become an infrastructure problem.</p><h4>Where Did the Design Go Wrong?</h4><p>The mistake wasn’t storing documents in Elasticsearch.</p><p>Elasticsearch obviously needs documents to search.</p><p>The problem was <strong>coupling the search model with the complete response model</strong>.</p><p>Every time the order response grew:</p><pre>New business requirement<br>        ↓<br>New response attributes<br>        ↓<br>Larger Elasticsearch document<br>        ↓<br>Larger index<br>        ↓<br>Heavier shards</pre><p>Even if those new attributes had absolutely nothing to do with search.</p><p>That was the architectural smell.</p><p><strong>Why should adding a non-searchable response field make our search infrastructure heavier?</strong></p><h4>A Better Separation</h4><p>Elasticsearch only needed enough information to answer:</p><blockquote><strong><em>Which orders match this query?</em></strong></blockquote><p>Once we knew the matching order IDs, the complete order could have been retrieved from a durable data store such as Blob/Object Storage, Cassandra, or another purpose-built order store.</p><pre>Search Request<br>      ↓<br>Elasticsearch<br>(~40 searchable fields)<br>      ↓<br>Matching Order IDs<br>      ↓<br>Order Store<br>      ↓<br>Complete Order JSON</pre><p>Now the responsibilities are clear:</p><p><strong>Elasticsearch → Find the order</strong></p><p><strong>Order Store → Return the complete order</strong></p><p>The order response can grow from 100 to 500 to 900 attributes without forcing the search index to grow with it.</p><h4>The Lesson</h4><p>The biggest lesson was not:</p><blockquote><em>“Don’t store data in Elasticsearch.”</em></blockquote><p>It was:</p><blockquote><strong><em>Don’t let your search index become your complete data store just because it is convenient.</em></strong></blockquote><p>In our case, only around <strong>40 attributes were needed for search</strong>, while <strong>800–900 attributes eventually became part of every order document</strong>.</p><p>At scale, that difference matters.</p><p>The Search API worked. Elasticsearch worked.</p><p>But the boundary between <strong>searching for data</strong> and <strong>storing the complete data</strong> had disappeared.</p><p>And that was the real design mistake.</p><blockquote><strong><em>Index what you need to search. Store the complete source of truth where it belongs.</em></strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8713f91ef79" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When Elasticsearch Aggregations Became Our Performance Bottleneck]]></title>
            <link>https://medium.com/@prachy.p/elasticsearch-could-do-it-that-didnt-mean-we-should-099c31ced971?source=rss-9368d6ebb0a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/099c31ced971</guid>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[aggregation]]></category>
            <dc:creator><![CDATA[Prachi Patil]]></dc:creator>
            <pubDate>Sun, 13 Sep 2026 11:39:53 GMT</pubDate>
            <atom:updated>2026-10-01T19:24:48.127Z</atom:updated>
            <content:encoded><![CDATA[<p>Some engineering mistakes do not look like mistakes at first.</p><p>They look practical. They look simple. They even use the right feature of the right technology.</p><p>That is what happened with our use of <strong>Elasticsearch Aggregations</strong>.</p><p>We had order data in Elasticsearch. Consumers needed aggregation-style answers. Elasticsearch supported aggregations.</p><p>So the solution felt obvious:</p><blockquote><em>“Let’s expose an Aggregation API on top of Elasticsearch.”</em></blockquote><blockquote>And it worked. Until scale changed the story.</blockquote><p><strong>The Requirement Looked Simple</strong></p><p>One of the use cases was:</p><blockquote><strong><em>For a customer, find the distinct addresses used across their orders in the last one year.</em></strong></blockquote><blockquote>There were similar requirements for distinct items, SKUs, and other order attributes.</blockquote><p>From an API perspective, this looked straightforward:</p><pre>Customer + Date Range<br>        ↓<br>Aggregation API<br>        ↓<br>Elasticsearch<br>        ↓<br>Response</pre><p>Clean design. Simple flow. No obvious problem.</p><p>But the important question was not:</p><blockquote><em>“Can Elasticsearch do this?”</em></blockquote><blockquote>It was:</blockquote><blockquote><strong><em>“What will Elasticsearch have to do when this runs on production-scale data?”</em></strong></blockquote><blockquote>That is the question we underestimated.</blockquote><p><strong>Small Query. Huge Dataset.</strong></p><p>Our platform was processing roughly <strong>3 million records per day</strong>.</p><p>That becomes:</p><pre>3 million records/day<br>≈ 90 million records/month<br>≈ 1.1 billion records/year</pre><p>Now the same request looks very different.</p><blockquote><em>“Find distinct addresses for a customer over one year” </em>is not just a simple API call anymore.</blockquote><p>Elasticsearch has to find matching historical records, read the aggregation field, calculate distinct values, merge shard-level results, and return the final response.</p><p>The API looked lightweight. The backend work was not. As the time range increased, the cost increased too.</p><p>We started seeing the impact clearly:</p><p><strong>CPU went up. Response time went up.</strong></p><p><em>The query was valid. The workload was the problem.</em></p><p><strong>The Mistake Was Not Using Aggregations</strong></p><p>Elasticsearch aggregations are powerful. They are useful and valid for many use cases.</p><p>The mistake was assuming:</p><blockquote><strong><em>Because Elasticsearch supports aggregations, our operational Elasticsearch cluster should run large historical aggregations at our scale.</em></strong></blockquote><p>A small aggregation over a short date range is fine.</p><p>But repeatedly calculating distinct values across months or years of order history, while the same cluster is also ingesting millions of records daily, is a different problem.</p><p>At that point, aggregation is no longer just a search feature.</p><p>It becomes an analytics workload.</p><p><strong>High-Cardinality Fields Made It Expensive</strong></p><p>Not all aggregations behave the same.</p><p>Aggregating a field with a few possible values is relatively cheap.</p><p>But fields like these are different:</p><pre>address<br>itemId<br>SKU<br>productId</pre><p>These can have many unique values.</p><p>That makes them <strong>high-cardinality fields</strong>.</p><p>Distinct-value aggregations on high-cardinality fields require more computation and memory, especially when the query spans large historical data.</p><p>So a request like this:</p><pre>Customer X<br>+ Last 1 year<br>+ Distinct addresses</pre><p>may look harmless in the API contract, but it can become expensive at runtime.</p><p><strong>We Mixed Operational Search With Analytics</strong></p><p>The Elasticsearch cluster was already doing its primary job: handling order ingestion and updates.</p><p>Then we added historical aggregations on top of it.</p><pre>Elasticsearch<br>                       |<br>          +------------+------------+<br>          |                         |<br>          v                         v<br>   Order ingestion           Historical<br>   and updates               aggregations</pre><p>Both workloads were now competing for the same CPU, memory, disk I/O, and shard resources.</p><p>That was the real architectural concern.</p><p>We had turned an operational search cluster into a historical analytics engine without treating analytics as a separate workload.</p><p><strong>What We Should Have Done Instead</strong></p><p>For repeated aggregation use cases, we should not have calculated everything at request time.</p><p>Instead of this:</p><pre>API Request<br>     ↓<br>Read historical orders<br>     ↓<br>Calculate aggregation<br>     ↓<br>Return response</pre><p>A better approach would be:</p><pre>Order Event<br>     ↓<br>Update customer-level summary<br>     ↓<br>Store pre-computed result<br>     ↓<br>API performs a lookup</pre><p>For example, if we frequently need distinct addresses for a customer, we can maintain that summary as orders arrive.</p><p>The API then reads a prepared result instead of recalculating from historical data every time.</p><p>Another option is to separate the workloads:</p><pre>Order Data<br>                        |<br>          +-------------+-------------+<br>          |                           |<br>          v                           v<br>   Elasticsearch              Aggregation Store<br>   for search                 for analytics</pre><p>The exact technology is secondary.</p><p>The important point is separation.</p><p>Operational search and historical analytics should not always run on the same infrastructure.</p><h3>The Lesson</h3><p><em>The biggest lesson was simple:</em></p><blockquote><strong><em>Do not design only around what a technology can do. Design around what your workload will make it do.</em></strong></blockquote><p>Elasticsearch could run the aggregation.</p><p>That was not the issue.</p><p>The issue was running large historical aggregations on an already busy operational cluster at production scale.</p><p>The feature existed.</p><p>The query worked.</p><p>The API worked.</p><p>But the workload did not belong there at that scale.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=099c31ced971" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scaling Event Consumption: Why We Moved from Event Hub to Kafka]]></title>
            <link>https://medium.com/@prachy.p/scaling-event-consumption-why-we-moved-from-event-hub-to-kafka-d192b5f18ddf?source=rss-9368d6ebb0a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/d192b5f18ddf</guid>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[azure-event-hub]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[partitioning]]></category>
            <dc:creator><![CDATA[Prachi Patil]]></dc:creator>
            <pubDate>Fri, 04 Sep 2026 10:08:36 GMT</pubDate>
            <atom:updated>2026-09-04T10:08:36.863Z</atom:updated>
            <content:encoded><![CDATA[<p>As our event-processing workload grew to <strong>millions of events</strong>, our existing Event Hub-based architecture started showing scalability limitations.</p><p>We were using a <strong>Standard Event Hub with 32 partitions</strong>. The setup worked well initially, but as the event volume increased, consumer lag started building up and processing latency gradually increased from seconds to, in some cases, <strong>minutes</strong>.</p><p>At first, our natural approach was to scale the number of consumer pods. However, we soon realized that the number of pods was not the only factor determining how much data we could consume.</p><p>The real constraint was the <strong>32 partitions behind those consumers</strong>.</p><h3>The Scaling Problem</h3><p>Our initial architecture looked like this:</p><pre>Event Producers<br>                    │<br>                    ▼<br>          ┌──────────────────┐<br>          │    Event Hub     │<br>          │   32 Partitions  │<br>          └────────┬─────────┘<br>                   │<br>        ┌──────────┼──────────┐<br>        ▼          ▼          ▼<br>      Pod 1      Pod 2      Pod 32<br>        │          │          │<br>        └──────────┼──────────┘<br>                   ▼<br>            Event Processing</pre><p>As the event volume increased, consumers had more data to process and the backlog started growing.</p><blockquote><strong><em>Add more consumer pods.</em></strong></blockquote><p>But with 32 partitions, there was a practical limit to how much parallelism we could achieve.</p><p>Once we reached around <strong>32 consumer pods</strong>, adding more pods did not provide meaningful additional throughput because there were no additional partitions to distribute the workload across.</p><p>For example, scaling from:</p><p><strong>32 pods → 50 pods → 100 pods</strong></p><p>does not automatically provide the same increase in consumption capacity.</p><p>The Event Hub still had only <strong>32 partitions</strong>.</p><blockquote><strong><em>Beyond 32 pods, increasing the number of consumer pods did not make sense for our workload because the partition count was the limiting factor.</em></strong></blockquote><h3>The Bottleneck Wasn’t Just the Pods</h3><p>As the event volume continued to grow, we started seeing pressure at multiple levels:</p><ul><li><strong>32 partitions limited consumer parallelism</strong></li><li>Increasing <strong>ingress and egress traffic</strong> added further pressure</li><li>The processing rate could not keep up with the incoming event rate</li><li>Consumer lag continued to increase</li></ul><p>This resulted in consumption latency increasing from <strong>seconds to seconds/minutes</strong> under heavy workloads.</p><p>At this point, simply scaling the application layer was no longer enough. We needed more parallelism at the <strong>event-stream level</strong>.</p><h3>Moving to Kafka</h3><p>We decided to move the workload to <strong>Kafka with 200 partitions</strong>.</p><p>The primary reason was straightforward:</p><blockquote><strong><em>We needed significantly more partitions to provide more consumer parallelism.</em></strong></blockquote><pre>Event Producers<br>                    │<br>                    ▼<br>          ┌──────────────────┐<br>          │      Kafka       │<br>          │  200 Partitions  │<br>          └────────┬─────────┘<br>                   │<br>        ┌──────────┼──────────┐<br>        ▼          ▼          ▼<br>     Consumer   Consumer   Consumer<br>       Pod        Pod         Pod<br>        │          │          │<br>        └──────────┼──────────┘<br>                   ▼<br>            Event Processing</pre><p>Moving from <strong>32 to 200 partitions</strong> gave us significantly more room to distribute the workload across consumers.</p><h3>Consumer Concurrency Added Another Level of Scaling</h3><p>Kafka also gave us the ability to configure <strong>consumer concurrency</strong> in our application.</p><p>This is important because scaling is not only about the number of pods. We can also control how many consumers run concurrently within those pods.</p><p>For example, with:</p><ul><li><strong>200 Kafka partitions</strong></li><li><strong>10 pods</strong></li><li><strong>10 consumer threads per pod</strong></li></ul><p>we could have up to <strong>100 consumers</strong> processing partitions concurrently.</p><pre>Kafka<br>                200 Partitions<br>                      │<br>        ┌─────────────┼─────────────┐<br>        ▼             ▼             ▼<br>      Pod 1         Pod 2         Pod 10<br>   10 consumers   10 consumers   10 consumers<br>        │             │             │<br>        └─────────────┼─────────────┘<br>                      ▼<br>              Parallel Processing</pre><p>The important point is that <strong>concurrency works together with partition count</strong>.</p><p>If we had only 32 partitions, increasing the number of consumer threads to 100 would not give us 100-way partition-level parallelism. There would still be only 32 partitions available to consume.</p><p>With <strong>200 partitions</strong>, however, we have much more room to increase consumer concurrency and utilize additional processing capacity.</p><p>This gave us two useful scaling levers:</p><p><strong>1. Increase the number of pods</strong></p><p><strong>2. Increase consumer concurrency within the pods</strong></p><p>Both are ultimately supported by having enough partitions to distribute the workload.</p><h3>The Result</h3><p>The move to Kafka gave us significantly more consumer parallelism and improved our ability to handle increasing event volumes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s-cvGlVciNSLkn6Z3Pj9UQ.png" /></figure><h3>Key Takeaway</h3><p>Our experience highlighted an important principle in high-volume event processing:</p><blockquote><strong><em>Consumer scalability is ultimately constrained by the number of partitions available in the event stream.</em></strong></blockquote><p>With our original Event Hub setup, <strong>32 partitions meant that scaling beyond roughly 32 consumer pods did not provide meaningful additional parallelism</strong>.</p><p>Kafka’s <strong>200 partitions</strong>, combined with configurable consumer concurrency, gave us significantly more flexibility to distribute and process events in parallel.</p><p>The migration therefore wasn’t simply about changing the messaging platform. It was about giving the application enough <strong>partition-level and consumer-level parallelism</strong> to keep up as the workload grew to millions of events.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d192b5f18ddf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[We Tried Moving 600 Million Files With AzCopy. Here’s Where It Broke Down.]]></title>
            <link>https://medium.com/@prachy.p/why-azcopy-didnt-scale-to-600-million-files-b12b2d4782b0?source=rss-9368d6ebb0a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/b12b2d4782b0</guid>
            <category><![CDATA[large-scale-projects]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[azcopy]]></category>
            <category><![CDATA[data-migration]]></category>
            <dc:creator><![CDATA[Prachi Patil]]></dc:creator>
            <pubDate>Tue, 25 Aug 2026 17:02:27 GMT</pubDate>
            <atom:updated>2026-10-01T19:27:39.379Z</atom:updated>
            <content:encoded><![CDATA[<p>Migrating data between Azure regions sounds simple: <strong>copy data from SCUS to WUS</strong>.</p><p>Our case was different.</p><p>We had <strong>TB-scale data distributed across approximately 600 million files</strong> that needed to be transferred from <strong>South Central US (SCUS) to West US (WUS)</strong>.</p><p>We started with AzCopy and tried multiple approaches to improve the migration. But as the number of files increased, the problem became less about transferring data and more about <strong>controlling and monitoring the transfer at scale</strong>.</p><p>Eventually, we moved away from AzCopy and built a Java-based transfer solution using <strong>Parquet files and Databricks to extract the file names</strong>.</p><h3>The Problem</h3><p>RequirementDetailsSourceSCUSDestinationWUSData volumeTBsNumber of files~600 millionTransferCross-region, asynchronousPrimary challengeLarge number of individual files</p><p>The challenge was not only the amount of data.</p><p><strong>600 million files meant 600 million individual objects that had to be discovered, transferred, retried and tracked.</strong></p><h3>Approach 1: AzCopy Copy</h3><p>Our initial approach was to use AzCopy for the cross-region transfer.</p><p>We used the standard azcopy copy operation to transfer the data from SCUS to WUS.</p><p>This worked as an initial solution, but the scale of the migration quickly exposed limitations.</p><h3>Approach 2: AzCopy Sync</h3><p>We then explored azcopy sync to make the migration incremental and avoid unnecessary re-copying.</p><p>We also used the following options:</p><p>OptionPurpose--overwrite falseAvoid re-copying already transferred blobs--check-length falseAvoid additional length validation--include-patternTransfer files matching specific filename patterns--log-level ERRORReduce logging overhead</p><p>Example:</p><pre>azcopy sync &lt;source_sas&gt; &lt;dest_sas&gt; \<br>  --overwrite false \<br>  --check-length false \<br>  --include-pattern &#39;a*;b*&#39; \<br>  --log-level ERROR</pre><p>The idea was to make the synchronization incremental and reduce unnecessary processing.</p><p>However, the migration was still not performing well at our scale.</p><h3>Approach 3: AzCopy Async + Filename-Based Parallelization</h3><p>We then tried running AzCopy transfers asynchronously and splitting the workload using filename patterns.</p><p>For example:</p><pre>600M Files<br>    │<br>    ├── a*, b* → AzCopy Job 1<br>    ├── c*, d* → AzCopy Job 2<br>    ├── e*, f* → AzCopy Job 3<br>    └── ...</pre><p>The idea was simple:</p><blockquote><em>Divide the massive dataset into smaller independent jobs and run them concurrently.</em></blockquote><p>We continued using the same optimizations:</p><p>OptionPurpose--overwrite falseAvoid re-copying completed blobs--check-length falseReduce validation overhead--include-patternPartition files by filename--log-level ERRORReduce logging overhead</p><p>This increased parallelism, but it still did not solve the fundamental problem.</p><h3>Why the AzCopy Approaches Didn’t Work</h3><p>Across the different approaches, we observed the following:</p><p>ProblemWhat we observedHuge number of files~600M individual objects created significant processing overheadAzCopy overloadIncreasing concurrent jobs did not scale proportionallyLong-running transfersMigration took an extremely long timeProcess stabilityProcesses could eventually hangProgress visibilityWe could not reliably determine the percentage transferredOperational controlDifficult to understand completed, failed and remaining files</p><p>The biggest concern was <strong>visibility</strong>.</p><p>For a migration involving 600 million files, we needed to know:</p><pre>Total files      : 600M<br>Transferred      : ?<br>Failed           : ?<br>Remaining        : ?<br>Progress         : ?%</pre><p>We didn’t have the level of visibility and control required to confidently operate the migration.</p><p>At this point, adding more AzCopy jobs or tuning additional parameters was no longer addressing the fundamental problem.</p><p>We decided to change the architecture.</p><h3>The Final Solution</h3><p>Instead of asking AzCopy to discover and manage the files, we separated <strong>file discovery</strong> from <strong>file transfer</strong>.</p><p>The final flow was:</p><pre>SCUS<br>                          │<br>                          ▼<br>                  ┌─────────────────┐<br>                  │  Parquet Files  │<br>                  │    in Blob      │<br>                  └────────┬────────┘<br>                           │<br>                           ▼<br>                  ┌─────────────────┐<br>                  │   Databricks    │<br>                  │ Extract Filenames│<br>                  └────────┬────────┘<br>                           │<br>                           ▼<br>                       File Names<br>                           │<br>                           ▼<br>                  ┌─────────────────┐<br>                  │ Java Transfer   │<br>                  │   Application   │<br>                  └────────┬────────┘<br>                           │<br>                           ▼<br>                          WUS</pre><h3>1. Generate Parquet Files</h3><p>We generated <strong>Parquet files in Blob Storage</strong> containing the required file information.</p><p>This gave us a structured source from which we could identify the files that needed to be transferred.</p><h3>2. Extract File Names Using Databricks</h3><p>A Databricks job processed the Parquet files and extracted the <strong>file names</strong>.</p><pre>Parquet Files<br>      ↓<br>Databricks<br>      ↓<br>Extract File Names</pre><p>Instead of relying on the transfer tool to discover millions of files, we now had the file names explicitly available.</p><h3>3. Transfer Using Java</h3><p>Our Java application consumed the extracted file names and transferred the corresponding files from:</p><pre>SCUS → WUS</pre><p>The application controlled the transfer process and its concurrency.</p><p>This also gave us the ability to build monitoring and failure-handling logic around the actual files being transferred.</p><h3>AzCopy vs. Final Solution</h3><p>AzCopyJava-Based SolutionFile discoveryAzCopyDatabricksInput to transferBlob storageExplicit file namesConcurrencyAzCopy processesJava applicationRetry handlingAzCopyApplication controlledProgress trackingDifficult at our scaleApplication controlledFailure visibilityLimitedCan be tracked per fileOperational controlLimitedHighScaleChallenging at ~600M filesDesigned around the file list</p><h3>What We Learned</h3><p>The lesson wasn’t that <strong>AzCopy is unsuitable for large data migrations</strong>.</p><p>AzCopy is a good choice for many migration scenarios.</p><p>Our challenge was the combination of:</p><p><strong>TBs of data + ~600 million files + long-running cross-region transfer + need for operational visibility.</strong></p><p>At that scale, the problem became more than simply moving data.</p><p>We needed to know:</p><blockquote><strong><em>Which files need to move, which files have moved, which failed, and how much is left?</em></strong></blockquote><p>That led us to separate the responsibilities:</p><pre>File Discovery<br>               │<br>               ▼<br>          Databricks<br>               │<br>          File Names<br>               │<br>               ▼<br>        Java Application<br>               │<br>        Controlled Transfer<br>               │<br>               ▼<br>              WUS</pre><p>The biggest architectural decision was recognizing when <strong>further tuning of the existing approach was no longer enough</strong>.</p><p>Instead of trying to make AzCopy handle the entire problem, we built a solution where <strong>we controlled the file list and the transfer process ourselves</strong>.</p><p>For migrations involving hundreds of millions of files, sometimes the biggest optimization isn’t increasing concurrency.</p><p><strong>It’s taking control of the workload.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b12b2d4782b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Adding More Elasticsearch Nodes Didn’t Solve Our Disk Usage Problem]]></title>
            <link>https://medium.com/@prachy.p/why-adding-more-elasticsearch-nodes-didnt-solve-our-disk-usage-problem-e5c4b5b25484?source=rss-9368d6ebb0a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5c4b5b25484</guid>
            <category><![CDATA[partitioning]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <dc:creator><![CDATA[Prachi Patil]]></dc:creator>
            <pubDate>Tue, 18 Aug 2026 17:49:37 GMT</pubDate>
            <atom:updated>2026-08-18T17:49:37.552Z</atom:updated>
            <content:encoded><![CDATA[<p>As our Elasticsearch data volume grew, we started seeing increasing disk utilization across the cluster.</p><p>Our first thought was simple:</p><blockquote><strong><em>More data → more disk usage → add more nodes.</em></strong></blockquote><blockquote>So we increased our Elasticsearch cluster from <strong>6 nodes to 12 nodes</strong>, and later from <strong>12 to 18 nodes</strong>.</blockquote><p>But the disk-usage problem continued.</p><p>This made us investigate what was actually limiting our scalability.</p><h3>Our Initial Setup</h3><p>We started with:</p><ul><li><strong>6 Elasticsearch nodes</strong></li><li><strong>6 primary shards</strong></li><li><strong>1 replica</strong></li></ul><p>This gave us <strong>12 shard copies</strong> in total.</p><pre>6 Primary Shards<br>        +<br>6 Replica Shards<br>        =<br>12 Shard Copies</pre><p>The shards were distributed across the cluster.</p><p>As disk usage increased, we scaled the cluster:</p><pre>6 Nodes<br>   ↓<br>12 Nodes<br>   ↓<br>18 Nodes</pre><p>We expected the additional nodes to distribute the data further and reduce disk pressure.</p><p>However, after increasing to 18 nodes, we were still seeing disk-usage issues.</p><p>That led us to the key question: Why weren’t the additional nodes helping?</p><h3>Why Adding More Nodes Didn’t Help</h3><p>Consider a simple example.</p><p>Suppose:</p><pre>P1 = 500 GB</pre><p>We might initially think that adding another node could allow Elasticsearch to distribute it like this:</p><pre>P1 = 500 GB<br>                    │<br>             ┌──────┴──────┐<br>             ↓             ↓<br>         Node A         Node B<br>         250 GB         250 GB</pre><pre>                ❌</pre><p>But this is <strong>not how an existing shard is distributed</strong>.</p><p>Instead, the primary and replica are separate complete shard copies:</p><pre>Primary P1<br>          500 GB<br>             │<br>             │ Replica<br>             ↓<br>        Replica R1<br>          500 GB</pre><pre>     ┌─────────────┐       ┌─────────────┐<br>     │   Node A    │       │   Node B    │<br>     │             │       │             │<br>     │ P1 = 500 GB │       │ R1 = 500 GB │<br>     └─────────────┘       └─────────────┘</pre><p>So the important point is:</p><blockquote><strong><em>A shard copy lives entirely on one node. It doesn’t get split across multiple nodes just because more nodes are added.</em></strong></blockquote><p>Therefore:</p><p><strong>More nodes ≠ smaller existing shards</strong></p><p>If our existing shards continue growing, the nodes holding those shards can still experience high disk utilization.</p><h3>What We Changed</h3><p>Once we identified that the shard configuration was the limiting factor, we moved away from simply adding more nodes.</p><p>We created a new index with a more appropriate number of primary shards and reindexed the data.</p><pre>Reindex<br>Old Index ───────────────→ New Index</pre><pre>6 Primary Shards          More Primary Shards<br>      │                         │<br>      ↓                         ↓<br>Large shards              Smaller data units<br>                              │<br>                              ↓<br>                       Better distribution</pre><p>This gave Elasticsearch more independent shards that could be distributed across the available nodes.</p><h3>Key Takeaways</h3><p>The main lesson from this issue was:</p><blockquote><strong><em>Scaling Elasticsearch is not just about adding nodes. You also need to design the right shard strategy.</em></strong></blockquote><p>When planning capacity, we need to consider:</p><p><strong>Node capacity + shard count + shard size + data growth</strong></p><p>Adding nodes gives the cluster more resources, but the shard layout determines how effectively those resources can be used.</p><h3>Bottom line</h3><p><strong>More nodes provide more capacity.<br>More appropriately sized shards provide better distribution.</strong></p><p>Both need to be considered together when designing a scalable Elasticsearch cluster.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5c4b5b25484" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Collectors.toList() Fixed Our Java parallelStream() Race Condition]]></title>
            <link>https://medium.com/@prachy.p/how-collectors-tolist-fixed-our-java-parallelstream-race-condition-e43c94366ceb?source=rss-9368d6ebb0a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/e43c94366ceb</guid>
            <category><![CDATA[java-parallel-streams]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Prachi Patil]]></dc:creator>
            <pubDate>Fri, 17 Jul 2026 15:33:21 GMT</pubDate>
            <atom:updated>2026-07-17T15:34:05.313Z</atom:updated>
            <content:encoded><![CDATA[<p>We recently encountered an interesting production issue while optimizing one of our Java services using parallelStream(). The goal was simple—parallelize the transformation of database records to improve performance.</p><p>Instead, we started seeing inconsistent API responses.</p><p>The surprising part? The fix was just replacing a forEach() with a collect(Collectors.toList()).</p><p>Here’s what happened!</p><h3>The Original Implementation</h3><p>Our service fetched a list of orders from the database and transformed each order into the API response format.</p><p>The implementation looked like this:</p><pre>List&lt;OrderResponse&gt; orderResponseList = new ArrayList&lt;&gt;();<br><br>orderList<br>    .parallelStream()<br>    .forEach(order -&gt;<br>        orderResponseList.add(<br>            ResponseProcessor.applyOrderFormat(order, responseStructure)<br>        )<br>    );<br><br>return orderResponseList;</pre><p>The logic looked straightforward:</p><ol><li>Process each order in parallel.</li><li>Format the response.</li><li>Add it to the response list.</li></ol><p><strong>However, this implementation contained a subtle concurrency bug.</strong></p><h3>The Production Issue</h3><p>Under load, we started observing inconsistent API responses.</p><p>Some of the issues included:</p><ul><li>Missing response objects</li><li>Unexpected null values</li><li>Inconsistent response sizes</li><li>Intermittent failures that were difficult to reproduce</li></ul><p>The transformation logic itself was correct.</p><p>The problem was somewhere else.</p><h3>The Root Cause</h3><p>The issue was this line:</p><pre>orderResponseList.add(...)</pre><p>Since we were using parallelStream(), multiple worker threads were executing this line simultaneously.</p><p>Conceptually, the execution looked like this:</p><pre>                 orderResponseList<br>                        ▲<br>        ┌───────────────┼───────────────┐<br>        │               │               │<br>    Thread-1        Thread-2        Thread-3<br>        │               │               │<br>      add()           add()           add()</pre><p>The problem is that <strong>ArrayList is not thread-safe</strong>.</p><p>Multiple threads modifying the same ArrayList at the same time can result in race conditions, leading to unpredictable behavior.</p><h3>The Fix</h3><p>We replaced the implementation with the following:</p><pre>return orderList<br>        .parallelStream()<br>        .map(order -&gt; ResponseProcessor.applyOrderFormat(order, responseStructure))<br>        .filter(Objects::nonNull)<br>        .collect(Collectors.toList());</pre><p>After this change, the issue disappeared.</p><p>Interestingly, the response formatting logic (ResponseProcessor.applyOrderFormat) remained exactly the same.</p><p>The only significant difference was replacing manual add() operations with Collectors.toList().</p><h3>Why Did Collectors.toList() Fix the Issue?</h3><p>At first glance, both implementations appear to do the same thing.</p><p>The difference lies in <strong>how the results are accumulated</strong>.</p><h3>Previous Approach</h3><p>Every worker thread was modifying the same shared list.</p><pre>                 Shared ArrayList<br>                        ▲<br>        ┌───────────────┼───────────────┐<br>        │               │               │<br>    Thread-1        Thread-2        Thread-3<br>        │               │               │<br>      add()           add()           add()</pre><p>This introduces concurrent writes to a non-thread-safe collection.</p><h3>How Collectors.toList() Works</h3><p>When used with a parallel stream, Java doesn’t let every thread write to the same list.</p><p>Instead, each worker thread creates its own temporary list.</p><pre>Thread-1<br><br>[Response1, Response2]<br><br>--------------------------<br><br>Thread-2<br><br>[Response3]<br><br>--------------------------<br><br>Thread-3<br><br>[Response4, Response5]<br><br>                ↓<br><br>      Collectors.toList()<br><br>                ↓<br><br>        Final Response List</pre><p>Once all threads finish processing, the Stream framework safely merges the individual lists into one final result.</p><p>Since no two threads modify the same ArrayList, the race condition disappears.</p><h3>What Happens Internally?</h3><p>Conceptually, Collectors.toList() works something like this:</p><pre>Supplier&lt;List&lt;T&gt;&gt; supplier = ArrayList::new;<br><br>BiConsumer&lt;List&lt;T&gt;, T&gt; accumulator = List::add;<br><br>BinaryOperator&lt;List&lt;T&gt;&gt; combiner = (left, right) -&gt; {<br>    left.addAll(right);<br>    return left;<br>};</pre><p>For a parallel stream:</p><ul><li>A separate ArrayList is created for each worker thread.</li><li>Each thread adds elements only to its own list.</li><li>Once processing completes, Java merges all the lists into a single result.</li></ul><p>This is why Collectors.toList() works safely even when the stream is executed in parallel.</p><h3>Key Takeaways</h3><p>❌ Avoid mutating shared collections inside a parallel stream.</p><p>parallelStream().forEach(order -&gt;<br> sharedList.add(transform(order))<br>);</p><p>✅ Prefer functional transformations with map() and collect().</p><pre>parallelStream()<br>    .map(this::transform)<br>    .collect(Collectors.toList());</pre><h3>Final Thoughts</h3><p>This issue reinforced an important lesson about Java Streams.</p><p>The problem wasn’t parallelStream() itself—it was the shared mutable state introduced by calling add() on a common ArrayList.</p><p>By switching to Collectors.toList(), we let the Stream framework manage result collection the way it was designed to, eliminating the race condition while making the code cleaner and easier to maintain.</p><p>Sometimes, the most effective production fixes come from writing code in the functional style that the Stream API was built for, rather than manually managing shared state.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e43c94366ceb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Elasticsearch Custom Routing: Reducing Cross-Shard Searches and CPU Usage]]></title>
            <link>https://medium.com/@prachy.p/how-custom-routing-helped-us-optimize-elasticsearch-cpu-usage-1731774fd563?source=rss-9368d6ebb0a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/1731774fd563</guid>
            <category><![CDATA[partitioning]]></category>
            <category><![CDATA[performance-optimization]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[routing]]></category>
            <dc:creator><![CDATA[Prachi Patil]]></dc:creator>
            <pubDate>Sat, 04 Jul 2026 18:48:30 GMT</pubDate>
            <atom:updated>2026-07-04T18:54:12.005Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A practical lesson on reducing unnecessary cross-shard searches by aligning routing keys with query patterns.</em></p><h3>Introduction</h3><p>When working with distributed search systems like Elasticsearch, performance issues are not always solved by adding bigger machines or increasing infrastructure capacity.</p><p>Sometimes, the real problem is not the hardware.</p><p>Sometimes, it is the way the data is distributed, routed, and queried.</p><p>This was one such learning from my work, where a simple routing decision had a huge impact on CPU utilisation, resource usage, and infrastructure cost.</p><h3>The Context</h3><p>We had an orders index in Elasticsearch that stored order-related information.</p><p>Each order document had fields such as:</p><p>- orderNo<br>- customerNo<br>- customerName<br>- customerAddress<br>- orderDate<br>- items</p><h3>In our initial setup:</h3><p>- orderNo was used as the document _id.<br>- Elasticsearch default routing was based on the document _id.<br>- Since _id was orderNo, documents were distributed across shards based on orderNo.<br>- The index had 60 primary shards and 1 replica.</p><p>At first, this looked fine because the data was distributed across shards.</p><p>But the issue appeared when we looked at how the application was actually querying the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q6-wYd9uzsk1oIJsD9bfHQ.png" /></figure><p><em>Caption:Orders were distributed across shards using orderNo as the default routing key.</em></p><h3>The Main Query Pattern</h3><p>Most of our user traffic came from the order history page.</p><p>On this page, users usually searched their order history using:</p><p>- customerNo<br>- orderDate</p><p>So even though the data was routed by orderNo, the application was mostly searching by customerNo.</p><p>That mismatch became the root cause of the performance problem.</p><h3>The Problem</h3><p>Since the index was routed by orderNo, Elasticsearch did not know which shard contained all orders for a specific customerNo.</p><p>So every time the order history page searched by customerNo, Elasticsearch had to search across multiple shards.</p><p>This caused unnecessary cross-shard searches.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ne-eys4C37CzhdYZPRnXlQ.png" /></figure><p><em>Caption:A customerNo-based search had to fan out across multiple shards because the index was routed by orderNo.</em></p><p><strong>The impact was visible in multiple areas:</strong></p><p>- CPU usage increased.<br>- Search latency increased.<br>- Shard-level work increased.<br>- Resource consumption increased.</p><p>Even though we had high-configuration machines, CPU usage was still high. Memory was not fully utilized, but CPU remained under pressure because every search was doing more work than required.</p><h3>The Fix: Changing Our Indexing Strategy</h3><p>To solve this, we changed our indexing strategy.</p><p>Earlier, orders were written to Elasticsearch with orderNo as the document _id. Because of this, the default routing was effectively based on orderNo.</p><p>But our most common search pattern was based on customerNo.</p><p>So we started writing every order document with customerNo as the custom routing key.</p><p><strong>While indexing an order:</strong></p><p>routing = customerNo</p><p>This meant orders for the same customer were routed using the same customerNo value.</p><p>Then, while searching order history, we passed the same routing key in the search request.</p><p><strong>While searching order history:</strong></p><p>search routing = customerNo</p><p>Because the same routing key was used during both indexing and searching, Elasticsearch could directly target the relevant shard instead of searching across multiple shards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LJ2qkfuXHifujPPj-3IGiw.png" /></figure><p><em>Caption:By using customerNo as the routing key during indexing and searching, the query could directly target the intended shard.</em></p><h3>The Result</h3><p>After changing the routing strategy:</p><p>- Unnecessary shard searches reduced.<br>- CPU usage came down.<br>- Query execution became more efficient.<br>- Resource utilization improved.<br>- Infrastructure cost was optimized.</p><p>The biggest improvement was that CPU usage came down by more than 80%.</p><p>This showed us that the issue was not just about query performance. It was mainly about resource optimization.</p><p>By making each search do less unnecessary work, the system became more efficient.</p><h3>Handling orderNo-Based Searches</h3><p>After changing the main orders index routing to customerNo, we still had a few flows where the request had only orderNo.</p><p>For example:</p><p>Search order details by orderNo</p><p>But the main index was now routed by customerNo.</p><p>So if we only had orderNo, we first needed to find the corresponding customerNo.</p><p>To solve this, we created a small lookup index.</p><p>The lookup index stored this mapping:</p><p>orderNo -&gt; customerNo</p><p>Example:</p><p>orderNo: ORD123<br>customerNo: CUST456</p><p>This lookup index was routed by orderNo because lookup requests were based on orderNo.</p><p>The flow became:</p><ol><li>Request comes with orderNo.</li><li>Search the lookup index using orderNo.</li><li>Get the corresponding customerNo.</li><li>Search the main orders index using customerNo routing.</li><li>Return the order details.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d9TdbpIQ2aGOeUSNtV0RUQ.png" /></figure><p><em>Caption:For orderNo-based searches, a lookup index helped fetch customerNo first, then query the main orders index using customerNo routing.</em></p><p>This helped us support both query patterns efficiently:</p><p>- customerNo-based order history search<br>- orderNo-based order lookup</p><p><strong>Before vs After</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EnKUJRyrfXXaIG-hnWpXQQ.png" /></figure><p><em>Caption:Changing the routing key from orderNo to customerNo reduced unnecessary shard searches and improved CPU utilization.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hYojDFNiVTiUlIc-w3UuuQ.gif" /></figure><h3>Key Learnings</h3><p><strong>1. Routing should match the query pattern</strong></p><p>A unique ID is not always the best routing key.</p><p>In our case, orderNo was a good document ID, but customerNo was a better routing key because most searches were customer-based.</p><p><strong>2. Indexing strategy matters</strong></p><p>The optimization was not only in the search request.</p><p>The important change was at the indexing layer.</p><p>We had to write documents using customerNo as the routing key so that later searches using customerNo could target the correct shard.</p><p><strong>3. Index design should consider read patterns</strong></p><p>When designing an Elasticsearch index, it is important to think about how the data will be queried.</p><p>Our data was stored as orders, but it was mostly read as customer order history.</p><p>That made customerNo a better choice for routing.</p><p><strong>4. Bigger machines do not always solve performance issues</strong></p><p>We had high-configuration machines, but CPU was still high because the queries were doing unnecessary distributed work.</p><p>The fix was not just adding more infrastructure.</p><p>The fix was making each query do less work.</p><p><strong>5. Custom routing should be used consistently</strong></p><p>Once custom routing is introduced, the same routing key should be used during:</p><p>- Indexing<br>- Searching<br>- Updating<br>- Deleting</p><p>If the routing key is missed, Elasticsearch may not search the correct shard.</p><p><strong>6. Validate routing decisions with real traffic patterns</strong></p><p>Routing decisions should be based on the most common access pattern.</p><p>In our case, order history searches were much more common than direct order number searches.</p><p>So optimizing for customerNo gave us the best performance improvement.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1731774fd563" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>