<?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 Inderpreet Singh Bindra on Medium]]></title>
        <description><![CDATA[Stories by Inderpreet Singh Bindra on Medium]]></description>
        <link>https://medium.com/@inderbindra?source=rss-6bd396d9b5c2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*yfMiA4-pGe8XCfL1Xe0Veg.jpeg</url>
            <title>Stories by Inderpreet Singh Bindra on Medium</title>
            <link>https://medium.com/@inderbindra?source=rss-6bd396d9b5c2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 19:59:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@inderbindra/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[I Don’t Prompt Claude Anymore. I Write Loops]]></title>
            <link>https://medium.com/@inderbindra/i-dont-prompt-claude-anymore-i-write-loops-bca08cd5a032?source=rss-6bd396d9b5c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/bca08cd5a032</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Inderpreet Singh Bindra]]></dc:creator>
            <pubDate>Wed, 02 Dec 2026 14:06:01 GMT</pubDate>
            <atom:updated>2026-12-02T14:06:01.783Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>The work didn’t disappear. It moved from writing prompts to engineering the systems that run, verify, and own the work.</strong></p><p>A good prompt feels like progress. You write it carefully, the agent writes good code, and for one afternoon the future arrives on schedule.</p><p>Then you run the same prompt on Monday. The model picks a different library. It renames a function you told it not to touch. It finishes with confidence and leaves the tests red.</p><p>Nothing in the prompt was wrong. The prompt was doing a job it was never built to do. It was being asked to hold the goal, the rules, the memory, the checking, and the stopping condition, all in one piece of text, in one conversation, with no one watching the loop.</p><p>That is the shift behind the move from prompt engineering to software factories. We did not replace prompting with something smarter. We moved the work up one level at a time, until prompting became one component of a larger engineering system.</p><p>This is not a formal taxonomy, and the boundaries overlap. A harness can contain a loop; a loop can use the same context and tools as an interactive agent. I use these stages to describe a change in the unit of engineering: from the instruction, to the environment, to the execution cycle, to the system that decides what work comes next.</p><figure><img alt="Conceptual illustration showing the evolution from prompt engineering to agent loops and an automated software delivery pipeline." src="https://cdn-images-1.medium.com/max/1024/1*kRSl_xT5QqiWlJ2-4NOGQQ.png" /><figcaption>The work didn’t disappear. It moved from writing prompts to engineering the systems that run, verify, and own the work.</figcaption></figure><h3>Prompt engineering: One Good Sentence, One Fragile Run</h3><p>Prompt engineering was the first skill because it was the only lever we had. You learned to be specific, to show examples, to say what good looks like, and to tell the model what not to do.</p><p>It works within a single interaction. It fails as a system for three plain reasons.</p><p>First, the model is not deterministic. The same words can produce a different plan in the next execution, and a small change in wording can change the result more than a small change in the code would.</p><p>Second, a prompt is not a durable project memory. A conversation can retain context, but that context is not a reliable substitute for versioned project knowledge and explicit state across repeated executions. Start a new execution without those artifacts, and the agent may have to reconstruct decisions that were already made.</p><p>Third, the prompt does not enforce its own acceptance criteria. It can ask the model to check its work, but the instruction alone does not guarantee that the check runs, that the result is correct, or that the execution stops when the criteria are met.</p><p>Prompt engineering is still useful. It is just not a production practice by itself. It is one interaction, and production work is a sequence of interactions, checks, and decisions.</p><h3>Context engineering: Stop Explaining The Project Every Time</h3><p>The next level was not a better sentence. It was better material around the sentence.</p><p>Context engineering means the agent starts with the things a good engineer would already know: the repo layout, the coding standards, the build and test commands, the architecture notes, the issue tracker, the database schema. In my team, we encode much of that in custom skills, short files that carry our code review and coding standards, so the agent reads the same rules in each execution instead of guessing them.</p><p>This helps a lot, but it creates a new failure. The agent has context, yet it still lacks an explicit contract for the task it is executing. It knows how we write code; it does not know the completion criteria, what evidence is required, or who makes the final decision.</p><blockquote><strong>Context gives the agent the information it needs to work. The task contract defines what it must do, what evidence demonstrates completion, and when it must stop or escalate.</strong></blockquote><h3>The Agent Harness: Context, Tools, Permissions, And Feedback</h3><p>Anthropic’s December 2024 article, <em>Building Effective Agents</em>, provides a useful architectural distinction: workflows follow predefined code paths, while agents dynamically direct their own process and tool use. An agent can be understood as a model operating with tools and feedback from its environment.</p><p>The harness governs how an agent operates during an execution. It includes the instructions and context assembled for the model, available tools, tool execution, permissions, hooks, feedback, and the environment in which the agent works.</p><p>A connector built on MCP, for example, can let an agent read an issue tracker, query a database, call a staging API, or send a message instead of asking you to paste the world into a prompt.</p><p>Anthropic’s advice still holds: start with the simplest solution that works, and add complexity only when a measurement says you must. It is tempting to skip that advice. Add a framework, then another agent, then a second framework to watch the first one.</p><p>A well-designed harness makes the operating conditions of an execution explicit and repeatable. It does not necessarily decide whether another execution should start, what work should be selected next, or when the larger process should stop.</p><p>The distinction is useful:</p><blockquote><strong>The harness governs how the agent operates during an execution; the loop governs whether another turn or execution cycle happens, and under what conditions.</strong></blockquote><figure><img alt="From Prompt Engineering To Software Factory: The progression from instructing an LLM to equipping an agent, controlling its execution loop, and coordinating software delivery with human accountability." src="https://cdn-images-1.medium.com/max/1024/1*8kMcXcs3BWPixCz5BvM_vQ.png" /><figcaption><strong>From Prompt Engineering To Software Factory: </strong>The progression from instructing an LLM to equipping an agent, controlling its execution loop, and coordinating software delivery with human accountability.</figcaption></figure><h3>Loop Engineering: Triggers, State, Verification, And Stopping Conditions</h3><p>This is where the job changes.</p><p>In June 2026, Boris Cherny, who leads Claude Code at Anthropic, said he does not prompt Claude anymore; he has loops running that prompt Claude and figure out what to do. Peter Steinberger described a similar shift that same week: instead of prompting coding agents directly, design loops that prompt the agents.</p><p>Addy Osmani helped popularize and articulate the concept that month in his article, <strong><em>Loop Engineering</em></strong>. His framing is that you replace yourself as the person prompting the agent by designing the system that does it instead.</p><p>Osmani describes <strong>five </strong>building blocks for loop engineering, along with a <strong>sixth </strong>element that makes the system persistent: <strong>memory</strong>.</p><ol><li><strong>Automations are the heartbeat</strong>. A trigger on a schedule, or on a repo event, finds work and starts an execution without you asking. Without a trigger, you have one good execution, not an automated loop.</li><li><strong>Worktrees are isolation.</strong> Two agents writing the same checkout will collide the way two engineers editing the same lines will collide. A git worktree gives each agent its own working directory on its own branch, sharing the same repo history.</li><li><strong>Skills are intent, written down.</strong> They are the project knowledge the agent would otherwise guess: conventions, build steps, and the rule that exists because of one incident nobody wants to repeat.</li><li><strong>Plugins and connectors are reach.</strong> They plug the loop into the tools you already use, so it can read real state instead of asking you for a summary.</li><li><strong>Sub-agents separate the maker from the checker.</strong> One agent produces the work while another independently reviews it. This creates an opportunity for verification, but using a separate agent does not automatically make the review independent. If the reviewer relies only on the implementer’s claims, it may reproduce the same mistakes. Verification should rely on evidence wherever possible: deterministic tests, builds, linting, static analysis, and human review. A separate review agent can challenge the implementation, but executable checks provide stronger evidence of correctness.</li><li><strong>Memory provides continuity.</strong> A loop needs durable state outside the conversation. That state might live in a versioned file, a database, an issue tracker, or a workflow store. The important property is that the next execution can recover what happened, what remains, and which evidence is still valid.</li></ol><p>Claude Code’s stop-condition evaluation is not equivalent to an independent verification system. A model evaluating whether a task is complete does not establish that the implementation is correct. That makes it a separate evaluator, not an objective verifier. A model can judge that tests passed based on the conversation; the test runner is the evidence that the tests passed.</p><p>Geoffrey Huntley’s Ralph technique, described in mid-2025, was already a simple loop feeding a prompt file back into the agent, with the filesystem carrying state between iterations. The idea is older than the name. But a loop without a reliable stopping mechanism can run indefinitely, consume resources, or damage working code.</p><blockquote><strong>That is the point. A loop without a stop condition is not automation. It is a runaway process with a nice name.</strong></blockquote><p>Consider a loop that handles a newly opened bug:</p><ol><li>A repository event identifies an issue that meets the loop’s criteria.</li><li>The orchestrator creates an isolated worktree and records the issue as the current task.</li><li>The agent reads the issue, project instructions, and relevant code, then proposes and implements a change.</li><li>A verifier runs the required tests and checks the diff against the acceptance criteria.</li><li>If the checks fail, the loop records the failure and allows a bounded retry.</li><li>If the checks pass, the loop creates a pull request and stops for human review.</li><li>If the retry or budget limit is reached, the loop records the evidence and escalates instead of continuing.</li></ol><blockquote><strong>The loop is not simply the agent repeating itself. It is the control flow that decides what happens after each result.</strong></blockquote><h3>The Software Factory: Connected Loops, With Humans At The Gates</h3><p>A software factory is what happens when individual agent loops are connected into a controlled software delivery pipeline.</p><p>Instead of handling one task at a time, the system moves work through a sequence of stages: issue triage, planning, implementation, testing, code review, and deployment. Each stage produces an output that the next stage can use.</p><p>The architecture behind it rests on three principles.</p><ol><li><strong>The orchestrator controls the workflow.</strong> The workflow definition lives in code or configuration, not in the model’s conversation. A deterministic orchestrator manages the state machine: which stage runs next, what conditions must be met, how failures are handled, and when execution must stop. Agents perform specific tasks within that workflow, but they do not control the overall process.</li><li><strong>Artifacts connect the stages.</strong> Each stage reads defined inputs and produces explicit outputs. A planning stage might produce an implementation plan and acceptance criteria. An implementation stage produces code and a test report. A review stage produces findings and a recommendation. These artifacts should be versioned and traceable, so another agent or a human can inspect the work, rerun a stage, or replace an agent without losing the history.</li><li><strong>Deployment remains controlled and reversible.</strong> Passing tests does not automatically mean a change is safe for production. Release should happen progressively, using feature flags or a canary deployment, with automated checks monitoring the service. If those checks detect a problem, the system should be able to roll back. Human approval should remain at the decisions where the risk justifies it, especially when a change affects production or users.</li></ol><p>Notice what changed. The goal is no longer to make one agent better at writing code. It is to design a system that coordinates multiple executions, preserves their outputs, checks their results, and controls how changes reach users.</p><p>The engineering responsibility moves up a level: defining the workflow, choosing the verification mechanisms, setting execution limits, and deciding where human judgment is required.</p><h3><strong>Failure Modes: </strong>What Agent Loop Break</h3><p>Loops fail in predictable ways. Most failures come from missing controls, weak verification, or poorly managed state.</p><ol><li><strong>A loop without a stopping condition keeps running.</strong> It can consume tokens, repeat failed approaches, or overwrite working code without making progress. Define the stopping conditions before execution begins: a maximum number of iterations, a token or cost budget, a time limit, and a machine-checkable definition of done.</li><li><strong>A loop with weak verification can produce incorrect results with confidence.</strong> If the agent that writes the code is also the only one deciding whether it works, you have no meaningful independent check. Use executable evidence wherever possible: tests, builds, linting, static analysis, and integration checks. A separate review agent can identify problems, but its approval is not proof that the implementation is correct.</li><li><strong>A loop without durable state loses continuity.</strong> Conversation history is not a reliable system of record. The next execution needs to recover what was attempted, what succeeded, what failed, and what remains. Store that information in a durable location, such as a versioned file, database, issue tracker, or workflow store. Without it, the loop may repeat work or make decisions based on outdated information.</li><li><strong>A loop without an escalation path keeps repeating the same mistakes.</strong> Some failures need human judgment: unclear requirements, repeated test failures, unexpected changes, security concerns, or exhausted execution budgets. Define when the loop should retry, when it should stop, and when it must hand the work to a human with its logs and evidence attached.</li></ol><p>There is also a broader question: how much evidence do we have that software factories deliver reliable productivity gains at organizational scale?</p><p>There are working examples of teams using coding agents and automated workflows. But examples of implementation are not the same as independently measured evidence of sustained improvements in delivery speed, quality, and cost. Much of the available evidence comes from vendor demonstrations, internal case studies, or customer reports.</p><p>That does not invalidate the approach. It means we should treat the software factory as an engineering hypothesis to test, not a proven operating model to roll out across an organization.</p><p>Start with a narrow workflow. Measure its results. Understand its failure modes. Expand only when the evidence justifies it.</p><h3><strong>The Loop Spec: A Practical Starting Point</strong></h3><p>If you build one thing, build this file. Call it a loop spec, and do not let a loop operate without one.</p><pre>TRIGGER: What starts this execution, and how often<br>GOAL: One sentence, in plain words<br>DONE WHEN: A check a machine can run, not a feeling<br>MAX TURNS: A number<br>TOKEN BUDGET: A number, with what happens when it is hit<br>RETRY POLICY: Which failures are retryable, and how many attempts<br>PERMISSIONS: What the loop is allowed to read, modify, and execute<br>VERIFIER: Tests, lint, or a separate checker<br>EVIDENCE: Where the results and artifacts are recorded<br>ESCALATE TO HUMAN WHEN: The failures that stop the loop<br>STATE: Where progress and next steps are stored<br>OWNER: The human who commits the result</pre><p>That last line is the one I care about most. On my team, the rule is simple: whoever commits AI-assisted code owns it personally. Committing means you did it, not the AI. Tests and reviews stay owned by developers and senior engineers, even when an agent wrote the first draft. A loop can write, test, and check. It cannot own.</p><p>Start with one small loop, not a factory. Triage new issues once a morning. Run the failing test suite on a schedule and file the failures with the log attached. Let the loop find the work, do the narrow job, check itself against a real verifier, and stop. Read what it did. Fix the spec where it guessed. Then, and only then, add the next loop.</p><p><strong>Prompt engineering asks:</strong> how do I say this well? <br><strong>Loop engineering asks a better question:</strong> how do I build a system that selects the task, instructs the agent, checks the result, remembers what happened, and stops before it does damage?</p><blockquote><strong>A software factory is that system operating across a team’s delivery pipeline. The work is in the loop around the prompt, and in the human who owns what comes out.</strong></blockquote><h3>Related Articles</h3><ol><li><a href="https://medium.com/@inderbindra/ai-systems-are-nothing-but-distributed-systems-43efbf1026d7">AI Systems Are Just Distributed Systems (And We Are Repeating Old Mistakes)</a></li><li><a href="https://medium.com/@inderbindra/agents-are-stateful-services-not-stateless-functions-59738c68737f">AI Agents Are Stateful Services, Not Stateless Functions</a></li><li><a href="https://medium.com/@inderbindra/agent-memory-is-an-ownership-consistency-problem-not-an-ai-problem-1c9fc8521c79">Agent Memory Is an Ownership &amp; Consistency Problem, Not an AI Problem</a></li></ol><h3>Before you go</h3><ul><li>Please take a moment to like the post, share your thoughts, and follow for more articles like this.</li><li>You can also follow me on <a href="https://www.linkedin.com/in/inderbindra">LinkedIn</a>.</li></ul><h3>References</h3><ul><li><a href="https://www.anthropic.com/engineering/building-effective-agents">Anthropic, Building Effective Agents, 19 December 2024</a>: The Anthropic article is a primary source for agent and workflow concepts.</li><li><a href="https://addyosmani.com/blog/loop-engineering/">Addy Osmani, Loop Engineering, 7 June 2026</a>: Osmani’s article is a practitioner framing of loop engineering.</li><li><a href="https://arxiv.org/pdf/2608.21884v2">Loop Engineering: Building Blocks, Adoption, and Impact, arXiv, 2026</a>: The arXiv paper is research evidence about adoption and its limitations.</li><li><a href="https://grimoire.artificerdigital.com/scouts/2026-07-10-loop-specification-software-factory/">The Loop Specification, and the Unproven Software Factory, 10 July 2026</a></li><li><a href="https://b.lemino.ai/prompt-to-production-agentic-software-factory-on-claude/">Prompt-to-Production: An Agentic Software Factory on Claude</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bca08cd5a032" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Payment Went Through. The System Still Got It Wrong.]]></title>
            <link>https://medium.com/@inderbindra/a-payment-went-through-the-system-still-got-it-wrong-8b490b224ced?source=rss-6bd396d9b5c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b490b224ced</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Inderpreet Singh Bindra]]></dc:creator>
            <pubDate>Tue, 17 Nov 2026 13:36:01 GMT</pubDate>
            <atom:updated>2026-11-17T13:36:01.620Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>What Uber’s money-movement architecture teaches us about building reliable systems, without copying Uber’s infrastructure.</strong></p><h3>About This Series</h3><p>Part 6 of a six-part series on how Uber engineered money movement for correctness at scale. This final article brings the earlier ideas together and turns them into questions you can use when designing other systems.</p><ul><li><a href="https://blog.stackademic.com/how-uber-rebuilt-its-money-movement-architecture-without-losing-financial-correctness-939a9b615c48">Part 1: The money-movement architecture</a></li><li><a href="https://medium.com/@inderbindra/why-ubers-financial-database-does-not-trust-update-512f5492aa11">Part 2: LedgerStore and immutable financial history</a></li><li><a href="https://medium.com/@inderbindra/how-uber-keeps-2-trillion-indexes-consistent-without-slowing-every-write-737025e5ee74">Part 3: Consistency across trillions of indexes</a></li><li><a href="https://medium.com/@inderbindra/how-uber-migrated-250-billion-financial-records-without-breaking-consistency-6917c7e7a01c">Part 4: Migrating 250 billion financial records</a></li><li><a href="https://medium.com/@inderbindra/why-ubers-docstore-guarantees-strict-serializability-only-within-a-partition-015b420bcb09">Part 5: Docstore’s partition-level consistency boundary</a></li></ul><p>The question behind this final article is not how to build another Uber. It is how to recognize the problems Uber had to solve, decide which ones apply to your system, and choose the simplest design that handles them.</p><p>The subscription example below is hypothetical. It is not an Uber implementation or a report of a production incident. Uber-specific details are identified as such and are drawn from the engineering articles cited at the end.</p><figure><img alt="An illustration representing reliable financial system design, showing interconnected services processing payments, maintaining consistent records, and recovering from failures." src="https://cdn-images-1.medium.com/max/1024/1*6lFg9EO7yQoKiC2JfZBwGQ.png" /><figcaption><strong>A Payment Went Through. The System Still Got It Wrong.</strong></figcaption></figure><h3>The Payment Succeeded. Why Doesn’t the Customer Have Access?</h3><p>Imagine a subscription service renewing a customer’s monthly plan.</p><p>The billing service sends a charge request to a payment provider. The provider accepts the payment, but the response never reaches the billing service. From the service’s point of view, the result is unknown: the payment may have gone through, or it may not have.</p><p>The billing service retries. Meanwhile, another part of the application is waiting for confirmation before extending the customer’s access. The account page still shows the previous billing period because its data has not updated yet.</p><p>This can produce several different problems:</p><ul><li>The provider captures the payment twice because the retry is treated as a new charge.</li><li>The customer is charged, but access is not extended.</li><li>Access is extended even though the payment failed.</li><li>Support sees conflicting information in different parts of the application and cannot tell what happened.</li></ul><p>None of these requires a major outage. A timeout, a delayed message, or a stale screen is enough.</p><p>The real design question is:</p><blockquote><strong>What must remain true when requests are repeated, services stop halfway through a task, data takes time to update, or the system moves to a new database?</strong></blockquote><p>That question applies well beyond payments. An online store must not sell the same last item twice. A logistics platform must not assign the same delivery to two drivers. A SaaS application must not grant or remove access based on an outdated account state.</p><h3>What Uber’s Architecture Teaches Us</h3><p>Across the five earlier articles, Uber addressed different parts of one larger problem: how to create financial records, preserve them, find them reliably, and change the storage underneath them without losing control.</p><figure><img alt="This table list the different Uber finanical system components along with its responsibilities and what are useful lesson we can learn from it." src="https://cdn-images-1.medium.com/max/711/1*7dV8Pfq8KiG_W4paLc_BVQ.png" /></figure><p>These are not five technologies that every company should adopt. They are five examples of a more general discipline: understand what can go wrong, decide what must never go wrong, and make sure each part of the design protects the right thing.</p><p>The rest of this article turns that discipline into eight practical questions.</p><h3>Eight Questions to Ask Before Building a Reliable System</h3><h3><strong>1. What must never go wrong?</strong></h3><p>Start with the business rule, not the database.</p><p>For the subscription service, the rule might be:</p><blockquote><strong>For each subscription and billing period, there can be no more than one successful payment capture. Access must be supported by a successful payment or an explicit business policy, such as a trial or grace period. Refunds and other corrections must be recorded.</strong></blockquote><p>This is more useful than saying “prevent duplicate charges.” It defines what counts as a duplicate, recognizes legitimate exceptions, and makes corrections part of the design.</p><p>Other systems need different rules:</p><ul><li><strong>E-commerce:</strong> An order must not reserve more units than are available.</li><li><strong>Logistics:</strong> A delivery must not have two active driver assignments.</li><li><strong>SaaS:</strong> A user must receive only the access allowed by the account’s current plan and policy.</li></ul><p>Write the rule so that the team can test it. Then ask whether it still holds if a request is repeated, a service crashes, or one part of the data is out of date.</p><h3>2. What happens when the same request arrives twice?</h3><p>Networks fail in inconvenient ways. A service may complete a task but fail to send its response. The caller cannot know whether the task happened, so it tries again. Message systems can also deliver the same message more than once.</p><p>The system must distinguish a repeated request from a new business action. This is commonly called <strong>idempotency</strong>: processing the same operation again does not create a second business effect.</p><p>For a subscription renewal, use one stable identity for the renewal obligation, such as the subscription and billing period. Separately, give each deliberate payment attempt its own identity.</p><p>That distinction matters when working with an external payment provider:</p><ul><li>A network retry of the same payment attempt must reuse the same provider idempotency key.</li><li>If the response is missing, check the provider’s status or retry using that same key.</li><li>Do not create a new payment attempt while the previous attempt’s result is still unknown.</li><li>Create another attempt only when the previous one has a known outcome that permits it.</li></ul><p>A database record saying “we already processed this renewal” does not, by itself, stop an external provider from charging the card twice. The provider must support a way to recognize the repeated attempt, or your integration must have a reliable way to check and resolve uncertain outcomes.</p><p>The same principle applies to order creation, inventory reservation, shipment assignment, and account provisioning. Give the business action a stable identity, and define what a repeated request means.</p><h3>3. What if the system stops halfway through?</h3><p>A common mistake is to call another service first and record the work afterward. If the process crashes between those steps, the system may have no durable record of what it intended to do.</p><p>Instead, save the work that needs to happen before starting an action that may outlive the current process.</p><p>For the renewal, the service first records the renewal and the payment attempt as pending. It then contacts the provider. If the service crashes, another worker can inspect the saved state and decide whether to continue, check the provider, or send the case for reconciliation.</p><p>This is sometimes called recording a <strong>durable intent</strong>. The plain idea is simple: save what you are trying to do so another process can pick it up if the first one disappears.</p><p>For work that must be sent to another service, a transactional outbox is one common option. The application saves its business change and an outgoing message in the same local database transaction. A separate process sends the message and retries if needed. The receiving service must still handle duplicates safely.</p><p>For example, after a paid order is recorded, an outbox message can ask the warehouse system to begin fulfillment. If the message is delivered twice, the warehouse should recognize that both messages refer to the same order action.</p><h3>4. Which changes must succeed together?</h3><p>A database transaction is useful because it lets a group of related changes succeed or fail as one unit. But that guarantee has a boundary.</p><p>In the subscription example, the billing service may be able to update the renewal record, payment result, and its own ledger entries in one database transaction. It cannot normally include the external card provider or a separately operated entitlement service in that same transaction.</p><p>That means the statement “charge the card and update every service in one transaction” is not a design. It describes a guarantee the system does not actually have.</p><p>Draw the boundary explicitly:</p><ul><li>Which records live in the same database and can be committed together?</li><li>Which actions happen in another service?</li><li>Which actions depend on an external provider?</li><li>What happens if one side succeeds and the other side does not?</li></ul><p>When a workflow crosses the boundary, use a deliberate process to finish or correct the work. That may involve an outbox, a durable workflow, retries, compensating actions such as a refund, and reconciliation.</p><p>Uber’s Docstore illustrates why the exact boundary matters. Its strict serializability guarantee applies within a partition, not across the entire database as one global transaction. An application that needs related records to change together must account for where those records are placed. A secondary index can make records easier to find; it cannot turn changes across separate transaction boundaries into one atomic operation.</p><h3>5. Which information must be correct before we act?</h3><p>Some parts of an application can tolerate old information. Others cannot.</p><p>A product listing that takes a few seconds to show updated stock may be acceptable if checkout checks the authoritative inventory before reserving an item. A cached subscription page may briefly show the previous renewal date, but the access-control decision must not rely on that stale page data.</p><p>This is the practical distinction behind <strong>strong consistency</strong> and <strong>eventual consistency</strong>:</p><ul><li>Use the authoritative or strongly consistent path when an outdated answer could cause an incorrect business action.</li><li>Use caches, search indexes, and reporting views that update later when temporary staleness is acceptable.</li><li>Make the expected delay visible and understood. “Eventually” should not mean “we have no idea when.”</li></ul><p>Uber’s indexing design makes this distinction deliberately. The engineering article describes different consistency choices for different indexes rather than requiring every lookup to pay the cost of the strongest guarantee.</p><p>For your own system, ask one question about every important read:</p><blockquote><strong>What bad thing could happen if this answer is out of date?</strong></blockquote><p>The answer should determine how fresh that read needs to be.</p><h3>6. Can we prove what happened?</h3><p>A system that stores only the latest value can make it difficult to explain how it got there.</p><p>Suppose a customer says they were charged twice. If the billing record was overwritten each time its status changed, the team may struggle to reconstruct the sequence of events. If the system preserves the original payment attempt, the provider response, and any later refund or correction, the investigation has evidence to work with.</p><p>Uber’s LedgerStore takes this idea much further. Its records are immutable; corrections are tracked through revisions; and sealed data ranges and signed manifests help detect missing or changed records.</p><p>A smaller application may not need signed manifests or the full LedgerStore design. It may be enough to keep an append-only history of important actions and record corrections as new entries. The right level of protection depends on audit requirements, regulation, and the consequences of tampering or data loss.</p><p>The key is not to make every table immutable. It is to preserve enough trustworthy history for the business to explain and verify important outcomes.</p><h3>7. How will we find and fix differences?</h3><p>Even a carefully designed system will encounter delayed messages, failed requests, provider timeouts, and bugs. Retrying helps, but it does not prove that every part of the workflow eventually reached the right result.</p><p>Build a way to compare the records that should agree.</p><p>For the subscription service, that could mean comparing successful payment captures with active entitlements after allowing time for normal processing. A successful capture with no entitlement after the agreed window needs investigation. A delayed entitlement message that is still within the expected window may not be an error.</p><p>A useful comparison process defines three things:</p><ul><li><strong>What is compared?</strong> For example, provider captures against internal payment records, and paid renewals against entitlements.</li><li><strong>When is a difference a problem?</strong> Define the expected processing delay and the point at which a mismatch needs action.</li><li><strong>How is it fixed?</strong> Complete the missing step, issue a refund or credit, or send the case for human review. Record the repair so it can be audited and safely repeated.</li></ul><p>This is called <strong>reconciliation</strong>. It is not just a report that lists mismatches. It is a controlled way to detect and resolve them.</p><p>Uber’s database migration used the same broad idea at a different level: compare data in the old and new stores, investigate differences, and promote the new store only after validation. A system should be able to detect when reality differs from what its records say.</p><h3>8. How do we change systems without losing control?</h3><p>A migration is not complete when the data has been copied. The team must know which system is in charge before, during, and after the change.</p><p>During a database migration, two systems may temporarily contain copies of the same data. If both are treated as equally authoritative, a failed write or conflicting update can leave the team unsure which value is correct.</p><p>Before starting, define:</p><ul><li>Which system accepts the authoritative writes at each stage?</li><li>How do changes reach the other system?</li><li>Can failed changes be retried or replayed?</li><li>How will the team compare the two systems?</li><li>What evidence is required before switching authority?</li><li>What is the rollback plan if validation or production behavior is unacceptable?</li></ul><p>Uber’s migration from DynamoDB to Docstore was staged. It included historical backfill, shadowing live writes, reading and comparing data, validating records, promoting Docstore, and only later stopping traffic to DynamoDB. Uber reports validating 250 billion unique records and completing the migration without a production incident or table rollback.</p><p>The exact sequence was designed for Uber’s systems and scale. The reusable lesson is simpler: keep a clear source of truth, validate the destination against the source, and make each stage reversible where practical. Never treat two independent writes as if they were one atomic write.</p><h3>Three Designs That May Be Enough</h3><p>These questions should help you choose a design that fits your requirements, not push you toward a complex distributed architecture.</p><p><strong>1. One relational database</strong></p><p>For many systems, this is the right starting point. Keep the records that must change together in one relational database transaction. Use an outbox to publish events to other services, and use database-backed reads for decisions that must be current.</p><p>The trade-off is that the database becomes an important scaling and availability boundary. More importantly, the transaction still cannot include an external payment provider. That part needs its own safe retry and recovery process.</p><p><strong>2. Separate services with a workflow</strong></p><p>If billing, payments, and entitlements need independent ownership or scaling, each service can keep its own data. A durable workflow coordinates the steps, and each service makes its operations safe to repeat. If a later step cannot complete, the workflow retries, compensates where appropriate, or raises the issue for repair.</p><p>The trade-off is complexity. There is no single transaction across all services, so teams must operate workflow state, retries, timeouts, monitoring, and repair. Splitting a system into services does not remove complexity; it moves it into the communication between them.</p><p><strong>3. A transactional core with separate read views</strong></p><p>A useful middle ground is to keep important business changes in one transactional core while updating search, reporting, and account-summary views asynchronously. The core decides whether an action is allowed; the other views make it easier to browse and analyze information.</p><p>The trade-off is that those views can be behind. Make sure they do not quietly become the authority for decisions they cannot safely make.</p><p>Start with the smallest design that protects the business rule. Add separate services, partitions, stronger indexes, or custom infrastructure only when a real workload or organizational constraint justifies the cost.</p><h3>What You Should Not Copy From Uber</h3><p>Do not build a database because Uber built Docstore. Uber’s published articles describe constraints that made its earlier storage choices increasingly expensive or difficult to operate at Uber’s scale. A managed relational database or established distributed store may be entirely sufficient for your workload.</p><p>Do not make every read strongly consistent. Stronger guarantees have costs, including coordination, latency, and reduced flexibility during failures. Use them where stale information can cause a business violation.</p><p>Do not copy LedgerStore’s complete history-verification machinery if your audit requirements do not need it. An append-only history and explicit correction records may be enough.</p><p>And do not use “we need to scale” as the explanation for a complicated design. Identify the actual constraint: a hot key, a write limit, a transaction that spans too much data, an unacceptable delay, or a migration that cannot safely happen in one step.</p><p>Uber’s architecture is useful because its engineers show how specific constraints led to specific decisions. The components are not the lesson. The reasoning is.</p><h3>Take These Questions Into Your Next Design Review</h3><ol><li>What business rule must never be broken, and what exceptions are allowed?</li><li>How does the system recognize the same business action when it is requested again?</li><li>What happens if a process stops after starting work but before recording the result?</li><li>Which changes can be committed together, and which cross a database, service, or provider boundary?</li><li>Which decisions require current information, and which can use data that updates later?</li><li>Can we reconstruct an important past action, including any correction?</li><li>How do we compare related records, identify a real mismatch, and repair it?</li><li>During a migration, which system is authoritative, and what evidence allows us to switch?</li><li>What extra latency, coordination, availability risk, and operational work does the design introduce?</li><li>What is the simplest architecture that still protects the business rule?</li></ol><p>If the team cannot answer these questions, adding another database, queue, or service will not solve the underlying problem. It will only spread the unanswered questions across more components.</p><h3>Closing the Series</h3><p>The five earlier articles followed Uber’s architecture through financial event processing, immutable history, selective index consistency, a large live database migration, and the transaction boundary inside Docstore.</p><p>Taken together, they show that reliable systems are not built by choosing the strongest technology available. They are built by understanding what must remain true, knowing where each guarantee stops, and planning what happens when work crosses that boundary.</p><p>That reasoning applies to payments, orders, inventory, logistics, subscriptions, and many other systems. Start with the business rule. Make repeated requests safe. Save work before relying on another system. Be clear about what can change together. Use current data where decisions depend on it. Keep evidence, compare related records, and make migrations deliberate.</p><p>You do not need Uber’s infrastructure to apply those lessons. You need to understand the risks in your own system and choose the least complicated design that addresses them.</p><h3>Before you go</h3><ul><li>Please take a moment to like the post, share your thoughts, and follow for more articles like this.</li><li>You can also follow me on <a href="https://www.linkedin.com/in/inderbindra">LinkedIn</a>.</li></ul><h3>References</h3><ul><li><a href="https://www.uber.com/ca/en/blog/money-scale-strong-data/">Revolutionizing Money Movements at Scale with Strong Data Consistency</a> — Gulfstream’s money-movement model, balanced orders, deterministic identities, and asynchronous processing.</li><li><a href="https://www.uber.com/ca/en/blog/how-ledgerstore-supports-trillions-of-indexes/">How LedgerStore Supports Trillions of Indexes at Uber</a> — different index consistency requirements and the handling of unresolved intents.</li><li><a href="https://www.uber.com/ca/en/blog/dynamodb-to-docstore-migration/">How Uber Migrated Financial Data from DynamoDB to Docstore</a> — staged migration, validation, and cutover.</li><li><a href="https://www.uber.com/ca/en/blog/schemaless-sql-database/">Evolving Schemaless into a Distributed SQL Database</a> — Docstore’s data model and partition-level transaction boundary.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b490b224ced" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Uber’s Docstore Guarantees Strict Serializability Only Within a Partition]]></title>
            <link>https://medium.com/@inderbindra/why-ubers-docstore-guarantees-strict-serializability-only-within-a-partition-015b420bcb09?source=rss-6bd396d9b5c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/015b420bcb09</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Inderpreet Singh Bindra]]></dc:creator>
            <pubDate>Tue, 03 Nov 2026 14:01:03 GMT</pubDate>
            <atom:updated>2026-12-02T04:28:53.578Z</atom:updated>
            <content:encoded><![CDATA[<h3>How Uber turned Schemaless into a transactional database and why its strongest consistency guarantee ends at the partition boundary.</h3><h3>About This Series</h3><p>Part 5 of a six-part series exploring how Uber engineered its money movement architecture for correctness at scale.</p><p>In <a href="https://blog.stackademic.com/how-uber-rebuilt-its-money-movement-architecture-without-losing-financial-correctness-939a9b615c48"><strong>Part 1</strong></a>, we mapped the architecture and the financial invariants driving its design.</p><p>In<strong> </strong><a href="https://medium.com/@inderbindra/why-ubers-financial-database-does-not-trust-update-512f5492aa11"><strong>Part 2</strong></a><strong>,</strong> we examined how LedgerStore preserves immutable financial history through sealing, signed manifests, and revisions.</p><p>In <a href="https://medium.com/@inderbindra/how-uber-keeps-2-trillion-indexes-consistent-without-slowing-every-write-737025e5ee74"><strong>Part 3</strong></a>, we looked at how Uber decides which of its trillions of indexes cannot tolerate stale data.</p><p>In <a href="https://medium.com/@inderbindra/how-uber-migrated-250-billion-financial-records-without-breaking-consistency-6917c7e7a01c"><strong>Part 4</strong></a>, we followed the live migration of more than 250 billion LedgerStore records from DynamoDB to Docstore.</p><p>This installment answers the question <a href="https://medium.com/@inderbindra/how-uber-migrated-250-billion-financial-records-without-breaking-consistency-6917c7e7a01c">Part 4</a> left open: what made Docstore a suitable destination in the first place, and where exactly do its guarantees end?</p><figure><img alt="Infographic illustrating Uber Docstore’s architecture, showing the query layer, MySQL storage engine with Raft replication, and partitioned nodes, highlighting strict serializability within a partition." src="https://cdn-images-1.medium.com/max/1024/1*hl3eBuJsybNyczXz5sFlZw.png" /><figcaption>From Schemaless to Docstore: How Uber combined MySQL transactions and Raft replication to deliver strong consistency — and why that guarantee ends at the partition boundary.</figcaption></figure><h3>Schemaless Was Reliable, but Too Rigid for Transactional Workloads</h3><p>Docstore’s strongest guarantee is deliberately local: strict serializability applies within a partition, not across the entire database. That boundary determines which related rows can change atomically and which workflows need coordination above the database.</p><p>Uber arrived at that design by evolving Schemaless, its append-only datastore. Its smallest entity, a cell, was immutable. That restriction reduced complexity and removed in-place update races, but it also made it difficult for applications to correct records, relate data, query by attributes beyond the original key, or change several related rows atomically.</p><p>Docstore was Uber’s answer: preserve the reliability of Schemaless while adding the transactional capabilities applications needed. Its contract is strong but bounded: transactions are strictly serializable within a partition, and later reads through the same key see the committed result or a later write.</p><h3>Cassandra Added Flexibility, but Eventual Consistency Shifted Complexity to Applications</h3><p>When Schemaless proved too restrictive, Uber tried Cassandra. It offered more flexible data modeling and updates, but Uber reported operational-maturity and efficiency challenges at its scale. Its eventual consistency also affected developer productivity: application teams had to reason about whether data they had just read was current enough to use.</p><p>Uber therefore faced two unsatisfactory choices. Schemaless provided reliability through immutability but lacked the transactional flexibility applications needed. Cassandra offered flexibility but shifted consistency concerns into application code. Teams can accept eventual consistency and manage version checks, reconciliation, idempotency, and read patterns themselves; that can be reasonable when stale reads are tolerable. Uber wanted the database to provide a stronger, reusable guarantee for data that required it.</p><h3>Uber Evolved Schemaless Instead of Starting from Scratch</h3><p>Uber describes Docstore as a general-purpose, multi-model database that scales horizontally and provides strict serializability at the partition level. It supports business-critical workloads, relational and hierarchical data shapes, and a strong consistency guarantee whose scope is one partition, not the entire database.</p><p>Uber’s stated goal was to combine the schema flexibility associated with document models and the schema enforcement associated with relational databases. Schema-on-write is the first part of that contract.</p><h3>Schema-on-Write with Flexible Document Modeling</h3><p>Docstore supports schema-on-write by default. The schema is explicit, and the database validates data against it when a record is written. Schemas can evolve: records with different schema versions can coexist, and schema updates do not require full table rebuilds. Docstore also supports sparse records and complex nested data types.</p><p>Tables use rows, columns, and values, while user-defined types allow nested records to be stored as rows. This is useful when an application wants to load a document-like hierarchy together. Docstore also supports Associations for representing one-to-many and many-to-many relationships. Uber calls this the Flexible Document Model because it supports relational and hierarchical representations in one database.</p><p>The trade-off is explicit rather than absent:</p><blockquote><strong>Writes are validated against a schema, and teams still need to plan how readers handle schema evolution. Flexibility means the data model can change without abandoning enforcement.</strong></blockquote><h3>How Docstore Distributes Tables Across Shards and Zones</h3><p>A Docstore deployment is an instance with three layers:</p><ul><li>A stateless query layer,</li><li>A storage engine,</li><li>And a control plane.</li></ul><p>The query layer routes requests to storage. Because it is stateless, request handling is separated from the placement and ownership of stored data. The storage engine holds data in partitions, where transaction execution and replication occur. The control plane assigns shards to partitions and adaptively adjusts placement in response to failure events.</p><p>These responsibilities should not be conflated: routing determines where a request goes, storage determines how data is committed, and the control plane manages where shards are placed.</p><p>Tables are sharded and distributed transparently to applications. A shard represents a set of rows from a table, on the order of a few hundred gigabytes, and is assigned in its entirety to a partition. A partition can contain one or more shards, and an instance typically contains multiple partitions.</p><p>A partition consists of three to five nodes. Each node is a unit of physical isolation deployed in an independent zone, and partitions are also replicated across geographic locations to provide resilience to data-center failures. The partition is the unit of replication and consistency; deploying its nodes across independent zones provides physical failure isolation. These are related but distinct responsibilities.</p><figure><img alt="Diagram of a Docstore instance with a stateless query layer routing to a storage layer organized as partitions. Each partition contains nodes deployed in independent zones, while the control plane assigns shards to partitions and adjusts placement after failures." src="https://cdn-images-1.medium.com/max/846/1*rcboRSB-C-33qcfRiwVOOQ.png" /><figcaption>Conceptual layered view based on Uber’s published Docstore architecture. It does not show internal APIs, shard counts for a specific table, or network topology.</figcaption></figure><p>The simplified contrast is:</p><figure><img alt="Table comparing different aspects of the Schemaless (before) and Docstore (after) databases used by Uber." src="https://cdn-images-1.medium.com/max/713/1*Hdm6T_42vdt7RdZrvD_kxA.png" /></figure><p>Docstore adds transactional power, but also introduces the partition as a fundamental architectural boundary.</p><h3>The Partition Is the Transaction Boundary</h3><p>Every table has a primary key, which can contain one or more columns and uniquely identifies a row. Docstore encodes primary-key and partition-key values into an order-preserving byte representation and stores rows in primary-key order. This supports queries such as retrieving rows for a partition key and narrowing the result with additional primary-key columns. The ordering is useful because a query can use the leading portion of a composite key to identify a range of relevant rows rather than treating every lookup as an unrelated point read. It also makes the key definition part of the access-path design, not merely a uniqueness constraint.</p><p>Applications influence data locality through key design. They can explicitly define partition keys in the schema; otherwise, Docstore uses primary keys to shard the data. This choice determines which rows can participate in one partition-scoped transaction.</p><p>Put rows that must change together in the same partition, and Docstore can make the transaction atomic and strictly serializable. If those rows land in different partitions, the single-partition guarantee does not cover the entire operation. The application must coordinate the workflow across that boundary or reconsider the data model. Key selection is therefore the act of drawing the transaction boundary.</p><p>A table can also have materialized views partitioned by columns different from those used by the main table. A view provides another access path for example, lookup by a non-primary-key column without forcing the main table to use that layout. It is an additional partitioned representation of the data, with storage and maintenance costs.</p><p>This is the same design question raised by indexes in <a href="https://medium.com/@inderbindra/how-uber-keeps-2-trillion-indexes-consistent-without-slowing-every-write-737025e5ee74">Part 3</a>:</p><blockquote><strong>Which lookups participate in decisions that cannot tolerate stale data, and which are convenience reads?</strong></blockquote><p>Docstore provides the mechanism; the workload determines whether the extra representation is worth maintaining.</p><h3>Why Docstore Needed Consensus Inside Each Partition</h3><p>A partition may have several replicas, but they must agree on one ordered history of committed writes. Docstore uses Raft to reach that agreement. Each partition has one leader and multiple followers; writes are initiated by the leader, and Raft keeps the replicated log consistent across the nodes.</p><p>A write is committed only when consensus is reached. It is not enough for one node to accept the request: the partition must agree on the write’s position in the log. This ordering is what allows replicas to converge on the same history even when requests arrive concurrently. Without a shared order, two replicas could accept different sequences of updates and expose different states for the same logical data. Raft addresses agreement on that sequence; it does not, by itself, define the application’s transaction model. Uber states the resulting read guarantee precisely: after a write to a key successfully commits, subsequent reads through that same key return the written data or a later write.</p><p>Docstore provides strict serializability within a partition. Transactions can be understood as if they executed sequentially, while respecting real-time ordering: if transaction A commits before transaction B begins, A must appear before B in the serial execution order. This guarantee should not be extended automatically to every query pattern or materialized-view access path.</p><p>During a network partition, Docstore favors consistency over availability. In CAP terminology, Uber characterizes it as a <strong>CP system</strong>: it protects the consistency guarantee rather than accepting writes that cannot be committed through consensus. That is a defensible choice for data where an uncertain write can corrupt downstream decisions, but it is not the right trade-off for every workload.</p><h3>MySQL Transactions, Replicated by Raft</h3><p>Raft provides an ordered replicated log, but applications also need transaction semantics. Docstore uses MySQL as its underlying database engine. The unit of replication in the replicated state machine is a MySQL transaction: operations execute within a MySQL transaction to provide ACID semantics, and those transactions are replicated across nodes using Raft.</p><p>The responsibilities are distinct. MySQL provides transaction execution and concurrency control; Raft coordinates the order in which replicas apply transactions. MySQL uses row locks for write operations such as inserts, updates, and deletes. Concurrent transactions that modify the same row are serialized through this locking behavior.</p><p>This design gives applications familiar MySQL transaction semantics alongside replication and automatic failover. The distinction between the two mechanisms matters: MySQL governs conflicts among transactions executing against rows, while Raft ensures replicas apply the agreed transaction history in a consistent order. Neither mechanism replaces the other. It also inherits MySQL’s constraints. Transaction size and duration, locking behavior, and contention still require careful consideration. Raft does not eliminate those constraints; it adds replication and consensus around the transactions being executed.</p><figure><img alt="Flowchart of a Docstore write. A client request reaches the stateless query layer, which routes it to the partition leader. The leader executes a MySQL transaction, replicates it through Raft to followers, and commits only after consensus is reached." src="https://cdn-images-1.medium.com/max/678/1*SDz8-KYwHzFF2JWmq79dlg.png" /><figcaption>Conceptual write path based on Uber’s published Docstore design. The source identifies three to five nodes per partition but does not specify the exact quorum configuration, leader-election timing, or internal replication messages.</figcaption></figure><p>The documented read guarantee is specifically for subsequent reads through the same key. It should not automatically be extended to every query, materialized-view access path, or cross-partition operation; those paths have their own consistency requirements.</p><h3>What Happens When Part of the System Fails</h3><p>The design becomes clearest under failure.</p><p><strong>Leader Failure:</strong> Docstore supports automatic failover among replicas while maintaining ACID properties. Committed transactions have already been agreed through the replicated log, so the system does not depend on one leader surviving for committed work to survive. The public documentation does not specify exact leader-election timing or every recovery step.</p><p><strong>Replica Unavailability:</strong> If a partition cannot reach Raft consensus for example, because enough replicas are unavailable or disconnected, the write cannot be committed. A single lagging or unavailable follower does not necessarily prevent progress if the remaining replicas can still reach consensus. This is the CP trade-off in practice: protect the ordering guarantee rather than accept a write without consensus.</p><p><strong>Row Contention:</strong> MySQL row locks serialize concurrent writes to the same row. The application may still need retry handling, but it does not have to reimplement the database’s row-level concurrency control.</p><p><strong>Cross-partition Operations:</strong> A transaction spanning partitions is not covered by Docstore’s single-partition strict-serializability guarantee. The application needs an explicit coordination strategy, such as a Saga with compensating actions, an intent and reconciliation pattern, or a data model change that keeps rows requiring atomic updates together. For example, a workflow may successfully update one partition and then fail before updating another. The system must know whether to retry the remaining step, compensate for the completed step, or record an intent that a background process can reconcile. That recovery logic is part of the application contract; the database’s local transaction guarantee does not decide it. These approaches manage partial completion and recovery; they do not create one global ACID transaction.</p><p>Uber’s public write-up does not specify every detail of internal failure handling. The documented design boundary is sufficient for application architects to reason about: consensus within a partition, MySQL transactions as the replicated unit, and consistency favored over availability when consensus cannot be reached.</p><h3>Choosing a Partition Key: Atomicity vs. Hotspots</h3><p>Consider a hypothetical payout service; this is an illustrative example, not Uber’s actual schema. Each payout has a driver identifier, payout identifier, status, total, and line items that must change together.</p><p>If the partition key groups rows by driver, a transaction that updates a driver’s payout and its line items can stay within one partition. Docstore can then apply the change atomically and strictly serializably.</p><p>But locality can create hotspots. If a partition key groups payouts by calendar day, high-volume writes for the same date can converge on the same partition key. The problem is not the date itself; it is concentrating too much concurrent activity behind one key. A very active driver can create the same problem through popularity rather than time.</p><p>Key choice therefore trades atomicity against distribution. Keeping related rows together supports a stronger transaction boundary; spreading activity can improve load distribution but may push workflows across partitions.</p><p>A materialized view can provide another layout for example, by payout date while the main table remains partitioned by driver but it adds another representation to store and maintain. The right design depends on which operations must be atomic, which queries need efficient access, and where contention is likely.</p><p>A useful design exercise is to list the important write workflows first, mark the rows each workflow must update together, and then test candidate partition keys against both locality and expected write distribution. Only after that should secondary query patterns drive materialized-view choices. Otherwise, a team can optimize reads while accidentally making its critical writes cross the transaction boundary.</p><h3>How LedgerStore Used Docstore’s Partition-Level Guarantees</h3><p><a href="https://medium.com/@inderbindra/how-uber-migrated-250-billion-financial-records-without-breaking-consistency-6917c7e7a01c">Part 4</a> examined Docstore as the destination for LedgerStore’s migration. The choice makes more sense now: Docstore offered a clear partition-scoped guarantee, a flexible model that could represent LedgerStore’s primary key without reducing it to generic string fields, and materialized views for secondary access patterns.</p><p>There is an important distinction around change data capture. Uber’s general Docstore description lists CDC among its capabilities, but the migration article identifies CDC and streaming as missing for LedgerStore’s manifest-generation workload. Uber therefore built Flux on top of Docstore, using Kafka in the streaming and manifest-generation pipeline.</p><p><a href="https://medium.com/@inderbindra/how-uber-keeps-2-trillion-indexes-consistent-without-slowing-every-write-737025e5ee74">Part 3</a> showed why a strong database guarantee does not automatically make every application access path strongly consistent. LedgerStore used intents and read-path resolution to protect strongly consistent indexes. This is a related example of coordination above the storage layer, but it solves a different problem: keeping indexes consistent with their corresponding records.</p><p>A database can make a committed row visible through its key while an index, view, cache, or downstream service still lags. The guarantee travels only as far as its boundary.</p><h3>What Docstore Deliberately Does Not Promise</h3><p>Docstore’s guarantees come with costs that should be understood before adopting a similar design.</p><ol><li><strong>No global strict serializability:</strong> Cross-partition atomicity requires application-level coordination, including handling partial completion, retries, reconciliation, and repair.</li><li><strong>No unconditional write availability:</strong> When a partition cannot reach consensus, writes cannot commit. That is appropriate when consistency is more important than accepting every request.</li><li><strong>No escape from MySQL constraints:</strong> Transaction duration, size, row locking, and contention still need careful design.</li><li><strong>No free operational simplicity:</strong> Query routing, replicated partitions, control-plane placement, materialized views, and consensus add moving parts. Uber built Docstore because its scale and operational experience made that complexity rational; smaller systems should not copy it without a matching need.</li><li><strong>No automatic data-model design:</strong> Schema evolution and nested types provide flexibility, but teams still need to choose keys, decide which views are worth maintaining, and plan for old and new schema versions.</li></ol><p>These are not flaws hidden behind the implementation. They are the trade-offs that define Docstore’s contract. The broader lesson is that a database’s consistency label is not enough to evaluate it. Architects need to understand the scope of the guarantee, the unit at which consensus is reached, the operations that remain outside that scope, and the operational cost of maintaining the guarantee under failure.</p><h3>A Checklist for Designing Around Partition Boundaries</h3><p>Before choosing a database with a partition-scoped guarantee, ask:</p><ol><li><strong>What is the invariant?</strong> What must remain true during retries, failures, and partial outages?</li><li><strong>Where is the atomicity boundary?</strong> Which rows must change together? Can they live in one partition?</li><li><strong>Which reads drive decisions?</strong> What breaks if each primary-key read, view lookup, or secondary access path is stale?</li><li><strong>What does the guarantee cost?</strong> Account for consensus, row locking, contention, and reduced write availability during partition failures.</li><li><strong>Do the keys fit the workload?</strong> Locality buys atomicity; distribution helps balance load. A key that optimizes one can weaken the other.</li><li><strong>What happens when consensus is unavailable?</strong> Define how clients handle failed or delayed writes without assuming an uncertain result succeeded.</li></ol><p>The transaction boundary matters more than the database brand. A team that can draw that boundary precisely and explain what happens outside it, has done much of the hard design work. A team that cannot may discover the boundary during an incident, when an operation assumed to be atomic turns out to have crossed a partition.</p><h3>Next: Turning Uber’s Architecture into a Design Framework</h3><p>Docstore gave Uber a clear storage contract: flexible data modeling, MySQL transactions replicated through Raft, and strict serializability within a partition. That contract alone does not make a financial system correct. Gulfstream had to define balanced orders and idempotent processing; LedgerStore had to preserve immutable history and prove completeness with manifests; indexing had to classify lookups by the consequence of staleness; and migration had to prove equivalence before promotion.</p><p>In <a href="https://medium.com/@inderbindra/a-payment-went-through-the-system-still-got-it-wrong-8b490b224ced">Part 6</a>, the final article in this series, we will synthesize these mechanisms into a transferable design framework for naming invariants, drawing transaction boundaries, classifying access paths, retaining audit evidence, designing reconciliation and repair, and managing source of truth transitions during migration.</p><h3>Before you go</h3><ul><li>Please take a moment to like the post, share your thoughts, and follow for more articles like this.</li><li>You can also follow me on <a href="https://www.linkedin.com/in/inderbindra">LinkedIn</a>.</li></ul><h3>References</h3><ul><li><a href="https://www.uber.com/ca/en/blog/schemaless-sql-database/">Evolving Schemaless into a Distributed SQL Database, Uber Engineering</a></li><li><a href="https://www.uber.com/ca/en/blog/dynamodb-to-docstore-migration/">How Uber Migrated Financial Data from DynamoDB to Docstore, Uber Engineering</a></li><li><a href="https://www.uber.com/ca/en/blog/how-ledgerstore-supports-trillions-of-indexes/">How LedgerStore Supports Trillions of Indexes at Uber, Uber Engineering</a></li><li><a href="https://www.uber.com/ca/en/blog/payments-platform/">Revolutionizing Money Movements at Scale with Strong Data Consistency, Uber Engineering</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=015b420bcb09" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Uber Migrated 250 Billion Financial Records Without Breaking Consistency]]></title>
            <link>https://medium.com/@inderbindra/how-uber-migrated-250-billion-financial-records-without-breaking-consistency-6917c7e7a01c?source=rss-6bd396d9b5c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/6917c7e7a01c</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Inderpreet Singh Bindra]]></dc:creator>
            <pubDate>Tue, 27 Oct 2026 13:06:01 GMT</pubDate>
            <atom:updated>2026-11-13T00:57:00.564Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>How shadow writes, dual reads, and cryptographic validation enabled a live database migration with zero reported production incidents.</strong></p><p>Moving 250 billion financial records between databases is difficult enough. Doing it while production traffic continues, without losing acknowledged writes, breaking read-your-writes consistency, or interrupting service, is a different class of problem.</p><p>Uber faced that challenge when it moved LedgerStore from DynamoDB to its internal Docstore database: <strong>roughly 300 TB of historical records</strong>, live writes arriving throughout the migration, and a requirement to preserve a path back if the new backend failed to meet expectations.</p><p>The motivation was economic. The difficult part was preserving financial correctness while changing the storage layer.</p><h3>About This Series</h3><p>Part 4 of a six-part series exploring how Uber engineered its money movement architecture for correctness at scale.</p><p>In <a href="https://blog.stackademic.com/how-uber-rebuilt-its-money-movement-architecture-without-losing-financial-correctness-939a9b615c48"><strong>Part 1</strong></a>, we mapped the architecture and the financial invariants driving its design.</p><p>In <a href="https://medium.com/@inderbindra/why-ubers-financial-database-does-not-trust-update-512f5492aa11"><strong>Part 2</strong></a>, we examined how LedgerStore preserves immutable financial history through sealing, signed manifests, and revisions.</p><p>In <a href="https://medium.com/@inderbindra/how-uber-keeps-2-trillion-indexes-consistent-without-slowing-every-write-737025e5ee74"><strong>Part 3</strong></a>, we looked at how Uber decides which of its trillions of indexes cannot tolerate stale data.</p><p>This installment focuses on the live storage migration: historical backfill, shadow writes, dual reads, verification, and cutover.</p><figure><img alt="Infographic illustrating Uber’s migration of 250 billion financial records from DynamoDB to Docstore, showing backfill, shadow writes, dual reads, validation, and final cutover." src="https://cdn-images-1.medium.com/max/1024/1*e426ScpxqyVK7-8mM65_BA.png" /><figcaption>250 billion records. Two databases. Zero reported production incidents. How Uber migrated its financial ledger to Docstore while keeping production traffic running and preserving data consistency.</figcaption></figure><h3>DynamoDB Worked. Its Economics No Longer Did.</h3><p>LedgerStore, Uber’s immutable financial ledger, had run on DynamoDB for almost two years. As trips and orders accumulated, the cost of keeping ledger records in a hot database grew. Operating another storage technology alongside Uber’s internal databases also increased fragmentation: more operational expertise, monitoring, and maintenance to sustain.</p><p>Uber framed the decision around two goals: near-term efficiency and longer-term technology consolidation. Docstore, its in-house general-purpose multimodel database, offered a path to both. But cost savings could not come at the expense of the live ledger’s guarantees. The migration had to involve no customer changes or downtime, preserve 100% read-your-writes consistency and existing latency objectives, and allow database roles to be switched back in an emergency.</p><p>A note on two different migrations: Uber has run more than one large migration in its payments history. The move from the legacy payment platform to Gulfstream is one story.</p><p>The move of LedgerStore’s storage backend from DynamoDB to Docstore is a different story, years later, at a different layer. This article is only about the second one. The first is <a href="https://blog.stackademic.com/how-uber-rebuilt-its-money-movement-architecture-without-losing-financial-correctness-939a9b615c48"><strong>Part 1</strong></a> territory.</p><h3>The Non-Negotiable Rule: No Lost Writes, No Stale Reads</h3><p>Before examining the migration mechanisms, we need to establish what could never become false. Uber was moving data between two independent databases while production writes continued. There was no single transaction that could atomically transfer 250 billion records and redirect every client. Correctness had to be maintained through a sequence of independently recoverable stages.</p><p>That made the promotion criterion critical:</p><blockquote><strong>The new database must prove that it contains equivalent data before becoming the source of truth.</strong></blockquote><p>Every mechanism in this article exists to serve that invariant. Backfill moves historical records. Shadow writes capture new activity. Spot Repair detects and repairs failed copies, while Dual Read and Merge protect reads during temporary divergence. Manifest comparison validates the copied data before promotion. Only after these mechanisms establish sufficient confidence does Docstore become primary.</p><p>Unlike an atomic transaction, this migration permits temporary differences between databases. The architecture must ensure that those differences do not violate the client-facing consistency requirements.</p><h3>Why Uber Migrated 75% of Its Storage Footprint First</h3><p>One option was to migrate records, metadata, and indexes together. Uber’s engineers rejected that scope for the initial phase. Their short-term goal was cost efficiency, and rearchitecting everything at once would have delayed the payoff while multiplying the risk. So they split the project by component complexity and by what each phase would buy them.</p><p>Phase one covered the core online read-and-write path for records. Phase two, deferred, would cover system metadata and indexes. The split was justified by a single number: records contributed 75 percent of the storage footprint and cost. Moving records first captured most of the savings while keeping the hardest coordination problems index consistency across a backend switch, for later.</p><p>This is worth pausing on, because it is a pattern that transfers far beyond Uber. When a migration is too big to do at once, the right split is not always the cleanest architectural boundary. Sometimes it is the boundary that buys the goal earliest with the least irreversible risk.</p><h3>Docstore Had One Missing Piece: Change Data Capture</h3><p>The first design decision was the database itself. The requirements list reads like a checklist for any serious storage backend: reliable and operationally hardened, 99.99 percent availability, horizontal scalability for dataset and request growth, plus a feature set of change data capture, secondary indexes, and a flexible data model. Docstore matched everything except change data capture, the streaming capability LedgerStore uses to build its manifests.</p><p>Manifest generation is a crucial part of the integrity story from <a href="https://medium.com/@inderbindra/why-ubers-financial-database-does-not-trust-update-512f5492aa11"><strong>Part 2</strong></a>. Rather than scanning tables to assemble sealed windows, LedgerStore reads from the database changelog stream. Stream reads are cheaper than table scans; they run on cheaper commodity hardware, and they can flow through a system like Kafka that is optimized for stream reading. There is a subtler reason too: reading from the stream lets the system verify that the data it wrote to the table is the same data that appears in the stream, which guards against bugs in the write path.</p><p>Faced with a missing capability, the team had options. They could have picked a different database that already had CDC. They could have built manifest generation on table scans instead of streams. Instead, they built a streaming framework for Docstore, project name <strong>Flux</strong>, and used it for manifest generation alongside Kafka.</p><p>The reasoning is worth stating plainly:</p><blockquote><strong>Picking a different database to avoid building one framework would have sacrificed the consolidation goal that motivated the migration in the first place.</strong></blockquote><p>Flux powers a verification scheme that makes several passes over the data. The inserted data is read from the local region and a checksum C1 is generated, then the database stream in that region is tailed and a second checksum C2 is calculated. For the data to be consistent from LedgerStore’s point of view, C1 and C2 must match. The same process repeats in the remote region, producing C3 and C4. A sealing window is only considered closed when all four checksums across both regions match.</p><p>The stream processing, built on Spark, handles 50 thousand records per second. Each Spark worker persists its checksum progress, along with the Kafka offset it has already processed, and the highest sequence number observed. The persisted offset supports recovery after interruptions, while the sequence information helps enforce the stream-processing deduplication guarantees described by Uber.</p><p>This matters because a restarted worker must not silently count the same event twice while producing a checksum intended to prove data completeness.</p><p>The team chose Spark over Flink because the sealing process does not need to be real time; bounded delay is acceptable, batch processing catches up quickly after lags, and larger in-memory batches amortize database calls better.</p><h3>A Database Migration That Also Simplified Queries</h3><p>One important design decision concerned how LedgerStore represented primary keys. Applications using LedgerStore could define their own primary keys, but DynamoDB did not directly reflect those definitions in its table schema. Instead, LedgerStore converted every user-defined primary key into a generic pair of string fields: pk and sk.</p><p>With Docstore, Uber took a different approach. Rather than translating application-defined keys into a generic representation, the team mapped those keys directly onto the Docstore table using its native data model. This allowed LedgerStore to pass complex query conditions directly to Docstore instead of translating them through the generic key representation.</p><p>The result was simpler query logic and, according to Uber’s engineering team, improved latency in both read and write paths.</p><p>This is a quiet lesson inside a loud project. Migrations are often treated as pure data movement, but the target schema is a design decision in its own right. Mapping the key faithfully instead of carrying over the old key-marshalling layer removed a translation layer from every query the system would ever run.</p><h3>Copying 250 Billion Records Without Starting Over</h3><p>With the design settled, the first mountain was the history: more than 250 billion unique records, roughly 300 terabytes, sitting in DynamoDB. Two approaches were on the table. Option one was a single Spark job that processed everything in one go and dumped it to Docstore. A failure late in that job could force an expensive restart. Option two was to break the history into subsets and process each one individually with checkpointing, so a failure only replays the subset that was in flight.</p><p>Option two won, and the reason it fit so cleanly is that LedgerStore already had a natural subset boundary. Recall from <a href="https://medium.com/@inderbindra/why-ubers-financial-database-does-not-trust-update-512f5492aa11">Part 2</a> that data is divided into sealing windows, typically 30-minute buckets, and that cold storage offloading already happens at sealing window granularity.</p><p>The backfill framework processes individual sealing windows, maintains a checkpoint of completed windows, and is idempotent by construction. It is multithreaded, with each worker processing a distinct sealing window, which drives throughput: the framework handles 1 million messages per second. Reading from cold storage instead of DynamoDB also drove the cost down, since cold storage reads are significantly cheaper. With this framework, the production dataset was backfilled in a couple of weeks.</p><p>There is a transferable insight here about idempotency and granularity. The backfill did not need a novel algorithm. It needed a unit of work small enough to retry cheaply, a checkpoint durable enough to survive crashes, and an existing system boundary, the sealing window, that already defined that unit. Migrations go wrong most often not in the steady state but in the failure handling, and this design made failures recoverable without restarting the entire migration.</p><h3>One Primary, Two Databases: The Shadow Write Strategy</h3><p>Backfill handles the past. The harder problem is the present: writes keep arriving while the backfill runs, and every one of them must land in the new database too. The mechanism Uber’s engineers built for this is the shadow writer, a module in LedgerStore’s write path that inserts incoming data into the secondary database alongside the primary.</p><p>A critical decision sits inside that sentence. <strong><em>The shadow write is asynchronous, not synchronous.</em></strong> Writing to two databases in the synchronous path would add latency to every client write and would couple the availability of the primary to the health of the secondary. But asynchronous copying introduces the exact failure the migration must prevent: a write can succeed on the primary and be acknowledged to the client, then fail on the secondary, leaving the two databases silently diverged.</p><p>Uber addressed this failure mode using two complementary mechanisms. According to its engineering write-up, a two-phase commit (2PC) protocol tracks asynchronous write failures, while a timer-based process called Spot Repair resynchronizes missing records from the primary database to the secondary.</p><p>An important distinction: Uber does not describe this as an atomic commit spanning DynamoDB and Docstore. The secondary write can fail after the primary has acknowledged success, which is precisely why failure tracking and subsequent repair are necessary.</p><p>Spot Repair is deliberately database role agnostic: it can resync in either direction, which keeps the roles swappable at every stage. In the first online phase, DynamoDB is primary and Docstore is secondary. Writes go to DynamoDB, are shadowed asynchronously to Docstore, and Spot Repair resyncs anything the shadow writer dropped, maintaining consistency between the two.</p><h3>When a Shadow Write Fails: How Spot Repair Recovers</h3><p>Consider a hypothetical fare correction written during this phase. The write lands in DynamoDB, and the client is acknowledged. The asynchronous shadow write to Docstore fails, perhaps due to a transient network error or due to a brief overload on the new cluster. The two-phase tracking records the failure rather than losing it.</p><p>Spot Repair subsequently fetches the missing entry from DynamoDB and resynchronizes it to Docstore. Until that succeeds, the databases contain different data. The length of that inconsistency window depends on how quickly the failure is detected and repaired; Uber does not publish a strict upper bound in their engineering blog.</p><p>Now consider a read that arrives inside that divergence window, asking for the corrected fare. This is where the next mechanism earns its place.</p><h3>Why Uber Read from Both Databases During Migration</h3><p>Even with shadow writes and repair, small inconsistency windows can slip through: during a database switch, or through a race condition no one predicted. To guarantee consistency and availability through those windows, the team introduced Dual Read and Merge in the read path. Instead of serving reads from a single database, the module reads from both databases concurrently regardless of their roles, merges the results, and returns the merged answer to the client.</p><p>This is the migration’s most instructive mechanism, because it inverts the usual instinct. The usual instinct is to make the secondary perfect before trusting it. Dual read accepts that perfection is unreachable during a live switch and designs around the imperfection instead. By reading from both sides and merging, the system can flip database roles without any moment where a read depends on a single database being fully caught up. It is also what protects the read in the worked timeline above: the fare correction is visible because DynamoDB has it, even though Docstore does not have it yet.</p><p>Dual Read and Merge is not a generic solution for making any two databases strongly consistent. Its correctness depends on the merge semantics and the guarantees of the underlying data model. LedgerStore’s immutable records make missing-record reconciliation conceptually simpler than reconciling arbitrary in-place updates, but duplicate handling, query ordering, pagination, and partial failures still require careful design. Uber’s article describes the concurrent reads and result merging, but does not publish the full merge algorithm.</p><h3>The Migration Phases: From DynamoDB to Docstore</h3><p>The mechanisms fit together as follows during the shadow-write and dual-read stages.</p><figure><img alt="Conceptual reconstruction, not an official Uber diagram. It shows the period when DynamoDB was primary; after promotion, Docstore became primary and shadow writes ran in the opposite direction. The illustration does not specify the internal implementation of result merging or repair tracking." src="https://cdn-images-1.medium.com/max/1024/1*G1jaRPK6e3oQTzB6JRMHeg.png" /><figcaption><em>Conceptual reconstruction, not an official Uber diagram. It shows the period when DynamoDB was primary; after promotion, Docstore became primary, and shadow writes ran in the opposite direction. The illustration does not specify how result merging or repair tracking is implemented internally.</em></figcaption></figure><p>The following is a simplified view of the migration stages and how the primary and secondary roles evolved. Historical backfill and online synchronization are separate responsibilities; the table should not be read as proof that every operational step was strictly sequential.</p><figure><img alt="This table is a simplified view of the migration stages and how the primary and secondary roles evolved. Historical backfill and online synchronization are separate responsibilities; the table should not be read as proof that every operational step was strictly sequential." src="https://cdn-images-1.medium.com/max/714/1*FzqgwZr9nBRTR7tD-qRf_g.png" /></figure><h3>Proving 250 Billion Records Match Before Cutover</h3><p>With backfill complete, shadow writes stable, and dual reads covering the gaps, the remaining question is the commit criterion from the opening:</p><blockquote><strong>How do you prove the new database holds the same truth before promoting it?</strong></blockquote><p>Uber’s engineers answered with the integrity machinery they already had. LedgerStore generates signed manifests for every sealed time window, listing records and their checksums. They compared the manifests generated from the historical and online data on Docstore against the manifests generated on DynamoDB, at scale. Matching manifests provided evidence that the copied historical and online data agreed for the covered sealed windows.</p><p>Manifest comparison validates the logical contents of the sealed data, rather than merely checking whether the copy process completed. A matching manifest provides strong evidence that the corresponding records and checksums agree between the databases. It does not, on its own, validate future write availability or every online read behavior. That is why Uber also required stable read and write paths, acceptable performance, and operational confidence before promotion.</p><p>Uber’s engineers report validating 250 billion unique records, roughly 300 terabytes, in Docstore through a Spark job within a single week. Only after the manifests matched, and after the read and write paths were stable with Docstore as secondary, did they swap the roles and promote Docstore to primary.</p><p>Docstore became authoritative only after Uber validated the copied sealed data against the existing ledger and confirmed that the online read and write paths met its requirements.</p><h3>Promote Docstore First. Retire DynamoDB Gradually.</h3><p>Promotion is not the end. The team then drained DynamoDB in stages, retaining the older backend as a fallback during the transition. First, they gradually removed reads from DynamoDB while continuing to shadow writes to it, draining traffic slowly and safely. The system stayed in this state for about a week. Only then came the final cutover: writes to DynamoDB stopped, the system was forced into single database operation through configuration, which bypassed the shadow writer and dual read modules entirely, and the DynamoDB tables were backed up and decommissioned.</p><p>Note the asymmetry, because it is deliberate. Reads were drained gradually, but the final write cutover was a single config-driven step. Reads are safe to drain gradually because dual read and merge keeps them correct at any mix. Writes need a clean, unambiguous transition point: at any instant, exactly one database is the primary that clients write to. The configuration-driven transition meant Uber could stop shadowing writes only after it had finished shifting reads and confirmed the new backend was stable.</p><h3>The Outcome: Zero Reported Incidents and $6M in Annual Savings</h3><p>Uber’s engineers measured the project the way a project this critical deserves to be measured. They reported no production incidents across the entire migration, and the migration was never rolled back for a single table. In its November 2021 engineering report, Uber stated that the new architecture had been running in production for more than six months without any detected data inconsistencies across the 250 billion migrated records. The new data model delivered latency improvements on both the read and write paths. And the business case closed: an estimated <strong><em>6 million dollars per year</em></strong> in savings from reduced DynamoDB spend, plus the technology consolidation that was the second founding principle.</p><p>Treat the incident and inconsistency numbers the way the source presents them: as reported outcomes of this specific project, not as a guarantee that this recipe cannot fail elsewhere. Those outcomes show what the design achieved in this migration, not that the approach is infallible.</p><h3>The Hidden Costs of Running Two Databases</h3><p>Every guarantee in this article had a price, and a Principal Engineer should be able to name them.</p><p>Running two databases temporarily expands the operational surface and introduces additional failure modes. Two write paths, a merge module, a repair scheduler, and config-driven role switching are all moving parts that must be monitored, and each one is a new failure mode that did not exist before the migration. The asynchronous shadow write accepts temporary divergence as a fact of life; Spot Repair and dual reads contain it, but they do not eliminate it, and their correctness becomes load-bearing for the whole project.</p><p>Config-driven role switching is a sharp tool. It makes rollback cheap, which is exactly what you want, but it also means a mistaken config change can redirect production traffic. Architecturally, this means the migration’s safety depends on the discipline around the config system as much as on the database machinery.</p><p>The manifest comparison at 250 billion records was itself a heavyweight Spark operation: the proof of equivalence is not free, and budgeting for it is part of budgeting for the migration. And reading the backfill from cold storage saved money but made the cold storage path a dependency of the migration’s critical path.</p><p>None of these costs invalidated the design. They are the reason the design looks the way it does. Acknowledging temporary divergence makes repair and verification necessary rather than optional. Uber reported completing this migration without production incidents.</p><h3>Five Rules for Migrating Critical Data Without Downtime</h3><p>Uber’s migration suggests five principles for correctness-critical storage changes. The mechanisms are not universal requirements; their value depends on the consequences of stale reads, missing writes, and unsuccessful rollback:</p><ol><li>Name the invariant the migration must never break, in this case no lost writes and no read that disagrees with the ledger, and design every mechanism against it.</li><li>Split the scope by what buys the goal earliest. Records were 75 percent of the footprint; moving them first captured the savings while deferring the hardest coordination.</li><li>Define evidence-based promotion criteria rather than a calendar deadline. Manifest comparison was necessary, alongside stable online behavior and performance, before Docstore became primary.</li><li>Preserve rollback options until confidence is high. Role-agnostic repair and configuration-driven switching let Uber change primary database roles before finally retiring DynamoDB.</li><li>Validate the logical data, not just the copy process. Matching manifests establish evidence of record completeness for covered sealed windows; online behavior also needs separate validation.</li></ol><p>Uber moved 250 billion financial records to Docstore, validated the copied data, and reported an estimated $6 million in annual savings. But the migration answers only half the architectural question.</p><blockquote><strong>What made Docstore a suitable destination for this workload in the first place?</strong></blockquote><p>Underneath its flexible document model, Docstore uses MySQL transactions, partitioned storage, and Raft-based replication. Those mechanisms determine where transactional guarantees apply, how replicas agree on writes, and what happens when part of the system becomes unavailable.</p><p><strong>In </strong><a href="https://medium.com/@inderbindra/why-ubers-docstore-guarantees-strict-serializability-only-within-a-partition-015b420bcb09"><strong>Part 5</strong></a><strong>, we’ll examine how Uber evolved Schemaless into Docstore, and why its transaction and consistency boundaries matter just as much as the migration mechanisms explored here.</strong></p><h3>Before you go</h3><ul><li>Please take a moment to like the post, share your thoughts, and follow for more articles like this.</li><li>You can also follow me on <a href="https://www.linkedin.com/in/inderbindra">LinkedIn</a>.</li></ul><h3>References</h3><ul><li><a href="https://www.uber.com/ca/en/blog/dynamodb-to-docstore-migration/">How Uber Migrated Financial Data from DynamoDB to Docstore, Uber Engineering</a></li><li><a href="https://www.uber.com/ca/en/blog/schemaless-sql-database/">Evolving Schemaless into a Distributed SQL Database, Uber Engineering</a></li><li><a href="https://www.uber.com/ca/en/blog/payments-platform/">Revolutionizing Money Movements at Scale with Strong Data Consistency, Uber Engineering</a></li><li><a href="https://www.uber.com/ca/en/blog/how-ledgerstore-supports-trillions-of-indexes/">How LedgerStore Supports Trillions of Indexes at Uber, Uber Engineering</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6917c7e7a01c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Uber Needs Strong Consistency for Some of Its 2 Trillion Indexes]]></title>
            <link>https://blog.stackademic.com/how-uber-keeps-2-trillion-indexes-consistent-without-slowing-every-write-737025e5ee74?source=rss-6bd396d9b5c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/737025e5ee74</guid>
            <category><![CDATA[database-architecture]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Inderpreet Singh Bindra]]></dc:creator>
            <pubDate>Wed, 21 Oct 2026 13:01:04 GMT</pubDate>
            <atom:updated>2026-10-26T23:09:08.734Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Why making every index strongly consistent would be expensive, and how Uber decides which financial lookups cannot tolerate stale data.</strong></p><h3><strong>About This Series</strong></h3><p><strong>Part 3 </strong>of a six-part series exploring how Uber engineered its money movement architecture for correctness at scale.</p><p>In <a href="https://medium.com/@inderbindra/how-uber-rebuilt-its-money-movement-architecture-without-losing-financial-correctness-939a9b615c48"><strong>Part 1</strong></a>, we mapped the architecture and the financial invariants driving its design.</p><p><a href="https://medium.com/@inderbindra/why-ubers-financial-database-does-not-trust-update-512f5492aa11"><strong>Part 2</strong></a> explored how LedgerStore preserves immutable financial history through sealing, signed manifests, and revisions.</p><p><strong>This article examines the next challenge:</strong></p><blockquote><strong>How can a system reliably find financial records without making every index strongly consistent and every write more expensive?</strong></blockquote><figure><img alt="Thumbnail illustrating Uber’s financial indexing architecture, featuring an Uber car, a credit card authorization hold, and a strongly consistent index workflow. The image highlights how Uber maintains financial correctness across more than 2 trillion indexes while balancing performance and availability." src="https://cdn-images-1.medium.com/max/1024/1*HROUTaAO3f4TMr83yy8TxA.png" /><figcaption>Not every index needs strong consistency. Discover how Uber manages over 2 trillion indexes while balancing financial correctness, write performance, and availability.</figcaption></figure><h3><strong>How a Missing Index Entry Could Lead to a Duplicate Charge</strong></h3><p>A rider requests a cab. Before the car moves, Uber places a hold on the rider’s credit card (the authorization). At the end of the trip, the hold becomes a charge, or gets voided if the trip was canceled. Somewhere in between, a payment workflow looks up the hold.</p><p>Now imagine the lookup finds nothing. The authorization record exists in the ledger, but the index the workflow reads has not caught up yet. The workflow concludes, reasonably and wrongly, that no authorization exists.</p><p>The rider gets charged while the original hold is still sitting on the card. Money has not been lost in some dramatic sense, but the financial state the system acted on disagreed with the financial state the system had recorded. In a business that processes <strong>tens of billions of financial transactions a quarter</strong>, that disagreement is <strong>not </strong>a cosmetic lag. It is a correctness violation wearing the clothes of a performance characteristic.</p><p>This is the failure mode Uber’s indexing architecture is designed to prevent, presented here the way Uber presents it: as an illustrative scenario, not a reported incident. And it sets up the central question of this article, which is sharper than how do you index at scale. <strong>It is:</strong></p><blockquote><strong>When does an index stop being a performance optimization and become part of the correctness story?</strong></blockquote><p>To understand how Uber answers that question, we need to distinguish two systems.</p><p><strong>LedgerStore</strong> is Uber’s append-only storage system for financial records, responsible for preserving trustworthy financial history and making it accessible through indexes.</p><p><strong>Docstore</strong> is Uber’s distributed database that provides the underlying storage. LedgerStore originally used DynamoDB before Uber migrated its backend to Docstore.</p><p>That distinction matters because LedgerStore defines the indexing guarantees, while the underlying database influences how efficiently those guarantees can be implemented.</p><h3><strong>When a Stale Index Becomes a Financial Correctness Problem</strong></h3><p>A correctness-critical index cannot contradict the record it represents. That is the governing invariant. Everything below is machinery for deciding, per lookup, whether this invariant is in force.</p><p>Here is the subtlety. Not every lookup at Uber participates in a decision that can violate a financial invariant. The payment history page in the rider app is allowed to lag by a few seconds; nobody’s money moves based on whether the last trip has appeared yet. The authorization hold lookup is not allowed to lag, because a stale answer changes what the system does next.</p><p>Uber’s indexing architecture addresses two separate questions. First, how fresh must an index be for the workflow that reads it? Second, how should index data be physically organized for the required access pattern? Strongly consistent and eventually consistent indexes answer the first question. Time range indexes address the second, introducing a different set of storage and operational challenges at Uber’s scale.</p><h3><strong>Strongly Consistent Indexes: Correct Reads at the Cost of Writes</strong></h3><p>For lookups like the authorization hold, Uber builds strongly consistent indexes. The guarantee is what every engineer wants, and few workloads can afford: once a record is written, any subsequent read is guaranteed to see the index entries for that record.</p><p>The mechanism is a T<strong>wo-phase commit (2PC) protocol built around index intents</strong>. What makes the design interesting is that committing the ledger record and finalizing its index are not single synchronous operation.</p><p><strong>The write path works in three steps:</strong></p><p>1. <strong>Write The Index Intent First: </strong>Before inserting the ledger record, LedgerStore writes an index entry in a temporary <strong><em>intent</em></strong> state. If any required index intent write fails, the entire record insertion fails. Accepting the record without its required index would break the consistency guarantee.</p><p>2. <strong>Write The Ledger Record:</strong> Only after the index intent succeeds does LedgerStore insert the actual record.</p><p>3. <strong>Commit The Index Intent Asynchronously: </strong>Once the record write succeeds, LedgerStore commits the index intent in the background. This keeps the final commit operation out of the user-facing insert latency.</p><figure><img alt="Flowchart of Uber LedgerStore’s strongly consistent indexing protocol. The write path creates an index intent, writes the ledger record, and asynchronously commits the intent. If an intent remains pending, the read path checks whether the corresponding record exists, committing the intent if present or rolling it back if absent." src="https://cdn-images-1.medium.com/max/1024/1*XQgPKv3wZWIXG1-JyaRWiw.png" /><figcaption>Conceptual representation based on Uber’s published intent and recovery protocol. It does not attempt to specify undocumented read result semantics.</figcaption></figure><p><strong>That third step raises an important question:</strong></p><blockquote><strong>What happens if the record write succeeds but the index intent never gets committed?</strong></blockquote><p>This is where the read path becomes part of the consistency mechanism.</p><p><strong>An index can remain in the intent state for two reasons:</strong></p><ol><li><strong>The record write succeeded, but the asynchronous index commit failed.</strong> The underlying record exists, but its index has not transitioned into the committed state.</li><li><strong>The index intent succeeded, but the record write failed.</strong> The index now points to a record that does not exist.</li></ol><p>When a read encounters an index in the intent state, LedgerStore checks the corresponding record. If the record exists, it initiates committing the intent. If the record does not exist, it rolls the intent back. These state transitions happen asynchronously to avoid adding latency to the read path.</p><p>There is an important distinction here: <strong>an index entry being in the intent state does not necessarily mean its underlying record is missing.</strong> It might represent a successfully written record whose index finalization is still pending.</p><p>Uber describes this intent resolution mechanism as part of its strongly consistent indexing design. Its public explanation, however, does not specify every detail of how an unresolved intent contributes to the immediate query result. The documented guarantee is that subsequent reads can see the indexes corresponding to a successfully written record, while asynchronous cleanup resolves outstanding intents.</p><p><strong>The broader architectural lesson</strong> is that maintaining a strongly consistent index involves more than making index writes synchronous. LedgerStore coordinates writes before accepting the record and uses the read path to resolve incomplete index operations. The system must handle failures on both sides of that boundary without allowing them to undermine its consistency guarantees.</p><p>That guarantee has a cost. Index intent writes and record writes must happen sequentially, increasing write latency. More importantly, a failure in any required index intent write causes the entire record insertion to fail. The more strongly consistent indexes a record requires, the more index operations its write depends on succeeding.</p><p><strong>This is an intentional trade-off:</strong></p><blockquote><strong>LedgerStore sacrifices some write availability rather than acknowledge a record whose required indexes cannot be guaranteed.</strong></blockquote><p>Uber explicitly recommends using strongly consistent indexes only when the business requirement justifies that cost.</p><p>But is a strongly consistent secondary index the only way to protect a financial decision? Not necessarily. If a workflow already knows the authorization’s unique identifier, it could query the authoritative record directly using its primary key, avoiding dependence on a potentially stale secondary index.</p><p>Another approach is to enforce idempotency through a transactional uniqueness constraint or conditional write, preventing duplicate financial operations even if an index lookup returns stale data, or by generating an authorization identifier from the application and sending it to the API.</p><p><strong>These alternatives have their own requirements: </strong>the primary key must be known, the database must enforce the relevant constraint atomically, and the application can preserve the authorization identifier across the payment lifecycle.</p><p>Strongly consistent secondary indexes matter when a workflow needs to locate records by other attributes while still requiring immediate visibility. Uber’s choice addresses that specific requirement, rather than establishing a universal rule for financial systems.</p><h3><strong>Eventually Consistent Indexes: When Stale Reads Are Acceptable</strong></h3><p>Most lookups do not demand any of this. The payment history page, internal dashboards, analytics-style queries over financial events: a few seconds of delay changes nothing about what the system decides. For these, Uber builds eventually consistent indexes in the background, using a process completely isolated from the online write path.</p><p>The implementation detail is worth one sentence: the background process uses materialized views from Docstore, Uber’s distributed database, to generate these indexes. But the architecture point is the isolation.</p><p>Because index construction never touches the write path, it cannot add latency to inserts and cannot fail them. The write path stays fast and available; the index converges a little later. This is the mirror image of the strong index trade. Where the strong index buys immediate visibility with coordination and availability, the eventual index buys a clean write path with delayed visibility.</p><p>If this sounds like the same consistency spectrum every database textbook draws, that is because it is. <strong>The difference is organizational discipline: </strong>the two index types exist side by side over the same records, and every new lookup is assigned to one side based on the consequence of staleness, not based on which is easier to build.</p><figure><img alt="This table lists the Index strategy you should choose based on the requirements and what are the trade-off." src="https://cdn-images-1.medium.com/max/662/1*eQ_aVaC8u-aDGLL801zOmg.png" /></figure><h3><strong>Time Range Indexes: Why Timestamp Partitioning Creates Hotspots</strong></h3><p>The third class serves a different purpose entirely. <a href="https://medium.com/@inderbindra/why-ubers-financial-database-does-not-trust-update-512f5492aa11"><strong>Part 2</strong></a> showed that LedgerStore seals history in time windows, typically thirty minutes, and offloads aging windows to cold storage. Both operations need to ask the same question: give me every ledger in this event-time range, in deterministic batches, at a volume orders of magnitude above what the other two index types handle. That is the time-range index, and that is where the story gets interesting, because partitioning directly by event time concentrates concurrent writes on the same partition, creating a throughput bottleneck.</p><p>Ledger events carry a business timestamp, and those timestamps tend to cluster around the current wall clock. Partitioning the index by timestamp creates a problem: <strong>writes arriving within the same time interval concentrate on the same physical partition.</strong></p><p>Uber illustrates this with approximately 1,000 peak trips per second. With a one-second partitioning interval and the write-capacity assumptions in Uber’s example, roughly 1,000 write capacity units (WCUs) could hit a single DynamoDB partition, approaching its per-partition write-capacity limit and triggering throttling.</p><p>Smaller time intervals might seem to solve the problem, but they introduce two trade-offs. As traffic grows, even finer intervals can develop hotspots. More intervals increase the number of reads required to retrieve a time range.</p><p>The underlying problem is the correlation between event timestamps and incoming write traffic. <strong>The workload concentrates writes, the database enforces partition-level throughput limits, and throttling becomes a bottleneck.</strong> That is why simply partitioning the index by time was insufficient for Uber’s workload.</p><p>Instead, Uber built two DynamoDB tables with opposite jobs. All online time index writes go to a <strong><em>buffer index</em></strong>, a temporary table whose entries are spread across M buckets by hashing the record modulo M. The hash spreads the write load uniformly, so no partition gets hot; M is chosen high enough to keep per-partition load calm and low enough to keep reads manageable.</p><p>Reads, though, need the opposite layout: a <strong><em>permanent index</em></strong> partitioned on timestamps aligned to N minute intervals, ten minutes in the reported design. A background process periodically batches the buffer contents into the permanent table, where throttling is harmless because it happens off the online path, then deletes the buffer tables. Reads scan N minute intervals with no scatter-gather.</p><figure><img alt="Architecture diagram of Uber’s DynamoDB time range indexing design, separating Write-Optimized (Buffer Index Table) and Read-Optimized (Permanent Index Table) Indexes. Incoming ledger index writes are distributed across hash-based buckets in a temporary buffer index. A background process batches entries into a permanent, timestamp-partitioned index optimized for time-range reads, introducing additional table lifecycle and coordination requirements." src="https://cdn-images-1.medium.com/max/1024/1*xEhQiL4sArMKyhog8-zb2w.png" /><figcaption>DynamoDB: Separating Write-Optimized (Buffer Index Table) and Read-Optimized (Permanent Index Table) Indexes</figcaption></figure><p>It worked, and it had a real cost: <strong>operational state</strong>. Somebody has to create the buffer tables on time, route reads to the right table, and coordinate the offload. Uber is honest that this bit them. If the temporary buffer tables weren’t created in time, writes couldn’t be accepted, and that failure mode caused availability incidents. The two-table design solved the physics problem and introduced an operations problem.</p><p>The Docstore redesign eliminates the operations problem. Docstore assigns a fixed number of shards to a variable number of physical partitions, and stores data sorted by primary key. Those two properties let Uber keep a single table for the time-range index, partitioned on the full timestamp. The full timestamp is granular enough that writes distribute uniformly, so no partition gets hot and no buffer table needs babysitting.</p><p><strong>Reads become bounded prefix scans: </strong>to fetch thirty minutes of data, scan each shard in ten-minute sub-windows, then scatter-gather across shards and merge the sorted results. Because Docstore’s shard count is fixed, we can know the number of read requests in advance. The same trick doesn’t transfer to DynamoDB, where the partition count keeps growing with table size.</p><figure><img alt="Architecture diagram of Uber’s Docstore time-range indexing design. Ledger index writes are distributed across shards in a single timestamp-partitioned table. Time range queries perform bounded prefix scans across the fixed set of shards, followed by scatter-gather and sorted merging to retrieve the matching index entries." src="https://cdn-images-1.medium.com/max/1024/1*UyoLO2lwdMvHPP8M3ELN_A.png" /><figcaption>Docstore: One Time-Range Index Table Using Bounded Shard Scans</figcaption></figure><p>Both designs solve the same problem, but their operational costs differ. DynamoDB required separate write-optimized and read-optimized index tables, along with background transfers and lifecycle coordination.</p><p>Docstore’s fixed shard count and sorted primary keys allowed Uber to consolidate those responsibilities into a single table with bounded range scans.</p><blockquote><strong>The broader lesson is that the same logical index may require a fundamentally different physical design depending on the storage engine’s capabilities.</strong></blockquote><h3><strong>How Uber Backfills and Validates New Indexes Without Downtime</strong></h3><p>New indexes get defined regularly as use cases evolve, and old ones get modified. Doing that by hand at this scale, hundreds of billions of ledgers, would be reckless, so <strong>Uber built the lifecycle into a state machine:</strong> create the index table, backfill it with historical entries, validate completeness, swap the new index in for reads and writes, decommission the old one.</p><p>Two of those steps deserve attention. The backfill reads historical data from cold storage. Because downloading is faster than processing, the pipeline is built with configurable rate limiting and batching, with the actual processing logic plugged in as a batch processor.</p><p><strong>The validation is the clever part:</strong> an offline job computes order-independent checksums at a fixed time window granularity over both the source of truth data and the new index table, then compares them. A missing or inconsistent index entry is expected to produce a checksum mismatch in the affected time window, allowing Uber to detect potential backfill errors. It is the same instinct as <a href="https://medium.com/@inderbindra/why-ubers-financial-database-does-not-trust-update-512f5492aa11"><strong>Part 2’s</strong></a> manifest, applied to indexes: prove completeness per time range, not per record.</p><h3><strong>2 Trillion Indexes, Zero Detected Inconsistencies</strong></h3><p>The numbers, all from Uber’s engineering write-up: <strong>more than two trillion unique indexes built on the new architecture</strong>, with not a single data inconsistency detected in over six months of production. No production incidents during the backfill. Uber also migrated the entire index corpus from DynamoDB to Docstore, consolidating its technology stack and reducing external dependencies.</p><p>As part of the broader LedgerStore re-architecture, Uber estimates annual <strong>savings </strong>of more than<strong> $6 million in DynamoDB spending.</strong> However,<strong> </strong>it does not separately quantify how much of that saving came specifically from index storage.</p><p>Notice what those numbers are measuring. <strong>Two trillion is indexes</strong>, not financial transactions; the trillion-scale figure in this series has always been about indexes, and it is worth keeping that distinction clean.</p><p>The interesting metric isn’t the size but the incident count: zero inconsistencies detected across a system whose entire job is never to disagree with the ledger. That is the invariant from the top of this article, holding at a scale where just making it consistent would have been a fine way to bankrupt the write path.</p><h3><strong>How to Choose the Right Index Consistency Model</strong></h3><p>Step back from Uber’s specifics and the framework is small enough to fit on an index card:</p><p>1. List the reads your system performs against critical state.</p><p>2. For each one, ask what breaks if the read is stale. Not staleness is ugly, but a stale answer can change a decision that moves money, inventory, or entitlements.</p><p>3. If nothing breaks, take the eventual index and keep your write path clean.</p><p>4. If something breaks, price the strong index honestly: serial coordination on writes, and a failed intent write fails the insert.</p><p>5. If the read is everything in this time window, design the partition scheme around your actual write correlation, and prefer the storage whose physical properties make that scheme operable.</p><p>The same reasoning applies well outside payments. An inventory reservation lookup that feeds an oversell decision is an authorization hold in disguise. A dashboard counting yesterday’s orders is a payment history page.</p><p>A common temptation is to make every index strongly consistent because stronger guarantees appear safer. But that adds coordination and failure dependencies to writes that may not need them.</p><p>The better approach is to evaluate each lookup based on its business consequences. If stale data can lead to an incorrect financial decision, the system must protect that decision, whether through a strongly consistent index, an authoritative lookup, or another mechanism that enforces the invariant. Uber’s architecture shows why consistency should be a deliberate choice rather than a system-wide default.</p><blockquote><strong>An index stops being a performance optimization the moment a business decision depends on it being correct.</strong></blockquote><h3><strong>Next: Migrating 250 Billion Records Without Losing Consistency</strong></h3><p>Uber had designed indexes that could make correctness-critical records immediately visible. But those indexes, and the financial history behind them, were originally stored in DynamoDB.</p><p>Moving that history to Docstore was not just a data-copying exercise. Uber needed to migrate more than <strong>250 billion records (~300 TB)</strong> while financial transactions continued arriving. During the transition, reads could reach either database, asynchronous writes could temporarily leave the two systems out of sync, and the migration still had to preserve read-your-writes consistency.</p><p><strong>That raises a harder architectural question:</strong></p><blockquote><strong>How do you switch the source of truth between two live databases without allowing even one incorrect read?</strong></blockquote><p>That’s the challenge we’ll explore in Part 4.</p><h3>Before You Go</h3><ul><li>Please take a moment to like the post, share your thoughts, and follow for more articles like this.</li><li>You can also follow me on <a href="https://www.linkedin.com/in/inderbindra">LinkedIn</a>.</li></ul><h3>References</h3><ol><li><a href="https://www.uber.com/ca/en/blog/how-ledgerstore-supports-trillions-of-indexes/"><strong>How LedgerStore Supports Trillions of Indexes at Uber </strong></a>— Uber Engineering, the primary source for this article: the three index classes, the intent-based two-phase commit protocol for strongly consistent indexes, the DynamoDB buffer and permanent index design, the Docstore redesign, index lifecycle management, backfill, validation, and the reported scale and savings figures.</li><li><a href="https://www.uber.com/ca/en/blog/dynamodb-to-docstore-migration/"><strong>How Uber Migrated Financial Data from DynamoDB to Docstore</strong></a><strong> </strong>— Uber Engineering. Background on LedgerStore’s sealing, revisions, and cold storage tiering, which the time-range indexes serve.</li><li><a href="https://www.uber.com/ca/en/blog/schemaless-sql-database/"><strong>Evolving Schemaless into a Distributed SQL Database</strong></a> — Uber Engineering. Background on Docstore’s fixed shard count and sorted primary keys, the two properties the redesigned time range index relies on.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=737025e5ee74" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/how-uber-keeps-2-trillion-indexes-consistent-without-slowing-every-write-737025e5ee74">Why Uber Needs Strong Consistency for Some of Its 2 Trillion Indexes</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Uber’s Financial Database Does Not Trust UPDATE]]></title>
            <link>https://blog.stackademic.com/why-ubers-financial-database-does-not-trust-update-512f5492aa11?source=rss-6bd396d9b5c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/512f5492aa11</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[database-architecture]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Inderpreet Singh Bindra]]></dc:creator>
            <pubDate>Tue, 13 Oct 2026 13:01:02 GMT</pubDate>
            <atom:updated>2026-10-21T23:40:35.951Z</atom:updated>
            <content:encoded><![CDATA[<p>How Uber uses append-only records, cryptographic proofs, and revisions to correct financial mistakes without rewriting history.</p><figure><img alt="Conceptual illustration of Uber’s financial database architecture, contrasting a crossed-out SQL UPDATE operation with an append-only financial ledger. Immutable transaction records, corrections through revisions, and a signed manifest illustrate how LedgerStore preserves verifiable financial history without overwriting original records." src="https://cdn-images-1.medium.com/max/1024/1*DwKqGvJZSdia_1HhD0rcAA.png" /><figcaption>Why Uber’s LedgerStore favors append-only records, signed manifests, and revisions over rewriting financial history. (Conceptual illustration)</figcaption></figure><h3><strong>The Instinct To Erase</strong></h3><p>A trip fare is recorded incorrectly: $81.40 instead of $18.40. Every engineer who has ever touched a database has the same instinct: run an <strong><em>UPDATE</em></strong>, fix the row, move on; in most systems, that is fine.</p><p>In a financial ledger, that <strong><em>UPDATE</em></strong> just destroyed evidence. Nobody can ever again answer the questions an auditor, a regulator, or an angry driver will eventually ask:</p><ul><li>What was originally recorded,</li><li>When did it change,</li><li>Who changed it, and why?</li></ul><p>Uber’s answer is architectural, not procedural. With <strong>tens of billions of financial transactions every quarter, </strong>each a potential dispute, <strong><em>“just be careful with UPDATEs”</em></strong> isn&#39;t a strategy.</p><p>LedgerStore, the immutable ledger behind Gulfstream (Uber’s fifth-generation collection and disbursement platform), does not offer UPDATE as a concept. Records are append-only.</p><p>A correction is a new record that references the old one, carries a business justification, and leaves the original readable forever. And because “immutable” is a claim rather than a guarantee, LedgerStore wraps its records in a verification machine built from <strong>three mechanisms:</strong> <strong>sealing, manifests, and revisions</strong>.</p><p>This article covers that machine, why each part exists, what it costs, and what it cannot do.</p><h3>Series Context</h3><p>This is <strong>Part 2</strong> of a six-part series on how Uber built a money-movement architecture that stays correct at scale.</p><p>In <a href="https://medium.com/@inderbindra/how-uber-rebuilt-its-money-movement-architecture-without-losing-financial-correctness-939a9b615c48"><strong>Part 1</strong></a>, we mapped the full architecture: Gulfstream turns business events into balanced financial Orders, while LedgerStore preserves those Orders as verifiable history.</p><p>Now we go inside LedgerStore to answer a harder question:</p><blockquote><strong>How do you correct financial mistakes without rewriting the past?</strong></blockquote><h3>The Four Guarantees LedgerStore Must Preserve</h3><p>Uber documents four data-integrity guarantees for LedgerStore, introduced in 2018 to back Gulfstream:</p><p>1. Individual records are immutable.</p><p>2. Corrections are trackable.</p><p>3. Unauthorized data changes and inconsistencies must be detected.</p><p>4. Queries are reproducible within a bounded time after write.</p><p>Everything below supports those four sentences.</p><p>Note the careful wording: the ledger does not promise that every record is <strong>correct; </strong>the correctness of the business logic belongs to Gulfstream, upstream. LedgerStore promises that whatever was written stays written, stays attributable, and stays checkable. That distinction matters, because it is what makes the guarantees achievable at all.</p><h3><strong>Why UPDATE Is The Wrong Primitive</strong></h3><p>Three obvious alternatives, each treated on its merits.</p><p><strong>Allow UPDATEs And Keep An Audit Log:<br></strong>Most databases offer this, and for many workloads it is enough. The weakness is structural: the audit log is a side channel, maintained by a different code path than the data, with its own failure modes. It answers “what changed” only if every write path remembered to log, in the right order, without loss. Architecturally, an audit log introduces a second representation of history whose completeness must itself be guaranteed. The ledger’s answer is to make the history <strong><em>be</em></strong> the data, not a commentary on it.</p><p><strong>Rely On The Storage Engine’s Durability:<br></strong>DynamoDB, LedgerStore’s original backend, can promise that your write will not be lost. But durability is <strong><em>“your write won’t disappear.”</em></strong> Immutability is <strong>“your write won’t be <em>changed</em>.”</strong> No general-purpose database promises the second, because it is a business constraint rather than a storage property. The layer that understands what a financial record has to enforce it.</p><p><strong>Sign Each Record Cryptographically:<br></strong> Per-record signatures detect modification but not omission. A deleted record leaves no checksum behind to mismatch. This is the subtle one, and it is the reason LedgerStore’s design centers on the <strong><em>manifest</em></strong>: a signed <strong><em>content list</em></strong> for a time range. Only a signed enumeration of <strong>“these records, and no others, belong to this window”</strong> makes completeness provable. Checksums prove integrity; the manifest proves completeness.</p><p>So the shape of the solution is forced: immutability must live in the ledger layer, not the storage layer; corrections must be first-class records rather than log entries; and completeness must be proven per time range rather than per record.</p><h3>How LedgerStore Makes History Verifiable</h3><p>Append-only prevents legitimate callers from rewriting history. Sealing, manifests, and revisions solve the harder problem: proving what history contains while still allowing the business to correct itself.</p><figure><img alt="Architecture diagram of Uber’s LedgerStore showing how append-only financial records are grouped into time windows, verified using four checksums across two regions, and sealed with signed manifests. Corrections are preserved as new revisions, allowing queries to retrieve either the original or corrected financial history without overwriting records." src="https://cdn-images-1.medium.com/max/1024/1*oOmOqozryfXRWpxVacZMMw.png" /><figcaption>Figure 1: How LedgerStore turns append-only financial records into verifiable history through cross-region validation, signed manifests, and revisions that preserve the original record.</figcaption></figure><p><strong>Records: Append-only By Construction<br></strong>A LedgerStore datastore is a collection of tables, and each table holds records modeled as documents. Writes append - LedgerStore is an append-only store, so the update path that every other database offers simply isn’t part of the model.</p><p>LedgerStore removes in-place mutation from the normal application write model. Applications using the LedgerStore API do not correct history by overwriting records; corrections are represented explicitly through revisions. Immutability stops being a policy that engineers must remember and becomes a property they cannot violate. That is the cheapest kind of enforcement: the kind with no code path to get wrong.</p><p><strong>Sealing: Closing A Time Range<br></strong>In the architecture Uber describes, LedgerStore groups data into 30-minute sealing windows. When a window is closed, signed, and sealed, no further writes are permitted, and any query reading only sealed windows is guaranteed reproducible.</p><p>The word <strong>“closed” </strong>is doing heavy work, so here is what closing entails. Before a window seals, LedgerStore runs a multi-pass verification: it reads the window’s data from the local region and computes a checksum (C1), then tails the database change stream in the same region and computes a second checksum (C2). It repeats both steps in a second region (C3, C4). The window seals only if all four checksums agree across both regions. If the write path and the stream disagree anywhere a write the stream never saw, a stream entry with no corresponding write — the window stays open until the discrepancy is resolved.</p><p>Three things are worth noticing. First, the sealing process trusts neither the write path nor the stream alone; it trusts their <strong><em>agreement</em></strong>, in two regions. Second, sealing does not need to be real-time. Uber processes the change stream in batches with Spark (capable of around 50K records per second) rather than a streaming engine like Flink, precisely because a bounded delay before a window closes is acceptable, a cheaper, simpler choice once you accept that finality lags writes by minutes rather than milliseconds. Third, the 30-minute window size is itself a trade-off knob, which we will return to.</p><p><strong>Manifests: The Signed Content List<br></strong>Sealing produces a manifest for each (datastore, table, time range, revision): the time range, the list of records in it with their checksums, and a signature over all of it made with a key pair that only LedgerStore holds. With the signature and the content list, LedgerStore can detect records changed, added, or removed through any unauthorized channel and applications can fetch and retain signed manifests to re-validate history later, independently.</p><p>This is the mechanism that squares the circle from the previous section. Individual record checksums catch modification. The signed content list catches addition and deletion. Together they make the claim <strong>“this is everything that happened in this window, and nothing else”</strong> checkable by anyone holding the manifest and the public key.</p><p><strong>Revisions: Corrections Without Erasure<br></strong>What about a legitimate correction to an already-sealed window, the $81.40 fare, discovered an hour later? That is what revisions are for. A revision is a table-level entity containing the record corrections and their business justifications. The originals stay; the corrections are added alongside them; queries can run at a specific revision. “What did the ledger say on March 3rd?” and “What does it say now?” are both answerable, from the same store. <strong>Guarantee 4: reproducible queries survive correction, which is the entire point: the ledger is allowed to learn, but never allowed to forget.</strong></p><p><strong>Why Sealed History Can Move to Cold Storage?<br></strong>Sealing has a second job that is easy to miss: it defines the unit of aging. LedgerStore offloads data to cold storage at sealing-window granularity, and provides data tiering <strong>“out of the box in a transparent, secure, and efficient manner.”</strong> This works because ledger reads skew young. Uber notes that data is mostly read within a few weeks or months of being written, so sealed windows naturally graduate from hot storage to cold as they age.</p><p>The manifest is what makes that graduation trustworthy: verifiability is a signed content list, not a property of any particular storage backend, so a window remains provably complete and untampered wherever its bytes currently live.</p><p><strong>Does Immutability Prevent Schema Evolution?<br></strong>Sealing closes a time range for changes; it does not freeze the schema definition forever. Docstore allows records written under different schema versions to coexist without requiring a full table rebuild. That is compatible with LedgerStore’s immutable-history model: schema evolution does not inherently require rewriting every historical record.</p><h3><strong>A Correction, End-To-End (Illustrative)</strong></h3><p>The identifiers and timings below are invented to show the mechanism; the mechanism itself is Uber’s documented design.</p><p>At 14:02, a trip completion writes record `fare-9f31`: rider charged $81.40. It lands in the sealing window [14:00, 14:30). At 14:30, the window closes: four checksums agree across two regions, the manifest is generated: content list, checksums, signature, and the window seals. Any query over [14:00, 14:30) is now reproducible.</p><p>At 14:47, the fare dispute arrives: the toll was never taken. LedgerStore cannot touch the sealed window and does not want to. Instead, it appends a correction record to revision 1 of the table, referencing `fare-9f31`, with the business justification “toll charge reversed; toll road not used.” Both records now exist. A query at revision 0 returns the world as it looked at 14:30 — the $81.40 charge, exactly as originally recorded. A query at revision 1 returns the corrected view. An auditor can replay either one, months later, and get the same answer both times.</p><p>Notice what did not happen: no UPDATE, no overwrite, no <strong><em>“current value”</em></strong> that silently absorbed the past. The correction is <strong>news</strong>, and like all news in this system, it is appended.</p><h3><strong>What The Signatures Cannot Do (Illustrative Failure)</strong></h3><p>Suppose someone with storage-level access modifies a record directly, bypassing LedgerStore entirely. Nothing stops the bytes from changing — signatures detect; they do not prevent. But the next background validation recomputes the window’s checksums and compares them against the signed manifest. The content list no longer matches: a checksum differs, or a record appears that the manifest never listed. The discrepancy can be detected and localized to the affected sealing window.</p><p>Now consider the harder question: what does a valid signature actually prove? It proves the manifest was produced by the holder of the private key and has not been altered since. It does not prove the original write was correct business logic; a perfectly signed record can still encode a wrong fare; that is Gulfstream’s problem, not the ledger’s. And the whole scheme leans on two things outside the cryptography: key management (who holds the signing key, how it rotates) and access control on the underlying store (who can write records in the first place). Uber’s wording is precise and worth quoting back: unauthorized changes “must be <strong><em>detected</em></strong>.” Detected — not prevented. The signature is an alarm, not a lock.</p><p>A second failure worth tracing: the four checksums disagree at seal time. Until the checksums agree, that window cannot be treated as sealed, so LedgerStore cannot extend its sealed-range reproducibility guarantee to it. Here the system explicitly sacrifices the availability of “closed” status for the correctness of the guarantee: a window should stay open rather than to seal a lie. That is the availability-versus-correctness trade-off made visible in a single code path.</p><h3>The Cost of Making History Verifiable</h3><p>Every guarantee here has a price, and the design is honest about them.</p><p><strong>Finality lags writes -</strong> A window is not sealed the instant its last write lands; reproducibility is a property of sealed ranges, not of fresh ones. Architecturally, window size creates a natural trade-off: shorter windows could reduce the time before a range becomes sealable, but increase manifest and verification overhead. There is no free choice of window size, only a chosen point on that curve.</p><p><strong>Corrections are heavier than UPDATEs: </strong>Each correction is a new record plus a justification plus revision bookkeeping, and every reader must be revision-aware. You trade write-path simplicity for an audit trail that cannot be misplaced, because it was never a separate thing to lose.</p><p><strong>Verification is real infrastructure: </strong>Cross-region checksum agreement over every window, change-stream tailing at tens of thousands of records per second, manifest generation and signing; this is a standing compute bill. It is justified the way all correctness spending is justified: the cost of <strong><em>unverifiable</em></strong> financial history, discovered during a dispute or an audit, is larger.</p><p><strong>The guarantee has a boundary: </strong>Sealing proves that the ledger’s contents are complete and untampered <strong><em>as written</em></strong>. It says nothing about whether the business event was modeled correctly upstream. Immutability preserves mistakes as faithfully as it preserves truth, which is exactly why revisions exist, and why the business justification travels with the correction.</p><h3>How Uber Validated 250 Billion Migrated Records</h3><p>During the DynamoDB-to-Docstore migration, Uber compared manifests from the two backends and reports validating more than <strong>250 billion records, roughly 300 TB</strong> within a week. That is an important architectural payoff: an integrity mechanism designed for normal ledger operation also became a way to prove migration correctness at scale.</p><p>The migration itself shadow writes, dual reads, and cutover is Part 4’s story. The point here is narrower:</p><blockquote><strong>When integrity proofs are built into the system, they can become reusable validation mechanisms.</strong></blockquote><h3><strong>The Transferable Lesson</strong></h3><p>For records that function as authoritative history, prefer making mutation structurally difficult rather than relying only on developer discipline. Whether that requires an append-only ledger, temporal tables, event sourcing, or a conventional audit log depends on the consequences of losing history.</p><p>LedgerStore takes the stronger route: corrections become first-class records that carry their business justifications, so the system can correct history without erasing it. And completeness is verified with signed content lists over time ranges, because per-record checksums alone cannot reveal that a record has disappeared.</p><p>The core trade-off of this article:</p><blockquote><strong>Verification latency and correction cost, in exchange for history you can prove.</strong></blockquote><p>For a financial ledger, that is not a hard call. For your system, the question is which records are history and how much engineering you are willing to spend to make that history provable.</p><h3><strong>Next: Finding Anything In 250 Billion Records</strong></h3><p>Immutable, sealed, verified history is useless if you cannot look anything up. The obvious answer is indexes, but an index is a second representation of the truth, and it can disagree with the first. What good is a manifest-proven record if the lookup path that finds it can lie, even briefly?</p><p><a href="https://medium.com/@inderbindra/how-uber-keeps-2-trillion-indexes-consistent-without-slowing-every-write-737025e5ee74"><strong>Part 3</strong></a> is about LedgerStore’s three index classes: strongly consistent, eventually consistent, and time-range.</p><p>And the single question each one answers:</p><blockquote><strong>When does a stale lookup become a correctness violation?</strong></blockquote><h3>Before You Go</h3><ul><li>Please take a moment to like the post, share your thoughts, and follow for more articles like this.</li><li>You can also follow me on <a href="https://www.linkedin.com/in/inderbindra">LinkedIn</a>.</li></ul><h3><strong>References</strong></h3><p>Drawn from Uber Engineering’s published posts:</p><ul><li><a href="https://www.uber.com/nz/en/blog/dynamodb-to-docstore-migration/">How Uber Migrated Financial Data from DynamoDB to Docstore</a> — LedgerStore, Data Integrity (Sealing, Manifests, Revisions), and Data Sealing sections. All LedgerStore mechanisms, guarantees, checksum procedures, tiering behavior, and migration figures in this article come from this post.</li><li><a href="https://www.uber.com/ca/en/blog/how-ledgerstore-supports-trillions-of-indexes/">How LedgerStore Supports Trillions of Indexes at Uber</a> — The <strong><em>“tens of billions of financial transactions every quarter”</em></strong> scale figure, and time-range indexes serving both sealing and cold-storage tiering.</li><li><a href="https://www.uber.com/us/en/blog/schemaless-sql-database/">Evolving Schemaless into a Distributed SQL Database</a> — Schema-on-write with evolution without full table rebuilds (used only for the schema-evolution implication, stated as interpretation).</li><li><a href="https://www.uber.com/ca/en/blog/money-scale-strong-data/">Revolutionizing Money Movements at Scale with Strong Data Consistency</a> — Gulfstream’s guarantee that orders are immutable.</li></ul><p>The worked example and the back-channel tampering scenario are illustrative.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=512f5492aa11" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/why-ubers-financial-database-does-not-trust-update-512f5492aa11">Why Uber’s Financial Database Does Not Trust UPDATE</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Uber Rebuilt Its Money Movement Architecture Without Losing Financial Correctness]]></title>
            <link>https://blog.stackademic.com/how-uber-rebuilt-its-money-movement-architecture-without-losing-financial-correctness-939a9b615c48?source=rss-6bd396d9b5c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/939a9b615c48</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[fintech]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Inderpreet Singh Bindra]]></dc:creator>
            <pubDate>Wed, 07 Oct 2026 12:06:01 GMT</pubDate>
            <atom:updated>2026-10-22T00:15:47.978Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Inside the architecture Uber evolved through years of scale pressure, and the invariant that shaped every decision along the way</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*thwQj13d-43M29OQJSfA8A.png" /></figure><p>A payment system can survive almost anything a normal distributed system survives: a timed-out request, a consumer crashing mid-message, a node vanishing and coming back with no memory of what it missed. In most systems, you retry, log it, and move on.</p><p>A payment system <strong>cannot </strong>survive losing track of where the money went. If a distributed cache loses an update, you get a stale page. If a financial ledger loses an update, you get a driver whose payout is short, a rider charged twice for the same ride, or a number that quietly stops being true and nobody notices until an audit six months later.</p><p>Uber’s money-movement platform processes <strong>tens of billions of financial transactions a quarter</strong>, across riders, drivers, eaters, couriers, restaurants, and merchants, in thousands of cities with different tax and payment rules. The hard problem isn’t the scale; many systems handle volume by throwing hardware at it.</p><p>The hard problem is that every transaction must be individually correct and permanently explainable, and survive the retries, duplicate messages, out-of-order events, and database migrations a system this size generates just by existing.</p><p>Uber didn’t design for that requirement from day one; it backed into it, one architectural failure at a time.</p><p>Follow a single ride’s money through the layers this article maps and you’ll touch every one of them: the fare is calculated, then adjusted days later when a tip lands; those events are recorded as balanced Orders; the Orders are processed asynchronously, survive retries and reordering, and land in immutable history; indexes answer <strong><em>“was the hold cleared?”</em></strong> and <strong><em>“what’s the driver’s payout this month?”</em></strong> and eventually the entire history moved from one database to another without a single customer noticing. Each layer exists because one of those steps broke at some point.</p><h3>The Architecture Assumed Riders Pay and Drivers Get Paid. Cash Trips Disagreed.</h3><p>Before Gulfstream, Uber’s payment platform was really two separate systems:</p><ul><li><strong>Collections -</strong> which took money from riders and eaters, and</li><li><strong>Disbursements -</strong> which paid out drivers and restaurants.</li></ul><p>At a high level, the architecture looked something like this:</p><figure><img alt="This diagram showcase the Uber Business Events i.e. Collection System &amp; Disburesement System." src="https://cdn-images-1.medium.com/max/452/1*znjQ7Ap05g-SYxijATH8xA.png" /></figure><p>That split isn’t an unreasonable design. Separate workflows, clear ownership, independent evolution. It breaks the day a participant refuses to stay in their lane. Uber’s example is cash trips: the driver collects cash directly from the rider, and suddenly Uber has to collect its commission <em>from the driver</em>. The payee became the payer.</p><figure><img alt="This diagram showcase the Payment flow between the normal trip vs the cash trip." src="https://cdn-images-1.medium.com/max/621/1*gV9N7pKDXCvQd23zsumgsQ.png" /></figure><p>The architecture had encoded <strong><em>“rider pays, driver gets paid”</em></strong> as a structural assumption, and cash trips don’t respect it. Two consequences, in Uber’s own telling: no holistic view of end-to-end money movement, and every new payment feature got slower to build.</p><p>Why not just add an orchestration layer over the two systems and route around the edge cases? Because the boundary itself was the problem, a workflow where the same person is both payer and payee still has to cross systems divided on exactly those roles. Patching exceptions onto each side works until the exceptions <strong><em>become</em></strong> the domain model.</p><p>So Uber rebuilt: Gulfstream, its fifth-generation platform, one integrated, SOX-compliant system that collects or disburses money for any user, regardless of role.</p><blockquote><strong>What should the common financial model actually look like?</strong></blockquote><h3>A Receipt Says Something Happened. Accounting Tells Where the Money Went.</h3><p>The old model was transaction-oriented: a record saying a rider paid $20 for a trip. Fine as a receipt. Useless for answering:</p><ul><li>How much left the payer’s account?</li><li>How much entered the driver’s?</li><li>How much became Uber’s revenue?</li><li>Do they reconcile?</li><li>What happens when a tip arrives tomorrow or a refund lands next week?</li></ul><p>Uber replaced the transaction record with double-entry accounting, a centuries-old discipline built on one rule:</p><blockquote><strong>Money never appears or disappears, it only moves between accounts, and every movement is recorded as a matching pair so the total always nets to zero.</strong></blockquote><p>The model is a hierarchy. A <strong>Job</strong> is a real-world event, like a trip. A Job holds multiple <strong>Orders: </strong>the original fare, a later adjustment, a tip added after the fact. Each Order holds <strong>Order Entries</strong>, and every Entry moves a specific amount between two accounts.</p><p><strong>For Example:</strong> A $20 trip made up of an $18 fare and a $2 service fee.</p><figure><img alt="This table displays the transaction breakup of an Uber trip." src="https://cdn-images-1.medium.com/max/408/1*bqHyALnhQhoKXi-9x2VjjQ.png" /></figure><p>The invariant is simple:</p><pre>SUM(Order Entries) = 0</pre><p>Adjustments get somewhere natural to live; a late tip is just another Order under the same Job, netting to zero on its own:</p><figure><img alt="This diagram showcase how the payment gets credited and debits from and to different accounts for a trip." src="https://cdn-images-1.medium.com/max/535/1*O7WjQQFIGM_yMv3FI3c61g.png" /></figure><p>If a code change ever lets entries sum to anything but zero, the model makes that easy to detect rather than easy to hide. That gives us the first governing property of the whole system:</p><blockquote><strong>Every financial event must balance to zero, and a duplicate delivery attempt must never be allowed to double its effect.</strong></blockquote><h3>Write It Down First. Process It Later.</h3><p>Creating an Order is not processing it. Processing means contacting a payment provider, moving money between escrow accounts, handling provider failures, none of which happens just because a record was written. Doing it all inline, on the request that created the Order, is simpler to reason about, and for lower-volume systems it’s often the right call. At Gulfstream’s volume, it would tie the entire write path’s availability to every downstream dependency.</p><p>So Gulfstream splits the two. An Order-insertion service creates and persists Orders, then publishes them to a messaging layer. A separate Order-processing service consumes them, routes collection and disbursement requests, and emits result Orders.</p><p><strong>Conceptually:</strong></p><figure><img alt="This diagram represents the business request flow from order insertion to oder processing." src="https://cdn-images-1.medium.com/max/428/1*mrfh_bHvR-Er4xOdW5AOnA.png" /></figure><p>Standby consumers run across regions, so a regional outage doesn’t stop processing. The synchronous alternative: create, call provider, update accounts, respond, all inline, would couple the caller’s latency and availability to every downstream step. Async buys real resilience. It also reopens every problem synchronous code quietly hides: duplicate delivery, retries, crashes, out-of-order arrival, partial failure.</p><h3>The Queue Saved Availability<strong>. T</strong>hen Tried to Charge the Rider Twice</h3><p>An Order processes successfully, but the acknowledgement is lost. The message is delivered again. If processing it again moves the money again, the queue just turned routine infrastructure failure into a financial error.</p><p>Gulfstream’s answer is deterministically generated IDs: every user, Job, and Order gets an identifier derived from the request itself, not assigned randomly. Two identical requests produce the <strong><em>same</em> </strong>Order ID, not two Orders. Orders are immutable and persisted before processing, so a redelivery is recognized, not re-executed.</p><blockquote><strong>Message delivery may repeat.<br>Financial effect must not.</strong></blockquote><p>This is why <strong>idempotency </strong>is important in payment systems.</p><h3>Every Event Was Valid. The Balance Was Still Wrong.</h3><p>Retries aren’t the only hazard. While migrating hundreds of millions of customers from the legacy platform to Gulfstream, both systems had to run at once, and async writebacks to the legacy system didn’t preserve order. Four valid events could arrive as 1 → 4 → 2 → 3 instead of 1 → 2 → 3 → 4, and the account would land in the wrong state.</p><p><strong>Uber’s fix:</strong> make ordering a property of the business data, not an assumption about the transport. Every account change is persisted to an <strong>EntityChangeLog </strong>with a per-user version number, and writebacks are serialized by that version. A version gap triggers a retry, then a reconciliation service replays the missing Orders in order.</p><figure><img alt="This diagram lists different operations Message Transaport and Entity Change Log" src="https://cdn-images-1.medium.com/max/711/1*CX2C08b8EzTcW10Rw8VgBg.png" /></figure><p>A more general principle applies past this one migration:</p><blockquote><strong>If business correctness depends on order, encode that order in the business state itself. Don’t assume the transport will preserve it forever.</strong></blockquote><h3>The Ledger That Refuses to Forget</h3><p>Representing money correctly and processing it safely still leaves the audit problem: a financial system must answer, months later, exactly what happened and prove the answer wasn’t quietly altered.</p><p>Suppose a bill was recorded as $15 when it should have been $10. The obvious fix is:</p><pre>UPDATE bill SET amount = 10 WHERE id = 123;</pre><p>That query fixes the number and destroys the evidence: no record that the $15 ever existed, no timestamp, nothing for an auditor or fraud investigator to reconstruct. The correct fix appends a $5 refund next to the original $15. History now tells the truth: a mistake happened and was corrected.</p><p>Uber built that discipline into <strong>LedgerStore (2018)</strong>, with <strong>four integrity guarantees:</strong></p><ul><li>individual records are immutable,</li><li>corrections are trackable,</li><li>unauthorized changes or inconsistencies can be detected, and</li><li>query results stay reproducible for a bounded period after they’re written.</li></ul><p>The point isn’t that a relational database <strong><em>couldn’t</em></strong> do append-only; it’s that Uber wanted those guarantees provided once by a shared platform, not re-implemented as discipline by every team. LedgerStore is the boundary where the write path itself refuses to do anything but append.</p><p>Second governing property:</p><blockquote><strong>Once something is written to the ledger, history must stay recoverable and provably untouched, even as the business keeps correcting it.</strong></blockquote><h3>Your Index Is Fast. Is It Telling the Truth?</h3><p>Durable truth is half the problem; something has to <strong><em>find</em> </strong>it.</p><ul><li>Was this trip’s authorization hold cleared?</li><li>What does this driver’s payout look like this month?</li><li>What happened to the order a customer is disputing right now?</li></ul><p>At Uber’s scale that’s over <strong>two trillion indexes</strong> across <strong>hundreds of billions of records,</strong> and an index is a performance knob until a business decision depends on it being current.</p><p>Take a credit-card authorization hold. When a trip starts, Uber holds the estimated fare on the rider’s card; when it ends, the system must answer one question: is there an active hold for this trip right now?</p><p>If the index lags the record for even a moment, the lookup returns nothing, the system concludes no hold was ever placed, and it creates a fresh charge, leaving the rider with a pending hold and a separate charge. Uber’s engineers cite exactly this as why certain indexes can’t lag. Not an incident that happened; a failure the design exists to prevent.</p><p>So some indexes are <strong>strongly consistent</strong>: the record write and the index write coordinate, so a lookup sees the write immediately. Others, like your in-app receipt history, are <strong>eventually consistent</strong>: nobody’s financial position changes if a receipt appears seconds late.</p><figure><img alt="This diagram depicts how to choose consistency while creating indexes." src="https://cdn-images-1.medium.com/max/524/1*1uHoRzuVeizT4qLzY9tIDg.png" /></figure><p>Strong consistency prices every write with coordination cost and turns an index hiccup into a failed write. Uber refused that trade globally and priced it per index instead. That’s a business question before it’s a database setting.</p><p>Third governing property:</p><blockquote><strong>A correctness-critical index can never be allowed to contradict the ledger it represents, but not every index needs to be correctness-critical.</strong></blockquote><h3>DynamoDB Didn’t Fail. The Bill Did.</h3><p><strong>LedgerStore’s</strong> first backend was DynamoDB, and it ran fine for years. The pressure built up operationally and economically, not as a correctness failure. Ledger timestamps cluster around <strong><em>“now,”</em></strong> so writes hammered a narrow set of partitions; Uber’s workaround, a buffer table fanned across partitions, batch-consolidated into a read-optimized table, worked, but meant running two tables plus a state machine to keep them in sync, and under-provisioned buffers had caused their own availability incidents.</p><p>Running LedgerStore on DynamoDB had simply become expensive, and every extra database technology in the portfolio added fragmentation. Staying put was a real option, meaning no migration of hundreds of billions of records, but it meant carrying the cost and complexity forever.</p><p>Uber chose its own <strong>Docstore </strong>instead: a document model’s flexibility with relational schema enforcement and transactional guarantees, grown out of Schemaless (too rigid) and Cassandra (too operationally immature at Uber’s scale, and its eventual consistency pushed complexity into every app). The one missing piece, a change-data-capture stream called Flux, Uber built itself. Docstore’s consistency boundary is the partition; strict serializability within one, no atomicity claimed across partitions.</p><h3><strong>Moving 250 Billion Records Without Anyone Noticing</strong></h3><p>By the time of the migration, the dataset held more than <strong>250 billion records, ~300 terabytes, </strong>and the move had to happen with no customer involvement, no downtime, read-your-writes consistency throughout, existing SLOs intact, and a way back at every stage.</p><p>Stop-the-world was the simplest migration and failed every requirement. Synchronous dual writes, every write landing in both databases or failing — coupled each write’s latency and availability to <strong><em>both </em></strong>databases; Uber rejected it and shadowed Docstore asynchronously instead, repairing anything that failed to land.</p><p><strong>The cutover ran in stages:</strong> backfill history, shadow live writes, read from both and reconcile, promote Docstore, retire DynamoDB with a rollback path at every step.</p><p><strong>The result:</strong> no production incidents, no rollbacks, better latency, roughly <strong>$6 million a year</strong> saved. And the quiet payoff: LedgerStore’s external contract never changed. The database had been an implementation detail from the start, so swapping it never touched Gulfstream’s business logic.</p><blockquote><strong>A high-risk migration is safer when every stage preserves a path forward and a path backward.</strong></blockquote><p>Throughput proves capacity. Reconciliation proves correctness. For financial infrastructure, you need both; <strong><em>“it handled the traffic”</em></strong> was never the bar.</p><h3>The Whole System on One Napkin</h3><p>Pulled together, the architecture reads as a set of layers, each answering a question the one before it can’t:</p><figure><img alt="This table list all the components involved in financial transaction and what each component does." src="https://cdn-images-1.medium.com/max/712/1*io9kcvk0ksG0-dg4NKGrBA.png" /></figure><p>Compare that with where the story started:</p><figure><img alt="This is comparsion diagram depicting the before and after of the Uber business events and how the transactions were saved and processed." src="https://cdn-images-1.medium.com/max/692/1*q_4hnaxYGA5nEgLHGh4_Aw.png" /></figure><p>Gulfstream no longer needs to know or care which role a participant is playing, and LedgerStore didn’t need to be rewritten when the database underneath it changed. Both are consequences of drawing boundaries around what has to stay true, rather than around org charts or role labels, arguably the most portable lesson in this system.</p><p>Most teams’ mistake isn’t picking the wrong database; it’s never writing down, plainly, what must always remain true about their data <strong><em>before</em> </strong>picking one.</p><h3><strong>A Decision Framework Worth Keeping</strong></h3><p>Before reaching for a consistency model, a queue, or a new database, it’s worth running through the same sequence this system was forced through, in order:</p><p>1. Identify the invariant that must never become false, not <strong><em>“the system should be consistent,” </em></strong>but the specific business fact, like <strong><em>“every Order must balance to zero.”</em></strong></p><p>2. Identify which reads participate in a decision that could violate that invariant if they’re stale, and which reads are purely informational.</p><p>3. Decide where atomicity actually ends: one row, one partition, one service, or across a boundary that needs its own coordination.</p><p>4. Work out what happens on duplicate delivery and out-of-order arrival before you write the retry logic, not after.</p><p>5. Only then price the coordination cost of protecting the invariant, and decide whether that cost is worth paying for this specific piece of data.</p><p>One more, implied by the migration above but worth stating plainly: <strong>design the path from old to new as part of the system, not as deployment housekeeping.</strong> If the only safe route to your target architecture is a hope and a maintenance window, the architecture is incomplete.</p><p>Uber’s answers produced Gulfstream, LedgerStore, per-index consistency choices, and eventually Docstore. A different workload with different invariants would produce a different stack; that’s the point.</p><p>The lesson worth keeping isn’t the technology list; it’s that the architecture got exactly as complicated as the invariant demanded, one forced decision at a time.</p><h3><strong>What’s Next</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RYeOeokrBLTlaEabPvAvvA.png" /></figure><p>This was the map; the depth lives in the five articles ahead.</p><ol><li>How do you correct history you’re not allowed to rewrite? Sealing, revisions, and signed manifests — that’s <a href="https://medium.com/@inderbindra/why-ubers-financial-database-does-not-trust-update-512f5492aa11"><strong>Part 2</strong></a>.</li><li>The index split hides a real protocol: two-phase-commit intents, read-path repair, time-range indexes at trillion scale — <a href="https://medium.com/@inderbindra/how-uber-keeps-2-trillion-indexes-consistent-without-slowing-every-write-737025e5ee74"><strong>Part 3</strong></a>.</li><li>Moving 250 billion records between live databases, stage by stage — <strong>Part 4</strong>.</li><li>Docstore’s partitions, Raft, and where its guarantees end — <strong>Part 5</strong>.</li><li>And the series closes by turning all of this into a design checklist for systems that will never see Uber’s scale — <strong>Part 6</strong>.</li></ol><h3>References</h3><p>Drawn from Uber Engineering’s published posts:</p><ul><li><a href="https://www.uber.com/ca/en/blog/money-scale-strong-data/">Revolutionizing Money Movements at Scale with Strong Data Consistency</a> — Gulfstream’s Job → Order → Entry model, async processing, idempotency, legacy migration</li><li><a href="https://www.uber.com/ca/en/blog/dynamodb-to-docstore-migration/">How Uber Migrated Financial Data from DynamoDB to Docstore</a> — LedgerStore integrity, sealing, storage-backend migration</li><li><a href="https://www.uber.com/ca/en/blog/how-ledgerstore-supports-trillions-of-indexes/">How LedgerStore Supports Trillions of Indexes at Uber</a> — index consistency classes, intents, validation at scale</li><li><a href="https://www.uber.com/ca/en/blog/schemaless-sql-database/">Evolving Schemaless into a Distributed SQL Database</a> — Docstore’s data model, partitioning, consistency boundary</li></ul><h3>Before you go</h3><ul><li>Please take a moment to like the post, share your thoughts, and follow for more articles like this.</li><li>You can also follow me on <a href="https://www.linkedin.com/in/inderbindra">LinkedIn</a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=939a9b615c48" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/how-uber-rebuilt-its-money-movement-architecture-without-losing-financial-correctness-939a9b615c48">How Uber Rebuilt Its Money Movement Architecture Without Losing Financial Correctness</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Six Databases Solve the Same Inventory-Concurrency Problem Differently]]></title>
            <link>https://blog.stackademic.com/how-six-databases-solve-the-same-inventory-concurrency-problem-differently-407781bde8e4?source=rss-6bd396d9b5c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/407781bde8e4</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Inderpreet Singh Bindra]]></dc:creator>
            <pubDate>Wed, 16 Sep 2026 14:16:51 GMT</pubDate>
            <atom:updated>2026-10-09T05:42:42.321Z</atom:updated>
            <content:encoded><![CDATA[<p>MySQL, SQL Server, DynamoDB, Cosmos DB, MongoDB, and Cassandra</p><figure><img alt="Technical infographic comparing inventory concurrency across MySQL, SQL Server, DynamoDB, Cosmos DB, MongoDB, and Cassandra, illustrating locking, conditional writes, atomic updates, and contention." src="https://cdn-images-1.medium.com/max/1024/1*iTEOjQFBKIc84VGz72EQRw.png" /></figure><h3>The Same Invariant, Six Different Concurrency Models</h3><p>Core invariant:</p><blockquote><strong>A unit of inventory cannot be reserved twice, and a reservation cannot consume more inventory than is available.</strong></blockquote><p>The interesting part isn’t the SQL syntax or whether a database supports SKIP LOCKED. The interesting part is <strong>how each database prevents two competing requests from successfully claiming the same capacity.</strong></p><blockquote><strong>The database primitive is different, but the architectural question is the same: how do I make “claim this capacity” atomic from the perspective of competing requests?</strong></blockquote><p>Throughout these examples, assume inventory is represented as independently claimable units or slots. The exact representation varies by database, but the invariant remains the same: only one request can successfully claim a given unit.</p><p>For example:</p><pre>Item: 123<br>Location: 10</pre><pre>Unit 1     AVAILABLE<br>Unit 2     AVAILABLE<br>Unit 3     RESERVED<br>Unit 4     AVAILABLE<br>...<br>Unit 1000  AVAILABLE</pre><p>Instead of repeatedly updating one hot row:</p><pre>Product<br>----------------------------<br>ProductId = 123<br>AvailableQty = 997</pre><p>you have multiple rows that can be independently locked and claimed.</p><p>This is the key architectural idea behind Shopify’s approach: <strong>change the shape of the contention rather than simply trying to make the same hot row faster.</strong></p><h3>1. MySQL: Pessimistic Locking + SKIP LOCKED</h3><h4>Concurrency Model</h4><p>Pessimistic concurrency using InnoDB row-level locking.</p><h4>Atomic Primitive</h4><p>SELECT ... FOR UPDATE SKIP LOCKED inside a transaction.</p><p>The transaction locks the candidate inventory rows before allocating them. SKIP LOCKED tells MySQL to skip rows that are already locked by another transaction instead of waiting for those locks to be released.</p><p><strong>For Example:</strong> Suppose inventory is represented as independently claimable units and a transaction is trying to reserve 1 unit:</p><pre>START TRANSACTION;<br><br>SELECT unit_id<br>FROM inventory_units<br>WHERE item_id = ?<br>  AND location_id = ?<br>  AND status = &#39;AVAILABLE&#39;<br>ORDER BY unit_id<br>LIMIT 1<br>FOR UPDATE SKIP LOCKED;<br>-- Mark the selected units as reserved<br>UPDATE inventory_units<br>SET status = &#39;RESERVED&#39;,<br>    reservation_id = ?<br>WHERE unit_id = ?;<br><br>COMMIT;</pre><p>The important part is that <strong>candidate selection and the state transition happen inside the same transaction</strong>.</p><h4>Contention Behavior</h4><p>Without SKIP LOCKED, if Transaction A has locked Unit 17, Transaction B may wait for Unit 17 to become available.</p><p>With SKIP LOCKED, Transaction B effectively says:</p><blockquote><strong>If this row is already locked, don’t wait for it. Give me another available row.</strong></blockquote><p>So if:</p><pre>Unit 17 → locked by Transaction A<br>Unit 18 → available<br>Unit 19 → available<br>Unit 20 → available</pre><p>Transaction B can skip Unit 17 and claim Unit 18/19/etc.</p><p>This changes the contention pattern from:</p><pre>Request A ──┐<br>Request B ──┼──&gt; same locked row ──&gt; WAIT<br>Request C ──┘</pre><p>to:</p><pre>Request A ──&gt; Unit 17<br>Request B ──&gt; Unit 18<br>Request C ──&gt; Unit 19</pre><p>The contention isn’t eliminated; <strong>it is distributed across independently claimable rows</strong>.</p><h4>When I’d Use It</h4><p>I’d consider this approach when:</p><ul><li>inventory is <strong>highly contended</strong></li><li>multiple requests compete for the same SKU/location</li><li>inventory can reasonably be modeled as a <strong>bounded pool of claimable units</strong></li><li>the reservation operation needs strong transactional consistency</li><li>waiting on locked rows would create unacceptable latency or throughput degradation</li><li>the database is already the transactional source of truth</li></ul><blockquote><strong>SKIP LOCKED doesn&#39;t eliminate contention. It prevents competing transactions from unnecessarily waiting on locks they don&#39;t need.</strong></blockquote><h3>2. SQL Server: READPAST + UPDLOCK</h3><p>SQL Server doesn’t call its feature SKIP LOCKED.</p><p>The closest analogue is:</p><pre>READPAST</pre><p><strong>Concurrency Model<br>Pessimistic concurrency</strong> using locks. Competing transactions can explicitly coordinate access to rows using locking hints such as UPDLOCK, while READPAST can allow a worker to skip rows that are currently locked.</p><p><strong>Atomic Primitive<br></strong>A transaction combined with row-level locking and conditional updates. For example, claim an available inventory row with UPDLOCK <em>(when selecting candidates for an update)</em> and prevent another transaction from claiming the same row.</p><p><strong>For Example:</strong></p><pre>SELECT TOP (@qty)<br>    UnitId<br>FROM dbo.InventoryUnit WITH<br>(<br>    ROWLOCK,<br>    READPAST,<br>    UPDLOCK<br>)<br>WHERE ShopId = @shopId<br>  AND InventoryItemId = @itemId<br>  AND LocationId = @locationId<br>  AND Status = 0<br>ORDER BY UnitId;</pre><p><strong>Contention Behavior<br></strong>Competing transactions can wait on the same locked row. READPAST can reduce waiting by allowing a transaction to skip locked rows and look for another available row. Importantly, it doesn’t skip page-level locks, so <strong><em>“row locking”</em></strong> isn’t a guarantee.</p><p>The idea is:</p><pre>Transaction A<br>    ↓<br>locks Unit 1<br>    ↓<br>Transaction B<br>    ↓<br>READPAST<br>    ↓<br>skip Unit 1<br>    ↓<br>claim Unit 2</pre><p><strong>When I’d Use It<br></strong>When the inventory data already lives in SQL Server and traffic is moderate, pessimistic locking is often the simplest and most predictable solution. For high-contention workloads, I’d consider a data model that distributes allocation across multiple rows rather than concentrating writes on one hot row.</p><blockquote><strong>The key distinction is that SQL Server is using pessimistic concurrency. The database knows a row is locked and deliberately routes another transaction around it.</strong></blockquote><h3>Important caveat</h3><p>Don’t casually combine this with READ_COMMITTED_SNAPSHOT and assume everything behaves as ordinary locking reads. SQL Server documents restrictions around READPAST when RCSI is enabled; in those cases READCOMMITTEDLOCK may be required.</p><p>The lesson isn’t <strong><em>“turn on every locking hint.”</em></strong></p><p>It’s:</p><blockquote><strong>Understand which concurrency model your isolation level is actually using.</strong></blockquote><h3>3. DynamoDB: Don’t look for locks</h3><p>DynamoDB doesn’t have a lock manager that you can tell:</p><blockquote><strong>“Skip the locked item.”</strong></blockquote><p>Instead, DynamoDB gives you <strong>conditional writes</strong>.</p><p>That changes the model completely.</p><p><strong>Concurrency Model<br>Optimistic concurrency</strong> using conditional writes rather than locks.</p><p><strong>Atomic Primitive<br></strong>A conditional write such as UpdateItem with a ConditionExpression. The write succeeds only if the item is still in the expected state.</p><p>Conceptually:</p><pre>Update inventory unit<br>IF status = AVAILABLE</pre><p>If another request already claimed it:</p><pre>ConditionalCheckFailedException</pre><p>The application chooses another candidate.</p><p><strong>Contention Behavior<br></strong>Concurrent requests don’t wait for a lock. Instead, one conditional write succeeds and competing writes fail their condition check. The application can then retry with another candidate.</p><p>So:</p><pre>My SQL / SQL Server     |       DynamoDB<br>                        |<br>locked row              |    conditional failure<br>    ↓                   |           ↓<br>database skips it       | application tries another candidate</pre><p>Those aren’t the same mechanism.</p><p>They’re two ways of solving the same concurrency problem.</p><blockquote><strong>The important design question therefore becomes: how do we efficiently generate candidate units without repeatedly discovering that another request already claimed them?</strong></blockquote><p><strong>When I’d Use It<br></strong>When the workload fits DynamoDB’s access-pattern-oriented model and I want horizontally scalable conditional writes without centralized row locking. I’d design carefully around partition-key distribution and avoid creating a single hot item or hot partition.</p><h3>And there is an important DynamoDB modeling trap</h3><p>Don’t assume this is efficient:</p><pre>Query<br>WHERE status = AVAILABLE</pre><p>using a FilterExpression.</p><p>DynamoDB applies the filter <strong>after reading the items</strong>, so filtering doesn’t reduce the read capacity consumed. A Query also processes at most 1 MB per request before filtering and may require pagination.</p><p>So if availability is a critical access pattern, <strong>model it into your keys/indexes rather than relying on filters to behave like an index.</strong></p><p>For multiple units, DynamoDB also supportsTransactWriteItems, which can atomically apply up to 100 actions, subject to the transaction constraints.</p><pre>100 actions ≠ necessarily 100 inventory units.</pre><p>If reserving one unit requires multiple writes, the action budget can be consumed faster.</p><p>That gives you:</p><pre>candidate units<br>      ↓<br>conditional writes<br>      ↓<br> all succeed<br>      OR<br>   all fail</pre><p>when the reservation semantics require all-or-nothing behavior.</p><h3>4. Cosmos DB: Optimistic concurrency and partition-scoped transactions</h3><p>Cosmos DB takes yet another approach.</p><p>There is no SKIP LOCKED.</p><p><strong>Concurrency Model<br></strong>Optimistic concurrency using ETags, with transactional operations available within a logical partition.</p><p><strong>Atomic Primitive<br></strong>An ETag-based conditional write for optimistic concurrency, or TransactionalBatch/stored procedures when multiple operations need to succeed or fail atomically within the same logical partition.</p><p>A TransactionalBatch is atomic for operations sharing the same logical partition key: either all operations succeed, or the entire batch is rolled back.</p><p>Conceptually:</p><pre>TransactionalBatch<br>│<br>├── Reserve Unit 1<br>├── Reserve Unit 2<br>├── Reserve Unit 3<br>└── Create Reservation<br><br>all succeed<br>     ↓<br>   COMMIT<br><br>any fails<br>     ↓<br>  ROLLBACK</pre><p><strong>Contention Behavior<br></strong>Concurrent updates to the same document can result in an ETag conflict rather than a waiting lock. Transactions involving the same logical partition can still contend, so transaction scope and duration matter.</p><p><strong>When I’d Use It<br></strong>When the workload already fits Cosmos DB’s partitioning model and I can align the inventory data and transaction boundary with the logical partition and stored procedures have bounded execution time, including a five-second limit. I’d be particularly careful about hot logical partitions under high contention.</p><p>So I wouldn’t blindly move a complex inventory allocator into a stored procedure.</p><p>The first design question should be:</p><blockquote><strong>Can I model the reservation so the atomic operation fits naturally within one logical partition?</strong></blockquote><p>If yes, Cosmos becomes considerably simpler.</p><blockquote><strong>A TransactionalBatch doesn’t solve candidate selection by itself; the application still needs an efficient way to identify available units within that partition.</strong></blockquote><h3>5. MongoDB: Single-document atomicity is a powerful primitive</h3><p>MongoDB gives you something fundamentally different again.</p><p>A single-document write is atomic, even when it modifies multiple fields. MongoDB also recommends putting the expected current value into the update filter when coordinating concurrent updates.</p><p><strong>Concurrency model<br></strong>Document-level atomicity with conditional updates.</p><p><strong>Atomic primitive<br></strong>A single-document atomic operation such as findOneAndUpdate with a condition on the document&#39;s current state.</p><p><strong>For Example:</strong></p><pre>db.inventory.findOneAndUpdate(<br>    {<br>        itemId: &quot;SKU-123&quot;,<br>        locationId: &quot;WH-1&quot;,<br>        status: &quot;AVAILABLE&quot;<br>    },<br>    {<br>        $set: {<br>            status: &quot;RESERVED&quot;,<br>            reservationId: &quot;R-123&quot;<br>        }<br>    }<br>)</pre><p>The operation atomically finds and updates one matching document.</p><p>Two buyers can execute this concurrently. Only one can successfully match the same available document. The second request must find another available unit.</p><p>For operations spanning multiple documents, MongoDB supports multi-document transactions.</p><p>But there’s an architectural lesson here:</p><blockquote><strong>Don’t automatically use a multi-document transaction just because the database supports one.</strong></blockquote><p>If the invariant can be represented as a single atomic document update, that is often the simpler concurrency model.</p><p><strong>Contention behavior<br></strong>Concurrent requests attempting to claim the same document are serialized at the document level. A request that no longer matches the condition must select another candidate or retry.</p><p><strong>When I’d use it<br></strong>When inventory can naturally be modeled as independent documents and the reservation operation can remain within MongoDB’s single-document atomicity model. I’d use multi-document transactions only when the business invariant genuinely requires them.</p><h3>6. Cassandra: Compare-and-set, not locks</h3><p>Cassandra gives you <strong>Lightweight Transactions (LWT)</strong>.</p><p><strong>Concurrency Model<br></strong>Optimistic compare-and-set using lightweight transactions (LWT), implemented through Paxos.</p><p><strong>Atomic Primitive<br></strong>An LWT can perform a compare-and-set operation:</p><pre>UPDATE inventory_units<br>SET status = &#39;Reserved&#39;<br>WHERE item_id = ?<br>  AND location_id = ?<br>  AND unit_id = ?<br>IF status = &#39;Available&#39;;</pre><p>The update succeeds only if the expected condition is still true.</p><p><strong>Contention Behavior<br></strong>The LWT mechanism serializes concurrent conditional writes against the same data. Competing operations may fail their condition and need to retry or select another candidate.</p><p>Conceptually:</p><pre>IF current state == AVAILABLE<br>        ↓<br>change to RESERVED</pre><p>If another request wins the race:</p><pre>[applied] = false</pre><p>Try another candidate.</p><p>Again:</p><pre>MySQL / SQL Server   |        Cassandra<br>    ↓                |            ↓<br>lock + skip          |     compare + set + retry</pre><p>Same business goal.</p><p>Different concurrency model.</p><p><strong>When I’d Use It<br></strong>When I need conditional state transitions in a Cassandra workload and the contention is bounded enough that LWT is appropriate. I would not use LWT as a general-purpose replacement for relational transactions.</p><h3>Six Databases, Six Concurrency Models And Their Hot Spots</h3><p>Every database has a contention boundary.</p><p>The question isn’t whether contention exists.</p><p><strong>The question is where your architecture concentrates it.</strong></p><p>Every database has a different hot spot, concurrency model, atomic/native primitive, and contention behavior:</p><pre>| Database       | Main Contention Point / Hot Spot | Concurrency Model                                      | Atomic / Native Primitive                 | Contention Behavior                                                |<br>| -------------- | -------------------------------- | ------------------------------------------------------ | ----------------------------------------- | ------------------------------------------------------------------ |<br>| **MySQL**      | Hot row / index / gap            | Pessimistic locking                                    | Transaction + `FOR UPDATE SKIP LOCKED`    | Skip locked rows                                                   |<br>| **SQL Server** | Hot row / page / index           | Pessimistic locking                                    | Transaction + `UPDLOCK` / `READPAST`      | Skip locked rows                                                   |<br>| **DynamoDB**   | Hot item / partition key         | Optimistic conditional writes                          | Conditional write (`ConditionExpression`) | Condition fails; retry/select another candidate                    |<br>| **Cosmos DB**  | Hot document / logical partition | Optimistic concurrency + partition-scoped transactions | ETag / `TransactionalBatch`               | Conflict or transaction failure                                    |<br>| **MongoDB**    | Hot document                     | Document-level atomicity                               | Atomic `findOneAndUpdate`                 | Competing update no longer matches; retry/select another candidate |<br>| **Cassandra**  | Hot partition / LWT key          | Compare-and-set (CAS) / LWT                            | Conditional write (LWT)                   | Conditional write fails; retry if appropriate                      |</pre><p>Notice what isn’t in the table:</p><p><strong>“SKIP LOCKED equivalent.”</strong></p><p>Because there isn’t one.</p><p>And that’s the point.</p><h3>How does the Primitive Change the Failure Mode?</h3><pre>| Model               | Competing request experiences  |<br>| ------------------- | ------------------------------ |<br>| Pessimistic locking | Waits or skips locked resource |<br>| Conditional write   | Fails condition and retries    |<br>| ETag concurrency    | Gets conflict and retries      |<br>| Document atomicity  | Predicate no longer matches    |<br>| LWT/CAS             | Conditional operation fails    |</pre><p>These mechanisms have different failure semantics.</p><p>A locking system tends to make contention visible as <strong>waiting</strong>.</p><p>An optimistic system tends to make contention visible as <strong>conflicts and retries</strong>.</p><p>A distributed database may make contention visible as <strong>partition pressure or conditional-write failures</strong>.</p><blockquote><strong>The concurrency primitive doesn’t merely determine correctness. It determines what your application experiences when correctness is contested.</strong></blockquote><h3>The Deeper Lesson</h3><p>The most important difference between these databases isn’t whether they can prevent double allocation.</p><blockquote><strong>All of them can.</strong></blockquote><p>The difference is <strong>how they make contention visible to your system.</strong></p><p>With pessimistic locking:</p><pre>contention<br>    ↓<br>waiting / lock pressure</pre><p>With optimistic conditional writes:</p><pre>contention<br>    ↓<br>conflict / failed condition<br>    ↓<br>retry</pre><p>With partition-oriented systems:</p><pre>contention<br>    ↓<br>hot partition / coordination pressure</pre><p>With document-level atomicity:</p><pre>contention<br>    ↓<br>predicate no longer matches</pre><p>That difference matters because the concurrency primitive becomes part of the application architecture.</p><p>It influences retry behavior, backoff strategy, data modeling, partitioning, transaction scope, observability, and ultimately the failure modes your system has to handle.</p><p>So when evaluating a database for a high-contention workload, don’t ask only:</p><blockquote><strong>Can this database do atomic writes?</strong></blockquote><p>Ask:</p><blockquote><strong>What does contention look like when 10,000 requests try to perform the same state transition?</strong></blockquote><p>That question reveals whether the database’s concurrency model fits your workload.</p><h3>Now Ask Yourself</h3><blockquote><strong>If 10,000 requests hit the same inventory key at once, where does your database make them wait, fail, retry, or contend?</strong></blockquote><h3>Related Article</h3><p><a href="https://medium.com/@inderbindra/3caa7a806c6f"><strong>How Shopify Replaced Redis with MySQL for Inventory Reservations</strong></a></p><p>This article<strong> </strong>talks about the Architecture Lessons Behind High-Concurrency Inventory Allocation.</p><h3>References</h3><ul><li><a href="https://learn.microsoft.com/en-us/sql/t-sql/queries/hints-transact-sql-table?view=sql-server-2016">SQL Server READPAST / UPDLOCK</a></li><li><a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.html">DynamoDB Conditional Writes</a></li><li><a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.html">DynamoDB FilterExpression</a></li><li><a href="https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_TransactWriteItems.html">DynamoDB TransactionsWriteItems</a></li><li><a href="https://learn.microsoft.com/en-us/rest/api/cosmos-db/transactional-batch">Cosmos DB Transactional Batches</a></li><li><a href="https://learn.microsoft.com/en-us/azure/cosmos-db/database-transactions-optimistic-concurrency">Cosmos DB ETags</a></li><li><a href="https://www.mongodb.com/docs/manual/core/write-operations-atomicity">MongoDB Atomic Updates</a></li><li><a href="https://www.mongodb.com/docs/v5.1/reference/method/db.collection.findOneAndUpdate/?utm_source=chatgpt.com">MongoDB findOneAndUpdate()</a></li><li><a href="https://docs.datastax.com/en/cql/dse-6.8/develop/inserting/insert-lwt.html">Cassandra Lightweight Transactions (LWT)</a></li><li><a href="https://docs.datastax.com/en/cassandra-oss/2.1/cassandra/dml/dml_ltwt_transaction_c.html">Cassandra LWT as compare-and-set</a></li></ul><h3>Before you go</h3><ul><li>Please take a moment to like the post, share your thoughts, and follow for more articles like this.</li><li>You can also follow me on <a href="https://www.linkedin.com/in/inderbindra"><strong>LinkedIn</strong></a>.</li><li>Did you know that over 400,000 developers share what they’re building, learning, and discovering across our platforms every month? Learn how you can contribute <a href="https://plainenglish.io/write-for-us">here</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=407781bde8e4" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/how-six-databases-solve-the-same-inventory-concurrency-problem-differently-407781bde8e4">How Six Databases Solve the Same Inventory-Concurrency Problem Differently</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Shopify Replaced Redis with MySQL for Inventory Reservations]]></title>
            <link>https://blog.stackademic.com/how-shopify-replaced-redis-with-mysql-for-inventory-reservations-3caa7a806c6f?source=rss-6bd396d9b5c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/3caa7a806c6f</guid>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[interview-questions]]></category>
            <dc:creator><![CDATA[Inderpreet Singh Bindra]]></dc:creator>
            <pubDate>Wed, 16 Sep 2026 14:16:48 GMT</pubDate>
            <atom:updated>2026-10-09T05:38:17.178Z</atom:updated>
            <content:encoded><![CDATA[<p>The Architecture Lessons Behind High-Concurrency Inventory Allocation</p><figure><img alt="Technical infographic showing Shopify’s migration from Redis atomic counters to MySQL transactional inventory reservations, highlighting contention, consistency, and high-concurrency checkout." src="https://cdn-images-1.medium.com/max/1024/1*syVDgjqxB_4k1IzYcLiqew.png" /></figure><h3>Shopify’s Problem</h3><p>Inventory reservation looks deceptively simple:</p><pre>available = available - requested</pre><p>Until thousands of customers try to buy the last 10 units at the same time.</p><p>Then the real problem appears:</p><blockquote><strong>Where does the reservation live, and where does the inventory truth live?</strong></blockquote><p>If the answer is:</p><pre>Redis              → reservation<br>SQL database       → inventory/order</pre><p>you have created a distributed consistency problem.</p><p>Redis isn’t the villain.</p><p><strong>The transaction boundary is.</strong></p><p>Shopify recently described how it replaced Redis with MySQL for inventory reservations. The important lesson wasn’t “Redis is bad.” Redis is good at atomic counters and low-latency operations.</p><p>The problem was that reservation state and the inventory ledger lived in different systems that couldn’t participate in one normal ACID transaction.</p><p>Shopify’s solution was to bring reservation state into MySQL and redesign the inventory model around a bounded pool of reservable rows, using SKIP LOCKED to avoid making concurrent buyers wait on the same locked rows.</p><p>But there is a more interesting question:</p><blockquote><strong>What if your database isn’t MySQL?</strong></blockquote><blockquote><strong>What does the same problem look like in SQL Server, DynamoDB, CosmosDB, MongoDB, or Cassandra?</strong></blockquote><p>The answer isn’t “find the equivalent of SKIP LOCKED.&quot;</p><p>The answer is:</p><blockquote><strong>Find the concurrency primitive your database gives you, and use it to enforce the inventory invariant atomically.</strong></blockquote><h3>The Common Relational Solution: Lock the Inventory, Check, Then Allocate</h3><p>The straightforward relational-database solution is to make inventory allocation transactional. Lock the inventory record, check whether quantity remains, decrement the available quantity, and insert the reservation, all before committing the transaction.</p><p>This is correct because concurrent requests cannot make allocation decisions against the same inventory state simultaneously.</p><p>But correctness comes with a cost: <strong>contention</strong>.</p><blockquote><strong>Correctness Isn’t the Problem. Contention Is.</strong></blockquote><h3>Why It Becomes a Hot Spot?</h3><p>The locking approach is not wrong. It is often the right solution at moderate contention.</p><p>Imagine a product with 10 units remaining and thousands of customers trying to buy it at nearly the same time.</p><p>The inventory might look like this:</p><pre>Product #123 <br>---------------- <br>AvailableQty = 10</pre><p>Every reservation needs to make a decision against that same piece of state:</p><pre>                   Product #123 <br>                  Available = 10 <br>                         │ <br>            ┌────────────┼────────────┐ <br>            │            │            │ <br>         Request A    Request B    Request C <br>            │            │            │ <br>            └────────────┼────────────┘ <br>                         │ <br>                        LOCK <br>                          │ <br>                     Serialize Access</pre><p>The first transaction acquires the lock and checks the available quantity.</p><p>The other transactions cannot make their allocation decision until the lock is released.</p><p>So although the database is protecting the inventory correctly, requests are effectively being serialized around a single logical resource.</p><p>The important distinction:</p><blockquote><strong>Locks protect correctness, but a heavily contended lock can limit concurrency.</strong></blockquote><p>For normal traffic, this may be perfectly acceptable. If a SKU receives only a handful of concurrent reservation requests, the simplicity of a single inventory row can be more valuable than the complexity of a distributed reservation scheme.</p><p>But consider a flash sale:</p><pre>100,000 buyers <br>     │ <br>     ▼ <br>  SKU #123 <br>     │ <br>     ▼ <br>AvailableQty = 10 <br>     │ <br>     ▼ <br>One heavily contended inventory record</pre><p>Now the database has a very different problem.</p><p>It isn’t struggling to determine whether inventory exists. It is struggling because <strong>many transactions are competing for the same piece of mutable state</strong>.</p><p>This is commonly called a <strong>hot spot</strong> or <strong>hot row</strong>.</p><blockquote><strong>That is where the data model starts to matter.</strong></blockquote><p>Shopify’s interesting insight wasn’t simply <strong><em>“use MySQL instead of Redis.”</em></strong> It was to change the shape of the reservation state itself: instead of making one quantity record the primary contention point, maintain a bounded pool of reservation units and allow concurrent transactions to claim different available rows using SKIP LOCKED.</p><h3>Atomic Counters: The Simpler Alternative</h3><p>A bounded reservation pool is not inherently better than an atomic counter. It is better only when contention makes the counter the bottleneck.</p><p>Before reaching for a sophisticated reservation pool, ask a simpler question:</p><blockquote><strong>Do I actually have enough contention to need one?</strong></blockquote><p>Suppose:</p><pre>Product<br>---------------------<br>Qty           = 100<br>AllocatedQty  = 73</pre><p>An atomic operation can be:</p><pre>UPDATE Product<br>SET AllocatedQty = AllocatedQty + 1<br>WHERE ProductId = @ProductId<br>  AND AllocatedQty &lt; Qty;</pre><p>If one row is updated:</p><pre>Allocation succeeded</pre><p>If zero rows are updated:</p><pre>Inventory exhausted</pre><p>This is often the best design.</p><p>It’s simple.<br>It’s cheap.<br>It’s easy to reason about.</p><p>The only <strong><em>caveat </em></strong>is that the counter update and reservation creation must be part of the same transaction if both represent the same correctness boundary.</p><p><strong>Otherwise this can happen:</strong></p><pre>UPDATE counter → succeeds<br>       ↓<br>INSERT reservation → fails<br>       ↓<br>inventory says 1 unit allocated<br>but reservation doesn&#39;t exist</pre><p><strong>Or:</strong></p><pre>INSERT reservation → succeeds<br>       ↓<br>UPDATE counter → fails<br>       ↓<br>reservation exists without inventory allocation</pre><p>An atomic counter is often the simplest solution but only if the inventory mutation and the corresponding reservation write participate in the same transactional boundary.</p><p>So an atomic counter solves one problem, <strong>making the allocation decision safely and efficiently</strong> but it doesn’t eliminate contention on a very <strong>hot SKU</strong>.</p><p>This leads to an important architectural question:</p><blockquote><strong>Can we represent inventory in a way that allows competing requests to claim different pieces of state instead of forcing every request through one record?</strong></blockquote><h3>Why Shopify Needed Something Else?</h3><p>Because an atomic counter creates a <strong>hot record</strong>.</p><p>If 100,000 buyers want the same SKU:</p><pre>                 100,000 requests<br>                         ↓<br>                  ┌────────────┐<br>                  │ Product    │<br>                  │ SKU #123   │<br>                  └────────────┘</pre><p>Every reservation is competing for the same logical record.</p><p>At that point, the problem isn’t correctness anymore.</p><p><strong>It’s contention.</strong></p><p>That’s where the next design becomes interesting.</p><h3>The Shopify insight: Distribute the contention</h3><p>Shopify didn’t eliminate the contention, but it distributed the contention across multiple independently claimable records.</p><p>Instead of representing:</p><pre>SKU #123<br>available = 10,000</pre><p>as one hot record, represent a bounded pool of reservable units.</p><p>Conceptually:</p><pre>   SKU #123<br>┌─────────────┐<br>│ Unit 1      │ AVAILABLE<br>│ Unit 2      │ AVAILABLE<br>│ Unit 3      │ AVAILABLE<br>│ ...         │<br>│ Unit 1000   │ AVAILABLE<br>└─────────────┘</pre><p>A reservation claims individual available units.</p><p>If another transaction is using Unit 17, you don’t need to wait for Unit 17.</p><p>You can claim Unit 18.</p><p>Shopify describes this as a bounded pool of up to 1,000 reservation rows per item/location, replenished from the underlying inventory ledger. The number isn’t a universal magic number; it was chosen based on observed reservation rates and the tradeoff between burst absorption and pool size.</p><pre>Before:<br><br>10,000 requests<br>       ↓<br>   Product row<br>       ↓<br>   one hot lock<br><br><br>After:<br><br>10,000 requests<br>       ↓<br> ┌─────┼─────┬─────┐<br> ↓     ↓     ↓     ↓<br>Unit1 Unit2 Unit3 Unit4 ...</pre><p>This leads to three important principles:</p><h4>1. Keep correctness in one transactional domain</h4><p>Reservation and inventory truth should not require a distributed commit.</p><h4>2. Don’t create a hot record unnecessarily</h4><p>If contention becomes the bottleneck, distribute the claimable resources.</p><h4>3. Don’t confuse the data model with the concurrency primitive</h4><p>Different databases can implement the same business invariant very differently.</p><p>That’s where databases diverge.</p><h3>The Real Architecture</h3><pre>                   CUSTOMER<br>                      │<br>                      ▼<br>              Reservation Request<br>                      │<br>                      ▼<br>               Idempotency Check<br>                      │<br>                      ▼<br>              Atomic Allocation<br>                      │<br>          ┌───────────┴───────────┐<br>          │                       │<br>       SUCCESS                 FAILURE<br>          │                       │<br>          ▼                       ▼<br>      RESERVED                SOLD OUT<br>          │<br>          ▼<br>       PAYMENT<br>          │<br>     ┌────┴────┐<br>     │         │<br>  SUCCESS    FAILURE<br>     │         │<br>     ▼         ▼<br>  CLAIMED    RELEASE</pre><p>The core reservation invariant is:</p><blockquote><strong>A unit cannot be successfully reserved twice, and a reservation cannot consume more inventory than is available.</strong></blockquote><p>The business invariant comes first; the database-specific concurrency mechanism is how we enforce it under contention.</p><p><strong><em>Atomic allocation</em></strong><em> means that the state transition deciding whether inventory can be reserved and the mutation that consumes that capacity are indivisible from the perspective of competing requests.</em></p><h3>The Hidden Bottleneck: Connections &amp; Transaction Duration</h3><p>So far, we have talked mostly about <strong>correctness</strong> and <strong>contention</strong>.</p><p>But there is another production bottleneck that is easy to miss:</p><blockquote><strong>How long does each request hold a database connection and transaction open?</strong></blockquote><p>Imagine an inventory reservation operation that looks simple:</p><pre>Begin Transaction<br><br>1. Find available inventory<br>2. Lock/claim it<br>3. Create reservation<br>4. Update reservation state<br>5. Commit<br><br>End Transaction</pre><p>The SQL queries themselves might each take only a few milliseconds.</p><p>But suppose the transaction holds a connection for 200 ms because the application performs additional work between those operations.</p><p>At 100 requests/second:</p><pre>100 requests/sec × 200 ms ≈ 20 concurrent database connections</pre><p>At 1,000 requests/second:</p><pre>1,000 × 200 ms ≈ 200 concurrent connections</pre><p>The database may still have plenty of CPU capacity.</p><p>Yet the application can begin exhausting its connection pool.</p><h3>Fast queries don’t necessarily mean a scalable system</h3><p>This is an important distinction:</p><blockquote><strong>Query latency and connection hold time are not the same thing.</strong></blockquote><p>A query can be fast while the overall transaction is long.</p><p>For example:</p><pre>Begin transaction<br>      │<br>      ├── SELECT/claim inventory      5 ms<br>      │<br>      ├── Application processing     100 ms<br>      │<br>      ├── INSERT reservation          5 ms<br>      │<br>      ├── More application work      80 ms<br>      │<br>      └── COMMIT                      5 ms<br><br>Total connection/transaction time ≈ 195 ms</pre><p>The database may have spent only a small portion of that time actually executing SQL.</p><p>The rest of the time, a valuable database connection and potentially locks is being held.</p><h3>Why this matters for inventory systems</h3><p>Inventory reservation is particularly sensitive because transactions often involve <strong>contended resources</strong>.</p><p>If a transaction:</p><ul><li>acquires a lock,</li><li>performs additional work,</li><li>waits on another resource,</li><li>or makes unnecessary database calls,</li></ul><p>the transaction remains active longer.</p><p>That increases:</p><ul><li>connection pool pressure</li><li>lock duration</li><li>lock wait time</li><li>transaction contention</li><li>request latency</li><li>probability of timeouts</li><li>overall database concurrency pressure</li></ul><p>This creates a feedback loop:</p><pre>Longer transactions<br>       ↓<br>Connections held longer<br>       ↓<br>Connection pool pressure<br>       ↓<br>Requests wait for connections<br>       ↓<br>Request latency increases<br>       ↓<br>More requests remain in flight<br>       ↓<br>More pressure on the database</pre><h3>The Principal Engineer Lesson</h3><p>When analyzing database scalability, don’t ask only:</p><blockquote><strong>How fast is this query?</strong></blockquote><p>Also ask:</p><blockquote><strong>How long does this business operation occupy a database connection and hold transactional state?</strong></blockquote><p>That changes the optimization strategy.</p><p>Instead of optimizing only individual queries, look at:</p><ul><li>number of database round trips</li><li>transaction scope</li><li>transaction duration</li><li>connection hold time</li><li>lock duration</li><li>unnecessary reads</li><li>batching opportunities</li><li>connection-pool utilization</li></ul><p>This is one reason Shopify’s experience is particularly interesting: after changing the concurrency model, they found that <strong>connection and transaction behavior itself became an important production constraint</strong>.</p><p>The lesson is broader than Shopify:</p><blockquote><strong>A database can have low CPU utilization and still be overloaded.</strong></blockquote><p>Sometimes the scarce resource isn’t CPU.</p><blockquote><strong>It is connections, locks, or transactional capacity.</strong></blockquote><h3>Expiration + Idempotency + Recovery</h3><p>Concurrency correctness is only one part of a reservation system.</p><p>A production system must also handle <strong>time, retries, failures, and recovery</strong>.</p><p>Consider this sequence:</p><pre>Customer<br>   │<br>   │ Reserve 2 units<br>   ▼<br>Reservation Service<br>   │<br>   ├── Allocate inventory<br>   │<br>   ├── Create reservation<br>   │<br>   └── Commit</pre><p>What happens if the response is lost?</p><pre>Database:       COMMIT succeeded<br>                 │<br>                 ▼<br>Reservation:    Created<br><br>Customer:       Did not receive response<br>                 │<br>                 ▼<br>Customer retries</pre><p>If the second request creates another reservation, you can double-allocate inventory.</p><p>This is why <strong>idempotency is part of correctness</strong>, not merely an API convenience.</p><h3>Idempotency</h3><p>Every reservation request should have a stable identifier, for example:</p><pre>ReservationRequestId = 8f2a...</pre><p>The service can then enforce:</p><pre>Same request ID<br>       ↓<br>Existing reservation?<br>       ├── Yes → return existing result<br>       └── No  → perform allocation</pre><p>Conceptually:</p><pre>Client<br>  │<br>  │ Reserve(requestId=123)<br>  ▼<br>Reservation Service<br>  │<br>  ├── Check requestId<br>  │<br>  ├── Already processed?<br>  │       ├── Yes → return previous result<br>  │       └── No<br>  │<br>  ├── Allocate inventory<br>  │<br>  ├── Create reservation<br>  │<br>  └── Commit</pre><p>The important part is that the <strong>idempotency record and the reservation outcome need to participate in the same correctness boundary</strong>.</p><p>Otherwise you can still get races such as:</p><pre>Request A ── check ── not found ──┐<br>                                  ├── both allocate<br>Request B ── check ── not found ──┘</pre><p>The exact implementation depends on the database:</p><ul><li>unique constraint on ReservationRequestId</li><li>conditional write</li><li>transactional insert</li><li>atomic upsert</li><li>or another database-specific mechanism</li></ul><p>The principle is the same:</p><blockquote><strong>A retry must not create a second business operation.</strong></blockquote><h3>Failure Matrix</h3><pre>| Failure                       | What can go wrong?                          | Design response                            |<br>| ----------------------------- | ------------------------------------------- | ------------------------------------------ |<br>| Client timeout                | Reservation succeeded but response was lost | Idempotency key                            |<br>| Client retry                  | Duplicate reservation                       | Idempotent operation                       |<br>| Service crash before commit   | Partial work                                | Transaction rollback                       |<br>| Service crash after commit    | Client may retry                            | Idempotency + durable state                |<br>| Reservation timeout           | Inventory remains unavailable               | Explicit expiration/release                |<br>| Release retry                 | Inventory released twice                    | Idempotent release                         |<br>| Payment succeeds, claim fails | Inventory/order state diverges              | Durable workflow + retry/reconciliation    |<br>| Worker crashes                | Expiration not processed                    | Retryable/background processing            |<br>| Database unavailable          | Reservation cannot be completed             | Fail closed / retry according to semantics |</pre><h3>Expiration Is A Business Event</h3><p>Now consider the other side.</p><p>A reservation might be valid for:</p><pre>10 minutes</pre><p>After that:</p><pre>Reservation<br>    │<br>    ├── Payment succeeds → Claimed<br>    │<br>    └── Timeout          → Expired</pre><p>When a reservation expires, the inventory becomes available again.</p><p>That sounds simple, but there is an important question:</p><blockquote><strong>Who is responsible for making that transition?</strong></blockquote><p>You could have:</p><ul><li>a background worker</li><li>a scheduled job</li><li>a queue-based delayed message</li><li>a database cleanup process</li><li>an expiration scanner</li><li>or a combination of these</li></ul><p>The important distinction is that <strong>expiration is a business state transition</strong>.</p><p>It should not depend on a storage engine’s cleanup mechanism accidentally becoming your business workflow.</p><p>Which brings us to TTL.</p><h3>Don’t Use TTL As Your Business Transaction</h3><p>There’s another subtle but important point.</p><p>A common temptation is to say:</p><blockquote><strong>Reservations expire after 10 minutes, so I’ll just use TTL.</strong></blockquote><p>For example:</p><pre>Reservation expiresAt = 10:30</pre><p>does not necessarily mean:</p><pre>At exactly 10:30<br>→ reservation is removed<br>→ inventory is returned<br>→ order state is updated<br>→ downstream systems are notified</pre><p>Reservation expiration is business state.</p><p>A storage TTL mechanism may simply remove the record eventually.</p><p>Therefore, separate the concepts:</p><pre>Business expiration<br>        │<br>        ▼<br>Reservation → Expired<br>        │<br>        ├── Release inventory<br>        ├── Update state<br>        └── Trigger downstream processing<br><br>Storage TTL<br>        │<br>        ▼<br>Eventually remove obsolete data</pre><p>So:</p><blockquote><strong>Use TTL to clean up expired data. Don’t use TTL as the mechanism that defines whether a reservation has expired.</strong></blockquote><h3>How I’d Choose the Reservation Model</h3><p>This is how I’d actually approach the design.</p><h4><strong>First Ask:</strong></h4><ol><li><strong>Do you have a hot inventory key?</strong></li></ol><p><strong>No,</strong> use an atomic conditional counter.</p><pre>available_qty &gt; 0<br>        ↓<br>    decrement</pre><p>Simple wins.</p><p><strong>If Yes,</strong> then ask:</p><p><strong>2. Can I distribute the contention?</strong></p><p>If yes:</p><pre>Inventory<br>   ↓<br>bounded/sharded reservation pool<br>   ↓<br>independent claims</pre><p>Then ask:</p><p><strong>3. Does the reservation and inventory ledger need to commit together?</strong></p><p>If yes:</p><pre>same transactional domain</pre><p>or use the database’s native atomic/conditional transaction primitive.</p><p><strong>4. What happens when a reservation expires?</strong></p><p>Make expiration an explicit state transition:</p><pre>RESERVED<br>   ↓<br>expired<br>   ↓<br>AVAILABLE</pre><p>with an idempotent conditional update.</p><h4>Finally:</h4><p><strong>5. How long is the transaction holding scarce resources?</strong></p><p>Because at high scale:</p><pre>10 ms transaction × 10,000/sec</pre><p>and</p><pre>500 ms transaction × 10,000/sec</pre><p>are radically different systems.</p><h3>The Deeper Lesson</h3><p>The Shopify story isn’t really about Redis.</p><p>It isn’t even really about MySQL.</p><p>It’s about <strong>where you put a correctness boundary</strong>.</p><p>If your architecture looks like:</p><pre>Redis<br>  ↓<br>reservation</pre><pre>MySQL<br>  ↓<br>inventory</pre><p>you have two systems participating in one business decision without sharing one transaction.</p><p>You can make that work.</p><p>But now you’re responsible for:</p><pre>dual writes<br>reconciliation<br>timeouts<br>retries<br>idempotency<br>partial failure<br>expiration<br>recovery</pre><p>You have moved the problem from local transactional consistency into distributed-systems consistency.</p><p>Sometimes that’s absolutely justified.</p><p>Sometimes it isn’t.</p><p>And when it isn’t, the simplest architecture is often:</p><pre>Reservation<br>     +<br>Inventory truth<br>     ↓<br>same consistency boundary</pre><p>The lesson is:</p><blockquote><strong>Choose the simplest design that meets the contention and consistency requirements.</strong></blockquote><h3>If you remember only three things</h3><h4>1. Don’t start with SKIP LOCKED</h4><p>Start with the invariant:</p><blockquote><strong><em>What state transition must be atomic?</em></strong></blockquote><h4>2. Don’t start with one row per inventory unit</h4><p>Start with an atomic counter if your contention is low enough.</p><p>Move to sharded or bounded reservation pools when a single inventory record becomes a measurable hot spot.</p><h4>3. Don’t ask whether another database has SKIP LOCKED</h4><p>Ask:</p><blockquote><strong>What is this database’s native concurrency primitive, and can I express my inventory invariant with it?</strong></blockquote><p>SQL Server has locking.</p><p>DynamoDB has conditional writes.</p><p>Cosmos has optimistic concurrency and partition-scoped transactions.</p><p>MongoDB has atomic document updates and transactions.</p><p>Cassandra has linearizable compare-and-set through LWT.</p><p>Different mechanisms.</p><p>Same problem.</p><p><strong>The architecture wins when the business invariant and the database’s concurrency model are aligned.</strong></p><pre>                  INVENTORY ALLOCATION<br>                          │<br>             ┌────────────┴────────────┐<br>             │                         │<br>       LOW CONTENTION            HIGH CONTENTION<br>             │                         │<br>       Atomic Counter            Shard Contention<br>             │                         │<br>             │                   Bounded Pool<br>             │                         │<br>             └────────────┬────────────┘<br>                          │<br>                     ATOMIC CLAIM<br>                          │<br>        ┌─────────────────┼───────────────┐─────────────┐──────────────┐<br>        │                 │               │             │              |<br> MySQL/ SQL Server     DynamoDB        Cosmos DB      MongoDB      Cassandra<br>   Lock + Skip        Conditional       ETag/Batch    Atomic Doc     LWT/CAS</pre><p><strong>The hard part isn’t choosing Redis, MySQL, or any particular database. It’s choosing where contention lives and where correctness must be enforced.</strong></p><p>But what happens when the database isn’t MySQL?</p><p>In the next article, I’ll take the <strong>same inventory invariant</strong> and implement the concurrency idea across <strong>MySQL, SQL Server, DynamoDB, Cosmos DB, MongoDB, and Cassandra</strong> — six databases, six concurrency models, and six very different ways to handle the same problem.</p><blockquote><strong>How Six Databases Solve the Same Inventory-Concurrency Problem Differently </strong><a href="https://blog.stackademic.com/how-six-databases-solve-the-same-inventory-concurrency-problem-differently-407781bde8e4"><strong>[LINK]</strong></a></blockquote><h3>References</h3><ol><li><a href="https://shopify.engineering/scaling-inventory-reservations?utm_source=chatgpt.com">Shopify Engineering — We replaced Redis with MySQL for inventory reservations — and it scaled</a></li></ol><h3>Before you go</h3><ul><li>Please take a moment to like the post, share your thoughts, and follow for more articles like this.</li><li>You can also follow me on <a href="https://www.linkedin.com/in/inderbindra"><strong>LinkedIn</strong></a>.</li><li>Did you know that over 400,000 developers share what they’re building, learning, and discovering across our platforms every month? Learn how you can contribute <a href="https://plainenglish.io/write-for-us">here</a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3caa7a806c6f" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/how-shopify-replaced-redis-with-mysql-for-inventory-reservations-3caa7a806c6f">Why Shopify Replaced Redis with MySQL for Inventory Reservations</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Agent Memory Is an Ownership & Consistency Problem, Not an AI Problem]]></title>
            <link>https://medium.com/@inderbindra/agent-memory-is-an-ownership-consistency-problem-not-an-ai-problem-1c9fc8521c79?source=rss-6bd396d9b5c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c9fc8521c79</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Inderpreet Singh Bindra]]></dc:creator>
            <pubDate>Wed, 18 Feb 2026 15:06:00 GMT</pubDate>
            <atom:updated>2026-10-09T05:19:46.784Z</atom:updated>
            <content:encoded><![CDATA[<p>Why vector databases aren’t enough and how state ownership, concurrency, and consistency help AI agents remember and recover reliably.</p><figure><img alt="Agent memory is an ownership and consistency problem. AI agent memory architecture illustrating how state ownership, consistency, and durable storage prevent conflicting updates, lost context, and failures in distributed multi-agent systems." src="https://cdn-images-1.medium.com/max/819/1*CzX3ji6sL2vcRZBmfqO9Lg.png" /></figure><p><strong>“Agent memory”</strong> has become a catch-all term.</p><p>In most systems, it means:</p><ul><li>Store embeddings in a vector database.</li><li>Let every agent read and write.</li><li>Retrieve relevant chunks.</li><li>Hope it works.</li></ul><p>And for simple demos, it does.</p><p>But at scale, something subtle breaks.<br>The failures don’t look like model failures.</p><blockquote><strong>They look like distributed systems failures</strong>.<br><strong>And that’s because they are.</strong></blockquote><h3>The Quiet Architectural Mistake</h3><p>When people say <strong><em>“agent memory”</em></strong>, what they usually mean is:</p><blockquote><strong>We persist information somewhere.</strong></blockquote><p>That sounds reasonable.<br><strong>But persistence is not ownership.</strong></p><p>A database can store:</p><ul><li>Facts</li><li>Logs</li><li>Embeddings</li><li>Artifacts</li></ul><p>It cannot:</p><ul><li>Enforce plan progression</li><li>Mark a decision as permanently rejected</li><li>Prevent concurrent mutation</li><li>Guarantee deterministic state transitions</li></ul><blockquote><strong>Storage is passive.<br>Agents are active.</strong></blockquote><p>If you don’t define who has authority over state evolution, you have a shared mutable state.</p><p>Shared mutable state is where systems often die.</p><h3>The Subtle but Fatal Confusion:</h3><h4>“We’ll Store Everything in a Vector DB”</h4><p>The common proposal:</p><ul><li>Persist state in a vector DB</li><li>Embed them</li><li>Retrieve relevant context</li><li>Feed it to a stateless agent</li></ul><blockquote><strong>This sounds right. It is not sufficient.</strong></blockquote><p><strong>Why?<br></strong>Because <strong>retrieval ≠ ownership</strong>.</p><p>A vector DB:</p><ul><li>Stores embeddings</li><li>Retrieves by similarity</li><li>Has <strong>no notion of progress, intent, or correctness</strong></li></ul><p>It cannot answer:</p><ul><li>“Which step of the plan am I on?”</li><li>“Was this decision already rejected?”</li><li>“Is this task completed or pending?”</li><li>“What must <em>not</em> be retried?”</li><li>“What is the authoritative next state?”</li></ul><p>It only answers:</p><ul><li>“What looks similar?”</li></ul><p><strong>That distinction is everything.</strong></p><h3>Concrete Failure Example: Retry Loop From Hell</h3><h4>Task</h4><p>“Deploy service to production safely.”</p><h4>Stateless + Vector DB Setup</h4><ol><li>Agent generates plan</li><li>Step 3 fails (bad config)</li><li>Error logged and embedded</li><li>New agent instance spins up</li><li>Retrieves “relevant context”</li><li>Recreates the <strong>same plan</strong></li><li>Repeats the <strong>same failure</strong></li></ol><p><strong>Why?</strong><br> Because:</p><ul><li>Failure is text, not state</li><li>Rejection is not enforced</li><li>There is no authoritative marker that says:</li></ul><blockquote><strong>This configuration path is invalid. Do not retry without modification.</strong></blockquote><p>The system has memory.<br>It does <strong>not </strong>have ownership.</p><blockquote><strong>You’ve built a stochastic retry engine.</strong></blockquote><h3>What “State Ownership” Actually Means</h3><p>Ownership is not about where bytes live.</p><p>State ownership means one thing:</p><blockquote><strong>There is a single authority responsible for evolving state forward.</strong></blockquote><p><strong>Ownership ≠ Physical storage.<br>Ownership = authority over state transitions.</strong></p><p>In distributed systems:</p><ul><li>Kafka partition owns offsets</li><li>DB shard owns rows</li><li>The workflow engine owns the execution state</li></ul><p>Ownership means:</p><ul><li>A single authority mutates the state.</li><li>Transitions are explicit.</li><li>Updates are durable.</li><li>Conflicts are controlled.</li><li>Replays are deterministic.</li></ul><p><strong>Now apply that to agents and not the:</strong></p><ul><li>Vector DB</li><li>Orchestrator</li><li>Prompt</li></ul><p>The agent must own:</p><ul><li>Goal</li><li>Plan</li><li>Current step</li><li>Completed steps</li><li>Rejected paths</li><li>Revision number</li></ul><p>Everything else is derivative.</p><h4>What “State Ownership” Prevents?</h4><p>Without ownership:</p><ul><li>Two agents retry the same failed step</li><li>Plans diverge</li><li>Failures repeat</li><li>Progress is ambiguous</li></ul><p>With ownership:</p><ul><li>Exactly-once state transitions</li><li>Deterministic recovery</li><li>Reproducible behavior</li><li>Debuggable systems</li></ul><h3>Where Does the “State” Live?</h3><p><strong>Not in the LLM. Ever.</strong><br>State lives in <strong>durable storage</strong>, typically one of:</p><ul><li>Relational Database</li><li>Document store</li><li>Key-value store with versioning</li></ul><h4>Minimal State Schema Example:</h4><pre>{<br>  &quot;agent_id&quot;: &quot;deploy-agent-22&quot;,<br>  &quot;goal&quot;: &quot;Deploy service X to prod&quot;,<br>  &quot;status&quot;: &quot;IN_PROGRESS&quot;,<br>  &quot;current_step&quot;: 3,<br>  &quot;plan&quot;: [<br>    &quot;validate config&quot;,<br>    &quot;run staging deploy&quot;,<br>    &quot;run prod deploy&quot;,<br>    &quot;monitor&quot;<br>  ],<br>  &quot;completed_steps&quot;: [1,2],<br>  &quot;failures&quot;: [<br>    {<br>      &quot;step&quot;: 3,<br>      &quot;error&quot;: &quot;invalid env var&quot;,<br>      &quot;timestamp&quot;: &quot;2026-01-31T10:42Z&quot;<br>    }<br>  ],<br>  &quot;revision&quot;: 7<br>}</pre><blockquote><strong>This is authoritative.<br>The LLM is not allowed to contradict it.</strong></blockquote><p>If the LLM suggests:</p><blockquote><strong><em>“Start from scratch.”</em></strong></blockquote><p>You discard it.</p><p>The LLM proposes actions.<br><strong> The agent enforces the state.</strong></p><h3>Deterministic Recovery</h3><h4>How “State” Is Retrieved After Failure:</h4><p>Now imagine a process crashes mid-step.</p><h4>On Restart:</h4><ol><li>New agent instance starts</li><li>Reads state by agent_id</li><li>Sees:</li></ol><pre>status = IN_PROGRESS<br>current_step = 3</pre><p>4. Sees last failure:</p><pre>&quot;failures&quot;: [<br>    {<br>      &quot;step&quot;: 3,<br>      &quot;error&quot;: &quot;invalid env var&quot;,<br>      &quot;timestamp&quot;: &quot;2026-01-31T10:42Z&quot;<br>    }<br>  ]</pre><p>5. Resumes <strong>from step 3</strong>, not from scratch.</p><p>No guessing.<br>No retrieval-based reconstruction.<br>No prompt archaeology.</p><p>This is identical to how:</p><ul><li>Workflow engines resume</li><li>Database migrations resume</li><li>CI pipelines resume</li></ul><p>Nothing magical here.<br><strong>Agents are no different.</strong></p><h3>Nondeterminism: The Real Failure Mode</h3><p>Without ownership:</p><ul><li>Two instances mutate state differently.</li><li>Plans diverge.</li><li>Failures repeat.</li><li>Progress is ambiguous.</li><li>Behavior becomes irreproducible.</li></ul><p>And when an engineer tries to debug it, they find:</p><ul><li>Prompt logs.</li><li>Vector hits.</li><li>Embeddings.</li><li>Stochastic outputs.</li></ul><p>But no authoritative execution history.</p><blockquote><strong>That’s not an AI failure.<br>That’s a consistency failure.</strong></blockquote><h3>LLM vs Agent: Who Decides What to Do Next?</h3><p>The <strong>agent</strong>, not the LLM.<br>The LLM is asked a constrained question:</p><blockquote><strong>“Given this state, what is the next action?”</strong></blockquote><p>It does <strong>not</strong> get to:</p><ul><li>Invent a new goal</li><li>Reset steps</li><li>Ignore failure history</li><li>Hallucinate progress</li></ul><p>If it tries, the agent discards it.<br>That’s how you build determinism on top of probabilistic reasoning.</p><p>If you implement this, your agent:</p><ul><li>Survives restarts</li><li>Recovers from failure</li><li>Improves over time</li><li>Behaves coherently</li></ul><p>If you don’t, you’re just looping prompts and hoping.</p><h3>The Correct Mental Model</h3><h4>Lock This In:</h4><ul><li>LLM = reasoning component (brain)</li><li>Agent = control loop + state machine + reasoning component</li><li>Durable store = source of truth</li><li>Vector DB = optional recall aid, not authority</li><li>Prompts = queries, not history</li></ul><h3>Conclusion: This Is a Ownership &amp; Consistency Model Question</h3><p>If your agent memory behaves unpredictably, contradicts itself, retries dead paths, or “forgets” decisions, the problem is not intelligence.</p><blockquote><strong>It’s consistency.</strong></blockquote><p>You built shared mutable state without defining:</p><ul><li>Who owns writes?</li><li>Who is allowed to transition state?</li><li>What happens under concurrent updates?</li><li>What guarantees exist after failure?</li></ul><p>Embeddings don’t solve that.<br>Bigger context windows don’t solve that.<br>Better prompts don’t solve that.</p><p>Distributed systems engineers learned this the hard way:</p><p><strong>If ownership is unclear and consistency is weak, behavior becomes nondeterministic.</strong></p><p>And nondeterministic systems are impossible to reason about.</p><p>Now ask yourself:</p><ul><li>When two agent instances write to memory at the same time, what prevents write skew?</li><li>What isolation level does your agent memory actually provide?</li><li>Is a failed decision permanently marked as invalid, or just “likely” to be remembered?</li><li>Can you replay an agent’s execution deterministically from logs?</li><li>If the system restarts mid-task, who guarantees forward-only state transitions?</li><li>Is memory authoritative — or advisory?</li></ul><p>If you can’t answer those precisely, you don’t have agent memory.<br><strong>You have shared text storage.</strong></p><p>And shared text storage under concurrency is just distributed chaos with embeddings on top.</p><h3>What Comes Next</h3><p>Once you fix ownership and consistency, another uncomfortable truth emerges:</p><p>Many systems that claim <strong>“agent autonomy”</strong> are not autonomous at all.</p><p><strong>They’re stochastic.</strong></p><p>They behave differently, not because they reason better but because <strong>nothing</strong> enforces deterministic progression.</p><p>What looks like autonomy is often just uncontrolled randomness.</p><p>In the next article:</p><p><strong>“Randomness Disguised as Autonomy”</strong></p><p>We’ll dissect why many agent systems appear intelligent simply because they are nondeterministic.</p><p>And why uncontrolled stochastic behavior is not autonomy, but architectural laziness.</p><p>That’s where the illusion really starts to crack.</p><h3>Related Articles</h3><ul><li><a href="https://medium.com/@inderbindra/ai-systems-are-nothing-but-distributed-systems-43efbf1026d7"><strong>AI Systems Are Just Distributed Systems (And We Are Repeating Old Mistakes)</strong></a><strong> </strong>— This article talks about how AI systems aren’t a new category of software. They’re distributed systems with language models embedded inside them.</li><li><a href="https://medium.com/@inderbindra/agents-are-stateful-services-not-stateless-functions-59738c68737f"><strong>AI Agents Are Stateful Services, Not Stateless Functions</strong> </a>— This article talks about how you don’t need better models, longer context windows, clever prompts, or bigger vector databases for your agent to remember or perform better. Instead, it’s about treating agents as <strong>long-lived stateful services</strong>, not disposable function calls.</li></ul><h3>Before you go</h3><ul><li>Please take a moment to like the post, share your thoughts, and follow for more articles like this.</li><li>You can also follow me on <a href="https://www.linkedin.com/in/inderbindra"><strong>LinkedIn</strong></a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c9fc8521c79" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>