<?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 Staff Engineer Mindset | ProdRescue By Devrim on Medium]]></title>
        <description><![CDATA[Stories by Staff Engineer Mindset | ProdRescue By Devrim on Medium]]></description>
        <link>https://medium.com/@developer_programmer?source=rss-6bdd1f176ebd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zFThAygnbIsOpXzQwr8stA.png</url>
            <title>Stories by Staff Engineer Mindset | ProdRescue By Devrim on Medium</title>
            <link>https://medium.com/@developer_programmer?source=rss-6bdd1f176ebd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 12:09:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@developer_programmer/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[The AI Made Our SQL Query 400 Times Faster. It Also Made It Wrong.]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/codeelevation/the-ai-made-our-sql-query-400-times-faster-it-also-made-it-wrong-6ebb28909205?source=rss-6bdd1f176ebd------2"><img src="https://cdn-images-1.medium.com/max/1012/1*Eiz3xYU9mYWjajKjNfFwzg.png" width="1012"></a></p><p class="medium-feed-snippet">Everybody was impressed by the benchmark. Nobody had checked what happened to the customers who disappeared.</p><p class="medium-feed-link"><a href="https://medium.com/codeelevation/the-ai-made-our-sql-query-400-times-faster-it-also-made-it-wrong-6ebb28909205?source=rss-6bdd1f176ebd------2">Continue reading on CodeElevation »</a></p></div>]]></description>
            <link>https://medium.com/codeelevation/the-ai-made-our-sql-query-400-times-faster-it-also-made-it-wrong-6ebb28909205?source=rss-6bdd1f176ebd------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ebb28909205</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Staff Engineer Mindset | ProdRescue By Devrim]]></dc:creator>
            <pubDate>Fri, 27 Nov 2026 09:27:00 GMT</pubDate>
            <atom:updated>2026-11-27T09:27:00.680Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Designing a Petabyte-Scale Object Storage System: The Architecture Behind Durable Data]]></title>
            <link>https://medium.com/engineering-playbook/designing-a-petabyte-scale-object-storage-system-the-architecture-behind-durable-data-faf277ea971d?source=rss-6bdd1f176ebd------2</link>
            <guid isPermaLink="false">https://medium.com/p/faf277ea971d</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[leadership]]></category>
            <dc:creator><![CDATA[Staff Engineer Mindset | ProdRescue By Devrim]]></dc:creator>
            <pubDate>Thu, 26 Nov 2026 17:28:56 GMT</pubDate>
            <atom:updated>2026-11-26T17:29:13.623Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*2fKNU76uvLQAXz-_0LtM0Q.png" /></figure><h4><em>Erasure coding, storage economics, metadata management, and the engineering decisions behind large-scale object storage.</em></h4><p>In 2014, Facebook published a paper describing f4, a storage system developed after engineers examined how frequently users accessed older photographs and videos. For eight of the nine content categories studied, week-old objects received roughly one-tenth the request rate of objects created within the previous day.</p><p>That observation had substantial infrastructure implications. Maintaining identical storage configurations for newly uploaded photographs and rarely accessed historical content meant paying for performance that much of the dataset no longer required.</p><p>Facebook’s engineers developed a specialized warm storage architecture around those access patterns. The research illustrates how closely storage architecture is connected to workload economics, particularly when a company manages petabytes of customer data.</p><p>Let’s examine the decisions involved in building such a system.</p><h3>The Financial Consequences of Three-Way Replication</h3><p>Suppose an enterprise storage platform contains 100 PB of logical customer data, with an average object size of 4 MB. The platform must retain documents, media files, historical backups, and analytical datasets for several years.</p><p>Three-way replication produces the following storage requirement:</p><pre>Logical data: 100 PB<br>Replication factor: 3<br>Raw storage: 300 PB</pre><p>Every additional petabyte of customer data requires another three petabytes of physical capacity. That relationship eventually becomes difficult to justify for objects receiving relatively few requests.</p><p>Consider an alternative configuration using ten data fragments and four parity fragments.</p><pre>Data fragments: 10<br>Parity fragments: 4<br>Storage amplification: 1.4x<br>Raw storage: 140 PB</pre><p>The theoretical reduction is 160 PB before accounting for operational headroom, metadata, padding, and other storage overhead.</p><p>Assuming an illustrative annual infrastructure cost of $30 per physical terabyte, the difference represents approximately $4.8 million per year in raw storage costs. Encoding and reconstruction require additional computational and networking resources, which must be included before estimating actual savings.</p><h3>What Erasure Coding Changes About the Storage System</h3><p>Reed-Solomon erasure coding divides information into data fragments and generates additional parity information from which unavailable fragments can be reconstructed.</p><p>For a simplified 40 MB object using a 10+4 configuration:</p><pre>Original object: 40 MB<br>Data fragments: 10 x 4 MB<br>Parity fragments: 4 x 4 MB<br>Encoded storage: 56 MB</pre><p>Any ten intact fragments from the fourteen can reconstruct the original data under the assumed Reed-Solomon coding scheme.</p><p>Ceph exposes configurable erasure coding profiles based on this general arrangement. Its documentation also emphasizes that placement across failure domains is part of the durability design.</p><p>The coding configuration alone says very little about whether a particular deployment can survive a rack or data center failure. Fragment placement determines whether that mathematical protection translates into meaningful infrastructure resilience.</p><h3>Four Parity Fragments Can Disappear During One Infrastructure Failure</h3><p>Consider a storage system distributing fourteen fragments across seven racks, with two fragments in each rack.</p><p>Losing a single rack removes two fragments. Losing two racks consumes the entire redundancy budget, leaving only the ten fragments required to reconstruct the object.</p><p>A subsequent unreadable sector affecting another required fragment could make reconstruction impossible.</p><p>The same encoding configuration distributed across fourteen independent racks can tolerate more simultaneous rack failures, assuming the relevant failure domains genuinely operate independently.</p><p>Physical topology must consequently influence placement decisions. Shared power distribution, network dependencies, hardware batches, and cooling infrastructure can correlate failures that appear independent in an abstract architecture diagram.</p><p>I would request the actual physical placement policy before accepting any durability argument based on fragment counts.</p><h3>Rebuilding a Failed Disk Is a Network-Intensive Operation</h3><p>A storage node contains 20 TB of encoded fragments and suffers a permanent disk failure.</p><p>With straightforward Reed-Solomon reconstruction, recreating each missing fragment may require reading ten surviving fragments of equivalent size.</p><p>Assuming all missing data requires this form of reconstruction:</p><pre>Lost fragments: 20 TB<br>Read amplification: 10x<br>Reconstruction reads: 200 TB<br>Replacement writes: 20 TB</pre><p>At an effective aggregate reconstruction read throughput of 10 GB per second:</p><pre>200,000 GB / 10 GB/sec<br>= 20,000 seconds<br>= approximately 5.56 hours</pre><p>This is an idealized lower bound for the assumed reconstruction workload. Actual recovery can take longer because foreground traffic consumes storage bandwidth, fragment availability varies, and reconstruction requires CPU resources. For large storage fleets, repair traffic deserves dedicated capacity planning. A cluster operating close to its normal bandwidth limit may have inadequate resources to restore redundancy following a significant hardware failure.</p><h3>Why Azure Investigated Locally Repairable Codes</h3><p>The reconstruction cost of conventional erasure coding motivated research into alternative coding schemes, including locally repairable codes for distributed storage.</p><p>These schemes introduce additional mathematical relationships that can allow certain missing fragments to be reconstructed using fewer surviving fragments. Suppose a particular coding configuration reduces ordinary single-fragment repair from ten fragment reads to five.</p><p>For the previous 20 TB disk failure, the reconstruction workload would fall from 200 TB to 100 TB under equivalent assumptions.</p><p>The potential reduction in network traffic is substantial, although additional parity requirements or other coding trade-offs can affect storage efficiency and failure tolerance.</p><p>At petabyte scale, choosing an erasure coding scheme involves understanding expected failure frequencies, the distribution of repair workloads, available network capacity, and the operational cost of prolonged degraded redundancy.</p><h3>The Metadata Problem: Twenty-Five Billion Objects</h3><p>A 100 PB platform storing objects with an average size of 4 MB contains approximately twenty-five billion objects.</p><pre>100 PB / 4 MB<br>= 25 billion objects</pre><p>Suppose each metadata record occupies 300 bytes before indexing and database overhead.</p><pre>25B x 300 bytes<br>= 7.5 TB of logical metadata</pre><p>With three replicated copies, the underlying records alone occupy 22.5 TB.</p><p>Object metadata might contain a namespace identifier, object key, generation, content checksum, length, and references to physical storage placement. A metadata service also needs to support listing, version management, lifecycle policies, and customer-specific access patterns.</p><p>A successfully reconstructed object is of limited use if the platform has lost the metadata necessary to locate it. The metadata architecture deserves its own durability model and recovery procedures, independent of the redundancy applied to customer content.</p><h3>Small Objects Can Destroy Storage Efficiency</h3><p>Now assume the platform receives one billion objects averaging 1 KB each.</p><p>The logical payload occupies approximately 1 TB. If every object requires an illustrative 300-byte metadata record, metadata consumes another 300 GB before replication and indexing.</p><p>Physical storage overhead can grow further when each object independently incurs filesystem allocation, fragment headers, and alignment requirements.</p><p>One architectural option is to pack small objects into larger immutable storage containers.</p><pre>Container A<br>Object 001: offset 0<br>Object 002: offset 1024<br>Object 003: offset 2048</pre><p>The metadata service records each object’s location within the container. The storage system can then encode and distribute larger units more efficiently.</p><p>Facebook’s historical BLOB storage architecture used volume-based aggregation. The approach is particularly attractive for workloads where content is predominantly immutable, although deletion and reclamation become more complicated when many independently managed objects share physical storage.</p><h3>Deleting an Object Creates a Second Storage Problem</h3><p>Suppose a 1 GB immutable container contains hundreds of thousands of objects. Customers subsequently delete objects representing 40% of its stored content.</p><p>Removing the corresponding metadata makes those objects inaccessible through the normal application interface. Their original bytes may nevertheless remain inside the physical container.</p><p>Recovering the occupied space requires identifying surviving objects, rewriting them into another container, updating their references safely, and eventually releasing the old container.</p><p>Across a hypothetical 10 PB of similarly fragmented storage:</p><pre>Original containers: 10 PB<br>Live data: 6 PB<br>Reclaimable data: 4 PB</pre><p>Compaction must potentially read 10 PB and rewrite 6 PB of logical container data before reclaiming the old capacity, with further costs depending on encoding and storage implementation.</p><p>For customers subject to data retention or deletion requirements, the architecture must distinguish logical deletion from physical reclamation. Versioning, backups, legal holds, and encryption-key management all affect when previously stored information actually becomes unrecoverable.</p><h3>What Happens When a Disk Returns Corrupted Data?</h3><p>A disk can successfully respond to a read operation while returning damaged content. If the application interprets a successful hardware response as evidence of correctness, corrupted data may remain unnoticed until the last healthy copy becomes unavailable.</p><p>Object storage therefore needs end-to-end content verification and periodic integrity checks.</p><p>Background scrubbing reads stored information and validates its integrity against trusted checksums or other redundancy information. Detected corruption can then trigger reconstruction while sufficient healthy fragments remain available.</p><p>The operational difficulty is deciding how frequently to inspect stored data. Scrubbing too aggressively competes with customer requests and repair operations; insufficient inspection increases the period during which latent corruption can accumulate.</p><p>For an archive containing rarely accessed financial records, ordinary customer traffic provides little assurance that historical data remains readable.</p><h3>Durability Claims Need an Explicit Failure Model</h3><p>Storage providers frequently express durability using a large number of nines. An engineering team designing its own storage system must establish what assumptions support that figure.</p><p>A credible model needs to account for correlated component failures, latent corruption, repair completion times, placement behavior, and software defects that can affect many objects simultaneously.</p><p>I would also examine whether the organization can recover from accidental deletion or an incorrect administrative operation. Erasure coding protects against missing fragments, but a valid deletion propagated throughout the storage system may remove every encoded fragment.</p><p>For an architecture interview, take the 100 PB scenario in this article and calculate the physical capacity, reconstruction bandwidth, metadata requirements, and operational headroom for two competing storage configurations. Decide which customer workloads belong in each configuration and document the circumstances under which either design can lose data.</p><p>If you cannot defend those decisions quantitatively, spend more time on the storage model before drawing the final architecture.</p><h3>Preparing for System Design Interviews Beyond the Textbook</h3><p>Storage system questions become difficult when the interviewer changes an assumption halfway through the discussion. Your original design might support large immutable objects, and suddenly the workload contains billions of small files, strict deletion requirements, and an infrastructure budget that has been reduced by 30%.</p><p>If you’re preparing for a Senior or Staff Engineer interview, practicing a complete design under changing constraints is substantially more useful than memorizing another reference architecture.</p><p>I put together <strong>Senior System Design Interview Prep</strong>, which includes 15 architecture walkthroughs and a structured 45-minute interview framework. You can use the material to practice organizing requirements, developing a defensible architecture, and explaining your decisions within an actual interview time limit.</p><p>Before spending another weekend collecting disconnected system design tutorials, look through the preparation material and decide whether it addresses the gaps in your current approach.</p><p><a href="https://devrimozcay.gumroad.com/l/qjlaki">Senior System Design Interview Prep: 15 Architecture Walkthroughs &amp; 45-Minute Framework</a></p><p>I’m also researching where experienced engineers struggle most during architecture interviews. If you’ve recently encountered a difficult system design round, I’d be interested in hearing what happened.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdocs.google.com%2Fforms%2Fd%2Fe%2F1FAIpQLScLD53xFU73sirxXmKFfL9-M7FGL_5mM6a8_B0qQdaYce2atA%2Fviewform%3Fembedded%3Dtrue&amp;display_name=Google+Docs&amp;url=https%3A%2F%2Fdocs.google.com%2Fforms%2Fd%2Fe%2F1FAIpQLScLD53xFU73sirxXmKFfL9-M7FGL_5mM6a8_B0qQdaYce2atA%2Fviewform%3Fusp%3Dheader&amp;image=https%3A%2F%2Flh6.googleusercontent.com%2F1c67GfSCyEA_IUtodYCJgYLDGOqIuo62OzVnGK9torhRzSxYtd_uTxCv79ExsxuD-Lv_OJR1vfzAR6s%3Dw1200-h630-p&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=google" width="760" height="675" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ff75ab6d435aa7f849ec31a69970e49/href">https://medium.com/media/0ff75ab6d435aa7f849ec31a69970e49/href</a></iframe><h3>A Note for Engineers Working Toward Staff and Principal Roles</h3><p>I’m building an engineering publication on Substack for people who want to understand the systems behind the infrastructure they use every day.</p><p>My upcoming investigation covers real-time fraud detection architecture, including temporal feature computation, delayed ground-truth labels, transaction scoring latency, and the financial consequences of incorrect classifications.</p><p>If you found yourself taking notes while reading this article, subscribe for free. You’ll receive future investigations by email as they are published, and you can reply with the architecture problems you would like me to investigate.</p><p><a href="https://substack.com/@devrimozcay1">Devrim Ozcay | ProdRescue | Substack</a></p><h3>Frequently Asked Questions</h3><h3>How do you design a petabyte-scale object storage system?</h3><p>The architecture requires efficient data placement, appropriate redundancy mechanisms, scalable metadata storage, integrity verification, and controlled background repair and reclamation.</p><h3>What is the difference between replication and erasure coding?</h3><p>Replication maintains complete copies of data. Erasure coding distributes data and parity fragments, potentially achieving fault tolerance with lower physical storage overhead at the expense of more complex reconstruction.</p><h3>Why is erasure coding commonly used for warm storage?</h3><p>Less frequently accessed data can benefit from the reduced storage requirements of erasure coding, provided the resulting access and recovery costs remain acceptable.</p><h3>What determines object storage durability?</h3><p>Durability depends on redundancy, physical failure-domain placement, integrity verification, repair performance, and the behavior of the software managing stored objects.</p><h3>Technical References</h3><p><strong>f4: Facebook’s Warm BLOB Storage System — USENIX OSDI 2014</strong></p><p><a href="https://www.usenix.org/system/files/conference/osdi14/osdi14-paper-muralidhar.pdf">https://www.usenix.org/system/files/conference/osdi14/osdi14-paper-muralidhar.pdf</a></p><p><strong>Ceph — Erasure Coding Architecture</strong></p><p><a href="https://docs.ceph.com/en/latest/architecture/erasure-coding/">https://docs.ceph.com/en/latest/architecture/erasure-coding/</a></p><p><strong>Ceph — Erasure Coding Profiles</strong></p><p><a href="https://docs.ceph.com/en/latest/rados/operations/erasure-code-profile/">Erasure code profiles - Ceph Documentation</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=faf277ea971d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/engineering-playbook/designing-a-petabyte-scale-object-storage-system-the-architecture-behind-durable-data-faf277ea971d">Designing a Petabyte-Scale Object Storage System: The Architecture Behind Durable Data</a> was originally published in <a href="https://medium.com/engineering-playbook">ProdRescue Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Distributed SQL Engines Execute Queries Across Billions of Rows]]></title>
            <link>https://medium.com/engineering-playbook/how-distributed-sql-engines-execute-queries-across-billions-of-rows-c067760c1b3f?source=rss-6bdd1f176ebd------2</link>
            <guid isPermaLink="false">https://medium.com/p/c067760c1b3f</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Staff Engineer Mindset | ProdRescue By Devrim]]></dc:creator>
            <pubDate>Thu, 26 Nov 2026 17:25:55 GMT</pubDate>
            <atom:updated>2026-11-26T17:26:50.422Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*OiwdjqIS0qVQ3_c3DnSE0A.png" /></figure><h4><em>Inside Trino’s architecture, distributed query planning, shuffle costs, memory management, and the economics of analytical infrastructure.</em></h4><p>A SQL query returning seventeen rows can consume more infrastructure than an entire backend microservice fleet. The result occupies a few kilobytes, yet producing it might require reading terabytes of data, transferring intermediate results between hundreds of machines, and allocating hundreds of gigabytes of memory.</p><p>Consider a financial analytics platform containing forty billion transaction records accumulated over several years. Analysts routinely join transactions with customer profiles, merchant information, geographical data, and historical exchange rates. Some queries complete within seconds, while others consume substantial portions of the cluster for several minutes. The SQL statements often look remarkably similar. Explaining the difference requires understanding how the query engine translates relational operations into distributed execution.</p><h3>What Happens After You Submit a SQL Query?</h3><p>Consider this relatively ordinary analytical query:</p><pre>SELECT<br>    c.country,<br>    SUM(t.amount)<br>FROM transactions t<br>JOIN customers c<br>    ON t.customer_id = c.id<br>WHERE t.year = 2026<br>GROUP BY c.country;</pre><p>A distributed SQL engine such as Trino translates this statement into an execution plan containing multiple stages. Workers read relevant source partitions, perform local computations, exchange intermediate data, and produce partial results that are subsequently consolidated.</p><p>The physical execution plan may resemble the following simplified representation:</p><pre>Transaction Scan<br>       |<br>Customer Join<br>       |<br>Partial Aggregation<br>       |<br>Hash Exchange<br>       |<br>Final Aggregation</pre><p>Each boundary has resource implications. A poorly chosen join can create enormous intermediate datasets before an aggregation reduces the final result to a handful of countries. Understanding those intermediate datasets is essential when investigating expensive analytical workloads.</p><h3>The Join That Consumes an Entire Cluster’s Memory</h3><p>Suppose the execution engine needs to join a 2 TB transaction dataset with a 4 GB filtered customer dataset. Assume the cluster contains 100 workers.</p><p>A broadcast join distributes the smaller dataset to every participating worker, allowing each machine to build its own hash table and process its portion of the transaction data.</p><p>The aggregate replicated dataset becomes:</p><pre>4 GB x 100 workers<br>= 400 GB</pre><p>That figure excludes hash-table overhead, decompression, execution buffers, and concurrent queries. If twenty queries independently execute similarly sized broadcast joins, their aggregate raw build-side data alone could reach 8 TB, assuming full concurrency and no sharing.</p><p>A partitioned join distributes both inputs according to their join keys. Each worker builds a hash table covering a portion of the customer dataset, reducing replicated memory requirements while introducing additional network exchanges. Trino’s cost-based optimizer uses statistics supplied by connectors when selecting join order and distribution. Its documented default broadcast size cap is 100 MB, specifically helping contain the consequences of poor estimates.</p><p>The 4 GB example illustrates what can happen when limits are overridden or the optimizer substantially underestimates the actual build-side size.</p><h3>Why Accurate Statistics Are Worth Infrastructure Money</h3><p>An analytical query joins three tables containing transaction records, customers, and merchants. The optimizer estimates that a filtered customer dataset contains 50,000 rows, although the actual result contains twelve million.</p><p>The cardinality estimation error is:</p><pre>12,000,000 / 50,000<br>= 240x</pre><p>An underestimated intermediate result can influence subsequent join ordering, distribution strategy, and memory consumption. A plan that appeared inexpensive during optimization may become impractical during execution.</p><p>Correlated predicates introduce another difficulty. Consider filtering customers by country, currency, and geographical region. Those attributes are related, and estimating their combined selectivity as though they were independent could produce misleading results. Maintaining useful statistics is part of operating an analytical platform. It deserves attention whenever data distributions change substantially, particularly after large imports, tenant growth, or historical backfills.</p><h3>A Single Customer Can Make 99 Workers Irrelevant</h3><p>Hash partitioning distributes records according to their keys. Its effectiveness depends on the amount of work associated with those keys.</p><p>Suppose a payment platform processes four billion transaction records, and one unusually large merchant accounts for 25% of the relevant dataset.</p><pre>Total records: 4 billion<br>Largest merchant: 1 billion<br>Workers: 100</pre><p>Under a straightforward hash partitioning strategy, every record belonging to that merchant reaches the same logical partition. Assuming the remaining records distribute approximately evenly, that partition could receive more than twenty-five times the average workload.</p><p>This produces the familiar analytical query where nearly every worker completes its stage while one task continues processing for several minutes. The cluster has substantial idle capacity, but the remaining work cannot automatically benefit from those machines. For suitable aggregations, introducing a secondary partitioning value can divide the hot key into independently processed groups. A subsequent aggregation combines those partial results.</p><p>Applying the same technique to joins requires more care because the matching input must be distributed consistently. Replicating a large matching relation across salted partitions could introduce another expensive execution problem.</p><h3>The Most Useful Optimization Might Be Avoiding the Scan</h3><p>Consider an enterprise data lake containing 80 TB of historical transactions. An analyst requests transactions belonging to merchants from a narrowly defined geographical segment.</p><p>The merchant dataset can be filtered relatively cheaply. Without additional optimization, however, the execution engine might still read large portions of the transaction dataset before discarding unmatched records.</p><p>Trino supports dynamic filtering, which allows information obtained during join execution to influence upstream data scans. Depending on connector capabilities and physical data organization, the engine can use those runtime filters to exclude unnecessary partitions or storage ranges.</p><p>Imagine that the filtered merchant identifiers allow the storage connector to eliminate 98% of otherwise relevant transaction data.</p><pre>Original scan: 80 TB<br>Remaining scan: 1.6 TB<br>Avoided reads: 78.4 TB</pre><p>Those savings depend on whether the storage layout actually permits such pruning. If matching merchant identifiers are scattered across nearly every partition and file, a highly selective logical filter may still produce limited physical I/O savings.</p><p>The table’s physical organization consequently determines how much benefit the query optimizer can deliver.</p><h3>Somewhere Between Two Operators, the Network Becomes the Database</h3><p>Suppose a query plan produces 1.2 TB of intermediate records requiring redistribution across workers.</p><p>At an effective aggregate exchange throughput of 20 GB per second, transferring that data requires at least sixty seconds under idealized assumptions.</p><pre>1,200 GB / 20 GB/sec<br>= 60 seconds</pre><p>The calculation excludes serialization, temporary buffering, compression, resource contention, and downstream processing.</p><p>A query can therefore spend substantial execution time moving information between computational stages. Reducing exchanged row width through projection, performing valid partial aggregations earlier, and choosing compatible data partitioning can significantly change this cost.</p><p>I would examine physical input bytes and exchanged bytes alongside execution time. Two queries with nearly identical SQL may have radically different infrastructure requirements because the physical planner places their computational boundaries differently.</p><h3>What Should Happen When a Worker Dies After Forty Minutes?</h3><p>A long-running financial reconciliation query has consumed forty minutes of cluster capacity. Shortly before completion, one worker becomes unavailable.</p><p>Restarting the entire query discards useful computation from healthy workers and repeats expensive data reads.</p><p>Trino supports fault-tolerant execution with configurable query-level or task-level retries. Task-level recovery can reuse previously materialized intermediate exchange data, allowing the engine to repeat smaller portions of failed work.</p><p>The additional durability carries storage and execution overhead. Trino’s documentation consequently distinguishes between workloads dominated by short interactive queries and larger batch workloads that benefit from task-level recovery.</p><p>For an enterprise analytics platform, I would evaluate interactive and batch workloads separately. A recovery architecture appropriate for a two-hour financial reconciliation may impose unnecessary latency on a dashboard query expected to complete within seconds.</p><h3>An Architecture Exercise Worth Spending Thirty Minutes On</h3><p>Imagine you are reviewing a distributed SQL platform before a major capacity expansion. The infrastructure team wants to purchase another fifty workers because several analytical queries regularly exceed their execution deadlines.</p><p>The available evidence shows that most workers remain underutilized during the final execution stage. A small number of tasks process disproportionately large amounts of data, while several expensive joins depend on inaccurate cardinality estimates.</p><p>Before approving the expansion, examine the physical execution plans and compare estimated row counts with actual execution statistics. Investigate whether partition skew, unnecessary exchanges, or excessive build-side replication explains the observed performance.</p><p>A Staff Engineer should be able to estimate the improvement expected from additional machines and explain which parts of the execution would remain constrained. That is the architecture discussion worth having before committing another year of infrastructure expenditure.</p><h3>Preparing for Architecture Decisions at the Staff Engineer Level</h3><p>If you understood the individual concepts in this article but would struggle to choose between them under interview pressure, your next step should be practicing complete architecture decisions under realistic constraints.</p><p>A Staff Engineer interview can begin with a straightforward scalability question and quickly move into infrastructure economics, workload distribution, consistency guarantees, and operational recovery. Knowing the terminology helps, but you also need to defend why your design deserves approval.</p><p>I created <strong>Staff Engineer Architecture Decisions</strong> around that preparation problem. It includes twelve architectural trade-offs, twelve case studies, and a risk assessment template you can use to structure your own design reviews.</p><p>If you have an architecture interview approaching, or you’re already responsible for technical decisions that affect multiple engineering teams, work through the cases before your next design review.</p><p>Explore the complete architecture preparation material here:</p><p><a href="https://devrimozcay.gumroad.com/l/qktrrh">Staff Engineer Architecture Decisions: 12 Critical Trade-offs + 12 Production Cases + Risk Template</a></p><p>I’m also collecting feedback from experienced engineers about the architecture questions and interview situations they find hardest. Your answers will help shape future engineering material.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdocs.google.com%2Fforms%2Fd%2Fe%2F1FAIpQLScLD53xFU73sirxXmKFfL9-M7FGL_5mM6a8_B0qQdaYce2atA%2Fviewform%3Fembedded%3Dtrue&amp;display_name=Google+Docs&amp;url=https%3A%2F%2Fdocs.google.com%2Fforms%2Fd%2Fe%2F1FAIpQLScLD53xFU73sirxXmKFfL9-M7FGL_5mM6a8_B0qQdaYce2atA%2Fviewform%3Fusp%3Dheader&amp;image=https%3A%2F%2Flh6.googleusercontent.com%2F1c67GfSCyEA_IUtodYCJgYLDGOqIuo62OzVnGK9torhRzSxYtd_uTxCv79ExsxuD-Lv_OJR1vfzAR6s%3Dw1200-h630-p&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=google" width="760" height="675" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ff75ab6d435aa7f849ec31a69970e49/href">https://medium.com/media/0ff75ab6d435aa7f849ec31a69970e49/href</a></iframe><h3>Receive the Next Engineering Investigation</h3><p>If distributed SQL execution is the kind of engineering knowledge you want to develop, consider joining my Substack. I want to build a publication that experienced engineers can return to when preparing for architecture reviews, investigating unfamiliar systems, or developing the technical judgment required for Staff and Principal roles.</p><p>The next subject in this series is petabyte-scale object storage, including erasure coding, metadata architecture, storage repair, and the cost of maintaining durability across thousands of machines.</p><p>Subscribe to receive future engineering investigations directly in your inbox rather than relying on Medium to recommend them.</p><p><a href="https://substack.com/@devrimozcay1">Devrim Ozcay | ProdRescue | Substack</a></p><h3>Frequently Asked Questions</h3><h3>How does a distributed SQL engine execute queries?</h3><p>It converts SQL into physical execution stages that distribute scans, joins, aggregations, and intermediate data exchanges across multiple workers.</p><h3>What is the difference between a broadcast join and a partitioned join?</h3><p>A broadcast join replicates one input across participating workers. A partitioned join redistributes inputs according to their join keys, reducing replicated memory at the expense of additional communication.</p><h3>What causes data skew in distributed SQL?</h3><p>Uneven key distributions can concentrate disproportionate amounts of computation within particular partitions, leaving other workers underutilized.</p><h3>How does Trino recover from worker failures?</h3><p>When appropriately configured, Trino’s fault-tolerant execution supports query or task retries and can reuse materialized exchange data.</p><h3>Technical References</h3><p>Trino — Cost-Based Optimizations</p><p><a href="https://trino.io/docs/current/optimizer/cost-based-optimizations.html">https://trino.io/docs/current/optimizer/cost-based-optimizations.html</a></p><p>Trino — Dynamic Filtering</p><p><a href="https://trino.io/docs/current/admin/dynamic-filtering.html">https://trino.io/docs/current/admin/dynamic-filtering.html</a></p><p>Trino — Fault-Tolerant Execution</p><p><a href="https://trino.io/docs/current/admin/fault-tolerant-execution.html">https://trino.io/docs/current/admin/fault-tolerant-execution.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c067760c1b3f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/engineering-playbook/how-distributed-sql-engines-execute-queries-across-billions-of-rows-c067760c1b3f">How Distributed SQL Engines Execute Queries Across Billions of Rows</a> was originally published in <a href="https://medium.com/engineering-playbook">ProdRescue Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deterministic Simulation Testing: How FoundationDB Finds Bugs Before Production Does]]></title>
            <link>https://medium.com/engineering-playbook/deterministic-simulation-testing-how-foundationdb-finds-bugs-before-production-does-92fb354e9a04?source=rss-6bdd1f176ebd------2</link>
            <guid isPermaLink="false">https://medium.com/p/92fb354e9a04</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Staff Engineer Mindset | ProdRescue By Devrim]]></dc:creator>
            <pubDate>Thu, 26 Nov 2026 15:45:12 GMT</pubDate>
            <atom:updated>2026-11-26T15:45:29.766Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*i5zVPzC8y4HGbjICsdQ7YA.png" /></figure><h4><em>An investigation into distributed system correctness, virtual execution environments, fault injection, and reproducible concurrency failures.</em></h4><p>According to FoundationDB’s engineering documentation, the database spent its first eighteen months of development running exclusively inside a simulation environment. Before communicating over a physical network, its developers could already execute distributed transactions across simulated machines, introduce network partitions, restart processes, and investigate failures involving persistent storage.</p><p>That development decision is worth examining. Distributed databases contain an enormous number of possible execution sequences, and conventional integration testing explores a relatively small portion of them. A transaction that succeeds ten million times can still violate an accounting invariant when several unrelated failures occur in an unfortunate order.</p><p>FoundationDB’s approach treats the execution environment itself as part of the testing architecture.</p><h3>The Bug That Disappears When You Investigate It</h3><p>Consider a hypothetical replicated database containing three storage nodes. A transaction coordinator submits an operation, receives acknowledgment from two replicas, and begins returning a successful response to the client.</p><p>Several events overlap.</p><pre>Transaction becomes committed.<br>Leader begins sending response.<br>Network connection disappears.<br>Follower starts an election.<br>Original client retries.</pre><p>An implementation defect allows the retried operation to produce a second logical transaction. The database remains available, its replication protocol appears healthy, and ordinary monitoring detects no infrastructure failure.</p><p>Reproducing this defect in a conventional integration environment requires recreating a particular relationship between network delivery, process scheduling, storage completion, and client behavior. Adding diagnostic logging could alter the timing sufficiently to make the failure disappear.</p><p>A deterministic simulator allows developers to investigate the same execution repeatedly while preserving its relevant event ordering.</p><h3>Put the Sources of Nondeterminism Behind an Interface</h3><p>Application code usually treats time, networking, storage, and randomness as services provided by the operating system. That arrangement becomes restrictive when a test needs precise control over the order in which independently executing operations complete.</p><p>FoundationDB integrates its simulator with Flow, its asynchronous execution framework. Simulated machines and communication channels operate inside a controlled environment, allowing an entire logical database cluster to execute within a single-threaded process.</p><p>For a Java application, the architectural principle could begin with interfaces resembling these:</p><pre>interface RuntimeClock {<br>    long now();<br>}</pre><pre>interface Transport {<br>    void send(Message message);<br>}</pre><pre>interface Storage {<br>    void write(<br>        Record record,<br>        Runnable onComplete<br>    );<br>}</pre><p>Production implementations interact with actual infrastructure. Simulation implementations schedule operations through a controlled event loop.</p><p>This separation must extend beyond obvious infrastructure interfaces. Direct calls to the system clock, uncontrolled background threads, unseeded random generators, and nondeterministic collection traversal can all compromise reproducibility.</p><p>Retrofitting these boundaries into a mature enterprise application may be considerably more expensive than establishing them during its original development.</p><h3>Virtual Time Changes the Economics of Failure Testing</h3><p>Suppose a distributed coordination service contains a lease that expires after thirty minutes. A suspected bug occurs when a delayed message arrives shortly after expiration, while the original lease holder is recovering from a storage failure.</p><p>Testing 10,000 independent executions in real time would require:</p><pre>10,000 x 30 minutes<br>= 300,000 minutes<br>= 5,000 hours</pre><p>Parallel execution reduces elapsed testing time, but the infrastructure still consumes resources while waiting for those timers.</p><p>A discrete-event simulator maintains a queue of future events. When no application work remains eligible for immediate execution, the simulated clock can advance directly to the next scheduled operation.</p><pre>00:00:00  Acquire lease<br>00:00:03  Storage failure<br>00:29:59  Recovery begins<br>00:30:00  Lease expires<br>00:30:01  Delayed message arrives</pre><p>Thirty minutes of logical time may pass with very little computation.</p><p>The actual acceleration depends on how much processing occurs between scheduled events. For protocols containing lengthy idle periods, virtual time makes repeated exploration of expiration and recovery scenarios economically practical.</p><h3>A Random Seed Is More Valuable Than a Failed Test Screenshot</h3><p>Suppose an overnight simulation discovers that a database has lost a previously acknowledged transaction.</p><p>The failure report contains the following information:</p><pre>Build: 7f2c91a<br>Random seed: 928174<br>Topology: 5 nodes<br>Workload: concurrent transfers<br>Virtual time: 18h 42m<br>Failed invariant: conservation</pre><p>If the simulator controls the relevant sources of nondeterminism, the engineering team can rerun the same build and configuration with the recorded seed. The seed determines the simulated random choices. Network delays, workload generation, injected failures, and other controlled decisions can therefore be reproduced.</p><p>Developers can add observation points to investigate the failure, provided those changes do not alter the simulated execution schedule or random decisions.</p><p>Preserving the failing binary, simulator version, workload configuration, and execution trace alongside the seed is particularly useful. A later implementation change may consume random numbers differently, causing the same seed to explore an entirely different execution.</p><h3>Inject Failures Into the Storage Contract</h3><p>Many integration environments simulate a database failure by terminating a container. That procedure tests important recovery behavior, although it may preserve storage operations that would have disappeared during an actual power failure.</p><p>Consider a storage engine executing the following sequence:</p><pre>Append transaction to log.<br>Update in-memory index.<br>Flush log to persistent storage.<br>Acknowledge transaction.</pre><p>A simulator can interrupt execution between any of these operations. It can also distinguish completed application writes from writes that have reached the required durability boundary.</p><p>This distinction is central to storage correctness. Depending on operating system and hardware behavior, data written without the necessary synchronization may disappear following a crash.</p><p>FoundationDB’s simulator includes storage fault modeling alongside network and machine failures. Its published design describes testing scenarios involving the loss or corruption of unsynchronized writes. An application with a durable transaction queue should receive similar scrutiny. Recovery tests need to establish whether acknowledged operations remain recoverable when failures interrupt the storage protocol at inconvenient boundaries.</p><h3>Test Business Invariants Instead of Individual Responses</h3><p>A financial transfer service offers a useful example of property-based correctness testing.</p><p>Suppose the system begins with 1,000 accounts, each containing 10,000 monetary units. Clients repeatedly transfer money between randomly selected accounts while infrastructure failures occur.</p><p>The initial aggregate balance is:</p><pre>1,000 x 10,000<br>= 10,000,000 monetary units</pre><p>Assuming there are no external deposits, withdrawals, or fees, the aggregate balance must remain unchanged across appropriate consistent snapshots.</p><p>A simplified Java assertion could express that property:</p><pre>long total = accounts.stream()<br>    .mapToLong(Account::balance)<br>    .sum();<br>assertEquals(<br>    10_000_000L,<br>    total<br>);</pre><p>This assertion can expose missing debits, duplicate credits, and partially committed transfers. It cannot establish complete correctness, because two unrelated accounting errors might cancel each other numerically.</p><p>Additional checks should examine individual operation identities, journal consistency, acknowledged transaction preservation, and the legality of observed transaction histories.</p><p>The quality of a simulator depends heavily on the properties being verified. A sophisticated fault generator running against weak assertions can execute millions of tests without detecting a serious correctness defect.</p><h3>The Combinatorial Problem With Distributed Failures</h3><p>Suppose a testing framework recognizes twelve distinct fault categories. If a generated scenario contains eight fault events, there are already:</p><pre>12^8<br>= 429,981,696 combinations</pre><p>That simplified calculation allows repeated categories and excludes the timing, location, duration, and severity of each failure.</p><p>Exhaustive exploration quickly becomes impractical. Randomized simulation offers a way to examine a substantial variety of executions, although the distribution used to generate failures affects which parts of the state space are explored.</p><p>FoundationDB’s documentation describes a network fault technique called swizzle-clogging. Network connections among selected nodes are progressively obstructed and subsequently restored in a varied sequence. This exposes intermediate connectivity configurations that a single clean partition would miss.</p><p>I would apply a similar principle when testing enterprise messaging infrastructure. Consumers could lose access to brokers at different moments while producers retain partial connectivity and storage nodes recover independently. Real infrastructure rarely moves cleanly from a healthy condition into a completely unavailable condition and back again.</p><h3>A Simulator Should Test Whether the System Eventually Recovers</h3><p>A database can preserve every safety property while remaining unavailable indefinitely.</p><p>Imagine a distributed transaction coordinator whose participants become disconnected after preparing their operations. Connectivity eventually returns, but a state-machine defect prevents the coordinator from resolving the unfinished transactions. No records have been corrupted. The affected business operations nevertheless remain incomplete. A useful simulation therefore needs separate checks for safety and liveness.</p><p>Safety properties describe outcomes the system must never produce, such as duplicated financial effects or contradictory committed histories. Liveness properties describe progress expected under explicitly stated environmental assumptions.</p><p>A recovery test might restore the required network connectivity and storage availability, advance simulated time, and verify that unfinished operations eventually reach permitted terminal states.</p><p>Such a test should define its recovery assumptions carefully. A system designed to wait for a quorum cannot reasonably guarantee progress while a majority of its replicas remain unavailable.</p><h3>What Deterministic Simulation Cannot Establish</h3><p>FoundationDB’s published research explicitly acknowledges limitations of simulation. Performance defects, third-party components outside the controlled runtime, and differences between modeled hardware and actual infrastructure still require other forms of testing.</p><p>A simulator that completes a transaction in five virtual milliseconds provides no direct evidence that the production database will achieve the same latency. Its scheduling and storage models intentionally abstract implementation details that matter to physical performance.</p><p>I would retain hardware-based testing for storage durability assumptions, real-network experiments for transport behavior, and conventional performance benchmarks for throughput and latency. History-based consistency testing can also provide independent evidence of the guarantees observed by real clients.</p><p>Every simulation result remains conditional on the accuracy of its fault model and the strength of its correctness checks.</p><h3>Introducing This Approach Into an Existing Backend Architecture</h3><p>Rebuilding an entire Spring Boot application around a deterministic runtime would rarely be my first recommendation. The most valuable starting point is a narrowly defined component whose failure could produce irreversible business consequences.</p><p>A payment state machine, message processing protocol, reservation manager, or distributed job coordinator would be a reasonable candidate.</p><p>Extract its decision logic from external infrastructure dependencies and introduce a controlled execution environment. Generate randomized operations, interrupt execution at different boundaries, and verify the business invariants after every relevant transition.</p><p>When the simulator discovers a failing execution, preserve the complete reproduction information and convert the scenario into a permanent regression test.</p><p>Over time, this can develop into a substantial engineering capability. Architecture reviews can then incorporate executable evidence about failure behavior alongside design documents and consistency arguments.</p><h3>Advanced System Design and Production Engineering Resources</h3><p>I developed <strong>Senior Backend Production Engineering OS</strong> for experienced engineers working with distributed systems, production failures, backend architecture, and complex operational problems. The collection brings together engineering systems, diagnostic tools, and production playbooks intended to develop practical reasoning beyond conventional interview exercises.</p><p><a href="https://devrimozcay.gumroad.com/l/epxiu">Senior Backend Production Engineering OS: 31 Systems, Tools &amp; Production Playbooks</a></p><p>I’m also conducting independent research into the production incidents that consume engineering time and create operational risks for technology companies.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdocs.google.com%2Fforms%2Fd%2Fe%2F1FAIpQLSdPmNpQj0vkuiUg6dLsEIIfCU3DF9s4w4LkmCRpG-iCsGle5w%2Fviewform%3Fembedded%3Dtrue&amp;display_name=Google+Docs&amp;url=https%3A%2F%2Fdocs.google.com%2Fforms%2Fd%2Fe%2F1FAIpQLSdPmNpQj0vkuiUg6dLsEIIfCU3DF9s4w4LkmCRpG-iCsGle5w%2Fviewform%3Fusp%3Dheader&amp;image=https%3A%2F%2Flh5.googleusercontent.com%2F0PjjoPdT-mhK0AMajyS6aQB9UNWiFUzsDnHh94GVSWX9epl-aNHIIY9y94sY2d4cY8mQ3ITguy2dbeE%3Dw1200-h630-p&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=google" width="760" height="675" frameborder="0" scrolling="no"><a href="https://medium.com/media/e0bbb0b75c005b9cea8eb8f348adbf29/href">https://medium.com/media/e0bbb0b75c005b9cea8eb8f348adbf29/href</a></iframe><p>Further investigations into distributed systems and advanced software architecture are available on my Substack.</p><p><a href="https://substack.com/@devrimozcay1">Devrim Ozcay | ProdRescue | Substack</a></p><h3>Frequently Asked Questions</h3><h3>What is deterministic simulation testing?</h3><p>Deterministic simulation testing executes software within a controlled environment that manages relevant sources of nondeterminism, allowing complex failure scenarios to be reproduced and investigated.</p><h3>How does FoundationDB test distributed system correctness?</h3><p>FoundationDB uses a simulation environment integrated with its asynchronous runtime, combining generated workloads, modeled infrastructure failures, and correctness assertions.</p><h3>What is the difference between deterministic simulation and chaos engineering?</h3><p>Deterministic simulation emphasizes controlled execution and reproducibility. Chaos engineering commonly introduces failures into running environments to investigate resilience under more realistic operational conditions. The approaches complement each other.</p><h3>Does deterministic simulation prove a distributed system is correct?</h3><p>Randomized simulation provides evidence about the executions and fault conditions tested. It cannot establish correctness across every possible execution or every unmodeled infrastructure behavior.</p><h3>Technical References</h3><p>FoundationDB: A Distributed Unbundled Transactional Key Value Store — ACM SIGMOD 2021.</p><p><a href="https://www.foundationdb.org/files/fdb-paper.pdf">https://www.foundationdb.org/files/fdb-paper.pdf</a></p><p>FoundationDB Engineering Documentation.</p><p><a href="https://apple.github.io/foundationdb/engineering.html">https://apple.github.io/foundationdb/engineering.html</a></p><p>FoundationDB Simulation and Testing.</p><p><a href="https://apple.github.io/foundationdb/testing.html">https://apple.github.io/foundationdb/testing.html</a></p><p>Deterministic Simulation Testing — Martin Fowler’s website.</p><p><a href="https://martinfowler.com/articles/deterministic-simulation-testing.html">https://martinfowler.com/articles/deterministic-simulation-testing.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92fb354e9a04" width="1" height="1" alt=""><hr><p><a href="https://medium.com/engineering-playbook/deterministic-simulation-testing-how-foundationdb-finds-bugs-before-production-does-92fb354e9a04">Deterministic Simulation Testing: How FoundationDB Finds Bugs Before Production Does</a> was originally published in <a href="https://medium.com/engineering-playbook">ProdRescue Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing a Search Engine for 10 Billion Documents: Architecture Beyond Elasticsearch]]></title>
            <link>https://medium.com/engineering-playbook/designing-a-search-engine-for-10-billion-documents-architecture-beyond-elasticsearch-e99cd4333128?source=rss-6bdd1f176ebd------2</link>
            <guid isPermaLink="false">https://medium.com/p/e99cd4333128</guid>
            <category><![CDATA[software]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Staff Engineer Mindset | ProdRescue By Devrim]]></dc:creator>
            <pubDate>Thu, 26 Nov 2026 15:42:59 GMT</pubDate>
            <atom:updated>2026-11-26T15:43:20.023Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*ztWxqnWbLuev_adnzou58Q.png" /></figure><h4><em>Inside distributed information retrieval, index compression, query optimization, relevance ranking, and large-scale search infrastructure.</em></h4><p>Suppose an enterprise search engine contains ten billion documents, and a customer searches for a phrase containing three relatively common words. Hundreds of millions of documents could contain at least one of those terms. The customer expects the twenty most relevant results within 100 milliseconds, leaving the system with an extraordinarily small processing budget relative to the size of its searchable corpus.</p><p>Adding servers provides additional processing capacity, but the economics become unreasonable if every query requires examining millions of documents. Much of the engineering behind modern search engines concerns establishing which documents can be safely excluded before expensive evaluation begins.</p><h3>The Storage Architecture Behind Ten Billion Documents</h3><p>Assume the average original document occupies 15 KB and contains approximately 800 indexed token occurrences.</p><pre>Documents: 10 billion<br>Average document size: 15 KB<br>Original corpus: 150 TB</pre><p>The indexing pipeline must transform approximately eight trillion token occurrences into searchable structures. The final index size depends heavily on vocabulary distribution, compression, stored fields, positional information, and the indexing strategy.</p><p>An inverted index associates searchable terms with documents containing those terms. A simplified representation might look like this:</p><pre>database -&gt; [12, 48, 91, 104]<br>replication -&gt; [12, 91, 217]<br>consensus -&gt; [48, 91, 302]</pre><p>A phrase query requires considerably more information than document identifiers alone. The index generally needs term positions to determine whether words appear in the required order and proximity.</p><p>For a corpus of this size, deciding which fields support phrase search, filtering, aggregation, and relevance scoring has significant storage consequences. Indexing every available field with every supported feature creates a permanent infrastructure obligation that may provide little measurable search value.</p><h3>Compressing the Posting Lists</h3><p>Document identifiers within posting lists are generally ordered. Instead of storing every identifier independently, an index can encode the differences between consecutive identifiers.</p><pre>Original identifiers:<br>1000, 1003, 1008, 1010<br>Delta representation:<br>1000, 3, 5, 2</pre><p>Small differences can be represented compactly using suitable integer compression techniques. Modern information retrieval systems also organize postings into blocks to support efficient decoding and skipping.</p><p>Compression affects query execution because search workloads frequently move substantial amounts of information through memory and CPU caches. A compressed representation may improve throughput enough to justify its decoding cost.</p><p>The appropriate encoding depends on posting-list density, access patterns, processor characteristics, and the frequency with which queries need to skip portions of a list.</p><h3>How Search Engines Avoid Scoring Millions of Documents</h3><p>Consider an OR query containing three terms. During retrieval, the search engine maintains a collection of its twenty highest-scoring documents discovered so far.</p><p>Suppose the current twentieth result has a relevance score of 8.4. A block of candidate postings has the following maximum possible additive score contributions:</p><pre>Term A: 2.1<br>Term B: 1.8<br>Term C: 3.2<br>Maximum possible score: 7.1</pre><p>No document within the relevant block can exceed the current competitive threshold under these scoring assumptions. The engine can skip evaluating those candidates without changing the final top twenty results.</p><p>This is the principle behind dynamic pruning techniques such as Block-Max WAND. Lucene introduced block-level score-bound metadata to accelerate ranked retrieval, and its subsequent development has also explored block-max MAXSCORE. The engineering constraint is that the upper bounds must remain valid for the active scoring function. An arbitrary scoring script that can assign unexpectedly large scores to otherwise insignificant candidates may prevent safe pruning unless the engine can establish a corresponding upper bound.</p><p>Custom ranking features consequently deserve performance evaluation before being introduced into high-volume query paths.</p><h3>Distributed Ranking Can Produce Incorrectly Ordered Results</h3><p>Suppose the corpus is distributed across 500 primary shards. Each shard contains documents belonging to a particular language, industry, or geographical market. A search for “investment banking” may produce a different statistical interpretation on financial document shards than on general-purpose document shards. Terms that appear frequently within one partition may be relatively rare within another, changing their contribution to relevance scores.</p><p>Even identical documents can receive different scores when evaluated against different shard-local corpus statistics.</p><p>Elasticsearch provides dfs_query_then_fetch as a way to collect distributed term and document statistics before executing the main retrieval phase. This improves scoring consistency when shard distributions differ substantially, although it introduces an additional coordination step.</p><p>The partitioning strategy therefore influences both query performance and ranking quality. Routing documents by customer or subject matter can reduce unnecessary search fan-out while making local relevance statistics less representative of the complete corpus.</p><h3>Returning the Top Twenty Results Can Generate Gigabytes of Internal Traffic</h3><p>Assume each search touches 500 shards. Every shard returns its twenty highest-scoring candidates to the coordinating node.</p><pre>500 shards x 20 candidates<br>= 10,000 candidate records</pre><p>If each candidate contains 48 bytes of identifiers, scores, and sorting metadata:</p><pre>10,000 x 48 bytes<br>= 480 KB per query</pre><p>At 20,000 search requests per second:</p><pre>480 KB x 20,000<br>= 9.6 GB/sec</pre><p>This represents approximately 76.8 Gbps of candidate-response traffic across the infrastructure before protocol overhead and document retrieval.</p><p>Returning twenty candidates from every shard is sufficient for an exact global top twenty under a consistent total ordering, provided each shard can determine its own exact local results. Problems arise when later ranking stages change that ordering. Shard selection, hierarchical result aggregation, and compact candidate representations can reduce coordination costs. Any optimization that excludes potentially relevant shards needs an explicit assessment of its effect on retrieval recall.</p><h3>The Hidden Quality Cost of Multi-Stage Ranking</h3><p>Large search engines often use relatively inexpensive retrieval algorithms to identify candidate documents before applying computationally expensive ranking models.</p><p>Consider the following pipeline:</p><pre>Inverted Index Retrieval<br>          |<br>    1,000 Candidates<br>          |<br>    Ranking Model<br>          |<br>    100 Candidates<br>          |<br>    Final Reranking<br>          |<br>    20 Results</pre><p>A document eliminated during the initial retrieval stage cannot be recovered by a subsequent ranking model. Improving the final reranker provides little benefit if the correct documents never enter its candidate set.</p><p>This becomes especially important when adding semantic search to an existing lexical retrieval architecture. An exact phrase match may perform exceptionally well for error identifiers, product codes, and legal references, while vector retrieval may produce better candidates for conceptual queries.</p><p>I would evaluate candidate recall before investing in a more expensive reranking model. Suppose a candidate set of 1,000 documents captures 96% of relevant results in a representative evaluation dataset. Reducing that set to 200 documents lowers candidate recall to 82%.</p><p>The resulting infrastructure savings need to be evaluated against the relevance lost before ranking even begins.</p><h3>Segment Merging Competes Directly With Search Traffic</h3><p>An index receiving continuous updates generally contains multiple immutable segments. Background merge operations consolidate those segments, removing obsolete document versions where reclamation is possible.</p><p>Suppose the search platform receives 50,000 document updates per second, each producing an average of 1 KB of new index data.</p><pre>50,000 x 1 KB<br>= 50 MB/sec logical index writes</pre><p>Assume an illustrative total write amplification factor of six, including merge-related rewriting.</p><pre>50 MB/sec x 6<br>= 300 MB/sec physical writes</pre><p>With three copies of the indexed data, aggregate physical writes could approach 900 MB per second under the same assumptions.</p><p>Search queries compete with indexing and merging for storage bandwidth, processor time, and filesystem cache capacity. A merge backlog can also leave additional segments available for querying, increasing the amount of per-segment work required by search execution.</p><p>This creates a scheduling problem between indexing freshness, query latency, and long-term storage efficiency. Increasing indexing throughput without examining merge capacity may simply postpone the performance cost.</p><h3>Deep Pagination Exposes the Cost of Distributed Sorting</h3><p>A customer requests the results between positions 100,001 and 100,020. If the engine implements distributed offset pagination by collecting the required prefix from every shard, the coordination workload becomes substantial.</p><pre>500 shards x 100,020 candidates<br>= 50,010,000 candidates</pre><p>At 48 bytes per candidate, the theoretical intermediate representation approaches 2.4 GB for a single query.</p><p>Actual implementations may apply optimizations, but the underlying problem remains: the system needs to establish the ordering of a substantial result prefix before returning a small page.</p><p>Cursor-based pagination can continue from the last returned sorting values. To maintain predictable results during concurrent index updates, it should use a stable total ordering and an appropriate point-in-time search context.</p><p>I would restrict arbitrary deep pagination in interactive search interfaces and provide a separate execution path for customers who need complete dataset exports.</p><h3>Search Quality Needs Its Own Production Metrics</h3><p>A search platform can maintain excellent latency while returning increasingly irrelevant results. Infrastructure dashboards will rarely identify that deterioration because successful HTTP responses reveal little about retrieval effectiveness.</p><p>An enterprise search team should evaluate candidate Recall@K, normalized discounted cumulative gain, and mean reciprocal rank against representative judgments. Online measurements can supplement these evaluations, although user interactions are influenced by presentation, result position, and interface design.</p><p>Changes to tokenization, relevance scoring, index routing, or candidate pruning should be evaluated against the same query populations before and after deployment.</p><p>Consider a customer searching for an exact regulatory reference. If a semantic ranking upgrade places conceptually similar documents above the actual reference, the resulting system may achieve better average relevance while becoming materially worse for that customer’s workflow.</p><p>Search quality must therefore be evaluated across meaningful query categories rather than exclusively through an aggregate metric.</p><h3>What I Would Investigate Before Approving This Architecture</h3><p>I would request a representative query distribution containing rare identifiers, common terms, complex Boolean expressions, phrase searches, and expensive filtering combinations. For each category, I would measure postings decoded, candidates evaluated, shard participation, ranking effectiveness, and resource consumption.</p><p>The same evaluation should run while the index receives sustained updates and background merges compete for storage resources. Search benchmarks performed exclusively against a static index exclude an important part of the production workload.</p><p>At ten billion documents, the strongest architectural decisions are often those that reduce the amount of work required per useful result while preserving the relevance guarantees customers depend on.</p><h3>Advanced System Design and Architecture Resources</h3><p>I developed <strong>Staff Engineer Architecture Decisions</strong> for experienced engineers responsible for evaluating complex distributed systems and explaining the long-term consequences of architectural choices. The material includes twelve architectural trade-offs, twelve case studies, and an architecture risk assessment template.</p><p><a href="https://devrimozcay.gumroad.com/l/qktrrh">Staff Engineer Architecture Decisions: 12 Critical Trade-offs + 12 Production Cases + Risk Template</a></p><p>I’m also researching the challenges experienced engineers encounter during Senior and Staff system design interviews.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdocs.google.com%2Fforms%2Fd%2Fe%2F1FAIpQLScLD53xFU73sirxXmKFfL9-M7FGL_5mM6a8_B0qQdaYce2atA%2Fviewform%3Fembedded%3Dtrue&amp;display_name=Google+Docs&amp;url=https%3A%2F%2Fdocs.google.com%2Fforms%2Fd%2Fe%2F1FAIpQLScLD53xFU73sirxXmKFfL9-M7FGL_5mM6a8_B0qQdaYce2atA%2Fviewform%3Fusp%3Dheader&amp;image=https%3A%2F%2Flh6.googleusercontent.com%2F1c67GfSCyEA_IUtodYCJgYLDGOqIuo62OzVnGK9torhRzSxYtd_uTxCv79ExsxuD-Lv_OJR1vfzAR6s%3Dw1200-h630-p&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=google" width="760" height="675" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ff75ab6d435aa7f849ec31a69970e49/href">https://medium.com/media/0ff75ab6d435aa7f849ec31a69970e49/href</a></iframe><p>Further investigations into distributed systems, database internals, and software architecture are available on my Substack.</p><p><a href="https://substack.com/@devrimozcay1">Devrim Ozcay | ProdRescue | Substack</a></p><h3>Frequently Asked Questions</h3><h3>How do you design a search engine for billions of documents?</h3><p>A large-scale search engine requires compressed inverted indexes, distributed retrieval, efficient candidate pruning, relevance ranking, controlled indexing workloads, and measurable search quality.</p><h3>What is Block-Max WAND?</h3><p>Block-Max WAND is a ranked retrieval optimization that uses block-level score upper bounds to avoid evaluating candidates that cannot enter the current top results.</p><h3>Why does database sharding affect search relevance?</h3><p>Shards may contain different statistical distributions of documents and terms. Relevance scores based on local statistics can therefore differ across partitions.</p><h3>What is the difference between retrieval and reranking?</h3><p>Retrieval identifies potentially relevant candidates from the searchable corpus. Reranking applies additional scoring mechanisms to reorder those candidates according to their estimated relevance.</p><h3>Technical References</h3><p>From MAXSCORE to Block-Max WAND: The Story of How Lucene Significantly Improved Query Evaluation Performance.</p><p><a href="https://pmc.ncbi.nlm.nih.gov/articles/PMC7148045/">https://pmc.ncbi.nlm.nih.gov/articles/PMC7148045/</a></p><p>Elastic Engineering — MAXSCORE and Block-Max MAXSCORE.</p><p><a href="https://www.elastic.co/search-labs/blog/more-skipping-with-bm-maxscore">https://www.elastic.co/search-labs/blog/more-skipping-with-bm-maxscore</a></p><p>Elastic Documentation — Getting Consistent Scoring.</p><p><a href="https://www.elastic.co/docs/solutions/search/full-text/search-relevance/consistent-scoring">https://www.elastic.co/docs/solutions/search/full-text/search-relevance/consistent-scoring</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e99cd4333128" width="1" height="1" alt=""><hr><p><a href="https://medium.com/engineering-playbook/designing-a-search-engine-for-10-billion-documents-architecture-beyond-elasticsearch-e99cd4333128">Designing a Search Engine for 10 Billion Documents: Architecture Beyond Elasticsearch</a> was originally published in <a href="https://medium.com/engineering-playbook">ProdRescue Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Metastable Failures: Why Distributed Systems Stay Down Even After You Fix the Problem]]></title>
            <link>https://medium.com/engineering-playbook/metastable-failures-why-distributed-systems-stay-down-even-after-you-fix-the-problem-ebbded60e3c1?source=rss-6bdd1f176ebd------2</link>
            <guid isPermaLink="false">https://medium.com/p/ebbded60e3c1</guid>
            <category><![CDATA[sre]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Staff Engineer Mindset | ProdRescue By Devrim]]></dc:creator>
            <pubDate>Thu, 26 Nov 2026 15:39:23 GMT</pubDate>
            <atom:updated>2026-11-26T15:39:23.196Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*yhY0ZS0wg7Lgs7wW8nuYCw.png" /></figure><h4><em>The failure dynamics that conventional load testing, autoscaling, and production monitoring struggle to explain.</em></h4><p>In 2022, researchers studying production outages published a particularly interesting paper at the USENIX Symposium on Operating Systems Design and Implementation. They examined 22 metastable failures across 11 organizations and identified this failure pattern in at least four of the fifteen major AWS outages considered in their research.</p><p>One of the cases involved Twitter, where garbage collection contributed to a persistent service failure. Growing request queues increased memory pressure, garbage collection consumed more processing time, and the resulting slowdown caused queues to grow further. Reducing the original source of pressure was insufficient; the system needed substantial load reduction before it could recover.</p><p>The research deserves more attention from engineers responsible for large distributed systems because it challenges a common assumption underlying production incident response: removing the original cause should eventually restore normal service.</p><h3>The Capacity Benchmark That Gives Engineers False Confidence</h3><p>Suppose a backend service handles 8,000 requests per second during ordinary production traffic. Performance testing establishes that the service can process 10,000 requests per second under healthy conditions.</p><p>The engineering team considers the remaining capacity sufficient. Kubernetes autoscaling is configured, database connections are monitored, and previous load tests have shown acceptable latency.</p><p>A temporary storage slowdown changes the service’s execution characteristics. Requests remain in memory longer, queues accumulate, and response times begin exceeding client deadlines.</p><p>The storage subsystem subsequently recovers, but the application continues struggling to process its ordinary workload. Its effective capacity has fallen because it is spending increasing amounts of time managing accumulated work.</p><p>Under these conditions, the original benchmark of 10,000 requests per second has limited relevance. The service’s maximum sustainable throughput now depends on how much unfinished work it already contains.</p><h3>Throughput Can Increase While Useful Work Collapses</h3><p>Consider the same service during an incident. Its monitoring dashboard reports 9,500 completed processing attempts per second, reasonably close to the capacity established during testing.</p><p>Examining the workload reveals a different situation.</p><pre>Successful business requests: 2,100<br>Expired request processing:   3,200<br>Duplicate work:               2,600<br>Failed processing attempts:   1,600</pre><p>Although the service completes 9,500 processing attempts each second, only 2,100 produce useful business outcomes.</p><p>Its effective goodput is approximately 22% of its measured processing throughput.</p><p>The distinction becomes particularly important when autoscaling policies rely on CPU utilization, incoming request volume, or queue length. Those measurements describe infrastructure activity without necessarily establishing whether the application is completing commercially useful operations.</p><p>For an order processing platform, I would measure successfully committed orders alongside infrastructure throughput. The same principle applies to settled transactions, completed document processing jobs, and successfully delivered notifications.</p><h3>The Mathematical Condition for Persistent Overload</h3><p>An illustrative model can explain why a system fails to recover after its original dependency becomes healthy.</p><p>Assume ordinary customer traffic arrives at 8,000 requests per second, while the degraded application can process 7,000 attempts per second. Failed attempts generate an additional average of 0.5 attempts per original request during the observed period.</p><pre>Original workload: 8,000/sec<br>Additional attempts: 4,000/sec<br>Total workload: 12,000/sec<br>Effective capacity: 7,000/sec</pre><p>The queue grows by approximately 5,000 operations every second under these simplified assumptions.</p><p>After five minutes, the application has accumulated approximately 1.5 million operations. Some may already have expired from the customer’s perspective, but the infrastructure still considers them eligible for processing.</p><p>The service would remain overloaded even if additional attempts disappeared completely, because ordinary traffic exceeds its current degraded capacity.</p><p>Recovery requires reducing admission below the capacity available in the degraded state. The admission threshold needs to leave sufficient resources for draining existing work and restoring healthy execution characteristics.</p><h3>When the JVM Becomes Part of the Failure Mechanism</h3><p>Java applications offer an especially useful example of this behavior. Requests frequently retain deserialized payloads, authentication information, tracing objects, asynchronous execution state, and intermediate business data while waiting for downstream operations.</p><p>Suppose each queued operation retains an average of 24 KiB of live heap objects.</p><pre>Queued operations: 300,000<br>Retained heap per operation: 24 KiB<br>Total retained heap: 6.87 GiB</pre><p>An application configured with an 8 GiB heap now has relatively little space remaining for unrelated application objects and new allocations.</p><p>Temporary downstream latency has effectively changed the application’s memory management workload. As more objects survive collection cycles, garbage collection costs may increase, leaving less processing capacity available for completing requests.</p><p>The relationship can become self-sustaining.</p><pre>Longer execution time<br>        |<br>Larger request queues<br>        |<br>More live heap objects<br>        |<br>Increased GC overhead<br>        |<br>Longer execution time</pre><p>Increasing the garbage collector’s available CPU might temporarily improve the situation, but an unbounded queue permits the application to continue accumulating work. The investigation needs to include retained objects per request, executor queue limits, allocation rates, and the lifetime of objects waiting for external dependencies.</p><h3>Why Autoscaling Can Make the Incident More Expensive</h3><p>Imagine a service whose autoscaler increases application replicas from 100 to 300 during persistent overload. Each pod maintains a database connection pool with a maximum size of thirty.</p><pre>Before scaling:<br>100 x 30 = 3,000 connections</pre><pre>After scaling:<br>300 x 30 = 9,000 connections</pre><p>If the database is already experiencing lock contention or storage saturation, the additional application capacity can increase concurrent pressure on the constrained dependency.</p><p>New replicas also require initialization resources. Depending on the application, startup may involve establishing connections, loading configuration, compiling frequently executed JVM methods, and populating local caches. The autoscaler may therefore introduce additional work precisely when downstream capacity is least available.</p><p>Scaling can resolve genuine compute shortages. Its effectiveness during a metastable failure depends on whether the additional capacity addresses the sustaining mechanism or simply increases demand elsewhere.</p><h3>Cache Warm-Up Can Prevent an Entire Fleet From Recovering</h3><p>Consider an application serving 60,000 cacheable reads per second. Under ordinary conditions, its cache hit rate is 99%, resulting in approximately 600 live database queries per second.</p><p>After a fleet-wide restart, the cache hit rate temporarily falls to 70%.</p><pre>Normal database demand: 600/sec<br>Cold-cache demand: 18,000/sec</pre><p>The database can sustainably process 5,000 queries per second alongside its other workloads. Consequently, many cache population requests fail or time out, preventing the application from rebuilding its normal cache state.</p><p>Restarting additional application instances may repeat the same cycle if those instances rely on local caches. A recovery procedure should reserve enough database capacity for controlled cache population. Gradually admitting customer traffic, coalescing requests for identical keys, and preserving usable cached data where appropriate can help the application escape its degraded condition.</p><p>The permitted use of stale information must remain consistent with the application’s correctness and security requirements.</p><h3>Most Load Tests Never Exercise the Recovery Curve</h3><p>A conventional performance test gradually increases incoming traffic, records latency, and identifies the workload at which the system becomes saturated. For metastability testing, I would extend the experiment considerably. Establish a sustainable baseline, introduce a temporary dependency slowdown, allow unfinished work to accumulate, and then remove the injected fault while maintaining the original customer arrival rate.</p><p>The relevant measurement is what happens after the fault disappears.</p><p>If the application remains degraded, gradually reduce admission until useful throughput recovers. Record the workload at which recovery becomes possible and compare it with the workload the healthy application could previously sustain.</p><p>A hypothetical result might resemble this:</p><pre>Healthy capacity: 10,000 RPS<br>Normal production: 8,000 RPS<br>Failure triggered at: 9,000 RPS<br>Recovery required: 3,500 RPS</pre><p>The gap between normal operating capacity and recovery capacity describes a property that ordinary peak-throughput benchmarks fail to capture.</p><p>In practice, this boundary may vary with the duration of the incident, accumulated queue size, dependency behavior, and workload composition.</p><h3>Engineering a Recovery Mode</h3><p>I would give critical services an explicit recovery mode that can be activated independently of their ordinary autoscaling policies.</p><p>During recovery, the application should reject work that cannot complete before its deadline and restrict access to constrained dependencies. Existing queues should be examined for abandoned requests, while durable business obligations must remain available for safe processing or reconciliation. This distinction matters in financial systems. An expired HTTP request may contain an operation whose external outcome remains unresolved. Discarding its execution record could introduce a financial inconsistency even if doing so improves infrastructure metrics.</p><p>Recovery procedures therefore need input from engineers who understand the business semantics of the queued operations.</p><p>The exit condition should depend on sustained useful throughput, declining backlog, and restored dependency capacity. CPU utilization returning to an acceptable range provides insufficient evidence when customers are still unable to complete their transactions.</p><h3>Production Engineering Resources</h3><p>I built <strong>Senior Backend Production Engineering OS</strong> for experienced engineers investigating failures that cross application, database, infrastructure, and distributed system boundaries. It brings together production engineering systems, diagnostic tools, and operational playbooks intended to develop practical investigation skills beyond conventional architecture exercises.</p><p><a href="https://devrimozcay.gumroad.com/l/epxiu">Senior Backend Production Engineering OS: 31 Systems, Tools &amp; Production Playbooks</a></p><p>I’m also conducting independent research into production incidents affecting engineering teams, including the operational problems that consume the most engineering time and business resources.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdocs.google.com%2Fforms%2Fd%2Fe%2F1FAIpQLSdPmNpQj0vkuiUg6dLsEIIfCU3DF9s4w4LkmCRpG-iCsGle5w%2Fviewform%3Fembedded%3Dtrue&amp;display_name=Google+Docs&amp;url=https%3A%2F%2Fdocs.google.com%2Fforms%2Fd%2Fe%2F1FAIpQLSdPmNpQj0vkuiUg6dLsEIIfCU3DF9s4w4LkmCRpG-iCsGle5w%2Fviewform%3Fusp%3Dheader&amp;image=https%3A%2F%2Flh5.googleusercontent.com%2F0PjjoPdT-mhK0AMajyS6aQB9UNWiFUzsDnHh94GVSWX9epl-aNHIIY9y94sY2d4cY8mQ3ITguy2dbeE%3Dw1200-h630-p&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=google" width="760" height="675" frameborder="0" scrolling="no"><a href="https://medium.com/media/e0bbb0b75c005b9cea8eb8f348adbf29/href">https://medium.com/media/e0bbb0b75c005b9cea8eb8f348adbf29/href</a></iframe><p>I publish further technical investigations into distributed systems and production failures on Substack.</p><p><a href="https://substack.com/@devrimozcay1">Devrim Ozcay | ProdRescue | Substack</a></p><h3>Frequently Asked Questions</h3><h3>What is a metastable failure in distributed systems?</h3><p>A metastable failure occurs when temporary overload activates a self-sustaining mechanism that keeps a system degraded after the original triggering condition disappears.</p><h3>How do you detect a metastable failure?</h3><p>Compare useful business throughput against processing attempts, accumulated work, and dependency health. Persistent degradation after removing a temporary fault warrants investigation into internal feedback mechanisms.</p><h3>Can Kubernetes autoscaling prevent metastable failures?</h3><p>Autoscaling may help when additional compute capacity addresses the underlying constraint. It can worsen degradation when newly created application instances increase pressure on an already saturated dependency.</p><h3>How do you test for metastability?</h3><p>Introduce a temporary fault under sustained traffic, remove the fault, and observe whether the application recovers independently. Measure the level of load reduction required to restore normal execution.</p><h3>Research References</h3><p><strong>Metastable Failures in the Wild — USENIX OSDI 2022</strong></p><p><a href="https://www.usenix.org/conference/osdi22/presentation/huang-lexiang">https://www.usenix.org/conference/osdi22/presentation/huang-lexiang</a></p><p><strong>We’re Still Down: A Metastable Failure Tale — SREcon 2023</strong></p><p><a href="https://www.usenix.org/conference/srecon23americas/presentation/lexmond">https://www.usenix.org/conference/srecon23americas/presentation/lexmond</a></p><p><strong>Experimental Applications for Reproducing Metastable Failures</strong></p><p><a href="https://github.com/lexiangh/Metastability">https://github.com/lexiangh/Metastability</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ebbded60e3c1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/engineering-playbook/metastable-failures-why-distributed-systems-stay-down-even-after-you-fix-the-problem-ebbded60e3c1">Metastable Failures: Why Distributed Systems Stay Down Even After You Fix the Problem</a> was originally published in <a href="https://medium.com/engineering-playbook">ProdRescue Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Google Zanzibar Solves Authorization at Scale: Designing a Global Permission System]]></title>
            <link>https://medium.com/engineering-playbook/how-google-zanzibar-solves-authorization-at-scale-designing-a-global-permission-system-4a251376bbe0?source=rss-6bdd1f176ebd------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a251376bbe0</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Staff Engineer Mindset | ProdRescue By Devrim]]></dc:creator>
            <pubDate>Thu, 26 Nov 2026 15:36:44 GMT</pubDate>
            <atom:updated>2026-11-26T15:37:19.328Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*q2VBV70u6CxWodvAnmYxsA.png" /></figure><h4><em>An advanced system design investigation into relationship-based access control, permission graphs, causal consistency, and enterprise authorization infrastructure.</em></h4><p>Imagine an investment bank using a collaborative document platform to manage confidential acquisition agreements. An employee is removed from a project, and several minutes later, the legal department uploads a revised agreement containing previously undisclosed financial information. The former project member attempts to access that document through an application server whose authorization cache has yet to observe the permission change.</p><p>The employee has a valid authentication token. The application performs its permission check successfully, yet confidential information becomes accessible to someone whose authorization was already revoked.</p><p>This class of problem motivated part of Google’s Zanzibar architecture, presented at the 2019 USENIX Annual Technical Conference. Google reported that Zanzibar supported trillions of access-control lists and millions of authorization requests per second, while maintaining a 95th-percentile latency below ten milliseconds.</p><p>Understanding how such a system works requires treating authorization as a distributed data problem.</p><h3>Why Conventional Role-Based Authorization Becomes Restrictive</h3><p>Consider an enterprise collaboration platform containing documents, folders, projects, organizations, and external contractors. A user may receive document access through direct assignment, project membership, or membership in a department that owns the parent folder.</p><p>Encoding every possible relationship as an application role becomes difficult to maintain. Department reorganizations and temporary project assignments can require extensive changes to authorization records, particularly when permissions inherit across organizational boundaries.</p><p>A relationship-based authorization system represents these connections as data.</p><pre>group:finance#member@user:alice<br>folder:reports#viewer@<br>group:finance#member</pre><p>The first relationship establishes Alice’s membership in the finance group. The second grants members of that group access to the reports folder.</p><p>A document can subsequently inherit permissions from its parent folder. The authorization engine evaluates these relationships when deciding whether Alice can access a particular resource.</p><p>Application services can therefore express access policies without independently implementing the entire organizational hierarchy.</p><h3>Designing the Permission Graph</h3><p>Suppose our hypothetical enterprise platform supports 50 million users, two billion protected resources, and five billion stored relationships.</p><p>A simplified authorization model could resemble the following SpiceDB-style schema:</p><pre>definition user {}<br>definition group {<br>    relation member:<br>        user | group#member<br>}<br>definition folder {<br>    relation viewer:<br>        user | group#member<br>    relation parent: folder<br>    permission view =<br>        viewer + parent-&gt;view<br>}<br>definition document {<br>    relation parent: folder<br>    relation editor:<br>        user | group#member<br>    permission view =<br>        editor + parent-&gt;view<br>    permission edit = editor<br>}</pre><p>A document viewer might have inherited access through several levels of folder ownership and nested group membership. Evaluating the permission consequently requires resolving a graph of relationships rather than retrieving a single database row.</p><p>An important schema decision concerns whether recursive folder and group relationships are permitted. Without structural restrictions or traversal limits, deeply nested relationships can consume substantial processing capacity. Cycles introduce additional complications because the authorization engine must detect or safely bound recursive evaluation. I would establish constraints on organizational hierarchy depth as part of the platform’s data model, particularly when enterprise customers can create their own authorization structures.</p><h3>The New Enemy Problem</h3><p>A permission cache introduces a security problem when resource contents and authorization state evolve independently.</p><p>Consider the following sequence:</p><pre>Revision 100:<br>Bob can access folder F.<br>Revision 101:<br>Bob&#39;s access is revoked.<br>Revision 102:<br>Confidential content is uploaded.</pre><p>Bob subsequently requests the newly uploaded content. An authorization check evaluated against revision 100 may still identify him as an authorized viewer.</p><p>The significant detail here is that the content was created after his access had already been removed. A stale authorization decision can therefore expose information he was never authorized to see.</p><p>Zanzibar addresses this problem using consistency tokens known as zookies. The application associates a content version with an authorization freshness requirement, allowing future permission checks to avoid snapshots that precede the relevant authorization state. The content service must participate in this protocol. Introducing a sophisticated authorization database while continuing to serve content independently of its authorization revision would leave the original problem unresolved.</p><h3>Why Every Permission Check Does Not Require the Latest Snapshot</h3><p>Assume our platform receives 500,000 authorization requests per second. Most concern resources whose permissions have remained unchanged for hours or days. Evaluating every request against the latest available authorization state would reduce opportunities for caching and could increase geographically distributed storage traffic.</p><p>Modern Zanzibar-inspired implementations such as SpiceDB expose different consistency options. A caller can prioritize cached results, require a snapshot at least as recent as a supplied token, or request a specific snapshot where supported.</p><p>Consider a document service storing an opaque authorization token alongside each sensitive content version.</p><pre>Document ID: 784<br>Content version: 19<br>Authorization token: opaque-value</pre><p>When retrieving version 19, the service supplies that token with its permission check. The authorization engine must evaluate the request using a revision satisfying the required freshness boundary. After subsequent revocations, the application still needs an appropriate revocation policy. A token associated with an older content version does not automatically guarantee that every later permission change will be observed immediately.</p><p>Different operations may therefore require different freshness guarantees.</p><h3>Permission Graph Fan-Out Can Dominate Infrastructure Consumption</h3><p>Suppose an authorization request explores an average of twelve relationship subproblems.</p><pre>500,000 permission checks/sec<br>x 12 relationship subproblems<br>= 6M graph operations/sec</pre><p>The average can conceal exceptionally expensive requests. An organization using deeply nested groups and extensively inherited permissions might require hundreds of subproblems to establish a single authorization decision.</p><p>Positive and negative decisions may also have different execution costs. For a permission defined as the union of several access paths, a successful path can establish access immediately. Proving that access is absent may require evaluating every relevant path. This asymmetry matters when sizing infrastructure and investigating latency distributions.</p><p>I would monitor graph dispatch counts, traversal depth, datastore queries, and cache effectiveness separately from the latency of the public authorization API. Otherwise, an apparently modest increase in permission-check traffic could produce a disproportionately large increase in storage workload.</p><h3>Cache Intermediate Permission Results Carefully</h3><p>Suppose 100,000 employees belong to an engineering department that has access to millions of documents through inherited folder permissions.</p><p>Caching only complete document-level authorization results would create an enormous key space. Many of those checks repeatedly evaluate the same underlying group memberships.</p><p>Intermediate graph results provide opportunities for reuse across otherwise unrelated document requests.</p><p>A cache identity might conceptually include:</p><pre>Object<br>Relation<br>Subject<br>Authorization revision<br>Policy version<br>Relevant context</pre><p>The revision and policy version matter because a cached graph result cannot safely be reused against an incompatible authorization snapshot. Where permissions depend on contextual conditions, such as resource attributes or session properties, those conditions also affect cache validity. Revision selection becomes an infrastructure decision. Excessively fragmented snapshots may reduce cache reuse, while unnecessarily stale snapshots can violate application requirements.</p><h3>Listing Accessible Resources Requires a Different Query Strategy</h3><p>Checking whether Alice can access a particular document is comparatively straightforward. Returning every document Alice is permitted to access presents a different workload.</p><p>Suppose a search operation identifies 20,000 candidate documents. Performing an independent authorization request for each document would introduce considerable execution overhead.</p><p>At 200 such search requests per second:</p><pre>200 x 20,000<br>= 4M permission checks/sec</pre><p>The search feature alone could generate eight times the platform’s assumed baseline authorization traffic.</p><p>Several approaches deserve evaluation. The authorization engine can perform reverse relationship lookups, the search system can maintain carefully controlled permission-aware indexes, or candidate resources can be evaluated through batched permission checks.</p><p>Precomputed indexes introduce another freshness problem. A stale index must not become the final authority for releasing confidential content after a permission has been revoked. Pagination also requires careful consideration. If permissions change between page requests, the platform must define whether the listing represents a stable historical snapshot or the user’s currently accessible resources.</p><h3>Authorization Schema Changes Can Alter Millions of Access Decisions</h3><p>Consider a policy that grants document editing privileges to explicitly assigned editors. An engineering team subsequently changes the policy to include every member of the document’s owning department. No underlying relationship records need to change for this deployment to expand access dramatically.</p><p>The authorization schema itself has become a security-sensitive production artifact.</p><p>Before deploying such a change, I would evaluate the old and proposed models against representative relationship graphs. Particular attention should go to permission expansions involving external contractors, confidential resources, and inherited administrative privileges.</p><p>The deployment architecture should also prevent application instances from unintentionally evaluating requests under incompatible policy versions. Shadow evaluation can expose unexpected access differences before the new model becomes authoritative.</p><h3>Capacity Planning for Enterprise Authorization</h3><p>Assume five billion relationship tuples, each consuming an illustrative 120 bytes before indexing and replication.</p><pre>5B x 120 bytes<br>= 600 GB logical storage</pre><p>With three replicas:</p><pre>600 GB x 3<br>= 1.8 TB replicated storage</pre><p>Secondary indexes, historical revisions, transaction logs, and storage engine overhead increase the actual requirement.</p><p>Now consider a workload where 90% of 500,000 permission requests per second can be satisfied without querying the authoritative datastore.</p><pre>500,000 x 0.10<br>= 50,000 remaining checks/sec</pre><p>If degradation reduces that cache effectiveness to 60%, the remaining workload increases to 200,000 checks per second.</p><p>This fourfold increase occurs without any change in customer traffic. The storage architecture must accommodate realistic cache degradation, and the platform must decide how to handle authorization requests when their required consistency guarantees cannot be satisfied. For sensitive resources, returning an unavailable response may be preferable to granting access based on an incompatible historical snapshot.</p><h3>The Architecture Review</h3><p>Consider an enterprise customer removing a contractor from a nested group while another employee simultaneously transfers confidential documents into a shared folder. The search index has not observed either change, and several authorization workers retain cached results from earlier revisions. A credible design needs to establish which content versions can be returned, what freshness requirement each permission check must satisfy, and whether indirect group membership has been evaluated correctly.</p><p>I would ask the engineering team to demonstrate this scenario through a reproducible integration test before approving the architecture. The test should verify actual disclosure behavior across the search service, content storage, authorization engine, and application cache. Testing the permission engine independently would miss failures in the surrounding integration.</p><h3>Advanced System Design Interview Preparation</h3><p>I developed <strong>Senior &amp; Staff Engineer Interview Mastery OS</strong> for experienced software engineers preparing for architecture interviews involving distributed systems, consistency models, backend infrastructure, and complex technical decisions.</p><p>The collection brings together eighteen engineering preparation products for engineers pursuing greater technical responsibility.</p><p><a href="https://devrimozcay.gumroad.com/l/oordy">Senior &amp; Staff Engineer Interview Mastery: 18 Premium Products for High-Paying Engineering Roles</a></p><p>I’m also researching the challenges experienced engineers encounter during Senior and Staff system design interviews.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdocs.google.com%2Fforms%2Fd%2Fe%2F1FAIpQLScLD53xFU73sirxXmKFfL9-M7FGL_5mM6a8_B0qQdaYce2atA%2Fviewform%3Fembedded%3Dtrue&amp;display_name=Google+Docs&amp;url=https%3A%2F%2Fdocs.google.com%2Fforms%2Fd%2Fe%2F1FAIpQLScLD53xFU73sirxXmKFfL9-M7FGL_5mM6a8_B0qQdaYce2atA%2Fviewform%3Fusp%3Dheader&amp;image=https%3A%2F%2Flh6.googleusercontent.com%2F1c67GfSCyEA_IUtodYCJgYLDGOqIuo62OzVnGK9torhRzSxYtd_uTxCv79ExsxuD-Lv_OJR1vfzAR6s%3Dw1200-h630-p&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=google" width="760" height="675" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ff75ab6d435aa7f849ec31a69970e49/href">https://medium.com/media/0ff75ab6d435aa7f849ec31a69970e49/href</a></iframe><p>Further investigations into distributed systems and enterprise architecture are available on my Substack.</p><p><a href="https://substack.com/@devrimozcay1">Devrim Ozcay | ProdRescue | Substack</a></p><h3>Frequently Asked Questions</h3><h3>What is Google Zanzibar?</h3><p>Zanzibar is Google’s globally distributed authorization system, described in a 2019 research paper. It provides a common framework for evaluating access-control relationships across different applications.</p><h3>What is relationship-based access control?</h3><p>Relationship-based access control, or ReBAC, determines permissions using relationships between users, groups, and resources. It supports authorization models involving nested membership and inherited permissions.</p><h3>What is the New Enemy Problem in distributed authorization?</h3><p>It occurs when authorization is evaluated against an outdated snapshot, potentially permitting access to content created after the user’s permissions were revoked.</p><h3>What is the difference between Zanzibar and SpiceDB?</h3><p>Zanzibar is Google’s internal authorization architecture. SpiceDB is a publicly available authorization database inspired by Zanzibar’s design.</p><h3>Technical References</h3><p>Zanzibar: Google’s Consistent, Global Authorization System — USENIX ATC 2019.</p><p><a href="https://www.usenix.org/conference/atc19/presentation/pang">https://www.usenix.org/conference/atc19/presentation/pang</a></p><p>SpiceDB Documentation — Consistency and ZedTokens.</p><p><a href="https://authzed.com/docs/spicedb/concepts/consistency">https://authzed.com/docs/spicedb/concepts/consistency</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a251376bbe0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/engineering-playbook/how-google-zanzibar-solves-authorization-at-scale-designing-a-global-permission-system-4a251376bbe0">How Google Zanzibar Solves Authorization at Scale: Designing a Global Permission System</a> was originally published in <a href="https://medium.com/engineering-playbook">ProdRescue Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing a Global Distributed Rate Limiter for One Billion Requests per Minute]]></title>
            <link>https://medium.com/engineering-playbook/designing-a-global-distributed-rate-limiter-for-one-billion-requests-per-minute-d7ed26a91151?source=rss-6bdd1f176ebd------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7ed26a91151</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Staff Engineer Mindset | ProdRescue By Devrim]]></dc:creator>
            <pubDate>Thu, 26 Nov 2026 15:29:42 GMT</pubDate>
            <atom:updated>2026-11-26T15:33:07.800Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*Tc-2Wz1sMf8GzINkxPgAYg.png" /></figure><h4><em>Advanced system design covering distributed quotas, regional consistency, hot-key contention, failure recovery, and API infrastructure at enterprise scale.</em></h4><p>A distributed rate limiter becomes considerably harder to design when its decisions have contractual consequences. An enterprise customer purchasing access to ten million API operations per hour expects that capacity to remain available across regions. Meanwhile, the infrastructure team needs to prevent excessive consumption without introducing a globally coordinated database operation into every incoming request.</p><p>Consider a global API platform handling one billion requests per minute during peak demand. Customers connect through North America, Europe, and Asia, with different subscription limits, endpoint restrictions, and infrastructure consumption patterns.</p><p>The central architectural problem is enforcing commercially meaningful limits without making the rate limiter the most expensive dependency in the request path.</p><h3>The Cost of Checking Every Request Against Redis</h3><p>The platform’s peak request volume translates into approximately 16.67 million requests per second.</p><pre>1,000,000,000 / 60<br>= 16.67M requests/sec</pre><p>Suppose every incoming request requires a remote Redis operation to check and update its quota. At an illustrative sustainable throughput of 100,000 operations per second per primary instance, the platform would require at least 167 primaries under ideal workload distribution.</p><p>With two replicas per primary:</p><pre>167 x 3<br>= 501 Redis instances</pre><p>This theoretical estimate excludes replication overhead, uneven key distribution, network saturation, failover capacity, and more expensive rate-limiting operations. Even with sufficient aggregate throughput, the architecture remains vulnerable to individual customers generating concentrated demand against a single quota key. Adding Redis shards increases overall capacity without necessarily improving the throughput available to that particular customer.</p><h3>Regional Quota Allocation Changes the Coordination Problem</h3><p>Suppose an enterprise customer purchases a global quota of 900,000 requests per minute. Its traffic arrives through three geographical regions.</p><p>The simplest architecture maintains one authoritative global counter, requiring geographically distributed gateways to coordinate against the same state.</p><p>An alternative distributes bounded quota allocations to individual regions.</p><pre>Global quota: 900,000<br>North America: 400,000<br>Europe:        300,000<br>Asia:          200,000</pre><p>Each region can independently authorize requests against its assigned capacity. Provided that allocations cannot be duplicated and their combined value remains within the global quota, the platform can enforce the overall limit without coordinating every request across continents.</p><p>The drawback becomes apparent when traffic distribution changes. Europe may exhaust its allocation while Asia retains substantial unused capacity.</p><p>A quota allocation service can redistribute available capacity, although the transfer protocol must establish that the original region can no longer spend the transferred quota. Otherwise, both regions could authorize requests against the same allocation.</p><h3>Hierarchical Rate Limiting Reduces Network Coordination</h3><p>At sixteen million requests per second, I would investigate how much authorization can safely occur inside individual gateway processes.</p><p>A hierarchical architecture could operate as follows:</p><pre>Global Quota Controller<br>          |<br>Regional Quota Allocator<br>          |<br>Gateway Token Allocations<br>          |<br>Local Request Authorization</pre><p>Suppose each gateway obtains an allocation of 1,000 request tokens from its regional controller. Under ideal utilization, the regional allocation request rate falls considerably.</p><pre>16.67M / 1,000<br>= approximately 16,667/sec</pre><p>The allocation system performs thousands of coordination operations per second instead of millions. Larger allocations improve coordination efficiency but increase the amount of capacity that can become stranded inside inactive or failed gateways. Smaller allocations reduce stranded capacity while increasing controller traffic.</p><p>The allocation size should reflect gateway consumption rates, remaining customer quota, and the cost of delayed quota redistribution.</p><h3>Gateway Failures Can Produce Duplicate Quota Allocations</h3><p>Consider a regional controller granting 10,000 tokens to Gateway A. The gateway consumes 4,000 tokens before losing connectivity to the controller.</p><p>The controller cannot immediately determine whether the remaining 6,000 tokens are unused. Gateway A might still be serving requests through an independent network path. Reissuing those tokens to Gateway B could allow both gateways to spend the same capacity.</p><p>A safer allocation record might contain:</p><pre>Allocation ID<br>Tenant ID<br>Gateway ID<br>Quota Window<br>Granted Tokens<br>Leadership Epoch<br>Expiration</pre><p>Reclaiming unused tokens requires a protocol that prevents the previous allocation holder from continuing to authorize requests. Depending on the architecture, this may involve explicit surrender, enforceable expiration with bounded clock uncertainty, or fencing at the relevant admission boundary. For strict quotas, the system may need to tolerate temporarily stranded capacity rather than reclaim tokens whose ownership cannot be established safely.</p><h3>A Request Is Often the Wrong Unit of Measurement</h3><p>An enterprise AI platform exposes two endpoints. The first retrieves a customer’s account information, while the second initiates a computationally expensive inference operation. Both consume one request from a conventional rate limiter.</p><p>The underlying infrastructure costs, however, differ substantially. A customer could remain within its contractual request limit while monopolizing inference capacity.</p><p>A weighted quota system might assign different resource costs:</p><pre>Account lookup:       1 unit<br>Document processing: 20 units<br>LLM inference:       50 units</pre><p>For operations whose final resource consumption cannot be predicted accurately, the platform can reserve an estimated amount before execution and reconcile the difference afterward. Concurrent reservations must be atomic within their authoritative quota boundary. Without that property, several workers could independently observe sufficient remaining capacity and collectively exceed the customer’s allocation.</p><p>This approach becomes particularly important for AI inference, analytical queries, bulk exports, and other workloads with highly variable execution costs.</p><h3>Rate Limiting and Concurrency Limiting Protect Different Resources</h3><p>An API permits a customer to submit 1,000 requests per second. Under normal conditions, each request completes in 100 milliseconds.</p><p>Using Little’s Law, the average number of in-flight requests is approximately:</p><pre>1,000 x 0.1<br>= 100 concurrent requests</pre><p>A downstream database incident increases average request duration to five seconds.</p><pre>1,000 x 5<br>= 5,000 concurrent requests</pre><p>The customer continues respecting its rate limit while consuming fifty times more concurrent execution capacity.</p><p>Connection pools, application memory, worker threads, and downstream dependencies can become saturated without any increase in incoming request rate. A production architecture should enforce concurrency limits alongside arrival-rate quotas. The concurrency boundary should protect the specific resources consumed by the operation, particularly when several endpoints share the same downstream database or inference cluster.</p><h3>Clock Differences Can Corrupt Window-Based Quotas</h3><p>A global customer has a fixed quota of one million requests per minute. Regional gateways independently calculate the current quota window using their local clocks.</p><p>One gateway enters the next minute before another gateway has finished processing requests against the previous window. Depending on how allocations are issued and validated, the customer could gain access to future capacity prematurely.</p><p>A globally managed quota window can provide a consistent allocation identity. Local enforcement should distinguish wall-clock time from monotonic elapsed time, especially when calculating token replenishment or allocation expiration. The platform also needs an explicit definition of its contractual limit. A fixed-window quota permits bursts around window boundaries, whereas a token bucket controls the sustained rate and allows a configured burst capacity.</p><p>Those algorithms offer different guarantees. Choosing one without establishing the customer’s expected traffic contract can create disputes even when the implementation behaves exactly as designed.</p><h3>The Rate Limiter Needs Its Own Failure Policy</h3><p>Suppose the regional quota controller becomes unavailable for ninety seconds. Gateways continue processing requests using previously issued allocations until those allocations are exhausted.</p><p>The next decision depends on the endpoint’s business consequences.</p><p>A public product catalog might permit a bounded emergency allowance. A costly AI inference endpoint could reject additional work once its existing allocation is exhausted. An endpoint protecting financial transaction exposure may require stricter admission controls.</p><p>Emergency allowances must also have a defined aggregate limit. If 20,000 gateways independently permit another 500 requests during an outage, the platform authorizes ten million additional requests.</p><pre>20,000 x 500<br>= 10M emergency requests</pre><p>A failure policy that appears conservative at the individual gateway level can become commercially unacceptable when multiplied across the entire infrastructure.</p><h3>What I Would Test Before Approving This Architecture</h3><p>I would begin with a customer generating traffic across all three regions while the quota controller is undergoing a leadership transition. During the transition, several gateways lose connectivity, regional traffic distribution changes, and delayed allocation responses arrive after their original requests have timed out.</p><p>The test should establish whether duplicate allocations are possible and whether any region can exceed its authorized capacity. It should also measure how much legitimate customer traffic is rejected because quota remains stranded elsewhere.</p><p>A useful architecture review would quantify the maximum permitted overshoot, the amount of unavailable quota during failures, and the coordination cost required to enforce stronger guarantees. Those measurements allow engineering and commercial leadership to agree on what the platform can realistically promise enterprise customers.</p><h3>Advanced System Design and Distributed Systems Preparation</h3><p>I developed <strong>Senior &amp; Staff Engineer Interview Mastery OS</strong> for experienced software engineers preparing for demanding architecture interviews involving distributed systems, consistency guarantees, scalability, and production failure scenarios.</p><p>The collection brings together eighteen engineering preparation products covering technical interviews and advanced backend architecture.</p><p><a href="https://devrimozcay.gumroad.com/l/oordy">Senior &amp; Staff Engineer Interview Mastery: 18 Premium Products for High-Paying Engineering Roles</a></p><p>I’m also researching the challenges experienced engineers encounter during Senior and Staff system design interviews.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdocs.google.com%2Fforms%2Fd%2Fe%2F1FAIpQLScLD53xFU73sirxXmKFfL9-M7FGL_5mM6a8_B0qQdaYce2atA%2Fviewform%3Fembedded%3Dtrue&amp;display_name=Google+Docs&amp;url=https%3A%2F%2Fdocs.google.com%2Fforms%2Fd%2Fe%2F1FAIpQLScLD53xFU73sirxXmKFfL9-M7FGL_5mM6a8_B0qQdaYce2atA%2Fviewform%3Fusp%3Dheader&amp;image=https%3A%2F%2Flh6.googleusercontent.com%2F1c67GfSCyEA_IUtodYCJgYLDGOqIuo62OzVnGK9torhRzSxYtd_uTxCv79ExsxuD-Lv_OJR1vfzAR6s%3Dw1200-h630-p&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=google" width="760" height="675" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ff75ab6d435aa7f849ec31a69970e49/href">https://medium.com/media/0ff75ab6d435aa7f849ec31a69970e49/href</a></iframe><p>Further advanced distributed systems and architecture investigations are available on my Substack.</p><p><a href="https://substack.com/@devrimozcay1">Devrim Ozcay | ProdRescue | Substack</a></p><h3>Frequently Asked Questions</h3><h3>How do you design a distributed rate limiter at global scale?</h3><p>Use hierarchical quota allocation, regional enforcement, local token consumption, and controlled redistribution. The coordination protocol must preserve the required global quota guarantees during failures.</p><h3>Can Redis handle millions of rate-limiting requests per second?</h3><p>A sufficiently provisioned Redis cluster can distribute substantial workloads across multiple instances. Hot-key contention, replication costs, network capacity, and failover requirements determine practical throughput.</p><h3>What is the difference between a token bucket and a sliding window?</h3><p>A token bucket enforces a sustained consumption rate while permitting configured bursts. A sliding-window algorithm evaluates consumption over a moving time interval, with accuracy depending on its implementation.</p><h3>How do distributed rate limiters maintain global consistency?</h3><p>They can use centralized coordination, consensus-backed quota ownership, or bounded regional allocations. Each approach introduces different latency, availability, and utilization trade-offs.</p><h3>What makes distributed rate limiting a Staff Engineer system design problem?</h3><p>The difficulty lies in enforcing global resource guarantees under concurrent execution, geographical partitions, ambiguous ownership, clock uncertainty, and infrastructure failures.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7ed26a91151" width="1" height="1" alt=""><hr><p><a href="https://medium.com/engineering-playbook/designing-a-global-distributed-rate-limiter-for-one-billion-requests-per-minute-d7ed26a91151">Designing a Global Distributed Rate Limiter for One Billion Requests per Minute</a> was originally published in <a href="https://medium.com/engineering-playbook">ProdRescue Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Design an AI Agent Platform That Handles 100 Million Tasks Without Losing Control]]></title>
            <link>https://medium.com/engineering-playbook/how-to-design-an-ai-agent-platform-that-handles-100-million-tasks-without-losing-control-c0ba82d9c170?source=rss-6bdd1f176ebd------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0ba82d9c170</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Staff Engineer Mindset | ProdRescue By Devrim]]></dc:creator>
            <pubDate>Thu, 26 Nov 2026 15:25:43 GMT</pubDate>
            <atom:updated>2026-11-26T15:26:17.438Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*-fN1CUNjnZJpDhxaFgcc1w.png" /></figure><h4><em>Advanced system design for enterprise AI agents, durable execution, distributed orchestration, inference economics, and operational safety.</em></h4><p>An AI agent that fails halfway through a financial workflow presents a considerably different engineering problem from a chatbot that produces an incorrect answer. The agent may have already modified customer records, submitted an external request, or consumed a substantial portion of its execution budget. Restarting the workflow from its original prompt could repeat operations that the business considers irreversible.</p><p>For this architecture exercise, consider an enterprise AI platform serving 5,000 organizations and executing 100 million tasks monthly. Agents can interact with databases, internal APIs, external applications, and other agents. Individual workflows may remain active for several hours while waiting for external systems or human approval.</p><h3>The Real Workload Is Hidden Inside Each Agent Execution</h3><p>Assume an average task requires eight model invocations and twelve external tool calls. The initial capacity calculation already reveals why conventional API request metrics provide an incomplete picture of agent infrastructure.</p><pre>Monthly tasks: 100M<br>Model calls per task: 8<br>Tool calls per task: 12</pre><p>The platform must accommodate 800 million model invocations and 1.2 billion tool calls every month.</p><p>Assuming a thirty-day month:</p><pre>800M / 2,592,000<br>= approximately 309 model calls/sec</pre><p>With a peak-to-average ratio of ten, inference demand approaches 3,086 model calls per second. Tool execution reaches approximately 4,630 calls per second under the same assumptions.</p><p>Agent execution lengths will also vary considerably. A difficult research task might consume fifty model invocations while a document classification task requires only one. Capacity planning should account for the distribution of execution costs rather than relying exclusively on average task complexity.</p><h3>Separate Agent Reasoning From Execution Authority</h3><p>I would avoid giving the language model direct access to production systems. The model can propose an operation, but an independently controlled execution layer should determine whether that operation is permitted.</p><p>A possible architecture separates these responsibilities:</p><pre>Client API<br>    |<br>Task Registry<br>    |<br>Durable Workflow Engine<br>    |<br>Agent Reasoning Runtime<br>    |<br>Policy Enforcement Gateway<br>    |<br>    +-- Tool Executor<br>    +-- Budget Controller<br>    +-- Approval Service<br>    +-- Credential Broker<br>    +-- Execution Journal</pre><p>The workflow engine owns execution state, while the reasoning runtime determines proposed next steps. The policy gateway evaluates those proposals against tenant permissions, operation restrictions, and remaining execution budgets.</p><p>Credentials should be scoped to the authorized operation and issued only when necessary. A model-generated request to access another organization’s records must fail independently of how convincingly the model describes its intentions.</p><h3>Durable Execution Requires More Than Conversation History</h3><p>Suppose an agent processes a supplier invoice through several operations. It extracts invoice information, validates the supplier, checks for duplicates, creates an accounting record, and requests payment approval.</p><p>The worker crashes immediately after creating the accounting record.</p><p>If another worker reconstructs the workflow exclusively from conversation history, it may repeat the accounting operation. The platform needs durable execution records identifying which steps have completed and which outcomes remain uncertain.</p><p>A simplified execution model could include:</p><pre>Task ID<br>Step ID<br>Execution Attempt<br>Workflow Version<br>Input Reference<br>Output Reference<br>Operation ID<br>Execution Status</pre><p>Each externally visible operation requires a stable identity that survives worker replacement. The recovery process should resume from committed execution state instead of asking the model to reconstruct what probably happened.</p><p>Workflow engines can provide durable orchestration, although their guarantees do not automatically extend to arbitrary external APIs.</p><h3>Exactly-Once Tool Execution Is Usually an External Contract</h3><p>Consider an agent authorized to issue a customer refund. The payment provider successfully processes the refund, but the tool executor times out before recording the response.</p><p>The workflow now contains an ambiguous external outcome.</p><pre>Operation: refund_7821<br>Requested amount: $450<br>Execution status: UNKNOWN</pre><p>Automatically retrying the refund with a new operation identifier could issue a second payment. Treating the timeout as definitive failure could leave the internal financial records inconsistent with the payment provider.</p><p>The execution gateway should preserve the original operation identity and use the provider’s supported idempotency or reconciliation mechanisms.</p><p>For external systems without reliable duplicate protection or status queries, the platform may need to suspend automatic recovery and request human investigation. A workflow engine cannot manufacture exactly-once financial guarantees when the external system provides no corresponding contract.</p><h3>Concurrent Agents Need Atomic Budget Reservations</h3><p>An enterprise customer allocates $10,000 to a collection of autonomous research agents. Several hundred workers execute concurrently, each estimating its remaining inference expenditure.</p><p>Reading the available budget before starting an operation creates a race condition. Multiple workers can observe sufficient funds and collectively exceed the authorized amount.</p><p>A simplified reservation mechanism could use an atomic database update:</p><pre>UPDATE execution_budget<br>SET reserved =<br>    reserved + :cost<br>WHERE tenant_id = :tenant<br>AND budget_limit<br>    - consumed<br>    - reserved &gt;= :cost;</pre><p>The reservation and execution authorization must be associated with a durable operation identifier. Otherwise, worker retries could reserve the same expenditure repeatedly.</p><p>After execution, the platform reconciles the reservation against actual consumption. Where model providers cannot guarantee a maximum charge, the architecture needs conservative reservation estimates, output limits, or explicit handling of potential overruns.</p><h3>Inference Economics Can Determine Whether the Platform Survives</h3><p>Assume each model invocation consumes an average of 4,000 input tokens and 800 output tokens.</p><p>At 800 million monthly invocations:</p><pre>Input tokens:<br>800M x 4,000<br>= 3.2 trillion tokens</pre><pre>Output tokens:<br>800M x 800<br>= 640 billion tokens</pre><p>Using illustrative inference rates of $2 per million input tokens and $8 per million output tokens:</p><pre>Monthly input cost:  $6.40M<br>Monthly output cost: $5.12M<br>Total inference:    $11.52M</pre><p>The platform would spend approximately $0.1152 in inference per completed or attempted task on average, before accounting for storage, orchestration, external tools, networking, and engineering operations. Suppose repeated reasoning steps and expanding conversation histories increase average model invocations from eight to twelve per task. Under unchanged token consumption and pricing assumptions, monthly inference expenditure rises to $17.28 million.</p><p>That additional $5.76 million originates from agent execution behavior. Infrastructure procurement alone cannot resolve it.</p><p>Model routing, context compression, deterministic workflow steps, and bounded reasoning loops should therefore be evaluated as architectural decisions with measurable financial consequences.</p><h3>Agent Memory Introduces a Persistent Security Boundary</h3><p>An enterprise agent retrieves historical documents and previous execution results to improve future decisions. One retrieved document contains instructions attempting to persuade the agent to export confidential information to an external endpoint.</p><p>If the agent stores those instructions in persistent memory, the malicious content may influence later workflows that have nothing to do with the original document. Memory records should preserve their provenance, tenant ownership, access restrictions, and retention policies. Information retrieved from documents, websites, or previous tool outputs must remain distinguishable from trusted execution policies.</p><p>The authorization gateway should evaluate every proposed external operation against the current security context. An agent remembering that a previous operation was permitted provides insufficient evidence that the same operation remains authorized today.</p><h3>Human Approval Must Be Bound to an Exact Operation</h3><p>An agent proposes deleting 500 obsolete customer records. An administrator reviews the operation and approves it. Before execution begins, another workflow modifies the underlying record selection. The original query now identifies 50,000 records.</p><p>Executing the modified operation under the previous approval would violate the administrator’s authorization.</p><p>A durable approval record should bind the authorization to a specific operation, its parameters, relevant resource versions, and an expiration policy.</p><pre>Approval ID<br>Operation ID<br>Payload Hash<br>Resource Version<br>Authorized Scope<br>Expiration</pre><p>If the operation changes materially after approval, the platform should invalidate the authorization and request another decision.</p><p>For destructive operations, the execution layer may also need conditional writes or transactional checks to prevent changes between final validation and execution.</p><h3>Model Upgrades Require Behavioral Compatibility Testing</h3><p>Traditional application deployments can often rely on deterministic regression tests. Agent behavior changes when the underlying model changes, even when prompts and tool definitions remain identical.</p><p>Suppose a replacement model improves average task completion from 92% to 95%. During evaluation, however, its unauthorized tool-call proposal rate increases from 0.1% to 0.4%.</p><p>At 100 million tasks monthly, assuming those percentages measure affected tasks:</p><pre>Previous model:<br>100M x 0.001 = 100,000 tasks</pre><pre>Replacement model:<br>100M x 0.004 = 400,000 tasks</pre><p>The policy gateway should reject unauthorized operations, but the increased proposal rate may still create additional inference costs, workflow failures, and investigation requirements. Model deployment decisions should incorporate behavioral evaluations covering financial correctness, tool authorization, instruction handling, recovery behavior, and cost per successful task.</p><p>Active workflows may also need pinned model and tool versions where changing execution behavior halfway through a task would create unacceptable uncertainty.</p><h3>Recovering From a Platform-Wide Execution Failure</h3><p>Assume the platform normally receives approximately 39 new tasks per second. An orchestration incident prevents new tasks from starting for two hours.</p><pre>39 x 7,200<br>= approximately 280,800 tasks</pre><p>After recovery, the infrastructure can initiate 60 tasks per second while new work continues arriving at the original rate.</p><pre>60 - 39<br>= 21 tasks/sec recovery capacity</pre><pre>280,800 / 21<br>= approximately 3.7 hours</pre><p>The backlog requires nearly four additional hours to dispatch under these assumptions. Actual completion recovery depends on workflow duration, inference capacity, and downstream service availability.</p><p>Recovery scheduling should distinguish time-sensitive operations from expired requests. An agent resuming a financial operation several hours after its original authorization may need to validate current business conditions before proceeding.</p><h3>What I Would Expect From a Staff Engineer Designing This Platform</h3><p>The most revealing architecture review would begin with an agent that has exhausted its budget while an external financial operation remains unresolved. Its worker has crashed, its approval has expired, and a newer model version has been deployed since the workflow began.</p><p>The engineer must explain which execution state remains authoritative, whether the external operation can safely be retried, and how the platform prevents recovery from violating its financial or security constraints.</p><p>An enterprise agent platform needs enough deterministic infrastructure to contain the uncertainty introduced by probabilistic reasoning. That requirement influences nearly every architectural boundary, from credential issuance to workflow persistence and financial reconciliation.</p><h3>Advanced AI System Design Interview Preparation</h3><p>I developed <strong>Senior &amp; Staff AI System Design Interview OS</strong> for experienced engineers preparing for architecture interviews involving AI agents, RAG systems, LLM infrastructure, and distributed AI applications.</p><p>The material covers seven AI system architectures and the technical decisions involved in designing production-grade AI infrastructure.</p><p><a href="https://devrimozcay.gumroad.com/l/orgnsy">Senior &amp; Staff AI System Design Interview OS: RAG, Agents, LLMs &amp; 7 Architectures</a></p><p>I’m also conducting independent research into the challenges experienced engineers encounter during Senior and Staff system design interviews.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdocs.google.com%2Fforms%2Fd%2Fe%2F1FAIpQLScLD53xFU73sirxXmKFfL9-M7FGL_5mM6a8_B0qQdaYce2atA%2Fviewform%3Fembedded%3Dtrue&amp;display_name=Google+Docs&amp;url=https%3A%2F%2Fdocs.google.com%2Fforms%2Fd%2Fe%2F1FAIpQLScLD53xFU73sirxXmKFfL9-M7FGL_5mM6a8_B0qQdaYce2atA%2Fviewform%3Fusp%3Dheader&amp;image=https%3A%2F%2Flh6.googleusercontent.com%2F1c67GfSCyEA_IUtodYCJgYLDGOqIuo62OzVnGK9torhRzSxYtd_uTxCv79ExsxuD-Lv_OJR1vfzAR6s%3Dw1200-h630-p&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=google" width="760" height="675" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ff75ab6d435aa7f849ec31a69970e49/href">https://medium.com/media/0ff75ab6d435aa7f849ec31a69970e49/href</a></iframe><p>Further investigations into enterprise AI infrastructure and distributed systems are available on my Substack.</p><p><a href="https://substack.com/@devrimozcay1">Devrim Ozcay | ProdRescue | Substack</a></p><h3>Frequently Asked Questions</h3><h3>How do you design a scalable AI agent platform?</h3><p>Use durable workflow orchestration, independently enforced authorization, resource-aware scheduling, execution journals, and explicit inference budgets. External operations require recovery procedures appropriate to their individual guarantees.</p><h3>How do AI agents prevent duplicate tool execution?</h3><p>Stable operation identifiers, durable execution records, external idempotency mechanisms, and reconciliation procedures help prevent repeated side effects.</p><h3>How do enterprises control AI agent costs?</h3><p>Establish atomic budget reservations, token limits, bounded execution loops, model routing policies, and cost measurements per successful business task.</p><h3>What are the hardest AI agent system design problems?</h3><p>Durable execution, ambiguous external outcomes, concurrent budget enforcement, persistent memory security, authorization boundaries, and behavioral compatibility during model upgrades require substantial architectural attention.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0ba82d9c170" width="1" height="1" alt=""><hr><p><a href="https://medium.com/engineering-playbook/how-to-design-an-ai-agent-platform-that-handles-100-million-tasks-without-losing-control-c0ba82d9c170">How to Design an AI Agent Platform That Handles 100 Million Tasks Without Losing Control</a> was originally published in <a href="https://medium.com/engineering-playbook">ProdRescue Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing a Multi-Tenant SaaS Platform for 10,000 Enterprise Customers]]></title>
            <link>https://medium.com/engineering-playbook/designing-a-multi-tenant-saas-platform-for-10-000-enterprise-customers-04bca5d6a404?source=rss-6bdd1f176ebd------2</link>
            <guid isPermaLink="false">https://medium.com/p/04bca5d6a404</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[saas]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Staff Engineer Mindset | ProdRescue By Devrim]]></dc:creator>
            <pubDate>Thu, 26 Nov 2026 15:23:15 GMT</pubDate>
            <atom:updated>2026-11-26T15:23:50.003Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*MMwxfI13pY5M-CeQjBb8-Q.png" /></figure><h4><em>Advanced system design covering tenant isolation, database partitioning, workload fairness, regional deployment, and enterprise infrastructure economics.</em></h4><p>The architectural requirements of an enterprise SaaS platform change considerably when customers begin negotiating their own security policies, data residency requirements, and availability guarantees. A database shared by thousands of small businesses may become commercially unacceptable to a bank that requires independently recoverable financial records. Meanwhile, a dedicated infrastructure deployment for every customer could make the entire business economically unsustainable. Consider a hypothetical B2B SaaS platform serving 10,000 organizations, two million active users, and 50 TB of operational data. Its largest customers generate several thousand times more traffic than its smallest customers, and some have contractual requirements governing where their information can be stored.</p><h3>Tenant Placement Becomes a Control Plane Responsibility</h3><p>A conventional multi-tenant application typically resolves the tenant identifier and executes requests against shared infrastructure. This approach becomes restrictive when customers require different deployment regions, database configurations, encryption policies, or isolation guarantees.</p><p>I would introduce a tenant placement control plane that maintains authoritative information about where each organization’s workload belongs.</p><pre>Tenant Registry<br>    |<br>    +-- Tenant ID<br>    +-- Deployment Region<br>    +-- Database Cluster<br>    +-- Isolation Tier<br>    +-- Routing Version<br>    +-- Encryption Policy</pre><p>Application gateways use this information to route requests to the appropriate infrastructure cell. Each cell contains the application and storage resources required to serve an assigned group of tenants. A placement change must be treated as a controlled infrastructure operation. If two gateways disagree about the current location of a tenant’s writable database, an ordinary migration can become a distributed data consistency incident.</p><p>Routing versions and write fencing become particularly important once customers can move between infrastructure cells.</p><h3>A Shared Database Can Make One Customer Responsible for Everyone’s Latency</h3><p>Suppose the platform processes 40,000 database operations per second during peak traffic. Its largest enterprise customer generates 12% of that workload.</p><pre>40,000 x 0.12<br>= 4,800 operations/sec</pre><p>That customer introduces a new reporting integration, increasing its database workload fivefold.</p><pre>4,800 x 5<br>= 24,000 operations/sec</pre><p>The platform’s total database workload increases from 40,000 to 59,200 operations per second, representing a 48% increase caused by one organization.</p><p>An application-level request limiter may provide insufficient protection because different requests consume dramatically different database resources. A single analytical query can require more CPU and disk bandwidth than thousands of indexed record lookups. Tenant-aware concurrency limits, workload classification, dedicated analytical infrastructure, and database resource isolation provide stronger protection against this type of interference.</p><p>The largest customers may eventually require dedicated database clusters, even when their application infrastructure remains shared.</p><h3>Database Isolation Should Follow Commercial Requirements</h3><p>A SaaS company can support several isolation models within the same product. Smaller organizations might share database tables, while regulated enterprises receive independently managed databases or dedicated infrastructure cells.</p><p>For shared tables, PostgreSQL row-level security can provide an additional tenant isolation boundary.</p><pre>ALTER TABLE invoices<br>ENABLE ROW LEVEL SECURITY;</pre><pre>ALTER TABLE invoices<br>FORCE ROW LEVEL SECURITY;</pre><pre>CREATE POLICY tenant_isolation<br>ON invoices<br>USING (<br>    tenant_id =<br>    current_setting(<br>        &#39;app.tenant_id&#39;, true<br>    )::uuid<br>);</pre><p>The application establishes the tenant context inside the transaction.</p><pre>BEGIN;</pre><pre>SELECT set_config(<br>    &#39;app.tenant_id&#39;,<br>    :tenant_id,<br>    true<br>);</pre><p>The transaction-local setting reduces the risk of tenant context leaking between requests through reused database connections. This example assumes the application obtains the tenant identifier from a trusted authorization process. The database role must also lack privileges that bypass row-level security. RLS provides limited protection against an application capable of arbitrarily changing its own tenant context.</p><h3>Tenant-Aware Scheduling Requires More Than Rate Limiting</h3><p>Consider an asynchronous document processing service receiving work from thousands of organizations. One enterprise submits an import containing two million documents, while smaller customers continue submitting interactive processing requests.</p><p>A conventional FIFO queue could place those smaller requests behind a substantial backlog.</p><p>At a processing capacity of 5,000 documents per second:</p><pre>2,000,000 / 5,000<br>= 400 seconds</pre><p>Under strict FIFO processing, newly submitted work could wait more than six minutes before execution begins.</p><p>A tenant-aware scheduler can distribute processing capacity using weighted fair scheduling, per-tenant concurrency budgets, and workload priorities. The scheduling cost should reflect the resources consumed by each job, particularly when document sizes and processing complexity vary significantly.</p><p>Enterprise service agreements can then influence scheduling weights without allowing a single customer to monopolize the infrastructure.</p><h3>Moving a Tenant Between Database Clusters</h3><p>Suppose an enterprise customer accumulates 2 TB of operational data and requests migration from shared infrastructure to a dedicated database.</p><p>At an effective transfer rate of 200 MB per second:</p><pre>2,000,000 MB / 200 MB/sec<br>= 10,000 seconds<br>= approximately 2.78 hours</pre><p>Keeping the customer’s application unavailable throughout the transfer may violate its contractual availability requirements.</p><p>A more practical migration begins with a consistent snapshot, followed by change data capture from the source database. Once the destination approaches the source’s replication position, the migration controller temporarily fences source writes, applies the remaining changes, validates the destination, and updates the authoritative routing configuration. The destination must remain protected from independent writes until ownership has been transferred.</p><p>Rollback becomes considerably more complicated after the destination begins accepting new transactions. Returning to the source requires a mechanism that preserves those subsequent changes.</p><h3>Enterprise Data Residency Extends Beyond the Primary Database</h3><p>A European customer requires its operational data to remain within approved European jurisdictions. The application stores its primary database in Frankfurt, but its observability pipeline exports request payloads to a centralized logging service in another region.</p><p>The architecture may already violate the customer’s contractual requirements. Data residency analysis must include secondary storage, backups, search indexes, message brokers, analytics pipelines, and support tooling. Even an AI feature that sends customer documents to an external inference provider can introduce a previously undocumented data transfer.</p><p>I would associate residency policies with tenant placement metadata and require infrastructure provisioning workflows to respect those policies. The organization also needs an accurate inventory of the systems receiving customer information, including derived data and operational telemetry.</p><p>The exact requirements depend on the applicable jurisdiction, contractual terms, and processing arrangements.</p><h3>Recovering One Customer Without Restoring Everyone Else</h3><p>An enterprise administrator accidentally deletes a substantial portion of the organization’s operational records. The customer requests recovery to the state that existed fifteen minutes earlier. The affected tenant shares a 20 TB database with hundreds of other organizations. Restoring the entire database to an earlier point would also reverse legitimate transactions belonging to unaffected customers.</p><p>A tenant-specific recovery procedure could restore a historical database copy into isolated infrastructure, extract the affected organization’s records, and reconcile them against its current state. External side effects, shared references, and transactions completed after the recovery point complicate this process.</p><p>For customers requiring aggressive tenant-level recovery objectives, dedicated storage or independently recoverable tenant partitions may justify their additional infrastructure cost.</p><p>This requirement should influence the original database architecture rather than emerge during contract negotiations.</p><h3>The Economics of Dedicated Infrastructure</h3><p>Suppose the SaaS platform provides dedicated infrastructure to 500 enterprise customers. Each deployment costs an average of $1,800 monthly to operate.</p><pre>500 x $1,800 x 12<br>= $10.8M annual expenditure</pre><p>An alternative cell-based architecture serves ten compatible enterprise customers per cell, with an average operating cost of $8,000 monthly per cell.</p><pre>50 x $8,000 x 12<br>= $4.8M annual expenditure</pre><p>The theoretical annual infrastructure difference is $6 million before migration costs, additional engineering expenditure, and customer-specific requirements.</p><p>Shared cells introduce a larger failure boundary than dedicated deployments. The organization must establish whether that boundary is acceptable under its customers’ contractual commitments. The infrastructure placement strategy directly influences gross margins, enterprise pricing, and the commercial viability of offering stronger isolation guarantees.</p><h3>The Architecture Review That Matters</h3><p>Imagine the company’s largest customer requests dedicated infrastructure, regional data residency, a fifteen-minute recovery objective, and guaranteed processing capacity during peak demand. The sales team has already incorporated these requirements into a proposed enterprise contract.</p><p>An experienced architect should be able to determine whether the existing platform can satisfy those commitments without introducing unacceptable risks to other customers. That assessment requires an understanding of the tenant placement system, storage boundaries, scheduling behavior, recovery procedures, and incremental operating costs. The commercial agreement becomes considerably easier to evaluate when the engineering organization can quantify what each guarantee requires.</p><h3>Advanced System Design and Production Engineering</h3><p>I developed <strong>Senior Backend Production Engineering OS</strong> for experienced engineers responsible for backend architecture, distributed systems, production reliability, and infrastructure decisions.</p><p>The collection brings together production engineering systems, technical tools, and operational playbooks for engineers working beyond conventional system design exercises.</p><p><a href="https://devrimozcay.gumroad.com/l/epxiu">Senior Backend Production Engineering OS: 31 Systems, Tools &amp; Production Playbooks</a></p><p>I’m also conducting independent research into infrastructure risks and engineering challenges affecting growing technology companies. Founders, CTOs, and engineering leaders can participate here:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdocs.google.com%2Fforms%2Fd%2Fe%2F1FAIpQLSc2xr8huMn7lTtbXdorNzwvCnXWNqkIP1AveHMVpK6hYb4sEg%2Fviewform%3Fembedded%3Dtrue&amp;display_name=Google+Docs&amp;url=https%3A%2F%2Fdocs.google.com%2Fforms%2Fd%2Fe%2F1FAIpQLSc2xr8huMn7lTtbXdorNzwvCnXWNqkIP1AveHMVpK6hYb4sEg%2Fviewform%3Fusp%3Dheader&amp;image=https%3A%2F%2Flh4.googleusercontent.com%2FkDdiXwt371UaIvVDaQ7V5OwBZP1mXzOr5rxdilkcOngcAEHU-9rnO40XhvUod9uElJKsRvTdqAAoG_I%3Dw1200-h630-p&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=google" width="760" height="675" frameborder="0" scrolling="no"><a href="https://medium.com/media/105f166ffb05027b8b56151e6fdf9d74/href">https://medium.com/media/105f166ffb05027b8b56151e6fdf9d74/href</a></iframe><p>Further enterprise architecture investigations are available on my Substack.</p><p><a href="https://substack.com/@devrimozcay1">Devrim Ozcay | ProdRescue | Substack</a></p><h3>Frequently Asked Questions</h3><h3>How do you design a multi-tenant SaaS architecture at enterprise scale?</h3><p>Use authoritative tenant placement, explicit isolation boundaries, tenant-aware workload scheduling, controlled migrations, and recovery procedures aligned with customer requirements.</p><h3>Should enterprise SaaS customers have separate databases?</h3><p>Dedicated databases can improve isolation and independent recovery, but introduce additional operating costs. The appropriate model depends on contractual guarantees, workload characteristics, and security requirements.</p><h3>How do you prevent the noisy neighbor problem in multi-tenant systems?</h3><p>Combine resource-aware scheduling, per-tenant concurrency limits, workload isolation, database capacity controls, and dedicated infrastructure for exceptionally demanding customers.</p><h3>What is cell-based SaaS architecture?</h3><p>Cell-based architecture divides customers among independently operated infrastructure units, limiting the impact of failures and allowing capacity to grow through additional cells.</p><h3>How do you migrate tenants without significant downtime?</h3><p>Use consistent snapshots, change data capture, controlled write fencing, destination validation, and authoritative routing updates. Establish a recovery strategy before transferring write ownership.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=04bca5d6a404" width="1" height="1" alt=""><hr><p><a href="https://medium.com/engineering-playbook/designing-a-multi-tenant-saas-platform-for-10-000-enterprise-customers-04bca5d6a404">Designing a Multi-Tenant SaaS Platform for 10,000 Enterprise Customers</a> was originally published in <a href="https://medium.com/engineering-playbook">ProdRescue Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>