<?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 Devanshusharma on Medium]]></title>
        <description><![CDATA[Stories by Devanshusharma on Medium]]></description>
        <link>https://medium.com/@devanshusharma658?source=rss-9043612addc6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*FWjQPp8en27QVhkaSbUo_Q.jpeg</url>
            <title>Stories by Devanshusharma on Medium</title>
            <link>https://medium.com/@devanshusharma658?source=rss-9043612addc6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 22:42:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@devanshusharma658/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The talk of the trillions.]]></title>
            <link>https://medium.com/@devanshusharma658/the-talk-of-the-trillions-e5ce2d07c616?source=rss-9043612addc6------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5ce2d07c616</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[payments]]></category>
            <dc:creator><![CDATA[Devanshusharma]]></dc:creator>
            <pubDate>Wed, 06 May 2026 13:11:49 GMT</pubDate>
            <atom:updated>2026-05-06T13:12:02.566Z</atom:updated>
            <content:encoded><![CDATA[<p>I love distributed systems. And at some point, if you spend enough time around them, you inevitably become obsessed with one thing: <strong>“transactions”</strong>.</p><p>Not the database textbook kind. Real-world transactions. The kind where money moves, banks respond whenever they feel like it, networks retry requests, and a tiny bug can accidentally charge someone twice. Suddenly, “eventual consistency” doesn’t sound nearly as charming.</p><p>Payment systems are where distributed systems stop being theoretical and start becoming very, very expensive. You’re no longer just moving bytes around. You are moving trust, compliance, and actual money. Every API call carries financial consequences. Each retry could result in a duplicate charge. Every outage is instantly visible to customers, merchants, and regulators alike.</p><p>And the scale is staggering. Modern payment platforms like Stripe process trillions of dollars annually, serve millions of businesses worldwide, and maintain near-perfect availability while coordinating across banks, card networks, and regulatory boundaries.</p><p>What makes payment infrastructure fascinating is the brutal set of constraints it operates under:</p><ul><li>Exactly-once semantics in an at-least-once world</li><li>Strict consistency where it matters</li><li>Fault tolerance across unreliable external systems</li><li>Global scale under unforgiving latency requirements</li><li>Compliance in dozens of jurisdictions</li></ul><p>This is one of the hardest engineering problems on the planet.</p><p>In this blog, we’ll design a payment processing platform capable of handling trillions of dollars in annual transaction volume and operating at the scale of Stripe. We’ll dive deep into architecture, consistency models, ledger design, idempotency, multi-region replication, and the operational realities of moving money safely across the globe.</p><p>Because when distributed systems meet finance, every edge case eventually becomes a production incident.</p><h3>Key Design Goals</h3><p>Designing a global payment system is really about balancing three things: scale, reliability, and correctness. It’s not enough to be fast. You must also be right, every single time. In payments, a single duplicate charge is far worse than a slightly slower response.</p><p>At the scale we’re targeting, the requirements become extreme.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FtVzD-Cw2x4aqCT4xGNezQ.png" /></figure><p>A few of these deserve special attention.</p><p><strong>Five-nines availability</strong> means less than six minutes of downtime per year. That rules out traditional “maintenance windows” entirely. The system must continue operating even during deployments, hardware failures, and regional outages.</p><p><strong>500,000 TPS</strong> isn’t just a scaling challenge; it’s a coordination challenge. Every transaction touches multiple systems: fraud detection, ledgering, payment orchestration, compliance checks, and external banking networks.</p><p><strong>Twelve nines durability</strong> means financial data can never be lost. Ever. If a payment succeeds, that record must survive disk failures, rack failures, datacenter failures, and even regional disasters.</p><p>And then comes the hardest requirement of all: correctness. Money cannot be “eventually consistent” in the same way social media likes can be. Your bank balance has very strong opinions about consistency.</p><p>These goals shape every architectural decision that follows.</p><h3><strong>Scale and Requirements.</strong></h3><h4>Back-of-the-Envelope Calculations</h4><p>Before drawing boxes and arrows, it’s worth doing some quick math. Otherwise, you risk designing a lemonade stand and calling it a payment processor.</p><p>We’re targeting something in the ballpark of Stripe, which processed around $1.4 trillion in 2024. Assuming an average transaction size of about $50, that’s roughly 28 billion transactions a year which is around 77 million every day. And that’s just an ordinary Tuesday. During Black Friday, Cyber Monday, or a particularly enthusiastic sneaker drop, traffic can spike dramatically. Sustained throughput might sit around 30,000 to 50,000 TPS, but peak bursts can easily hit 500,000 TPS. In payments, “rare traffic spikes” are really just scheduled holidays.</p><p>Storage gets serious very quickly. A single transaction might only be a couple of kilobytes, but payments are accountants in disguise. Every transaction generates multiple ledger entries, audit logs, events, and reconciliation records. At scale, you’re writing nearly 10 TB of new data every day. Over a year, that’s multiple petabytes before replication. Triple-replicate it(as you absolutely should) and suddenly you’re managing over 10 PB of critical financial data. This isn’t the kind of workload you casually point at a single database and hope for the best.</p><p>Then there’s the network. A payment usually involves several API calls: creation, authorization, capture, settlement, webhook delivery, and often a few retries because the internet enjoys keeping engineers humble. That translates to hundreds of millions of API requests daily and multiple terabytes of network traffic. At this scale, your API gateway isn’t just routing requests, it’s effectively air traffic control for money.</p><h4>Functional Requirements</h4><p>The functional requirements are extensive because a real payment platform has to handle far more than simply charging a card. It must support the entire payment lifecycle like authorization, capture, refunds, and voids and across cards, bank transfers, digital wallets, and Buy Now, Pay Later providers. It needs real-time foreign exchange across 135+ currencies, robust merchant onboarding with KYC/KYB, payout management, and marketplace capabilities similar to Stripe Connect. Recurring billing is essential, complete with subscriptions, proration, invoicing, and dunning workflows for failed payment recovery. At the core sits an immutable double-entry ledger with automated reconciliation, because money and “best effort” should never appear in the same sentence. Merchants also expect real-time webhooks, dashboards, financial reporting, and bulk data exports. And, of course, the system must fully support disputes like chargebacks, evidence submission, and representment workflows. In payments, all of this is table stakes.</p><h4>Non-functional requirements</h4><p>The non-functional requirements are where payment systems get serious. Availability has to hit 99.999%, which gives you barely five minutes of downtime a year, and even that can feel uncomfortably high when money is involved. Authorization latency needs to stay under 100ms at p50 and under 500ms at p99, because every extra millisecond can cost real conversions. Consistency for financial operations must be strong; bank balances are not something you eventually figure out. Analytics can relax a little, but money movement absolutely cannot.</p><p>Durability means zero data loss. Not almost zero. Zero. The system must scale horizontally and absorb massive traffic spikes, even 10x normal load, without an engineer scrambling to add capacity. Security starts with PCI-DSS Level 1, end-to-end encryption, and tokenization. Those are table stakes. Compliance across frameworks like GDPR, PSD2, and SOX has to be built into the architecture from day one, because retrofitting compliance later is about as enjoyable as performing surgery on a moving train.</p><p>Finally, every cent that moves through the system must leave behind a complete, immutable audit trail. In payment infrastructure, “we’re pretty sure what happened” is not an acceptable debugging strategy.</p><p><strong>High Level Architecture:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nQOcNTOZZpftgVpZYW8GlQ.png" /></figure><h3>Design Principles</h3><p><strong>API-First</strong><br>Every capability should be exposed through a versioned, backward-compatible API. Payments power other businesses, so breaking integrations is a fantastic way to make enemies.</p><p><strong>Layered Architecture</strong><br>Keep strict boundaries between layers: Edge, Application, and Data. Each layer should have a single job. When everything talks to everything, debugging becomes archaeology.</p><p><strong>Event Sourcing</strong><br>Every state transition must be recorded as an immutable event. Financial systems should remember everything, even the mistakes.</p><p><strong>Double-Entry Bookkeeping</strong><br>Money never appears or disappears. Every debit must have a corresponding credit. Accounting has been solving this problem for centuries, so it’s wise not to get creative here.</p><p><strong>Idempotency Everywhere</strong><br>Every write operation must be safely retryable. Networks fail, clients retry, and duplicate charges tend to ruin everyone’s day.</p><p><strong>Defense in Depth</strong><br>Security should exist at every layer. Authentication, authorization, encryption, validation, rate limiting, and continuous monitoring all work together.</p><p><strong>Blast Radius Containment</strong><br>Failures should stay local. A single broken payment processor should not turn your entire platform into modern art.</p><p><strong>Boring Reliability</strong><br>This is not the place to debut your revolutionary new consensus algorithm. In payments, proven and predictable beats clever every single time.</p><h3>Core Components</h3><h4><strong>API Gateway</strong></h4><p>The API Gateway is the front door to the entire payment platform. Every single request from every merchant, mobile app, partner integration, and webhook callback enters through this layer first. At global scale, this isn’t one gateway sitting behind a load balancer. It’s a worldwide fleet of edge proxies distributed across multiple continents, strategically placed close to merchants. Whether a request originates in Tokyo, London, São Paulo, or New York, the first hop should always be nearby. Latency matters, and in payments, every millisecond counts.</p><p>This layer carries an enormous amount of responsibility. Before a request ever reaches your business logic, the gateway has already terminated TLS, validated certificates, authenticated the caller, checked API keys or OAuth tokens, validated the request schema, enforced rate limits, selected the correct API version, and routed traffic to the appropriate backend service. It also logs every request and response for observability, security, and compliance. That’s intentional. Cross-cutting concerns belong at the edge. Backend services should focus on payments, not on parsing headers or arguing with malformed JSON.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zqgru4aJadRDxeShk7Er0Q.png" /></figure><p>Rate limiting here is much more sophisticated than simply counting requests per second. The first layer uses a token bucket to enforce per-API-key request limits while still allowing merchants some burst capacity. A merchant might normally be allowed 100 requests per second, but brief spikes above that are perfectly reasonable during flash sales or checkout surges. The second layer limits concurrent in-flight requests per merchant. This protects expensive endpoints from being overwhelmed by aggressive clients opening hundreds of parallel connections. Throughput matters, but fairness matters too.</p><p>Things get really interesting when the entire fleet starts feeling pressure. At that point, protecting the platform becomes more important than serving every request equally. Traffic gets classified into critical and non-critical categories. Creating charges, authorizing payments, and processing captures are critical. Listing past transactions or generating reports is not. Once fleet utilization climbs past a predefined threshold, non-critical traffic begins getting shed automatically, preserving capacity for actual money movement. Nobody likes seeing a dashboard timeout, but it’s infinitely better than declining a legitimate payment.</p><p>The gateway also monitors the health of individual workers. Even if overall fleet utilization looks fine, a single hot node can still melt down under uneven traffic distribution. Per-worker CPU, memory, queue depth, and latency are continuously tracked. As a worker approaches saturation, it progressively rejects lower-priority traffic before it becomes unhealthy. This keeps failures isolated and prevents one overloaded machine from cascading into a broader incident.</p><p>Under the hood, this layer is typically powered by Envoy Proxy with custom filters for authentication, routing, and advanced rate limiting. Shared counters usually live in a globally replicated Redis cluster so limits apply consistently across every edge location. Without shared state, a merchant could accidentally multiply their quota simply by hitting multiple regions, which would be… creatively unfair.</p><p>API versioning is another place where payment systems must be uncompromising. Once an API version is published, it becomes a contract. Not a suggestion. Not a living document. A contract. Merchants build real businesses on top of these APIs, and silently changing behavior is a wonderful way to ruin someone’s weekend. Backward compatibility is sacred.</p><p>At this scale, the API Gateway is far more than a reverse proxy. It’s a security perimeter, a traffic cop, a shock absorber, and occasionally a bouncer. When the rest of the system is under stress, this layer decides what gets through and what politely gets told to come back later. In many ways, the reliability of the entire platform starts right here.</p><h4>Authentication Service</h4><p>Right after a request clears the API Gateway, it lands at the Authentication Service. This component answers one very important question: “Who exactly is asking?” In payments, that’s not a question you ever want to get wrong.</p><p>The flow is straightforward but extremely performance-sensitive. The service extracts the API key from the request, usually from the Authorization header, and looks it up. Hot keys are served directly from an in-memory cache, while cache misses fall back to a distributed datastore. Once the key is found, the system verifies that it’s active, hasn’t expired, hasn’t been revoked, and belongs to a valid merchant account. Only then does it move on to permissions.</p><p>Permissions are where things get interesting. Not every key should be able to do everything. A frontend application should never have the same privileges as a backend payment server. That’s why payment platforms typically support multiple key types. Publishable keys are designed for client-side use and can only perform safe operations like tokenizing card details. Secret keys are server-side credentials with full API access. Restricted keys sit somewhere in the middle, allowing merchants to grant narrowly scoped permissions for specific use cases, like read-only analytics or refund-only access.</p><p>Once the key is validated, the service enforces its scopes and permissions. Can this key create charges? Issue refunds? Access customer data? Read payout reports? Every request gets checked against a precise permission matrix. If the answer is no, the request stops right there. The fastest request is the one you never forward.</p><p>After successful validation, the Authentication Service attaches merchant context to the request. This usually includes the merchant ID, account tier, enabled capabilities, region, risk profile, and feature flags. Downstream services should never need to perform another identity lookup. By the time a request reaches the payment orchestrator, it already knows exactly who the merchant is and what they’re allowed to do.</p><p>API key storage deserves special care. Raw keys are never stored directly. Instead, they’re hashed using Argon2, specifically Argon2id, which is resistant to both GPU and side-channel attacks. Even if the key store were compromised, attackers wouldn’t simply walk away with usable credentials. In payment infrastructure, assuming breaches are impossible is an excellent way to eventually become a case study.</p><p>For dashboard users, the system relies on short-lived JWT session tokens after initial authentication. These tokens carry the necessary identity and authorization claims, minimizing repeated database lookups while keeping sessions secure. Short expiration times reduce blast radius if a token is ever leaked.</p><p>Key rotation is another feature that seems optional until the first security incident. Merchants must be able to rotate keys without downtime. The usual approach is overlapping validity periods, where both old and new keys work simultaneously during a grace window. This gives merchants time to update their systems without breaking production traffic. Abrupt key invalidation may be secure, but it tends to create very memorable support tickets.</p><p>At scale, the Authentication Service becomes one of the hottest paths in the entire platform. Every request passes through it. That means ultra-low latency, aggressive caching, and rock-solid availability are mandatory. If authentication goes down, everything goes down. It’s not glamorous, but it’s absolutely mission-critical.</p><h4>Payment Orchestrator</h4><p>If the API Gateway is the front door, the Payment Orchestrator is the brain. This is the component that actually understands what a payment is supposed to do. It coordinates the entire lifecycle, talks to half a dozen downstream systems, handles failures, and somehow keeps everything consistent even when external providers behave like external providers.</p><p>At a high level, every payment follows the same journey. First, the request is validated. Is the amount valid? Is the currency supported? Does the merchant have permission to use this payment method? Are all required fields present? It’s amazing how many bad requests can be stopped before they become expensive.</p><p>Once the request passes validation, it moves to risk evaluation. Fraud detection systems score the transaction in real time, often in just a few milliseconds. The orchestrator might consult machine learning models, velocity checks, device fingerprints, geolocation signals, and merchant-specific rules. A payment is only valuable if it’s legitimate.</p><p>Next comes processor selection, which is one of the most important decisions in the entire system. The orchestrator chooses which acquiring bank, payment gateway, or alternative payment provider should handle the transaction. This decision can depend on geography, currency, card network, historical success rates, latency, cost, or even real-time outages. Routing a Visa card issued in Germany through the same path as a UPI payment in India would be… adventurous.</p><p>After selecting the optimal processor, the orchestrator executes the payment. This is where the system leaves the comfort of its own datacenter and starts talking to networks it does not control. Timeouts, retries, partial failures, duplicate callbacks, and bizarre edge cases are all part of the job description.</p><p>Because payment processing spans multiple services, the orchestrator typically implements the Saga pattern for it. Traditional distributed transactions across banks, ledgers, fraud engines, and third-party processors would be painfully slow and, frankly, impossible. Instead, each step commits independently, and if something fails later, compensating actions are executed. Think of it as carefully undoing a very expensive mistake.</p><p>For example, suppose authorization succeeds at the processor, but ledger recording fails. The orchestrator can issue a compensating void or reversal. If a downstream webhook system is temporarily unavailable, the payment still succeeds while delivery is retried asynchronously. The goal isn’t to avoid failure. The goal is to survive it gracefully.</p><p>Once the processor responds, the orchestrator records the transaction in the immutable ledger. This is the point where the payment becomes financially real inside your system. Money may still settle later, but the economic event has occurred.</p><p>Finally, the orchestrator emits domain events such as payment.authorized, payment.captured, or payment.failed. These events fan out to webhooks, analytics, notifications, reconciliation pipelines, and any other interested consumers. In a modern payment platform, events are the nervous system.</p><p>The orchestrator also owns idempotency. If a merchant retries the same request because their network timed out, the system must return the original result rather than creating a second charge. Charging a customer twice is an excellent way to get very prompt feedback.</p><p>At scale, this service becomes one of the most critical pieces of the entire platform. It needs to be stateless, horizontally scalable, and extremely resilient. Every payment flows through it. Every outage is instantly visible. Every bug has a monetary value attached.</p><p>This is where distributed systems meet finance, and suddenly “eventual consistency” starts sounding like a career-limiting phrase.</p><p><strong>Payment State machine</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kXcnk3H3jXHmYwYNxtl31A.png" /></figure><p>Payments may look simple from the outside. Click a button, see a success message, move on with life. Under the hood, though, every payment is really a carefully controlled state machine. And that’s a very good thing. Money should never freestyle.</p><p>A payment always starts in the Created state. At this point, the request has been accepted, validated, and assigned a globally unique identifier, but no money has moved yet. From there, it transitions to Pending Authorization, where the system reaches out to the acquiring bank, card network, or alternative payment provider.</p><p>Once authorization completes, one of three things happens. The payment is either approved, declined, or encounters a temporary error. Declines are terminal. The bank has spoken. Temporary errors, on the other hand, often trigger retries, because financial networks occasionally communicate through interpretive dance.</p><p>If authorization succeeds, the payment moves into the Captured state. This is the point where funds are officially reserved or collected, depending on the payment method. From here, the payment can eventually settle, be refunded, or enter a dispute workflow if the customer decides to keep life interesting.</p><p>The final states usually include Settled, Refunded, and Disputed. Settlement means the funds have actually moved through the banking rails. Refunded means some or all of the money has been returned. Disputed means you&#39;re about to become intimately familiar with card network rules and evidence submission deadlines.</p><p>Every transition is atomic. Either the entire state change happens, or none of it does. There is no such thing as being “mostly captured.” Each transition is also event-sourced, meaning an immutable event is written to the event log before the system acknowledges success. This gives you a complete audit trail of every step the payment has ever taken.</p><p>The state machine strictly enforces valid transitions. You cannot refund a declined payment. You cannot capture a payment that was never authorized. You cannot settle something that failed three states ago and is currently enjoying retirement. These rules eliminate entire categories of bugs before they ever reach production.</p><p>To handle concurrency safely, every payment carries a version number. State transitions use optimistic concurrency control, ensuring that two competing updates cannot both succeed. This matters more than you’d think. Webhooks retry, clients reconnect, and distributed systems are very enthusiastic about doing the same thing twice.</p><p>In payments, the state machine is not just an implementation detail. It’s the source of truth. When engineers ask, “What happened to this payment?”, the answer lives here.</p><h4>Payment Router</h4><p>If the Payment Orchestrator is the brain, the Payment Router is the air traffic controller. Its job is simple in theory and wonderfully complicated in practice: given a payment, figure out the absolute best path to get it approved.</p><p>That decision depends on a surprising number of variables. The card network matters. A Visa transaction may take a completely different route than an American Express one. The issuing country matters. So does the currency. A payment in euros issued by a French bank should probably not take the same path as a UPI transaction in India or an ACH transfer in the United States.</p><p>Then comes the business side. Different processors have different fee structures, authorization rates, geographic strengths, and latency characteristics. Sometimes the cheapest processor isn’t the fastest and sometimes the fastest isn’t the most reliable. Sometimes one of them is having a very public bad day. The router has to balance all of that in real time.</p><p>Merchant preferences also play a major role. Large merchants often negotiate custom acquiring relationships, preferred processors, or region-specific routing rules. Some care deeply about cost optimization. Others care more about approval rates. The router needs to support both without judgment.</p><p>A typical routing decision considers the card BIN to determine issuer geography, the payment currency, transaction amount, processor limits, real-time health metrics, recent authorization rates, and interchange economics. It is essentially a tiny financial decision engine running for every single payment.</p><p>When a processor is unavailable, failover must be instant. The router automatically falls back from the primary processor to a secondary, then tertiary option if necessary. Ideally, the customer never notices. The processor might be on fire, but checkout should remain pleasantly boring.</p><p>The real magic lies in abstraction. Every payment processor has its own API, quirks, timeout semantics, and creative interpretation of industry standards. One returns XML. Another returns JSON. A third appears to have been designed during a particularly difficult week in 2007.</p><p>To shield the rest of the platform from this chaos, every processor implements a common interface:</p><pre>interface PaymentProcessor {<br>    authorize(request: AuthRequest): Promise&lt;AuthResponse&gt;;<br>    capture(authId: string, amount: Money): Promise&lt;CaptureResponse&gt;;<br>    refund(captureId: string, amount: Money): Promise&lt;RefundResponse&gt;;<br>    void(authId: string): Promise&lt;VoidResponse&gt;;<br>    getStatus(transactionId: string): Promise&lt;TransactionStatus&gt;;<br>}</pre><p>Each concrete adapter translates this clean internal contract into whatever the external provider expects.</p><pre>class VisaNetAdapter implements PaymentProcessor { /* ... */ }<br>class MastercardAdapter implements PaymentProcessor { /* ... */ }<br>class ACHAdapter implements PaymentProcessor { /* ... */ }<br>class SEPAAdapter implements PaymentProcessor { /* ... */ }<br>class UPIAdapter implements PaymentProcessor { /* ... */ }</pre><p>This abstraction is incredibly valuable. The orchestrator never needs to know whether it’s talking to Visa, Mastercard, ACH, SEPA, or UPI. It simply calls authorize(). The adapter handles the messy details.</p><p>That separation pays off in multiple ways. Adding a new processor becomes straightforward. Testing becomes dramatically easier. Failover logic stays centralized. And most importantly, your core payment flow remains blissfully unaware of the wonderfully inconsistent world beyond your walls.</p><p>At scale, routing isn’t static either. Modern systems continuously learn. They track approval rates, latency, error rates, and costs in real time, dynamically adjusting routing weights. If one processor starts underperforming, traffic shifts automatically. It’s less like a switch statement and more like a tiny high-frequency trading system, except the asset being traded is authorization success.</p><h4>Webhook / Event Delivery Service</h4><p>Webhooks are one of those features that seem trivial until you try to run them at scale. “Just send an HTTP POST” sounds innocent enough. Then you realize you’re delivering billions of events to millions of merchant endpoints, many of which are slow, flaky, misconfigured, or occasionally hosted on what appears to be a potato.</p><p>Every important payment event eventually flows through this system. Payment succeeded. Refund issued. Charge disputed. Payout completed. Merchants depend on these notifications to keep their own systems in sync. For many of them, webhooks are the source of truth.</p><p>The biggest challenge is isolation. A merchant’s broken endpoint should never impact core payment processing. If their server is timing out, that’s unfortunate for them, but your authorization pipeline still needs to hum along at hundreds of thousands of TPS.</p><p>That’s why event delivery is fully asynchronous. Payment services publish events to a durable Kafka topic and immediately move on. From that point onward, webhook delivery becomes its own separate problem, which is exactly how you want it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9r988myJ6MWEKLXKlLfaEg.png" /></figure><p>Each worker consumes events partitioned by merchant ID. That detail matters. It gives you horizontal scalability while preserving best-effort ordering for each merchant. One merchant’s traffic won’t block another’s, and related events usually arrive in sequence.</p><p>Before delivery, the worker serializes the event payload and signs it using HMAC-SHA256 with the merchant’s unique webhook secret. This allows merchants to verify authenticity and reject forged requests. In payments, trusting unsigned callbacks would be a bold career choice.</p><p>The worker then performs the HTTP POST and records the full delivery attempt, including status code, latency, headers, and response body. Observability is crucial here because debugging someone else’s webhook server is already enough fun without missing logs.</p><p>Failures are expected, not exceptional. Merchant endpoints go down. DNS breaks. TLS certificates expire at the least convenient moment. When delivery fails, the system retries using exponential backoff.</p><p>After exhausting the retry policy, the event is moved to a dead-letter queue for manual inspection or automated recovery workflows. Sometimes the internet wins.</p><p>The delivery guarantee is at-least-once. Exactly-once delivery over HTTP is the sort of thing people promise right before a distributed systems professor starts laughing. Merchants must therefore implement idempotent webhook handlers using event IDs.</p><p>Ordering is best-effort, not absolute. Network retries and parallel processing can occasionally reorder events. Merchants should always rely on event timestamps and object versions rather than assuming perfect sequence.</p><p>Most importantly, webhook traffic is completely decoupled from payment processing. A global outage affecting merchant endpoints should create a very busy retry queue, not a payment outage. Core money movement and external notifications live in separate failure domains.</p><p>At scale, the Webhook Delivery Service becomes one of the largest outbound HTTP fleets you’ll ever run. It spends its days talking to the public internet, which is both brave and deeply unwise. But when designed correctly, it turns payment events into a reliable, developer-friendly stream that merchants can trust.</p><h4>Storage Architecture Overview</h4><p>Payment systems are a masterclass in using the right tool for the right job. Trying to store everything in one database is a little like bringing a spoon to a construction site. Technically possible, but everyone’s going to have concerns.</p><p>Different types of payment data have wildly different access patterns. A payment being authorized right now needs ultra-low latency and strong consistency. A merchant generating last quarter’s revenue report cares more about scan speed than write latency. A regulator asking for records from six years ago mostly cares that you still have them. One storage engine simply cannot excel at all three.</p><p>That’s why large-scale payment platforms use a tiered storage architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*IudmgSx8uLD0yp1KYaXjjw.png" /></figure><p>The hot tier handles live traffic. This is where today’s payments live. Redis clusters serve low-latency caches for idempotency keys, sessions, and frequently accessed merchant metadata. The primary transactional database, typically something like sharded PostgreSQL or CockroachDB, stores active payment records, ledger entries, and transactional state. Alongside it sits Kafka, acting as the real-time event backbone for asynchronous processing. This tier is optimized for speed, consistency, and surviving the kind of traffic spikes that make dashboards exciting.</p><p>The warm tier is where data goes once it cools down a bit. Payments from last week probably aren’t being updated anymore, but they’re still queried constantly. Read replicas absorb reporting and dashboard traffic without burdening the primary write path. Analytical workloads move into columnar systems like ClickHouse or Google BigQuery, where scanning billions of rows feels pleasantly normal. Unstructured data, such as dispute evidence, KYC documents, and webhook payloads, often lives in document stores like MongoDB.</p><p>Then comes the cold tier, where data goes to enjoy a long, compliant retirement. Historical transactions are archived into object storage such as Amazon S3 or Google Cloud Storage, typically stored in columnar formats like Parquet for efficient retrieval. Older relational data may be compressed into read-optimized archival databases. Compliance records, meanwhile, are locked away in immutable, encrypted storage with multi-year retention policies. Financial regulators tend to have excellent memories.</p><p>This separation delivers three huge benefits. First, performance stays predictable because hot transactional workloads never compete with massive analytical queries. Second, storage costs remain sane, since you aren’t keeping seven years of data on premium SSD-backed databases. Third, compliance becomes much easier when archival and retention policies are built directly into the storage lifecycle.</p><p>In payments, data rarely dies. It simply gets progressively cheaper to keep around.</p><h4><strong>Primary Transactional Database</strong></h4><p>Choosing the primary database for a payment system is one of those decisions that will either quietly serve you for years or become the subject of several very expensive migration projects. This is the system of record. Every payment, every authorization, every refund, every ledger entry eventually lands here. It needs to be fast, durable, strongly consistent, and utterly boring in the best possible way.</p><p>For most teams, the safest default is sharded PostgreSQL. PostgreSQL has earned its reputation the hard way. Its ACID guarantees are rock solid, the ecosystem is phenomenal, and every operational problem you encounter has almost certainly been encountered, documented, and complained about by thousands of engineers before you. That’s a feature.</p><p>The downside, of course, is sharding. PostgreSQL doesn’t magically become distributed just because you ask nicely. Once you outgrow a single node, you’re responsible for partitioning data, routing queries, handling rebalancing, and explaining to new hires why cross-shard joins are forbidden fruit. It’s fantastic if you’re starting in a single region and want maximum consistency with minimal surprises.</p><p>If you’re building globally from day one, CockroachDB becomes extremely compelling. It offers automatic sharding, strong consistency, and multi-region replication out of the box. You get a familiar SQL interface while the database handles distribution, replica placement, and failover. The tradeoff is latency. Global consensus is physics wearing a database costume. Cross-region writes are inevitably slower than local ones.</p><p>For pure financial ledgers, TigerBeetle is a fascinating option. It was designed specifically for high-throughput financial workloads and can comfortably push over a million transactions per second on modern hardware. That’s absurdly impressive. The catch is that it’s young, specialized, and not intended to replace your entire application database. Think of it as a race car, not a family sedan.</p><p>Historically, Stripe famously built much of its early infrastructure on MongoDB. That choice made a lot of sense at the time. Flexible schemas enabled rapid product iteration, and horizontal scaling was far easier than traditional relational systems offered back then. Over time, Stripe engineered that stack into an absolute monster, reportedly handling millions of queries per second with extraordinary reliability. It’s a reminder that great engineering matters more than fashionable technology choices.</p><p>That said, document databases like MongoDB come with tradeoffs. Strong consistency requires careful configuration, multi-document transactions arrived relatively late, and financial workloads often fit relational models more naturally. MongoDB shines when schema flexibility and rapid iteration are priorities.</p><p>For teams deeply invested in MySQL, Vitess is another battle-tested option. Originally developed at YouTube, it adds sharding, routing, and scaling capabilities on top of MySQL. If your organization already has MySQL expertise, Vitess can be an excellent choice. Reinventing your operational muscle memory is rarely fun.</p><p>So what should you actually choose?</p><p>If you’re building a payment company today, sharded PostgreSQL is the pragmatic starting point. It offers the strongest balance of consistency, ecosystem maturity, and operational familiarity. You can always evolve later, but starting with a boring, reliable database is often the smartest move you’ll make.</p><p>If global active-active deployment is a hard requirement from day one, CockroachDB deserves serious consideration.</p><p>If your primary workload is ledgering at extreme scale, TigerBeetle is worth watching very closely.</p><p>The best database is not the most impressive one. It’s the one that lets your team sleep at night while moving billions of dollars.</p><h4>Sharding Strategy</h4><p>Once your payment system grows beyond a single database, sharding stops being an architectural option and becomes a lifestyle choice. The key question is simple: what do you shard on? The wrong answer will haunt you for years.</p><p>For payments, the obvious and usually correct choice is merchant_id (or account_id). Most operations are naturally scoped to a single merchant. A merchant creates payments, issues refunds, views payouts, and queries their own data. Very few workflows need to touch multiple merchants simultaneously, which is exactly what you want.</p><p>That single decision eliminates an enormous amount of complexity. By colocating all of a merchant’s data on the same shard, you avoid cross-shard transactions for the overwhelming majority of requests. And cross-shard transactions are where happiness goes to die.</p><p>It also provides excellent data locality. A merchant’s payments, customers, subscriptions, disputes, and ledger entries all live together. Queries stay fast, joins remain local, and cache efficiency improves dramatically. Your database and your future self will both appreciate this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*psm17CJ5aFp8KpvGp04dQQ.png" /></figure><p>To make scaling manageable, you typically create a large number of logical shards upfront, far more than you initially need. A common choice is 256 logical shards. That number is small enough to reason about yet large enough to support years of growth and painless rebalancing.</p><p>These logical shards are then mapped onto a smaller number of physical database clusters. Today, 256 shards might live across eight clusters. Tomorrow, maybe sixteen. The application doesn’t care. That’s the beauty of indirection.</p><p>Each physical cluster usually consists of one primary and at least two replicas. The primary handles writes. Replicas absorb read traffic and provide high availability. On top of that, asynchronous cross-region replication ensures disaster recovery. If an entire region decides to have a terrible day, your data still exists somewhere else.</p><p>Routing requests efficiently is critical. The application computes the logical shard using consistent hashing:</p><pre>const logicalShard = hash(merchantId) % 256;</pre><p>That logical shard is then looked up in a shard map, typically cached locally for speed and periodically refreshed from a centralized configuration service.</p><pre>const cluster = shardMap.get(logicalShard);<br>return cluster.primaryConnection();</pre><p>This extra lookup might seem like overhead, but it gives you tremendous operational flexibility. You can rebalance shards, migrate tenants, or replace hardware without changing application logic.</p><p>Consistent hashing also helps distribute merchants evenly across the fleet. A few giant merchants will always keep life interesting, but overall distribution remains stable and predictable.</p><p>One subtle advantage of merchant-based sharding is operational isolation. If one merchant suddenly experiences Black Friday levels of traffic or accidentally writes a very enthusiastic while loop, the blast radius stays largely contained to their shard.</p><p>In payment systems, that kind of isolation is priceless. One merchant should never be able to ruin checkout for everyone else.</p><h4>Zero-Downtime Migrations</h4><p>At some point, every successful payment company discovers an inconvenient truth: databases do not stay still. You will outgrow hardware, redesign schemas, split shards, move regions, or replace entire storage engines. The only real question is whether you’ll do it gracefully or while everyone is refreshing the status page.</p><p>For a payments platform, downtime during a migration is rarely acceptable. Merchants do not appreciate hearing, “Please wait while we move several petabytes of your money-related data.” So the only viable approach is migrating live, while the system continues serving traffic.</p><p>This is exactly the kind of problem Stripe has famously solved at enormous scale. Their approach is elegant, battle-tested, and just the right amount of terrifying.</p><p>The process begins with dual writes. Every new write is sent to both the old datastore and the new one simultaneously. Reads still come from the old system, but the new system quietly stays in sync. This gives you confidence that fresh traffic is safely replicated while you prepare for the bigger challenge.</p><p>Next comes the backfill phase. Historical data, often petabytes of it, is copied in the background. This can take hours, days, or occasionally enough time to develop a new hobby. The important part is that production traffic continues uninterrupted throughout.</p><p>Once the backfill completes, verification begins. Checksums, row counts, and consistency scans compare the old and new stores. This is where you discover whether your migration is perfect or whether reality has once again chosen violence.</p><pre>Old Store  ────────┐<br>                   ├── Compare Checksums<br>New Store  ────────┘</pre><p>After verification, the fun part arrives: cutover. Read traffic is switched from the old store to the new one. If everything has been designed correctly, this transition takes milliseconds. Ideally, customers never notice. Engineers, meanwhile, notice quite a lot.</p><p>The old system isn’t immediately shut down. That would be optimistic in the wrong way. Instead, it remains available during a validation period. Metrics, error rates, and data consistency are monitored obsessively. Only after confidence is high does the old store finally retire.</p><pre>1. Dual Write<br>2. Backfill<br>3. Verify<br>4. Cutover<br>5. Cleanup</pre><p>This pattern is incredibly powerful because rollback remains simple during the riskiest stages. If anything looks suspicious after cutover, traffic can be redirected back almost instantly.</p><p>At large scale, migrations are no longer rare events. They’re a core operational capability. The companies that master them can evolve continuously. The ones that don’t eventually end up scheduling “mandatory maintenance windows,” which is corporate for “please don’t shop right now.”</p><h4>Caching Layer</h4><p>At payment scale, databases are precious resources. You want them handling critical writes, not repeatedly answering the same question a million times a minute. That’s where the caching layer comes in, and for most payment systems, that means a large, very busy Redis cluster.</p><p>Redis sits directly on the hot path. Nearly every request touches it. Authentication checks, merchant configuration lookups, idempotency enforcement, rate limiting, processor health, foreign exchange rates, card metadata, all of it. If your database is the vault, Redis is the cashier.</p><p>Different data types need different caching strategies. There’s no universal setting that magically works for everything, despite what configuration files may imply at 2 AM.</p><p>API keys and auth tokens are classic cache-aside candidates. The first request fetches from the database and populates Redis, while subsequent requests are served directly from memory. A five-minute TTL is usually enough to absorb most traffic while keeping revocation delays reasonable.</p><p>Merchant configuration follows a similar pattern, but with much shorter expiration. Merchant settings can change frequently, especially during onboarding or feature rollouts. A one-minute TTL strikes a nice balance, and explicit invalidation on updates keeps things fresh. Stale pricing rules are a surprisingly effective way to ruin everyone’s afternoon.</p><p>Rate limiting is a different beast entirely. These counters must be updated atomically and immediately. That makes write-through the obvious choice. Redis excels here, particularly with sliding-window algorithms and Lua scripts for atomicity.</p><p>Idempotency keys are perhaps the most important cache entries in the entire system. They prevent duplicate charges when merchants retry requests. These keys must be written synchronously before processing begins and retained long enough to cover realistic retry windows, typically 24 hours. Accidentally expiring them too early can get very expensive very quickly.</p><p>Processor health data is extremely dynamic. A payment processor that was healthy ten seconds ago might currently be reenacting a small disaster. Health signals are continuously written into Redis with very short TTLs, often around ten seconds. Routing decisions depend on this data being fresh.</p><p>Foreign exchange rates are another classic cache workload. Nobody wants to hit an external FX provider for every payment. Refreshing rates every thirty seconds is usually more than sufficient, unless global currency markets have decided to spice things up.</p><p>BIN lookups, which map card prefixes to issuer metadata, are relatively static and perfect for long-lived caching. A one-hour TTL works well, though in practice many systems refresh even less frequently.</p><p>At scale, the numbers stay surprisingly manageable. Suppose you have ten million active merchants, each with roughly two kilobytes of configuration. That’s only about twenty gigabytes. Fifty million daily idempotency keys at a couple hundred bytes each adds another ten gigabytes. Rate limiting state contributes a few more.</p><p>Altogether, your hot working set often lands somewhere around fifty gigabytes. That’s comfortably handled by a moderately sized Redis cluster, perhaps ten to twelve nodes with plenty of room for replication and failover.</p><p>The real challenge isn’t capacity. It’s availability. Redis becomes part of the critical path, so it must be treated like first-class infrastructure. Multi-AZ deployment, automatic failover, persistence, and careful memory management are mandatory. A cache outage quickly becomes everyone’s problem.</p><p>In high-scale payment systems, Redis isn’t an optimization. It’s infrastructure. Without it, your database would file for emotional support.</p><h3>Message Broker (Apache Kafka)</h3><p>In a modern payment system, not everything should happen synchronously. Charging a card must be fast, but updating analytics, triggering webhooks, running fraud models, and reconciling ledgers can all happen asynchronously. That’s where Apache Kafka comes in.</p><p>Kafka acts as the central nervous system of the entire platform. Every important event flows through it. If the transactional database is the source of truth, Kafka is the bloodstream carrying that truth everywhere else.</p><p>When a payment is authorized, dozens of downstream systems may care. The ledger needs to record entries. Fraud systems need fresh signals. Webhook services must notify merchants. Analytics pipelines want the data immediately. Kafka makes this fan-out effortless.</p><h4>Cluster configuration</h4><p>A production-grade payment platform typically runs a large Kafka cluster in every region.</p><p>Each region might have fifty or more brokers, giving the system enough capacity and fault tolerance to handle enormous traffic spikes. Replication factor is almost always set to three, which means every message exists on three separate brokers. Losing a machine should be an inconvenience, not a company-wide event.</p><p>Topics are heavily partitioned, usually between 256 and 1024 partitions depending on throughput requirements. More partitions mean more parallel consumers, which directly translates into higher scalability.</p><p>Retention is tiered. Hot data stays in Kafka for around seven days, allowing fast replay and debugging. Warm storage may extend retention to thirty days using lower-cost disks or tiered storage. Beyond that, events are typically archived to object storage like Amazon S3 for long-term retention and compliance.</p><p>At serious scale, a single cluster can comfortably process over two million events per second. Kafka was built for exactly this kind of abuse.</p><h4>Core Topics</h4><p>The topic structure mirrors the business itself.</p><p>payment.events is the master stream, containing every payment state transition. If a payment moves from created to authorized to captured, all of those changes appear here.</p><p>payment.authorized and payment.captured provide specialized streams for consumers interested only in successful milestones. This keeps downstream systems simpler and more efficient.</p><p>ledger.entries is one of the most critical topics. Every financial movement eventually lands here, where the accounting system converts events into balanced double-entry records.</p><p>webhook.delivery powers merchant notifications. The webhook service consumes this topic and handles delivery, retries, and dead-lettering.</p><p>fraud.signals streams transaction features into fraud detection models in near real time.</p><p>reconciliation.events feeds settlement and bank matching pipelines.</p><p>Finally, audit.log stores a complete, immutable history of everything. Compliance teams tend to sleep better knowing this exists.</p><h4>Why Kafka Fits Payments So Well ?</h4><p>Payments are naturally event-driven.</p><p>A single card authorization might trigger twenty independent workflows. Without Kafka, your payment service would become a giant, tangled octopus making synchronous calls to everyone.</p><p>With Kafka, the payment service simply publishes an event and moves on. Consumers process it independently, at their own pace.</p><p>This decoupling is enormous. Services can be deployed, scaled, or even temporarily broken without taking down the payment path.</p><h4>Partitioning Strategy</h4><p>Most payment topics are partitioned by merchant_id or payment_id.</p><p>Partitioning by merchant preserves ordering for merchant-specific events, which is critical for webhooks and reporting.</p><p>Partitioning by payment guarantees that all lifecycle events for a given payment land in the same partition, ensuring strict ordering.</p><p>Choosing the wrong partition key is a classic way to accidentally invent distributed sadness.</p><h4>Reliability Guarantees</h4><p>Kafka provides durable, replicated storage. Producers use idempotent writes and acknowledgments from all replicas. Consumers commit offsets only after successful processing.</p><p>This combination gives you effectively-once delivery semantics for most practical workflows, assuming consumers are written correctly.</p><p>And yes, “assuming consumers are written correctly” is doing a lot of heavy lifting there.</p><h4>Operational Benefits</h4><p>Kafka also becomes your universal replay mechanism.</p><p>Need to rebuild fraud models? Replay historical events.</p><p>Need to fix a broken analytics pipeline? Replay.</p><p>Need to investigate an incident from three days ago? Replay.</p><p>It’s basically a time machine, except with more YAML.</p><p>Kafka is the backbone of the asynchronous side of the payment platform. It decouples services, absorbs spikes, guarantees durability, and enables massive fan-out.</p><p>Without Kafka, every payment service would eventually turn into an overworked group chat.</p><h3>The Ledger: Financial System of Record</h3><p>If the payment processor is the heart of the system, the ledger is the memory. Every dollar, every refund, every fee, every reserve movement ultimately lives here. This is the system that answers the question every finance team eventually asks:</p><p><strong>“Where did the money go?”</strong></p><p>And unlike many systems, the ledger must always have an answer.</p><p>At companies like Stripe, the ledger processes billions of financial events every day. It’s not just another database. It is the financial system of record and the final authority when every other service disagrees.</p><p>If your analytics pipeline says one thing and your payment processor says another, the ledger wins. Every time.</p><h4>Immutability</h4><p>Ledger entries are never updated or deleted.</p><p>Ever.</p><p>If a mistake happens, you don’t edit history. You append a correction. Financial systems care deeply about auditability, and rewriting old transactions is how auditors develop trust issues.</p><p>For example, if you accidentally record a $100 charge instead of $10, you don’t modify the original entry. You post a reversing entry for $100 and then record the correct $10 transaction.</p><p>History remains intact. Every mistake, correction, and adjustment is permanently visible.</p><p>This gives you a complete, tamper-evident audit trail.</p><h4>Double-Entry Bookkeeping</h4><p>Every financial movement must balance.</p><p>Always.</p><p>For every debit, there is an equal and opposite credit. Money cannot appear from nowhere, and more importantly, it cannot quietly disappear either.</p><p>A simple card authorization might look like this:</p><ul><li>Debit: Customer Clearing Account</li><li>Credit: Merchant Pending Balance</li></ul><p>The total debits equal the total credits.</p><p>If they don’t, the transaction is invalid and must never be committed. Accounting tends to be quite firm on this point.</p><p>Double-entry bookkeeping is one of humanity’s oldest distributed consistency protocols, and frankly, it’s held up remarkably well.</p><h4>Event Sourcing</h4><p>The ledger doesn’t store balances directly as its primary truth.</p><p>Instead, it stores an ordered stream of immutable events. Account balances are derived by replaying those events.</p><p>This approach offers enormous advantages:</p><ul><li>Complete historical reconstruction</li><li>Perfect audit trails</li><li>Easy debugging</li><li>Natural replication</li><li>Time-travel queries</li></ul><p>Want to know a merchant’s balance at exactly 2:17 PM three weeks ago? Just replay events up to that point.</p><p>Traditional databases can do many things. Time travel is usually not one of them.</p><h4>Fund Flow Modeling</h4><p>Real-world payments are rarely simple.</p><p>A single customer payment might flow through multiple internal and external accounts:</p><pre>Customer → Acquirer → Processor Clearing → Merchant Reserve → Merchant Available Balance → Bank Settlement</pre><p>Each step is represented explicitly in the ledger.</p><p>Rather than treating a payment as one giant black box, the system models it as a chain of connected fund flows.</p><p>This makes complex operations like partial captures, disputes, chargebacks, rolling reserves, and instant payouts far easier to reason about.</p><p>It also makes finance teams dramatically less likely to send panicked Slack messages at midnight.</p><h4>Why This Matters ?</h4><p>Every other system can fail temporarily.</p><p>Caches can evict data.<br>Webhooks can retry.<br>Analytics can lag.</p><p>The ledger cannot be wrong.</p><p>A payment processor can survive downtime. It cannot survive losing track of money.</p><p>That’s why the ledger is built with extreme conservatism, rigorous invariants, and almost pathological attention to correctness.</p><p>Because in payments, latency is negotiable.</p><p>Accuracy is not.</p><h4>Ledger Data Model</h4><p>The ledger is the financial source of truth for the entire system, and the data model reflects that it is designed around immutability, correctness, and auditability first, with everything else being a secondary concern. Getting this wrong isn’t a bug you fix in the next sprint; it’s a financial integrity problem that regulators and auditors care deeply about.</p><pre>-- Core Ledger Tables<br>CREATE TABLE ledger_accounts (<br>    account_id          UUID PRIMARY KEY,<br>    account_type        ENUM(&#39;asset&#39;, &#39;liability&#39;, &#39;equity&#39;, &#39;revenue&#39;, &#39;expense&#39;),<br>    owner_type          ENUM(&#39;merchant&#39;, &#39;platform&#39;, &#39;processor&#39;, &#39;reserve&#39;),<br>    owner_id            UUID NOT NULL,<br>    currency            CHAR(3) NOT NULL,<br>    current_balance     BIGINT NOT NULL DEFAULT 0,  -- stored in smallest unit (cents)<br>    pending_balance     BIGINT NOT NULL DEFAULT 0,<br>    created_at          TIMESTAMP NOT NULL,<br>    updated_at          TIMESTAMP NOT NULL,<br>    version             BIGINT NOT NULL DEFAULT 0    -- optimistic concurrency<br>);</pre><p>ledger_accounts is the master registry of every financial account in the system -- merchant accounts, platform accounts, processor accounts, reserve accounts. A few design decisions worth calling out here. Balances are stored as BIGINT in the smallest currency unit (cents for USD, pence for GBP, and so on) rather than as floats or decimals. This is non-negotiable in financial systems -- floating point arithmetic has rounding errors, and rounding errors in money are not acceptable. Storing everything as integers eliminates that entire class of bug. The currency column sits on the account itself, which enforces that every account is denominated in a single currency -- cross-currency conversions happen at the transaction layer, not by mixing currencies within an account. The version field is for optimistic concurrency control: before updating a balance, you read the current version, do your math, and then write back with a WHERE version = :expected_version condition. If another process updated the account between your read and your write, the version won&#39;t match, your update affects zero rows, and you retry. This is how you avoid lost updates without holding a database lock for the entire duration of the operation.</p><pre>CREATE TABLE ledger_entries (<br>    entry_id            UUID PRIMARY KEY,<br>    transaction_id      UUID NOT NULL,      -- groups related entries<br>    account_id          UUID NOT NULL REFERENCES ledger_accounts,<br>    entry_type          ENUM(&#39;debit&#39;, &#39;credit&#39;),<br>    amount              BIGINT NOT NULL,     -- always positive; direction from entry_type<br>    currency            CHAR(3) NOT NULL,<br>    description         TEXT,<br>    metadata            JSONB,<br>    idempotency_key     VARCHAR(255) UNIQUE, -- prevents duplicate entries<br>    created_at          TIMESTAMP NOT NULL,<br>-- Immutable: no updated_at column<br>    INDEX idx_transaction (transaction_id),<br>    INDEX idx_account_time (account_id, created_at),<br>    INDEX idx_idempotency (idempotency_key)<br>);</pre><p>ledger_entries is where the actual double-entry bookkeeping lives. Every financial movement generates at least two entries -- a debit on one account and a credit on another -- and they&#39;re linked by transaction_id so you can always retrieve the complete set of entries that make up a single logical transaction. The amount field is always positive; direction is captured by entry_type being either debit or credit. This is cleaner than storing signed amounts because it&#39;s unambiguous -- a negative amount in a signed scheme could mean different things depending on convention, whereas entry_type: debit, amount: 5000 means exactly one thing. Notice there&#39;s deliberately no updated_at column. Ledger entries are immutable by design -- you never update or delete them. If you need to correct an error, you post a new correcting transaction. This is standard accounting practice and it&#39;s also what makes the audit trail complete and tamper-evident. The idempotency_key with a unique constraint is the last line of defense against duplicate entries -- even if your application layer somehow fires the same write twice, the database rejects the second one at the constraint level.</p><p>The three indexes are worth explaining individually. idx_transaction is for fetching all entries belonging to a transaction, which you do constantly when displaying transaction details or doing reconciliation. idx_account_time is the workhorse for balance calculations and account history -- any query that asks &quot;show me all movements on this account between these dates&quot; hits this index. idx_idempotency makes idempotency key lookups fast, since you&#39;re checking this on every write.</p><pre>CREATE TABLE ledger_transactions (<br>    transaction_id      UUID PRIMARY KEY,<br>    transaction_type    VARCHAR(50) NOT NULL,  -- &#39;payment&#39;, &#39;refund&#39;, &#39;payout&#39;, &#39;fee&#39;<br>    status              ENUM(&#39;pending&#39;, &#39;posted&#39;, &#39;voided&#39;),<br>    idempotency_key     VARCHAR(255) UNIQUE,<br>    metadata            JSONB,<br>    created_at          TIMESTAMP NOT NULL<br>-- Immutable: corrections create new transactions<br>);</pre><p>ledger_transactions is the envelope that groups related ledger entries together into a coherent financial event. It&#39;s deliberately thin -- it doesn&#39;t store amounts or account references directly, because all of that lives in the entries. What it does store is the type (payment, refund, payout, fee), the status, and its own idempotency key at the transaction level. The status progression matters here: a transaction starts as pending when the entries are being written, moves to posted once everything has settled and balances are updated, and can be voided if the transaction needs to be unwound. Critically, voiding doesn&#39;t delete anything -- it creates a new set of reversing entries and marks the original transaction as voided. Same as the entries table, there&#39;s no updated_at because the record itself doesn&#39;t change after creation. If a payment needs to be corrected, you don&#39;t edit the original transaction -- you create a new one that offsets it. The ledger only ever grows, never gets revised.</p><h4>Ledger Invariants &amp; Data Quality</h4><p>A ledger is only valuable if you can trust it completely. In payments, “mostly correct” is just an expensive way of saying “wrong.” Every financial system therefore revolves around a few non-negotiable invariants.</p><p>The most fundamental is the <strong>clearing invariant</strong>: for every fund flow, total debits must always equal total credits. Money cannot be created, destroyed, or mysteriously wander off for coffee. Every transaction must balance perfectly. Even a one-cent discrepancy is treated as a critical incident. Continuous verification systems monitor this in real time, and any imbalance is flagged immediately for investigation.</p><p>Next comes <strong>timeliness</strong>. A perfectly accurate ledger that updates tomorrow is not particularly useful today. Financial events must be ingested within strict service-level objectives. A common target is that 99.99% of dollar volume reaches the ledger within four hours of occurring upstream. This ensures finance, risk, and operations teams are always working from fresh data rather than yesterday’s news.</p><p>Equally important is <strong>completeness</strong>. Every event generated by upstream systems like payment processors, banking rails, fraud systems, payout engines, dispute handlers must eventually appear in the ledger. Missing events are often more dangerous than incorrect ones, because they can remain invisible until reconciliation uncovers them. The ledger must be exhaustive, not merely accurate.</p><p>To maintain these guarantees, mature payment platforms build a dedicated data quality layer around the ledger. Real-time balance verification continuously checks accounting invariants as transactions are posted. Hourly cross-system reconciliation compares ledger balances against upstream payment systems and downstream settlement systems. Daily end-of-day settlement matching ensures bank movements align with internal records. Regulatory reporting pipelines perform additional daily and monthly validation to catch discrepancies before auditors do.</p><p>Leading platforms like Stripe target an extraordinary standard: <strong>99.9999% explainability of all money movement</strong>. That means virtually every dollar can be traced, reconciled, and justified at any moment. It’s an ambitious goal, but in financial infrastructure, ambition tends to be cheaper than unexplained money.</p><p>Finally, anomaly detection systems continuously scan for unusual patterns: unexpected balance shifts, delayed ingestion, reconciliation breaks, duplicate postings, or settlement mismatches. When something looks suspicious, alerts fire automatically and investigation tooling provides engineers and finance teams with the exact trail needed to diagnose the issue.</p><p>Because in payments, finding a missing dollar quickly is good engineering. Finding it before anyone notices is even better.</p><h3>Payment Processing Pipeline</h3><p>A payment request begins when the merchant’s application sends a charge request to the API Gateway. The gateway serves as the platform’s front door, handling TLS termination, request validation, rate limiting, and routing. From there, the request moves to the authentication layer, where API keys are verified, permissions are checked, and the merchant’s account context is attached. Only authenticated, authorized requests are allowed any further. Payments are not an area where “close enough” is acceptable.</p><p>Once validated, the request enters the Payment Orchestrator, the brain of the entire payment system. This service coordinates the full lifecycle of the transaction, deciding what checks to run, which processor to use, and how to handle the final result.</p><p>Before money ever touches a card network, several critical checks run in parallel. The fraud engine evaluates the transaction using machine learning models, behavioral signals, device fingerprints, and merchant-specific rules. Simultaneously, the platform determines whether Strong Customer Authentication, such as 3D Secure, is required based on issuer requirements, geography, and risk profile. Running these steps concurrently minimizes latency while maintaining security and compliance.</p><p>If fraud systems flag the transaction, it may be blocked immediately, approved automatically, or routed for manual review. This decision point acts as a gatekeeper, preventing risky transactions from progressing further into the payment network.</p><p>Approved transactions then flow into the Processor Gateway. This layer abstracts the complexity of multiple payment processors, acquirers, and banking partners. Based on routing rules, processor health, geography, card type, cost optimization, and historical success rates, the gateway selects the best available processor for that specific payment.</p><p>The chosen external processor communicates with the relevant card network, such as Visa or Mastercard, which in turn contacts the issuing bank for authorization. This is the moment where the actual “Can this card be charged?” question gets answered.</p><p>Once the issuer responds, the authorization result flows back through the same chain like card network, processor, gateway, and finally the orchestrator.</p><p>But approval is only the halfway point.</p><p>The post-processing pipeline immediately takes over. First, the payment state machine transitions the payment into its new state, such as authorized, captured, or failed. Next, the ledger records the financial impact using immutable double-entry bookkeeping. This step is non-negotiable; if the ledger write fails, the system treats the payment as incomplete.</p><p>After persistence, the platform publishes events to Apache Kafka, allowing downstream systems to react asynchronously. Webhook services notify merchants, analytics pipelines update dashboards, fraud systems ingest new signals, and reconciliation services prepare for settlement.</p><p>This separation between synchronous and asynchronous work is crucial. The customer receives a fast response, while the rest of the ecosystem catches up in the background.</p><p>In just a few hundred milliseconds, the system has authenticated the merchant, evaluated fraud, handled regulatory requirements, routed across global payment rails, recorded money movement, and notified the broader platform.</p><p>Payments may look simple from the checkout page. Under the hood, they are a carefully choreographed distributed systems dance one where nobody is allowed to miss a step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zn_YloZJKV1itKtGv1vDLw.png" /></figure><h4>Payment Authorization (Critical Path)</h4><p>Authorization is the most latency-sensitive operation in the entire payment stack. The customer is literally waiting at checkout, finger hovering over the refresh button, already wondering whether they just got charged twice. Every millisecond matters.</p><p>A well-engineered payment system targets a <strong>p99 latency under 500 milliseconds</strong>. Not average latency, p99. The slowest one percent is what determines whether checkout feels instant or painfully awkward.</p><p>The request first hits the API Gateway, which handles TLS termination, authentication, schema validation, and basic request checks. This stage typically consumes around 20 milliseconds. It’s the bouncer at the club which is quickly deciding whether you’re even allowed inside.</p><p>Next comes fraud scoring. Modern fraud engines run machine learning inference in real time, evaluating hundreds of signals such as device fingerprints, merchant behavior, geolocation, and historical patterns. Despite the complexity, this must complete in roughly 30 milliseconds. Fraud models do not get unlimited contemplation time.</p><p>Once cleared, the orchestrator chooses the optimal processor. This routing decision is usually lightning fast, often around 5 milliseconds, because all routing rules and processor health metrics are already cached in memory.</p><p>The payment is then transmitted to the external processor, costing roughly 50 milliseconds of network latency. Physics remains stubbornly unoptimized.</p><p>The processor, card network, and issuing bank now perform the actual authorization. This is the largest and least predictable component, often taking around 200 milliseconds. Networks like Visa and Mastercard are incredibly reliable, but they do not share your p99 objectives.</p><p>The response travels back across the network, consuming another 50 milliseconds.</p><p>At this point, the critical business decision has been made. The card is approved or declined. Everything after this must be ruthlessly optimized.</p><p>Instead of synchronously writing to the ledger which could easily add tens of milliseconds and introduce database contention, the system publishes a durable event to Apache Kafka. Kafka acknowledges the write almost immediately, and the dedicated ledger service processes the event asynchronously.</p><p>This is one of the most important architectural decisions in modern payment systems.</p><p>By moving ledger persistence off the synchronous path, the platform preserves low checkout latency while still guaranteeing durability. Kafka acts as the durable handoff point. If the ledger service is temporarily unavailable, the event waits safely in the queue.</p><p>After publishing the event, the payment state machine updates the transaction status, typically in around 20 milliseconds. The response is then serialized, which usually takes another 5 milliseconds.</p><p>Finally, the result travels back to the merchant, costing another 50 milliseconds over the network.</p><p>The full latency breakdown typically looks like this:</p><ul><li>API Gateway: ~20ms</li><li>Fraud Scoring: ~30ms</li><li>Routing Decision: ~5ms</li><li>Network to Processor: ~50ms</li><li>Processor + Card Network + Issuer: ~200ms</li><li>Network Return: ~50ms</li><li>Kafka Publish: ~0–5ms</li><li>State Update: ~20ms</li><li>Response Serialization: ~5ms</li><li>Network to Merchant: ~50ms</li></ul><p>That brings the total to roughly <strong>430 milliseconds</strong>, comfortably inside the 500ms p99 budget.</p><p>The biggest lesson here is simple: external dependencies dominate latency. Your code might be fast, but banks have their own schedule.</p><p>That’s why payment systems aggressively optimize everything they control, hide everything they can behind asynchronous boundaries, and treat every millisecond like a precious resource. Because at checkout, speed isn’t just convenience, it’s conversion.</p><h4>Capture, Refund, and Void Flows</h4><p>Once a payment is authorized, the story isn’t over. In fact, most of the real financial movement happens after authorization. Capture, refund, and void flows are typically <strong>merchant-initiated or system-triggered</strong>, and unlike authorization, they’re not sitting on a customer’s critical path. That gives us a bit more breathing room on latency, but correctness still matters just as much.</p><ul><li><strong>Capture Flow</strong></li></ul><p>Capture is what turns an authorization into actual money movement. When a payment is authorized, funds are only reserved. Capture is the step where those funds are officially collected.</p><p>The system first validates that the authorization exists, hasn’t expired, and hasn’t already been captured. Card networks enforce strict windows here, so timing matters.</p><p>Once validated, the ledger updates the state by moving funds from a “pending_authorized” account to a “captured” state. This is where the financial impact becomes real inside your system.</p><p>After that, a capture request is sent to the processor and card network. This confirms that the merchant wants to collect the funds. The transaction is then scheduled for settlement, which typically happens in batch cycles depending on the payment method and region.</p><p>Finally, an event like payment.captured is emitted through Apache Kafka so downstream systems like webhooks, analytics, reconciliation can react.</p><ul><li><strong>Refund Flow</strong></li></ul><p>Refunds are essentially the reverse of a capture, but with more rules and more opportunities for things to go wrong.</p><p>The system starts by validating that a capture exists and that the refund amount does not exceed what was originally captured. Partial refunds are common, so this check must be precise.</p><p>Next comes the ledger update. Funds are moved in the opposite direction which is typically debiting the merchant’s balance and crediting the customer or processor clearing account. This is done using new immutable entries, never by modifying the original transaction.</p><p>A refund request is then sent to the processor, which pushes it through the card network back to the issuing bank. From the customer’s perspective, this is when the money starts making its way back.</p><p>Once processed, the system emits a charge.refunded event, allowing merchants to update order states, notify customers, and adjust accounting.</p><ul><li><strong>Void flow</strong></li></ul><p>Voids are the cleanest outcome, because they cancel a payment before money actually moves.</p><p>The system validates that the authorization exists and has not yet been captured. If capture has already happened, it’s too late for a void then you’re in refund territory now.</p><p>The ledger then releases the held funds by reversing the authorization entries. Since no actual settlement occurred, this is effectively undoing the reservation.</p><p>A void request is sent to the processor and card network, informing them to cancel the authorization hold. From the customer’s perspective, the charge simply disappears instead of being refunded later.</p><p>Finally, a payment.voided event is emitted, keeping the rest of the system in sync.</p><p><strong>Why These Flows Matter ?</strong></p><p>Unlike authorization, these operations don’t need sub-500ms latency, but they do need:</p><ul><li><strong>Strong validation</strong> to prevent invalid financial actions</li><li><strong>Accurate ledger updates</strong> to maintain accounting correctness</li><li><strong>Reliable communication with processors</strong></li><li><strong>Event emission</strong> for system-wide consistency</li></ul><p>They also highlight an important truth about payments: authorization is just the beginning. The real complexity lives in everything that happens after.</p><h3>Event-Driven Architecture &amp; Async Processing</h3><p><strong>Why Event-Driven?</strong></p><p>At small scale, synchronous request-response feels clean and intuitive. Service A calls Service B, gets a response, and moves on. Simple.</p><p>At trillion-dollar scale, that model starts breaking in very predictable and very painful ways.</p><p>If Service B gets slow, Service A slows down with it. Latency stacks up across the entire call chain, and suddenly a simple payment request is waiting on five different systems having a good day at the same time. That’s not a bet you want to take.</p><p>If Service B goes down, things get worse. Now Service A either fails outright or starts retrying aggressively, which usually just makes the outage louder. In contrast, with an event-driven system, Service A simply publishes an event and continues. The work is safely queued, and Service B can process it when it comes back online. No drama, no cascading failures.</p><p>Throughput mismatches are another killer. In a synchronous world, Service A is limited by how fast Service B can respond. If B can handle 10K requests per second, A is effectively capped there too. With an event stream like Apache Kafka, bursts are absorbed naturally. A can publish at high speed, and B can consume at its own pace without bringing the system to its knees.</p><p>Then comes extensibility. In a synchronous architecture, if you add new consumers lets say analytics, fraud models, notifications then Service A now needs to know about Services C, D, and E. That coupling spreads quickly. In an event-driven system, new consumers just subscribe. No changes required upstream. You get fan-out for free.</p><p>And finally, auditability. In traditional systems, you build audit logs separately. In event-driven systems, the events themselves are the audit trail. Every state change, every transition, every action is already captured as an immutable record.</p><p>That’s why at scale, event-driven isn’t just an architectural preference. It’s survival.</p><p><strong>Event Schema</strong></p><p>Every event in the system follows a structured schema. Think of it as a contract between producers and consumers. If this breaks, everything downstream breaks with it.</p><p>Here’s what a typical payment authorization event looks like:</p><pre>{<br>  &quot;id&quot;: &quot;evt_1234567890abcdef&quot;,<br>  &quot;type&quot;: &quot;payment.authorized&quot;,<br>  &quot;api_version&quot;: &quot;2024-01-01&quot;,<br>  &quot;created&quot;: 1704067200,<br>  &quot;data&quot;: {<br>    &quot;object&quot;: {<br>      &quot;id&quot;: &quot;pi_abc123&quot;,<br>      &quot;amount&quot;: 10000,<br>      &quot;currency&quot;: &quot;usd&quot;,<br>      &quot;status&quot;: &quot;requires_capture&quot;,<br>      &quot;merchant_id&quot;: &quot;acct_xyz789&quot;,<br>      &quot;payment_method&quot;: {<br>        &quot;type&quot;: &quot;card&quot;,<br>        &quot;card&quot;: {<br>          &quot;brand&quot;: &quot;visa&quot;,<br>          &quot;last4&quot;: &quot;4242&quot;,<br>          &quot;country&quot;: &quot;US&quot;<br>        }<br>      },<br>      &quot;metadata&quot;: {}<br>    },<br>    &quot;previous_attributes&quot;: {<br>      &quot;status&quot;: &quot;requires_payment_method&quot;<br>    }<br>  },<br>  &quot;idempotency_key&quot;: &quot;idk_unique_request_123&quot;,<br>  &quot;sequence_number&quot;: 42<br>}</pre><p>A few fields here are doing a lot of heavy lifting.</p><p>The id uniquely identifies the event. This is critical for deduplication, especially in systems that guarantee at-least-once delivery.</p><p>The type tells consumers what happened. payment.authorized, payment.captured, charge.refunded, and so on. This drives routing and handling logic across the platform.</p><p>api_version ensures backward compatibility. Consumers can evolve safely without breaking when the schema changes.</p><p>created is the event timestamp, usually in epoch seconds. This becomes important for ordering and replay.</p><p>The data.object contains the current state of the entity, while previous_attributes shows what changed. This makes events self-describing. Consumers don’t need to fetch additional data to understand what happened.</p><p>The idempotency_key ties the event back to the original request, helping systems safely handle retries without duplicating side effects.</p><p>Finally, sequence_number helps maintain ordering within a given entity or stream. Perfect ordering in distributed systems is hard, but this gives you a reliable way to reason about progression.</p><p>This schema becomes the language of your system. Every service speaks it. Every workflow depends on it. And once it’s in production, changing it casually is a very effective way to create chaos.</p><p>So you treat it like a contract. Because it is.</p><p><strong>Outbox Pattern for Reliable Event Publishing</strong></p><p>One of the trickiest problems in distributed systems is this: <strong>how do you make a database write and an event publish behave like a single atomic operation?</strong> Because if those two drift apart, things get weird very quickly.</p><p>Imagine you update a payment to authorized in your database, but the event never gets published. Downstream systems never hear about it. Now your ledger, webhooks, analytics, and reconciliation pipelines are all missing a critical piece of truth. Flip the scenario and it’s just as bad like an event gets published, but the database write never committed. Now you’ve told the world something happened that… didn’t.</p><p>The Outbox Pattern exists to eliminate this entire class of bugs.</p><p>Instead of trying to write to the database and publish to Apache Kafka in the same step (which is not atomic), you make <strong>the database the source of truth for both</strong>.</p><p>Inside a single database transaction, you do two things:</p><ol><li>Update your business state (for example, mark a payment as authorized)</li><li>Insert a corresponding event into an outbox_events table</li></ol><p>Both happen together, or neither happens.</p><pre>BEGIN;<br><br>UPDATE payments<br>SET status = &#39;authorized&#39;<br>WHERE payment_id = &#39;pi_123&#39;;<br><br>INSERT INTO outbox_events (id, topic, payload, created_at)<br>VALUES (<br>    gen_random_uuid(),<br>    &#39;payment.authorized&#39;,<br>    &#39;{...json payload...}&#39;,<br>    NOW()<br>);<br><br>COMMIT;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_TNtLIr0OfW8qW6yIXeM8w.png" /></figure><p>If the transaction commits, you now have a guaranteed record of both the state change and the event that needs to be published. If it fails, neither exists. No inconsistencies, no ghost events.</p><p>From there, a background worker takes over. It continuously polls the outbox_events table for new, unpublished events, publishes them to Kafka, and then marks them as published.</p><pre>1. Read unpublished events from outbox<br>2. Publish to Kafka<br>3. Mark as published (or store offset)</pre><p>This decouples event publishing from the request path while preserving correctness. Even if Kafka is temporarily unavailable, the events are safely stored in the database and will be retried later. Nothing is lost.</p><p>The key guarantee is simple but powerful:</p><p><strong>An event is published if and only if the database transaction committed.</strong></p><p>No more, no less.</p><p><strong>What About CDC?</strong></p><p>An alternative approach is Change Data Capture (CDC), using tools like Debezium.</p><p>Instead of explicitly writing to an outbox table, CDC reads the database’s write-ahead log (WAL) and streams changes directly into Kafka. In this model, the database itself becomes the event source.</p><p>This reduces application complexity, since you don’t need a separate outbox table or polling workers. But it comes with its own trade-offs: tighter coupling to database internals, more operational complexity, and less explicit control over event shaping.</p><p><strong>Why This Matters ?</strong></p><p>Without the outbox pattern (or CDC), you’re relying on best-effort coordination between two systems that don’t share a transaction boundary.</p><p>And “best effort” is not something you want anywhere near money movement.</p><p>The outbox pattern turns that uncertainty into a deterministic guarantee. It’s one of those patterns that feels like overengineering. Right up until the day it saves you from a very expensive inconsistency.</p><h3><strong>Stream Processing Pipeline</strong></h3><p>Once events start flowing through Apache Kafka, you don’t just store them, you <em>compute on them in real time</em>. That’s where stream processing comes in.</p><p>Think of this layer as the “live brain” sitting on top of your event streams. Instead of waiting for batch jobs or offline analytics, systems like Apache Flink or Apache Spark Streaming continuously consume events, transform them, and produce new insights or actions within seconds.</p><p>The pipeline looks simple on paper: Kafka topics go in, processing jobs run, and outputs come out. In reality, this is where a lot of the platform’s intelligence lives.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aU0B1Qq6YnuooolBCihlOA.png" /></figure><ul><li><strong>Fraud Signal Aggregation</strong></li></ul><p>Fraud rarely shows up in a single transaction. It shows up in patterns.</p><p>This job continuously aggregates signals across related dimensions like card number, device fingerprint, IP address, or merchant. For example, if the same card suddenly attempts ten transactions across different merchants in a few seconds, that’s interesting.</p><p>The stream processor builds rolling windows of activity and feeds enriched signals back into the fraud engine. This allows the system to detect coordinated or bursty fraud in near real time, instead of after the damage is done.</p><ul><li><strong>Real-Time Analytics</strong></li></ul><p>Merchants expect dashboards to feel alive.</p><p>This pipeline computes live metrics such as Total Payment Volume (TPV), authorization success rates, failure breakdowns, and latency percentiles. Instead of querying the primary database which would be a terrible idea at scale and these metrics are derived directly from the event stream.</p><p>The result is dashboards that update in seconds, not hours, without putting pressure on the transactional systems.</p><ul><li><strong>Reconciliation Engine</strong></li></ul><p>Eventually, your internal records must match what banks and processors say actually happened.</p><p>This job continuously compares internal events (payments, captures, refunds) with external data like processor reports or bank statements. Mismatches are flagged early, not discovered days later during finance reconciliation.</p><p>At scale, reconciliation is less about fixing errors and more about proving that no errors exist.</p><ul><li><strong>Settlement Calculator</strong></li></ul><p>Captured payments don’t immediately land in a merchant’s bank account. They go through settlement cycles.</p><p>This job aggregates captured transactions, subtracts fees, applies adjustments, and computes the net amount owed to each merchant. It prepares settlement batches that will eventually be paid out.</p><p>Because this runs continuously, merchants can see near real-time estimates of what they’ll receive, even before actual settlement occurs.</p><ul><li><strong>Compliance Event Logger</strong></li></ul><p>Regulators care about very specific slices of data.</p><p>This pipeline filters out compliance-relevant events like large transactions, cross-border payments, suspicious activity and routes them to dedicated audit storage. This ensures that reporting systems have exactly what they need without scanning the entire dataset.</p><p>It also makes audits far less painful than they would otherwise be.</p><p><strong>Why This Layer Matters ?</strong></p><p>Without stream processing, you’re stuck in a batch world where everything is delayed.</p><p>With it, your system becomes reactive. Fraud detection improves, dashboards feel real-time, reconciliation becomes continuous, and settlement calculations stay fresh.</p><p>More importantly, it keeps heavy analytical workloads off your core transactional systems. Your payment database continues doing what it does best like handling money while the stream processing layer handles insight.</p><p>At scale, this separation isn’t optional. It’s what keeps the system fast, accurate, and sane at the same time.</p><h3>Reliability &amp; Fault Tolerance</h3><ul><li><strong>Idempotency</strong></li></ul><p>If you had to pick just one mechanism that keeps payment systems sane, it’s idempotency.</p><p>Because retries are not a bug, they’re a guarantee. Networks drop packets, clients timeout, mobile apps retry aggressively, and users double-click buttons. Without idempotency, every retry risks creating a duplicate charge. And duplicate charges are about the fastest way to lose user trust.</p><p>Idempotency is how you make <strong>“retry” behave like “try once.”</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wb-UUwq0-RiOgawQNY3ttg.png" /></figure><p><strong>How the Flow Works ?</strong></p><p>Every write request (like creating a payment) comes with an Idempotency-Key. Think of it as a unique fingerprint for that specific operation.</p><p>When a request arrives, the system first checks an idempotency store (usually Redis):</p><ul><li>If the key already exists and the request <strong>completed earlier</strong>, the system simply returns the cached response. No reprocessing, no duplicate side effects.</li><li>If the key exists but is <strong>still in progress</strong>, the system returns a 409 Conflict. This prevents concurrent execution of the same request.</li><li>If the key doesn’t exist, the system proceeds to process it.</li></ul><p>Before doing any real work, the system acquires a <strong>distributed lock</strong> on that idempotency key. If another request is already processing it, the lock won’t be available, and again you return a 409 Conflict.</p><p>Once the lock is acquired, the request is processed normally. On success or failure, the full response (not just status) is stored against the idempotency key, and the lock is released.</p><p>From that point on, any retry with the same key gets the exact same response. Byte for byte identical.</p><p><strong>Why Full Response Caching Matters ?</strong></p><p>It’s not enough to just remember “this succeeded.”</p><p>You need to return the exact same response payload. Same status code, same body, same metadata.</p><p>Why? Because clients depend on deterministic behavior. If the first request returned a payment ID, the retry must return that exact same ID, not a new one.</p><p>Anything else breaks assumptions and introduces subtle bugs upstream.</p><p><strong>Storage Strategy</strong></p><p>The hot path for idempotency lives in Redis:</p><ul><li>Keys stored with a TTL of around <strong>24 hours</strong></li><li>Fast lookups for low latency</li><li>Handles the majority of retries</li></ul><p>But Redis alone isn’t enough. For stronger guarantees, many systems also persist idempotency records in a database as a backup layer.</p><p>This combination gives you both speed and durability.</p><p>Idempotency keys are always <strong>scoped per merchant</strong>. Two different merchants can use the same key without colliding, but a single merchant cannot reuse a key for different operations.</p><p>Locks are <strong>distributed and time-bound (TTL-based)</strong> to prevent deadlocks. If a worker crashes mid-request, the lock eventually expires and the system recovers automatically.</p><p>One subtle but important detail is tying idempotency to your transaction boundary. Using patterns like the outbox pattern, you ensure that storing the idempotency result and executing the business logic happen atomically. Either both happen, or neither does.</p><p><strong>Why This Is Non-Negotiable ?</strong></p><p>Without idempotency:</p><ul><li>Retries create duplicate charges</li><li>Timeouts become dangerous</li><li>Clients need complex retry logic</li><li>Debugging becomes a nightmare</li></ul><p>With idempotency:</p><ul><li>Retries are safe</li><li>Failures are recoverable</li><li>Systems become predictable</li></ul><p>It’s one of those concepts that sounds simple on paper but ends up being foundational to everything.</p><p>Because in payments, “probably executed once” is not good enough.</p><p>It has to be <strong>exactly once from the user’s perspective. E</strong>ven if under the hood, it took three retries, two timeouts, and a small existential crisis to get there.</p><ul><li><strong>Circuit Breaker Pattern</strong></li></ul><p>External payment processors are outside your control and they <em>will</em> fail. Latency spikes, partial outages, degraded networks, weird edge-case errors… all of it happens. If your system blindly keeps sending traffic to a failing dependency, you don’t just inherit the failure, you amplify it.</p><p>That’s how cascading failures start.</p><p>The circuit breaker pattern exists to stop that chain reaction early.</p><p>How It Works ?</p><p>A circuit breaker wraps calls to external processors and continuously monitors their health. Instead of treating every request equally, it adapts based on recent behavior.</p><p>In the <strong>CLOSED</strong> state, everything operates normally. Requests flow through to the processor, and the system tracks success and failure rates over a sliding window (typically ~30 seconds). As long as the failure rate stays below a defined threshold, say 50%, nothing changes.</p><p>But once failures cross that threshold, the system assumes something is wrong externally, not just a random blip, and flips the circuit to <strong>OPEN</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K25I7woFw3V64IXAC3BpYw.png" /></figure><p><strong>OPEN State (Fail Fast + Failover)</strong></p><p>When the circuit is OPEN, the system stops sending requests to that processor entirely.</p><p>No retries. No waiting. No hope-based engineering.</p><p>Instead, requests fail fast and are immediately routed to a secondary processor via the routing layer. This is critical in payments, availability matters more than loyalty to any single processor.</p><p>Fail-fast behavior also protects your own system. Threads aren’t blocked waiting on slow or broken dependencies, which keeps latency stable and prevents resource exhaustion.</p><p>After a cooldown period (typically around 30 seconds), the system doesn’t blindly trust that things are fixed. It moves into a testing phase.</p><p><strong>HALF-OPEN State (Probing Recovery)</strong></p><p>In the HALF-OPEN state, the system cautiously allows a small percentage of traffic lets say 10% to flow to the previously failing processor.</p><p>This is essentially a health probe using real traffic.</p><ul><li>If the success rate recovers above a threshold (for example, 90%), the system considers the processor healthy again and transitions back to CLOSED.</li><li>If failures continue, the circuit immediately snaps back to OPEN, and traffic continues to be routed elsewhere.</li></ul><p>This prevents flapping and avoids prematurely trusting an unstable dependency.</p><p><strong>Why This Matters in Payments ?</strong></p><p>Payment systems are deeply dependent on external networks such as card processors, banks, gateways. Unlike internal services, you cannot fix them when they break.</p><p>What you <em>can</em> control is how your system reacts.</p><p>Without circuit breakers:</p><ul><li>Failures cascade across services</li><li>Latency spikes uncontrollably</li><li>Threads and connections get exhausted</li><li>Entire systems can go down due to one bad dependency</li></ul><p>With circuit breakers:</p><ul><li>Failures are isolated</li><li>Traffic is rerouted automatically</li><li>System stability is preserved</li><li>Users still complete payments via alternate paths</li></ul><p>Circuit breakers don’t work in isolation. They pair tightly with the payment router.</p><p>When a processor’s circuit is OPEN, the router dynamically shifts traffic to secondary or tertiary processors. This is how platforms maintain high availability even when individual providers are struggling.</p><p>Circuit breakers turn unpredictable external failures into controlled, manageable behavior.</p><p>They acknowledge a simple truth: dependencies fail.</p><p>And instead of pretending otherwise, they make sure your system keeps working anyway.</p><ul><li><strong>Retry Strategy</strong></li></ul><p>Retries are one of those things that sound simple until you realize they can either save your system or completely break it. In payments, you don’t get to choose whether retries happen, they <em>will</em> happen. The real question is whether they’re controlled or chaotic.</p><p>A good retry strategy is not one-size-fits-all. Different operations have very different constraints. Some are user-facing and latency-sensitive, others are background workflows where eventual success matters more than speed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*im6hS3hcKy9upgWbd_bX7Q.png" /></figure><p><strong>Payment Authorization (User on Checkout Page)</strong></p><p>This is the most sensitive path. The customer is waiting, and every extra retry adds visible latency.</p><p>So the strategy is intentionally conservative:</p><ul><li>Maximum of <strong>2 retries</strong></li><li>Backoff intervals of <strong>100ms and 500ms</strong></li><li>Retry only on <strong>transient failures</strong> like network timeouts, connection issues, or HTTP 503</li></ul><p>What you explicitly do <em>not</em> retry:</p><ul><li>Any <strong>4xx errors</strong> (validation issues, bad requests)</li><li><strong>Declined payments</strong> (the bank already said no and asking again won’t help)</li></ul><p>The safety net here is idempotency. Even if a retry happens, the idempotency key ensures the system does not accidentally create duplicate charges.</p><p>The goal is simple: recover from transient issues quickly without making the user wait forever.</p><p><strong>Webhook Delivery (Eventually Consistent, Not Time-Critical)</strong></p><p>Webhooks are a completely different story. The merchant’s server might be slow, temporarily down, or misconfigured. That’s normal.</p><p>Here, the system is patient:</p><ul><li>Up to <strong>8 retries spread over ~72 hours</strong></li><li>Exponential backoff: 1 minute → 5 minutes → 30 minutes → 2 hours → 8 hours → 24 hours → 48 hours → 72 hours</li><li>Retry on <strong>5xx errors, timeouts, and connection failures</strong></li></ul><p>And importantly:</p><ul><li><strong>Do not retry on 2xx responses</strong> (success means you’re done)</li></ul><p>If all retries fail, the event is moved to a dead letter queue for manual inspection or tooling-based replay.</p><p>This ensures reliability without overwhelming the merchant’s system or your own infrastructure.</p><p><strong>Settlement &amp; Reconciliation (Must Eventually Succeed)</strong></p><p>This is where retries become relentless.</p><p>Settlement and reconciliation deal with actual money movement between systems and banks. Failure here is not acceptable long-term.</p><ul><li><strong>Unlimited retries</strong></li><li>Exponential backoff with <strong>jitter</strong> (to avoid synchronized retry storms)</li><li>Backoff capped at around <strong>1 hour</strong></li></ul><p>If failures persist for an extended period (typically 24 hours), the system escalates to human operators. At that point, something deeper is likely broken such as API contract mismatch, bank outage, or data inconsistency.</p><p>For common issues, automated repair mechanisms kick in like replaying events, re-triggering flows, or correcting known reconciliation mismatches.</p><p><strong>Why Different Strategies Exist</strong></p><p>Each workflow optimizes for a different goal:</p><ul><li><strong>Authorization → latency + user experience</strong></li><li><strong>Webhooks → reliability over time</strong></li><li><strong>Settlement → absolute correctness</strong></li></ul><p>Treating them all the same would either slow down checkout or make backend systems fragile.</p><p><strong>The Bigger Picture</strong></p><p>Retries are tightly coupled with other reliability mechanisms:</p><ul><li><strong>Idempotency</strong> prevents duplicate side effects</li><li><strong>Circuit breakers</strong> prevent retry storms against failing systems</li><li><strong>Message queues (like Apache Kafka)</strong> absorb retry workloads asynchronously</li></ul><p>Together, they turn unreliable networks into predictable systems.</p><p>Because retries aren’t just about “trying again.”</p><p>They’re about <strong>trying again safely, intelligently, and without making things worse</strong>.</p><ul><li><strong>Saga Pattern for Distributed Transactions</strong></li></ul><p>Payments don’t happen inside a single database transaction. They span multiple systems such as API services, processors, ledgers, event pipelines and many of which you don’t control. That immediately rules out classic two-phase commit (2PC). It’s slow, fragile across network boundaries, and simply not practical when one of the participants is an external card network.</p><p>Instead, modern payment systems use the <strong>Saga pattern</strong>.</p><p>A saga breaks a large transaction into a sequence of smaller, independent steps. Each step commits its own changes. If something fails midway, the system doesn’t roll everything back automatically and it <strong>executes compensating actions</strong> to undo what already happened.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bo-t0pQi4zaar8yiSNrVOQ.png" /></figure><p><strong>The Happy Path</strong></p><p>In the ideal case, everything works in sequence:</p><ol><li>Funds are reserved via authorization</li><li>The processor debits the customer</li><li>The ledger records the transaction</li><li>The merchant’s balance is credited</li><li>Events are emitted to downstream systems</li></ol><p>Each step completes successfully, and the system moves forward. No global lock, no distributed transaction coordinator, just a well-orchestrated flow.</p><p><strong>When Things Go Wrong</strong></p><p>The real value of a saga shows up during failures.</p><p>Let’s say everything works until the ledger write fails:</p><ol><li>Authorization succeeds (funds reserved)</li><li>Processor successfully debits the customer</li><li>Ledger write fails</li></ol><p>At this point, you’re in an inconsistent state. The customer has been charged, but your system hasn’t recorded it properly. You can’t just “roll back” the processor because it already happened.</p><p>So the saga executes <strong>compensating actions</strong>:</p><ol><li>Issue a refund via the processor to reverse the debit</li><li>Release the authorization hold (if applicable)</li><li>Mark the transaction as failed</li></ol><p>Each compensation step undoes a previous step, in reverse order.</p><p>The system eventually reaches a consistent state again, not by rewinding time, but by applying corrective actions.</p><p><strong>Key Idea: Every Step Has an Undo</strong></p><p>For a saga to work, every forward action must have a corresponding compensating action:</p><ul><li>Authorization → Void (release hold)</li><li>Capture → Refund</li><li>Ledger write → Reversal entry</li><li>Balance credit → Balance debit</li></ul><p>This is why payment systems rely heavily on immutability and append-only logs. You don’t erase mistakes, you counteract them.</p><p><strong>Orchestration vs Choreography</strong></p><p>There are two common ways to implement sagas:</p><p><strong>Orchestration (central coordinator)</strong><br>A central service (like the Payment Orchestrator) controls the flow, decides the next step, and triggers compensations on failure. This is the most common approach in payments because it gives you explicit control and observability.</p><p><strong>Choreography (event-driven)</strong><br>Each service reacts to events and decides what to do next. There’s no central brain, just a chain of reactions over something like Apache Kafka.</p><p>Payments often use a hybrid: orchestration for critical flows, events for propagation and side effects.</p><p><strong>Why Not 2PC?</strong></p><p>Two-phase commit tries to guarantee atomicity across systems. Sounds great in theory.</p><p>In practice:</p><ul><li>It introduces high latency</li><li>It doesn’t work well with external systems</li><li>It creates blocking dependencies</li><li>It fails badly under partial outages</li></ul><p>Saga trades strict atomicity for <strong>eventual consistency with explicit recovery paths</strong>.</p><p>And in payments, that’s the right trade-off.</p><p><strong>Design Challenges</strong></p><p>Sagas aren’t free. They introduce complexity:</p><ul><li>You must define compensating actions for every step</li><li>You need to handle partial failures carefully</li><li>Observability becomes critical (you need to know where the saga is stuck)</li><li>Idempotency becomes mandatory (retries must not break consistency)</li></ul><p>But this complexity is controlled and predictable unlike the chaos of distributed transactions without a recovery model.</p><p><strong>Why This Works for Payments ?</strong></p><p>Payments are inherently long-running workflows. They involve external systems, asynchronous steps, and delayed finality (think settlement cycles).</p><p>The saga pattern fits this reality perfectly:</p><ul><li>It handles partial failures gracefully</li><li>It keeps systems decoupled</li><li>It avoids global locks</li><li>It ensures eventual consistency</li></ul><p>Most importantly, it guarantees that even when something fails halfway through, the system can <strong>recover to a financially correct state</strong>.</p><p>Because in payments, failure is acceptable.</p><p>Ending up in the wrong state is not.</p><ul><li><strong>Graceful Degradation Hierarchy</strong></li></ul><p>At this scale, failure isn’t a question of <em>if</em> ,it’s <em>when</em>. The real design challenge is making sure the system doesn’t collapse under pressure. Instead, it should <strong>degrade in a controlled, predictable way</strong>, preserving the most important functionality while shedding everything else.</p><p>Think of it like a priority ladder. As stress increases such as traffic spikes, downstream failures, resource exhaustion, the system progressively turns off less critical features to protect the core: <strong>moving money</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dEa-JG5tdTY7RYgYDpE_UQ.png" /></figure><p>Level 0: Normal Operation:</p><p>Everything is working as intended.</p><p>All features are available, payment processing, analytics, dashboards, exports, subscriptions, fraud checks, webhooks. Latency is within targets, systems are healthy, and users get the full experience.</p><p>This is where you spend most of your time, until you don’t.</p><p>Level 1: Shed Non-Critical Traffic</p><p>When load starts creeping up or parts of the system show strain, the first move is to cut off non-essential work.</p><p>Analytics queries, bulk data exports, and heavy list operations get disabled or rate-limited aggressively. These are useful features, but they don’t directly generate revenue.</p><p>Core flows stay untouched:</p><ul><li>Payment authorization</li><li>Captures and refunds</li><li>Webhook delivery</li></ul><p>The goal here is simple: <strong>reduce load without impacting money movement</strong>.</p><p>Level 2: Reduce Feature Set</p><p>If things continue to degrade, the system starts making harder trade-offs.</p><p>Some features that improve experience but aren’t strictly required get temporarily disabled. For example:</p><ul><li>3D Secure flows (which can increase friction and latency)</li><li>Subscription billing workflows</li><li>Non-critical background jobs</li></ul><p>Core payment operations still remain intact such as authorization, capture, and essential webhooks continue to function.</p><p>At this level, the system is actively optimizing for <strong>throughput and reliability over completeness</strong>.</p><p>Level 3: Emergency Mode</p><p>This is where things get serious.</p><p>All non-payment traffic is cut off. The system focuses entirely on <strong>revenue-generating operations</strong>:</p><ul><li>Payment authorization remains active</li><li>Everything else is either paused or queued for later</li></ul><p>Refunds, analytics, reporting, and even some internal workflows may be deferred.</p><p>Incoming non-critical requests are not dropped, they’re queued. Once the system stabilizes, they can be processed asynchronously.</p><p>The mindset here is clear: <strong>keep the checkout alive at all costs</strong>.</p><p>Level 4: Regional Failover</p><p>If an entire region becomes unhealthy like network partition, cloud outage, or major infrastructure issue , traffic is rerouted to other regions.</p><p>This is where multi-region architecture pays off.</p><p>Requests are sent to healthy regions, even if it means higher latency. A slightly slower payment is acceptable. A failed payment is not.</p><p>Systems rely on replication and distributed infrastructure (including pipelines built around Apache Kafka) to ensure continuity during failover.</p><p><strong>Why This Matters ?</strong></p><p>Graceful degradation is about <strong>prioritization under pressure</strong>.</p><p>Without it:</p><ul><li>Systems try to do everything and end up doing nothing well</li><li>Failures cascade across services</li><li>Critical paths get blocked by non-critical work</li></ul><p>With it:</p><ul><li>Core functionality survives</li><li>Load is reduced intelligently</li><li>Recovery is faster and cleaner</li></ul><p><strong>The Big Picture</strong></p><p>Not all features are equal.</p><p>When things break(and they will) then you want a system that knows what to sacrifice first.</p><p>Because in payments, the hierarchy is simple:</p><ol><li><strong>Can users still pay?</strong></li><li>Everything else comes later.</li></ol><h3>Active-Active Multi-Region Design</h3><p>At global scale, running in a single region isn’t just risky , it’s irresponsible. Regions go down, networks partition, latency varies wildly across geographies. If your entire payment system depends on one location behaving perfectly, you’re one incident away from global downtime.</p><p>The solution is <strong>active-active multi-region architecture</strong>.</p><p>Instead of having one primary region and a passive backup, you run <strong>fully functional stacks in multiple regions simultaneously</strong>. Each region can independently serve traffic, process payments, and operate the system end-to-end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-e62SNM79m50QnUOoCmDsA.png" /></figure><p><strong>What Each Region Contains</strong></p><p>Every region is essentially a complete mini-version of your entire platform:</p><ul><li>API Gateway handling incoming traffic</li><li>Application services (auth, orchestrator, routing, etc.)</li><li>Databases for transactional data</li><li>Apache Kafka for event streaming</li><li>Redis clusters for caching and rate limiting</li></ul><p>So whether a request lands in US, Europe, or APAC, it can be fully processed locally without needing to hop across continents.</p><p>This is critical for both <strong>latency and resilience</strong>.</p><p><strong>Traffic Routing</strong></p><p>Traffic is routed to the nearest healthy region using geo-routing (DNS or edge-based).</p><ul><li>A user in the US hits US-EAST</li><li>A user in Europe hits EU-WEST</li><li>A user in Asia hits AP-SOUTHEAST</li></ul><p>This minimizes latency and improves user experience, especially on the critical authorization path.</p><p>If a region becomes unhealthy, traffic is automatically rerouted to other regions. The system prioritizes <strong>availability over latency</strong> in failure scenarios.</p><p><strong>Cross-Region Replication</strong></p><p>Now comes the hard part: keeping all these regions in sync.</p><p>Not all data is treated equally.</p><p><strong>1. Asynchronous Replication (Most Data)</strong><br>For the majority of data such as events, analytics, logs, non-critical state like replication happens asynchronously across regions.</p><p>This keeps latency low and avoids blocking writes. Systems like Kafka replicate streams across regions, allowing each region to eventually converge.</p><p>The trade-off is <strong>eventual consistency</strong>, which is acceptable for many use cases.</p><p><strong>2. Strong Consistency (Critical State)</strong><br>For truly critical data like payment state transitions or ledger invariants, you need stronger guarantees.</p><p>This is where consensus-based systems (like globally distributed databases) come in. Writes may require coordination across regions to ensure correctness.</p><p>The trade-off here is higher latency, but for financial correctness, that’s non-negotiable.</p><p><strong>Why Active-Active Matters ?</strong></p><p>This design gives you several major advantages:</p><p><strong>High Availability</strong><br>If one region goes down, others continue serving traffic with minimal disruption.</p><p><strong>Low Latency</strong><br>Requests are handled close to the user instead of crossing continents.</p><p><strong>Fault Isolation</strong><br>Issues in one region don’t automatically cascade globally.</p><p><strong>Scalability</strong><br>You can scale regions independently based on demand.</p><p><strong>The Hard Parts</strong></p><p>Active-active sounds great, but it introduces real complexity:</p><ul><li>Handling data consistency across regions</li><li>Dealing with clock skew and ordering</li><li>Avoiding duplicate processing during failover</li><li>Designing idempotent systems everywhere</li><li>Managing cross-region replication lag</li></ul><p>You also need to carefully decide <strong>what must be globally consistent</strong> and what can tolerate eventual consistency. Getting this wrong either hurts performance or breaks correctness.</p><p><strong>Real-World Behavior</strong></p><p>During normal operation, each region mostly handles its own traffic and replicates data in the background.</p><p>During partial failures:</p><ul><li>Traffic shifts away from unhealthy regions</li><li>Other regions absorb the load</li><li>Systems rely on replication and queues to catch up</li></ul><p>During major outages:</p><ul><li>The system continues operating in remaining regions</li><li>Latency increases, but availability is preserved</li></ul><p><strong>The Big Trade-Off</strong></p><p>Active-active architecture is fundamentally about balancing:</p><ul><li><strong>Latency vs Consistency</strong></li><li><strong>Availability vs Complexity</strong></li></ul><p>You don’t get all three perfectly. You design carefully based on what matters most.</p><p>In payments, the priority is clear:</p><ul><li>Availability must be extremely high</li><li>Financial correctness must never be compromised</li><li>Latency should be as low as possible, but not at the cost of the above</li></ul><p>Running multi-region isn’t just about redundancy, it’s about <strong>designing for failure as a first-class scenario</strong>.</p><p>Because at this scale, failure isn’t an edge case.</p><p>It’s part of the normal operating model.</p><h4><strong>Data Partitioning Strategy</strong></h4><p>Once you go multi-region, the next question is: <strong>where does a given transaction actually run?</strong> Because if a single payment starts bouncing between regions mid-flight, you’ve just turned a 400ms flow into a latency nightmare.</p><p>The core principle is simple and very intentional:</p><p><strong>All steps of a single transaction execute within the same region.</strong></p><p>This is exactly how systems like Stripe approach it. You pick a region upfront, and the entire lifecycle, auth, routing, processor call, state update, event emission happens there. No cross-region chatter on the critical path.</p><p><strong>Region Assignment</strong></p><p>So how do you decide which region owns a transaction?</p><p>It’s a mix of business rules and performance optimization.</p><p>The primary factor is the <strong>merchant’s registration country</strong>. A merchant based in Europe is typically assigned to an EU region. This keeps their data localized and aligns with regulatory requirements.</p><p>Compliance is the next constraint. Regulations like GDPR may require that certain data never leaves a geographic boundary. That forces assignment to specific regions regardless of latency considerations.</p><p>After that comes <strong>proximity to the end customer</strong>. If multiple regions are valid from a compliance standpoint, the system prefers the one closest to the user to minimize latency which is especially important for authorization flows.</p><p>In practice, this becomes a deterministic routing decision: given a merchant and request context, the system always knows which region owns the transaction.</p><p><strong>Data Ownership Model</strong></p><p>Once a region is assigned, it becomes the <strong>primary owner</strong> of that merchant’s data.</p><p>All writes for that merchant such as payments, ledger entries, state transitions all happen in that region first.</p><p>To ensure durability and disaster recovery:</p><ul><li>Data is <strong>asynchronously replicated</strong> to one or two secondary regions</li><li>These secondary regions act as failover targets if the primary goes down</li></ul><p>For read-heavy workloads like dashboards and analytics, <strong>read replicas</strong> can exist in multiple regions. This allows global access to data without routing every query back to the primary region.</p><p>So you get a clean separation:</p><ul><li>Writes → primary region</li><li>Reads → local replicas (where possible)</li></ul><p><strong>Cross-Region Consistency</strong></p><p>Not all data needs the same level of consistency. Treating everything as strongly consistent would destroy latency. Treating everything as eventually consistent would break financial correctness.</p><p>So the system categorizes data based on how critical it is.</p><p><strong>1. Critical State (Balances, Ledger Invariants)</strong><br>This is where correctness is absolute.</p><p>Balances and core ledger state rely on <strong>consensus protocols</strong> (like Raft or Paxos) across a quorum of nodes. This ensures that even in a distributed setup, you never end up with conflicting views of money.</p><p>Yes, this adds latency. But this is one place you don’t compromise.</p><p><strong>2. Transaction Records</strong><br>Payment records themselves are written <strong>synchronously in the primary region</strong> and then replicated asynchronously to others.</p><p>This guarantees that once a transaction is acknowledged, it is durably stored in the primary region, while still allowing replication lag for secondary regions.</p><p><strong>3. Analytics Data</strong><br>Analytics pipelines operate on event streams (often via Apache Kafka) and are <strong>eventually consistent</strong>.</p><p>A few seconds or even minutes of lag is acceptable here. The goal is insight, not real-time correctness.</p><p><strong>4. Config &amp; Metadata</strong><br>Things like merchant configuration, feature flags, routing rules, etc., are also eventually consistent.</p><p>These are typically cached aggressively with short TTLs. Minor staleness is acceptable, and caching keeps latency low.</p><p><strong>Why This Model Works</strong></p><p>This partitioning strategy strikes a balance between:</p><ul><li><strong>Low latency</strong> (keep transactions local)</li><li><strong>High availability</strong> (replicate across regions)</li><li><strong>Strong correctness where needed</strong> (ledger, balances)</li><li><strong>Flexibility elsewhere</strong> (analytics, configs)</li></ul><p>It avoids the biggest trap in distributed systems: over-coordinating everything.</p><p><strong>The Trade-Off</strong></p><p>You’re explicitly choosing:</p><ul><li><strong>Local consistency for transactions</strong></li><li><strong>Global eventual consistency for most other data</strong></li></ul><p>This keeps the critical path fast while still maintaining a globally coherent system.</p><p>Multi-region systems aren’t just about copying data everywhere.</p><p>They’re about <strong>deciding where truth lives, where it propagates, and how fast it needs to converge</strong>.</p><p>Get that right, and the system feels fast, reliable, and consistent.</p><p>Get it wrong, and you spend your time debugging why a payment succeeded in one region and “doesn’t exist” in another.</p><h4><strong>Failover Mechanism</strong></h4><p>Multi-region only pays off if you can <strong>detect failures quickly and shift traffic without breaking correctness</strong>. The goal isn’t just to survive a regional outage, it’s to do it fast, automatically, and without creating duplicate or inconsistent money movement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RxkGGlOCAkX1GUCtuRJO2A.png" /></figure><p>Here’s how a production-grade failover loop works end to end.</p><p><strong>1) Health Monitoring (continuous signal, not guesswork)</strong></p><p>You don’t wait for users to tell you something is broken. Regions constantly prove they’re healthy:</p><ul><li><strong>Heartbeats (every ~1s):</strong> lightweight pings between regions and control-plane services. Fast signal for liveness.</li><li><strong>Synthetic transactions (every ~5s):</strong> real, end-to-end checks that exercise the critical path (auth → processor → state update). This catches “it’s up but not working” scenarios.</li><li><strong>External monitors (third-party):</strong> independent vantage points to avoid blind spots in your own telemetry.</li></ul><p>Multiple signals matter because any single signal can lie.</p><p><strong>2) Failure Detection (fast, but not trigger-happy)</strong></p><p>You want to react in seconds , but not flap on false positives.</p><ul><li>A region is marked <strong>unhealthy after ~3 consecutive missed heartbeats</strong> (≈3 seconds).</li><li>The signal must be <strong>confirmed by at least two systems</strong> (e.g., heartbeats + synthetic checks) to avoid accidental failovers.</li><li>Once thresholds are met, <strong>failover is automatic</strong>. No human in the loop. Humans are too slow for sub-minute recovery.</li></ul><p>This is the balance: <strong>fast detection + multi-signal confirmation</strong>.</p><p><strong>3) Traffic Rerouting (shift load without dropping requests)</strong></p><p>Once a region is declared unhealthy, traffic moves away immediately:</p><ul><li><strong>DNS failover with low TTL (~30s):</strong> new connections resolve to healthy regions quickly.</li><li><strong>Load balancer health checks:</strong> stop sending traffic to bad targets <em>right now</em> (no need to wait for DNS everywhere).</li><li><strong>Client-side retries:</strong> SDKs/clients can retry against alternate region endpoints if the primary fails mid-request.</li></ul><p>In practice, all three work together. DNS handles broad routing, load balancers handle immediate cutover, and clients cover edge cases.</p><p><strong>4) Recovery (catch up without double-processing)</strong></p><p>When the failed region comes back, the job isn’t done. It’s now <strong>behind</strong>.</p><p>Recovery is about catching up safely:</p><ul><li>The region <strong>replays missed events</strong> from the global log (typically backed by systems like Apache Kafka).</li><li><strong>Idempotency keys</strong> ensure reprocessing doesn’t create duplicates. Replays are safe by design.</li><li>A <strong>reconciliation job</strong> validates that balances, transactions, and ledger entries match expected state post-recovery.</li><li>Traffic is <strong>shifted back gradually</strong> (canarying) to avoid reintroducing load spikes or uncovering latent issues all at once.</li></ul><p><strong>Why This Works</strong></p><ul><li><strong>Detection is fast</strong> (seconds), but <strong>verified</strong> (multi-signal)</li><li><strong>Rerouting is layered</strong> (DNS + LB + client)</li><li><strong>Recovery is deterministic</strong> (event replay + idempotency)</li></ul><p>The system never assumes a clean cut. It plans for partial progress, retries, and duplication and neutralizes them.</p><p><strong>Failure Modes This Handles Well</strong></p><ul><li>Full regional outage (network, cloud, power)</li><li>Partial degradation (e.g., database unhealthy, processor connectivity issues)</li><li>Split-brain risks (mitigated by consensus on critical state + reconciliation)</li></ul><p>Failover isn’t a single switch , it’s a <strong>loop</strong>:</p><p><strong>detect → decide → reroute → recover → validate → rebalance</strong></p><p>Do each step well, and outages become short-lived events instead of long, expensive incidents.</p><h4>Compliance-Driven Data Residency</h4><p>At global scale, data placement isn’t just a performance decision, it’s a legal one. Where you store and process data is tightly governed by regional regulations, and payments sit right in the middle of that complexity. So instead of treating data residency as an afterthought, the system bakes it directly into the architecture.</p><p>In the US-East region (Virginia), you typically handle US merchant data along with aggregated global analytics workloads. The compliance stack here revolves around standards like PCI-DSS for payment security, SOX for financial reporting integrity, and SOC 2 for operational controls. This region often becomes a hub for cross-border analytics because US regulations are comparatively flexible when it comes to processing aggregated, non-sensitive data , though raw payment data is still tightly controlled.</p><p>For Europe, everything changes. Regions like Ireland or Frankfurt handle EU merchant and customer data under strict regulatory frameworks like GDPR and PSD2, along with PCI-DSS. GDPR in particular enforces strong rules around data privacy, user consent, and data locality. That means sensitive customer data (like payment details or personally identifiable information) must stay within EU boundaries unless very specific conditions are met. As a result, EU regions operate with stricter isolation, and even internal data movement across regions is heavily controlled and audited.</p><p>In APAC regions such as Singapore, the system handles merchant data for countries across Asia-Pacific, aligning with a mix of local data protection laws while still adhering to global standards like PCI-DSS. The challenge here is fragmentation.Different countries have different rules so the architecture needs to be flexible enough to adapt to varying compliance requirements without redesigning the system for each market.</p><p>Then there’s the most restrictive category: <strong>country-specific isolation</strong>. Some countries mandate that certain types of payment data never leave their borders. India is a good example with UPI-related data, and Brazil has similar requirements for financial data. In these cases, you run <strong>isolated deployments per country</strong>, ensuring that all sensitive data is stored and processed locally. Cross-border replication is either heavily restricted or completely disallowed. Even analytics pipelines have to be redesigned to work within those boundaries, often relying on anonymization or aggregation before any data can leave the region.</p><p>The end result is a system where <strong>data residency rules directly influence routing, storage, and processing decisions</strong>. A payment isn’t just routed based on latency or cost, it’s routed based on where it is legally allowed to exist. This adds complexity, but it’s non-negotiable. Because in payments, violating data residency laws isn’t just a technical issue, it’s a regulatory and financial risk that can shut down entire markets.</p><h3>Scalability Patterns</h3><ul><li><strong>Horizontal Scaling Strategy</strong></li></ul><p>At this scale, vertical scaling hits a wall very quickly. You don’t build a system that depends on “bigger machines”, you build one that <strong>adds more machines seamlessly</strong>. Every core component is designed to scale horizontally, but the way you scale each one is different because their bottlenecks are different.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4ictEk4JEWgCnwXqd6jshw.png" /></figure><p>Starting at the edge, the <strong>API Gateway</strong> scales by expanding its global footprint. You add more edge POPs (points of presence) closer to users and scale capacity within each region based on request rate. This is mostly stateless, which makes it the easiest layer to scale, just spin up more instances, distribute traffic, and you’re done. Auto-scaling kicks in based on incoming request volume, ensuring the edge never becomes a bottleneck.</p><p>The <strong>application services</strong> layer is where things get more dynamic. These services run on orchestration platforms like Kubernetes, using Horizontal Pod Autoscaling (HPA). Scaling decisions are driven not just by CPU or memory, but also by custom metrics like queue depth, request latency, or Kafka lag. Services can scale up within seconds (around a 30-second reaction window) and even scale down to zero for non-critical or low-traffic workloads. This keeps resource usage efficient while still being able to absorb sudden spikes.</p><p>For the <strong>database layer</strong>, scaling is more nuanced because of state. Write scaling is achieved by adding more shards, distributing data across multiple partitions so no single node becomes a bottleneck. Read scaling is handled via replicas, which offload query-heavy workloads like dashboards and reporting. Within each shard, you can still scale vertically to increase capacity, but the primary lever is horizontal: more shards, more throughput. The trick is balancing shard distribution and avoiding hotspots.</p><p>With <strong>Apache Kafka</strong>, scaling is all about partitions and brokers. If you need more throughput for a topic, you increase the number of partitions, allowing more consumers to process data in parallel. If the cluster itself is hitting limits, you add more brokers to distribute storage and network load. Kafka’s consumer groups automatically rebalance when partitions or consumers change, which makes scaling relatively smooth without manual intervention.</p><p>The <strong>Redis caching layer</strong> scales by adding more nodes to the cluster and distributing keys across them. Sharding is typically done using key prefixes or consistent hashing so that data is evenly spread. Since Redis sits on the hot path (rate limiting, idempotency, configs), keeping latency low is critical, so scaling here is both about capacity and maintaining sub-millisecond response times.</p><p>The <strong>fraud detection engine</strong> is a different beast altogether. This is compute-heavy, often involving machine learning inference. Scaling here means adding more model replicas, often backed by GPUs, and placing them behind a load balancer. As transaction volume increases, you scale the inference fleet horizontally to maintain low-latency scoring. This layer is tightly coupled with latency budgets, so scaling decisions here directly impact authorization performance.</p><p>Horizontal scaling isn’t just about adding capacity , it’s about <strong>removing single points of failure and bottlenecks across the system</strong>.</p><ul><li>Stateless layers scale easily with more instances</li><li>Stateful systems scale via partitioning and replication</li><li>Streaming systems scale via parallelism (partitions)</li><li>Compute-heavy systems scale via specialized hardware (GPUs)</li></ul><p>Each layer has its own scaling lever, and the system works because all of them can expand independently.</p><p>A system like this is never “done scaling.” It’s constantly adjusting, adding nodes, rebalancing load, reacting to traffic patterns.</p><p>Because at 500K+ TPS, scaling isn’t an event.</p><p>It’s the default state of the system.</p><ul><li><strong>Handling Traffic Spikes (Black Friday / Flash Sales)</strong></li></ul><p>Traffic spikes like Black Friday aren’t “unexpected load”, they’re <strong>predictable chaos</strong>. The mistake most systems make is treating them like regular scaling problems. They’re not. You’re dealing with synchronized global demand, bursty traffic patterns, and zero tolerance for failure. So instead of reacting in real time, you <strong>prepare aggressively ahead of time</strong>, operate defensively during the event, and learn from it afterward.</p><p><strong>Pre-Event (Weeks Before)</strong></p><p>This is where most of the real work happens. By the time the event starts, you shouldn’t be discovering limits, you should already know them.</p><p>First, you run <strong>capacity tests at 3x the expected peak</strong>. Not just synthetic API calls, but full end-to-end simulations including payment flows, processor interactions, and event pipelines. The goal is to find breaking points early, not during checkout.</p><p>Then you <strong>pre-scale everything, </strong>API gateways, app services, databases, Kafka clusters, caches and to expected peak plus at least <strong>50% headroom</strong>. Auto-scaling alone isn’t enough here; cold starts and scaling lag can kill you during sudden bursts.</p><p>Caches are <strong>pre-warmed</strong> with hot data like merchant configs, BIN lookups, routing rules so the system doesn’t waste time fetching or recomputing during peak traffic. Cold cache during Black Friday is a self-inflicted outage.</p><p>At the same time, you <strong>freeze non-critical deployments</strong>. No risky releases, no schema changes, no “quick fixes.” Stability beats progress here.</p><p>You also <strong>verify failover procedures</strong>. Not just on paper, do actual drills. Regions go down in simulations, traffic reroutes, recovery paths are tested. If failover doesn’t work smoothly now, it definitely won’t under real load.</p><p><strong>During Event</strong></p><p>Once the event starts, the mindset shifts from building to <strong>protecting the system</strong>.</p><p>You continuously monitor real-time dashboards with traffic, latency, error rates, saturation levels across every layer. This isn’t passive monitoring; it’s active decision-making.</p><p>Auto-scaling kicks in early, typically when systems hit around <strong>70% utilization</strong>, so you stay ahead of the curve instead of reacting too late. At the same time, <strong>pre-warmed standby capacity</strong> in secondary regions is ready to absorb overflow or handle partial failures.</p><p>If pressure keeps increasing, the system starts <strong>progressive load shedding, </strong>cutting off non-critical traffic first (analytics, exports, list APIs) to preserve core payment flows. This ties directly into the graceful degradation strategy.</p><p>You also have <strong>on-call teams mapped to each major component like </strong>API layer, databases, streaming, fraud systems, etc. At this scale, you don’t want a single team trying to debug everything. Ownership needs to be clear and immediate.</p><p>Behind the scenes, systems like Apache Kafka help absorb bursts by decoupling producers and consumers, preventing downstream services from getting overwhelmed instantly.</p><p><strong>Post-Event</strong></p><p>Just because traffic drops doesn’t mean the system is done working.</p><p>You <strong>don’t scale down immediately</strong>. Settlement, reconciliation, webhook retries, and delayed processing are still running heavily in the background. Dropping capacity too early can create a second wave of failures.</p><p>Scale-down happens gradually, based on actual load trends, not assumptions.</p><p>Then comes the most important part: the <strong>post-mortem</strong>. Every anomaly like latency spike, partial failure, retry storm is analyzed. Not to assign blame, but to understand limits and improve resilience.</p><p>Finally, you <strong>update capacity models using real data</strong>. Black Friday gives you the most valuable dataset you’ll get all year. If you don’t feed that back into planning, you’re wasting it.</p><p>Handling spikes isn’t about hoping your system scales.</p><p>It’s about:</p><ul><li><strong>Over-preparing before the event</strong></li><li><strong>Protecting the core during the event</strong></li><li><strong>Learning aggressively after the event</strong></li></ul><p>Flash sales and Black Friday don’t break systems because of high traffic.</p><p>They break systems because of <strong>unpreparedness under high traffic</strong>.</p><p>If you treat them like a normal day with more requests, you’ll fail.</p><p>If you treat them like a controlled stress test of your entire architecture, you’ll survive and probably come out stronger.</p><ul><li><strong>Database Scaling Deep Dive</strong></li></ul><p>Scaling the database is where things stop being straightforward. Stateless layers scale easily like you just add more instances. Databases don’t give you that luxury. You’re dealing with consistency, coordination, and real money. So the strategy is a mix of <strong>replication for reads, sharding for writes, and extreme discipline around schema changes</strong>.</p><p><strong>Read Scaling</strong></p><p>Most database traffic in a system like this is actually reads such a as dashboards, reports, API fetches, internal queries. If all of that hits the primary, you’re done.</p><p>So you introduce <strong>read replicas</strong>, typically <strong>2–3 per shard per region</strong>. These replicas asynchronously replicate data from the primary and serve read-heavy workloads.</p><p>Routing becomes important:</p><ul><li><strong>Writes → always go to the primary</strong></li><li><strong>Reads → go to replicas by default</strong></li></ul><p>For many use cases like dashboards or analytics, <strong>slightly stale data is fine</strong>. A lag of under a second is usually acceptable and buys you massive scalability.</p><p>But not all reads are equal. Some queries like checking a balance before a transaction require <strong>strong consistency</strong>. Those are explicitly routed to the primary to avoid stale reads.</p><p>So you end up with a split:</p><ul><li><strong>Eventually consistent reads → replicas</strong></li><li><strong>Strongly consistent reads → primary</strong></li></ul><p>That distinction is critical in payments. Showing slightly outdated analytics is fine. Showing the wrong balance is not.</p><p><strong>Write Scaling</strong></p><p>Writes are harder. You can’t just replicate your way out of write bottlenecks, you need to <strong>partition the data</strong>.</p><p>The primary strategy here is <strong>sharding by </strong><strong>merchant_id</strong>.</p><p>Each merchant’s data lives on a specific shard, which means most operations are isolated to a single shard. This avoids cross-shard transactions for the vast majority of requests.</p><p>Instead of hardcoding shards, you define something like <strong>256 logical shards</strong>, which are then mapped to physical database clusters. This gives you flexibility and you can rebalance shards across machines without changing the logical structure.</p><p>As the system grows, you monitor for <strong>hot shards, </strong>cases where a few merchants generate disproportionate traffic (think large platforms or flash sales). When that happens, shards can be <strong>rebalanced</strong> across clusters to distribute load more evenly.</p><p>For non-critical workloads like analytics ingestion or logging you can also use <strong>batch writes</strong>. Instead of writing every event individually, you group them and write in bulk. This reduces write amplification and improves throughput without affecting correctness.</p><p><strong>Schema Evolution</strong></p><p>Schema changes are where many production systems go down. At this scale, you can’t afford downtime or risky migrations.</p><p>Everything is done <strong>online and incrementally</strong>.</p><p>For traditional databases, tools like pt-online-schema-change or gh-ost allow you to modify tables without locking them. Under the hood, they create shadow tables, copy data gradually, and switch over with minimal disruption.</p><p>For larger changes, you use <strong>blue-green table migrations</strong>:</p><ul><li>Create a new version of the table/schema</li><li>Dual-write to both old and new</li><li>Backfill historical data</li><li>Gradually shift reads to the new schema</li><li>Decommission the old one</li></ul><p>Crucially, all schema changes are <strong>backward-compatible</strong>.</p><ul><li>You can <strong>add columns</strong></li><li>You can <strong>add indexes</strong></li><li>But you never remove or break existing fields immediately</li></ul><p>This ensures older services or API versions don’t suddenly break.</p><p>On top of that, <strong>feature flags</strong> control when new schema features are actually used. The schema can exist in production long before it’s fully activated, giving you a safe rollout path.</p><p>Database scaling is about <strong>separating concerns</strong>:</p><ul><li>Replication handles <strong>read scalability</strong></li><li>Sharding handles <strong>write scalability</strong></li><li>Careful migrations handle <strong>evolution without downtime</strong></li></ul><p>And all of it is layered on top of strict consistency guarantees where it matters.</p><p>You don’t “scale a database” in one step.</p><p>You build a system where:</p><ul><li>Reads don’t fight writes</li><li>Writes don’t fight each other</li><li>Changes don’t break production</li></ul><p>And once you get that right, the database stops being a bottleneck and starts behaving like infrastructure.</p><h3>Security and Compliance</h3><p><strong>PCI-DSS Level 1 Architecture</strong></p><p>At this scale, security isn’t a feature, it’s the foundation. <strong>PCI-DSS Level 1</strong>, the highest tier of compliance for systems processing millions of card transactions annually, forces you to design your entire architecture around <strong>strict isolation, minimal exposure, and controlled access to sensitive data</strong>. The key idea is simple but powerful: <strong>reduce the scope of systems that ever touch raw card data</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*naEX9liYNNsxCNxPrmJUpQ.png" /></figure><p>The architecture is divided into clearly separated zones. The <strong>public zone (DMZ)</strong> sits at the edge and handles all incoming traffic like API gateways, CDNs, WAFs, and DDoS protection. This layer is exposed to the internet but contains no sensitive data. Behind a firewall sits the <strong>application zone</strong>, where your business logic runs such as merchant services, orchestration, analytics. These services process requests and coordinate workflows, but they never directly handle raw card numbers.</p><p>At the core is the <strong>Cardholder Data Environment (CDE): </strong>the most restricted and tightly controlled part of the system. This is the only place where sensitive card data (like PANs) is ever processed or stored. It includes components like the tokenization service, secure card vault backed by hardware security modules (HSMs), payment processor integrations, and encrypted storage. Access into this zone is heavily restricted via strict firewall rules and allowlists, and every interaction is audited.</p><p>The most important design principle here is <strong>tokenization</strong>. The moment card data enters the system, it is converted into a token which is a surrogate value with no exploitable meaning outside the CDE. From that point on, all other services operate purely on tokens, not raw card data. This dramatically reduces the compliance surface area, because most of your system is no longer in PCI scope.</p><p>The result is a layered, defense-in-depth architecture where <strong>sensitive data is isolated, access is minimized, and every boundary is enforced</strong>. Because in payments, a security failure isn’t just a bug, it’s a breach with legal, financial, and reputational consequences.</p><p><strong>Tokenization Flow</strong></p><p>Tokenization is the trick that makes the whole security model actually workable. Instead of letting raw card data flow through every service (which would put your entire system in PCI scope), you <strong>capture it once, lock it down inside the Cardholder Data Environment (CDE), and replace it with a safe token everywhere else</strong>.</p><p>Here’s how that flow plays out in practice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9D7Ni10FfoGdgB1SSU0AQA.png" /></figure><p>The customer enters their card details on the client side (usually via a secure JS SDK). That card number like 4242 4242 4242 4242 is <strong>sent directly to the tokenization service</strong>, not to the merchant’s backend. This is important. The merchant server never touches raw PAN data at any point in the flow.</p><p>Inside the tokenization service (which lives strictly within the CDE), a few critical things happen in sequence. First, the PAN is <strong>encrypted using a key stored in an HSM (Hardware Security Module)</strong>. This ensures that even if storage is compromised, the raw data is still protected by hardware-backed cryptography. Then the encrypted PAN is stored securely in the <strong>card vault</strong>, which is designed specifically for handling sensitive data with strict access controls and audit trails.</p><p>Once the card is safely stored, the system generates a <strong>token (</strong>something like tok_1a2b3c4d5e). This token is just a reference. It has no exploitable meaning outside the system and cannot be reversed to obtain the original card number without access to the vault.</p><p>That token is then returned back through the client to the merchant’s server. From this point forward, <strong>every operation such as authorization, capture, refund uses the token instead of the actual card number</strong>.</p><p>The result is a massive reduction in risk and compliance burden. The merchant never sees or stores sensitive card data, which means their systems are largely out of PCI scope. Meanwhile, your platform keeps tight control over where and how raw card data is handled.</p><p>In other words, tokenization turns a highly sensitive workflow into something that’s <strong>safe to pass around across services without constantly worrying about exposing real card details</strong>.</p><p><strong>Compliance Matrix</strong></p><p>At this scale, compliance isn’t a checklist you run at the end; it’s something that shapes the architecture from day one. Different regulations apply to different parts of the system, and each one introduces its own constraints. The challenge is not just meeting them individually, but making sure they all work together without turning the system into a bottleneck.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AN06H9W5hb_q5OaDYZnYqg.png" /></figure><p>For <strong>PCI-DSS v4.0</strong>, the focus is card processing security. It comes with strict requirements around network segmentation, encryption, and access control(12 major controls in total). The system addresses this through <strong>tokenization, HSM-backed encryption, and strict isolation of the Cardholder Data Environment (CDE)</strong> so that raw card data is never exposed outside tightly controlled boundaries.</p><p>With <strong>GDPR</strong>, the concern shifts to personal data protection in the EU. This includes principles like data minimization, user consent, and the “right to erasure.” Architecturally, this translates into <strong>data residency (keeping EU data within EU regions), pseudonymization, and dedicated governance roles like a Data Protection Officer (DPO)</strong>. It also affects how logs, analytics, and backups are handled.</p><p><strong>PSD2 with Strong Customer Authentication (SCA)</strong> adds another layer for European payments. It requires multi-factor authentication for certain transactions. In practice, this is implemented through <strong>3D Secure 2.0 flows</strong>, which integrate directly into the payment authorization pipeline without breaking user experience too much.</p><p>For financial integrity, <strong>SOX (Sarbanes-Oxley)</strong> mandates strong internal controls and auditability. This is where the <strong>immutable ledger and strict access controls</strong> come into play. Every financial event must be traceable, and no data can be silently modified without leaving a trail.</p><p><strong>SOC 2 Type II</strong> focuses more broadly on operational trust like security, availability, and data integrity over time. This pushes the system toward <strong>continuous monitoring, alerting, and regular third-party audits</strong>. It’s less about a specific feature and more about proving that your processes are consistently reliable.</p><p>Finally, <strong>AML/KYC regulations</strong> apply across jurisdictions and deal with preventing fraud and financial crime. This requires a full <strong>identity verification pipeline</strong>, ongoing monitoring of transactions, and risk scoring to detect suspicious behavior.</p><p>Compliance at this level isn’t optional, and it’s not something you “add later.”It becomes part of how you design storage, routing, authentication, and even data models.Because in payments, being technically correct is not enough.You also have to be <strong>legally correct, auditable, and provably secure</strong> at all times.</p><h3>Fraud Detection (Radar-like System)</h3><p>Fraud detection in payments isn’t a side feature, it’s part of the critical path. Every transaction gets evaluated in real time, and the system has milliseconds to decide whether to allow, block, or escalate. At trillion-dollar scale, this becomes a data and inference problem as much as a systems problem.</p><p>The pipeline starts the moment a <strong>payment request</strong> comes in. Before anything hits the processor, the system runs <strong>feature extraction</strong>. This is where raw request data gets transformed into signals the model can understand. Things like card BIN, issuing country, device fingerprint, IP reputation, merchant history, transaction velocity, and behavioral patterns. A single transaction might generate hundreds of features, often enriched with historical context pulled from fast stores like Redis or streaming systems like Apache Kafka.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y93OQ0NmtQacNk54ZSPlWA.png" /></figure><p>These features are then fed into the <strong>ML scoring engine</strong>, which runs one or more models (typically a mix of gradient-boosted trees and deep learning models). The output is a <strong>risk score between 0 and 100</strong>, representing the probability that the transaction is fraudulent. This scoring has to happen fast(usually within ~20–30ms) so the models are optimized for low-latency inference and often deployed as a horizontally scaled service (sometimes GPU-backed for more complex models).</p><p>Once the score is computed, the system makes a decision:</p><ul><li><strong>Low risk (&lt; 30)</strong> → Allow the transaction to proceed</li><li><strong>Medium risk (30–75)</strong> → Send for review or trigger step-up authentication</li><li><strong>High risk (&gt; 75)</strong> → Block the transaction outright</li></ul><p>This decision layer isn’t purely ML-driven. There’s also a <strong>rules engine overlay</strong> where merchants can define custom logic like blocking certain countries, limiting transaction sizes, or flagging unusual patterns specific to their business.</p><p>For borderline cases, the system can trigger <strong>step-up authentication</strong> like 3D Secure. This adds friction, but only when needed, balancing fraud prevention with conversion rates.</p><p><strong>Feedback Loop (Where the System Gets Smarter)</strong></p><p>The real power of a system like this comes from the feedback loop.</p><p>Every chargeback, dispute, or confirmed fraud case feeds back into the system. That data is used to <strong>retrain models continuously</strong>, improving accuracy over time. At scale, this creates a strong network effect , the more transactions you process, the better your fraud detection becomes.</p><p>This feedback loop is often implemented via streaming pipelines, where events are logged, labeled, and fed into offline training systems, then periodically pushed back into production models.</p><p><strong>Why This Architecture Works</strong></p><ul><li><strong>Real-time scoring</strong> keeps fraud detection on the critical path without slowing down payments</li><li><strong>Feature-rich models</strong> capture both transaction-level and behavioral patterns</li><li><strong>Hybrid decisioning</strong> (ML + rules) provides flexibility and control</li><li><strong>Continuous learning</strong> improves detection over time</li></ul><p><strong>The Trade-Off</strong></p><p>Fraud systems are always balancing two competing goals:</p><ul><li><strong>Reduce fraud (block bad transactions)</strong></li><li><strong>Maximize conversion (don’t block good users)</strong></li></ul><p>Too aggressive, and you lose legitimate customers. Too lenient, and fraud slips through.</p><p>The architecture is designed to operate in that narrow middle ground making fast, informed decisions with incomplete information.</p><p>Fraud detection isn’t about catching every bad transaction.</p><p>It’s about building a system that gets <strong>better with every transaction it sees</strong>, adapts to new attack patterns, and makes the right trade-offs in real time.</p><p>Because in payments, fraud isn’t static.</p><p>It evolves and your system has to evolve faster.</p><h3>ML Model Architecture</h3><p>Fraud detection at this level is never a single model, it’s a <strong>stack of models, rules, and feedback loops</strong> working together under tight latency constraints. You need something fast, something expressive, and something controllable. That’s why the architecture is layered instead of relying on one “perfect” model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zVRogweJaj1-kRV2BZzXww.png" /></figure><p>At the core sits the <strong>primary model: gradient boosted trees</strong> (typically XGBoost or LightGBM). This is the workhorse. It handles mixed feature types (categorical, numerical, sparse signals) extremely well, gives <strong>very fast inference (&lt;10ms)</strong>, and importantly provides some level of interpretability. You can actually explain <em>why</em> a transaction was flagged (high-risk country, unusual velocity, mismatched device, etc.), which is critical for debugging and compliance. Most transactions are decided here.</p><p>On top of that, you introduce a <strong>secondary deep neural network</strong>. This model is better at capturing <strong>complex, non-linear relationships and sequential behavior t</strong>hings like spending patterns over time, subtle correlations across merchants, or coordinated fraud attacks. It’s heavier and slightly slower, so you don’t run it on every request. Instead, it’s typically invoked for <strong>borderline or high-uncertainty cases</strong>, where the extra signal is worth the latency cost.</p><p>The outputs of these models are then combined using an <strong>ensemble approach</strong>. Instead of trusting one model blindly, you take a weighted combination of their scores. This improves overall accuracy and robustness, if one model misses a pattern, another might catch it.</p><p>But models alone aren’t enough. On top of the ML layer sits a <strong>rules engine overlay</strong>, which brings determinism and control:</p><ul><li><strong>Merchant-defined rules</strong> let businesses enforce their own risk policies (for example, blocking large transactions from unfamiliar regions).</li><li><strong>Global rules</strong> handle known bad signals like compromised BIN ranges or flagged IPs.</li><li><strong>Regulatory rules</strong> enforce compliance requirements, like triggering Strong Customer Authentication (SCA) for certain European transactions.</li></ul><p>This hybrid approach(ML + rules) is what makes the system practical. Models handle patterns, rules handle guarantees.</p><p><strong>Training Pipeline (Where Models Evolve)</strong></p><p>The system is only as good as its data, and in fraud detection, labels come from real-world outcomes.</p><p>Training data consists of <strong>labeled transactions</strong> fraud vs. non-fraud. Labels are derived from sources like chargebacks and reports from card networks (e.g., TC40/SAFE). These signals often arrive with delays, so the system needs to continuously incorporate new data as it becomes available.</p><p>Retraining happens at multiple cadences:</p><ul><li><strong>Weekly full retrains</strong> to rebuild models from scratch with fresh data</li><li><strong>Daily incremental updates</strong> to quickly adapt to new fraud patterns</li></ul><p>Before deploying a new model, you don’t just flip a switch. You run <strong>A/B testing in shadow mode</strong>, where the new model scores transactions alongside the current one without affecting decisions. This lets you compare performance safely.</p><p>Once validated, rollout happens gradually via <strong>canary deployment</strong>:</p><ul><li>Start with 1% of traffic</li><li>Increase to 10%, then 50%</li><li>Finally reach 100% if everything looks stable</li></ul><p>This staged rollout ensures that if something goes wrong, the blast radius is minimal.</p><p>Why This Works</p><ul><li><strong>GBT models</strong> provide speed and reliability for the majority of cases</li><li><strong>Neural networks</strong> capture deeper, harder-to-detect patterns</li><li><strong>Ensembling</strong> improves accuracy and resilience</li><li><strong>Rules engine</strong> adds control and guarantees</li><li><strong>Continuous training</strong> keeps the system adaptive</li></ul><p><strong>The Trade-Off</strong></p><p>We’re balancing:</p><ul><li><strong>Latency vs. model complexity</strong></li><li><strong>Automation vs. control</strong></li><li><strong>Accuracy vs. interpretability</strong></li></ul><p>There’s no perfect point , only a system that continuously adjusts.</p><p>Fraud models are never “done.”</p><p>Attack patterns evolve, user behavior shifts, and new payment methods introduce new risks.</p><p>So the real architecture isn’t just the models , it’s the <strong>system that keeps those models learning, validating, and improving without breaking production</strong>.</p><ul><li><strong>Real-Time Inference Architecture</strong></li></ul><p>Fraud detection only works if it fits inside the authorization path and that means <strong>you get ~30ms, not a millisecond more</strong>. This entire pipeline has to fetch features, run models, and make a decision before the request even reaches the processor. That constraint drives everything about how the system is designed.</p><p>The flow is tight and purpose-built. A payment request hits the fraud system, which first pulls data from the <strong>feature store which is </strong>a hybrid setup backed by in-memory systems like Redis for ultra-fast access, combined with precomputed aggregates. These features are then passed to a <strong>model serving layer</strong> (typically something like TensorFlow Serving or TorchServe), which runs inference and returns a risk score. That score is then fed into the <strong>decision engine</strong>, which combines it with rules and outputs a final verdict (allow, review, or block).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AJNC3cjFVKC8CLBpW2kNUg.png" /></figure><h4><strong>Feature Store Design</strong></h4><p>The feature store is the real bottleneck if you get it wrong. Models are fast. Data access is not. So the system splits features into three categories based on how fresh and how expensive they are to compute.</p><p><strong>1. Pre-computed features (updated every minute)</strong><br>These are the backbone of the system and cheap to fetch, already aggregated, and stored in Redis for sub-millisecond access. Examples include:</p><ul><li>Card velocity counters (how many transactions in the last N minutes)</li><li>Email/IP reputation scores</li><li>Merchant-level fraud rates</li></ul><p>These are continuously updated via streaming pipelines so they stay fresh without being recomputed on every request.</p><p><strong>2. Real-time features (computed per request)</strong><br>These are derived on the fly from the current transaction. They’re lightweight but highly contextual:</p><ul><li>Amount anomaly (is this transaction unusual for this user?)</li><li>Geo mismatch (card country vs. IP location mismatch)</li><li>Behavioral signals (typing speed, device fingerprint, session patterns from the JS SDK)</li></ul><p>These features add immediate context that precomputed aggregates can’t capture.</p><p><strong>3. Batch features (updated daily)</strong><br>These are heavier, slower-moving signals that come from offline systems:</p><ul><li>Card network fraud reports (like TC40/SAFE)</li><li>Merchant risk tier classification</li><li>Long-term behavioral patterns</li></ul><p>They’re not latency-sensitive, so they’re computed offline and periodically pushed into the feature store.</p><p><strong>Model Serving Layer (Fast, Stateless, Scalable)</strong></p><p>Once features are assembled, they’re sent to the model server. This layer is:</p><ul><li><strong>Stateless</strong> → easy to scale horizontally</li><li><strong>Optimized for low latency</strong> → models are preloaded in memory</li><li><strong>Versioned</strong> → multiple model versions can run side by side</li></ul><p>Inference typically takes <strong>5–10ms</strong>, which leaves enough room in the latency budget for feature fetching and decisioning.</p><p><strong>Decision Engine (Where ML Meets Reality)</strong></p><p>The final step is the decision engine. It takes:</p><ul><li>Model score (0 to 100 risk)</li><li>Rules (merchant + global + regulatory)</li></ul><p>And produces a deterministic outcome:</p><ul><li>Allow</li><li>Block</li><li>Step-up (3DS / review)</li></ul><p>This layer is intentionally simple and fast. No heavy computation, just combining signals and enforcing policies.</p><p>Why This Architecture Works ?</p><ul><li><strong>Precomputation + caching</strong> avoids expensive runtime work</li><li><strong>In-memory feature access</strong> keeps latency predictable</li><li><strong>Stateless model servers</strong> scale easily under load</li><li><strong>Clear separation (features → model → decision)</strong> keeps the system debuggable</li></ul><p><strong>The Real Constraint</strong></p><p>You’re not optimizing for accuracy alone.</p><p>You’re optimizing for:</p><ul><li><strong>Accuracy under 30ms</strong></li><li><strong>Consistency across millions of requests per second</strong></li><li><strong>Graceful degradation when dependencies fail</strong></li></ul><p>If the feature store slows down, the whole system slows down. If inference spikes, you miss your SLA. So every component is designed to be fast, predictable, and horizontally scalable.</p><p>In fraud detection, the model is not the hard part.</p><p>Getting the <strong>right data, at the right time, within a brutal latency budget</strong> and that’s the real engineering challenge.</p><p>Because a model that’s 2% more accurate but 50ms slower is not better.</p><p>It’s unusable.</p><h3>Observability &amp; Monitoring</h3><ul><li><strong>Three Pillars of Observability</strong></li></ul><p>At this scale, you can’t debug a payments system by SSHing into a box and tailing logs. You need a proper observability stack, and the industry has largely converged on three pillars: metrics, logs, and traces. Each one answers a different question like metrics tell you <em>something is wrong</em>, logs tell you <em>what happened</em>, and traces tell you <em>where exactly it went wrong across which services</em>. You need all three.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GsRmudw25tGi350AH212bw.png" /></figure><p><strong>Metrics</strong> are your real-time pulse on the system, and they operate at three levels. At the business level you’re tracking things like total payment volume, authorization success rates, and auth rates broken down by card network and these are the numbers that tell you whether the product is actually working for merchants, not just whether the servers are up. At the system level you’re watching latency percentiles (p50, p95, p99), error rates, and throughput per service. At the infrastructure level it’s the usual CPU, memory, disk, network utilization. And then on top of all of that you’re tracking SLO-specific metrics: how much error budget is remaining and at what rate you’re burning through it. Prometheus works well for the self-hosted approach, Datadog if you want managed and are okay paying for it.</p><p><strong>Logs</strong> need to be structured from the start: unstructured logs at this volume are essentially unsearchable. Every request gets a structured JSON log, and critically every log carries a correlation ID that’s propagated across every service that touches that request. That correlation ID is what makes it possible to reconstruct the full lifecycle of a single payment across a dozen microservices without going insane. One non-negotiable here: PII gets redacted or tokenized before it ever hits a log store. Card numbers, CVVs, account details and none of that lives in plaintext in your logging pipeline. Retention is tiered: 30 days hot (fast, queryable, expensive) for operational debugging, and 7 years cold for compliance, because SOX and PCI don’t care how inconvenient long-term storage is.</p><p><strong>Traces</strong> are what you reach for when metrics tell you p99 latency spiked and logs tell you requests are slow, but you need to know <em>exactly which service in the call chain</em> is the culprit. With distributed tracing via Jaeger and OpenTelemetry, you get a full visualization of the request lifecycle across every service it touched, with latency broken down per hop. The sampling strategy here is deliberate: 100% of errors get traced (you always want full fidelity on failures), but only 1% of successful requests do. At 400 million API calls a day, tracing everything would be its own infrastructure problem.</p><p>The alerting layer sits across all three pillars. Rather than naive threshold-based alerts (“alert if error rate &gt; 1%”), the system uses SLO-based alerting on error budget burn rate which is smarter because a 1% error rate for one minute is very different from a 1% error rate that’s been sustained for six hours and is about to blow your monthly budget. Anomaly detection is ML-based rather than static thresholds, which matters in a payments system where traffic patterns are highly seasonal and a “normal” Tuesday looks nothing like a Black Friday. When something does fire, the escalation path is PagerDuty to on-call engineer to incident commander, and every single alert has a runbook linked directly to it. That last part sounds like a detail but it’s genuinely important: an alert that pages someone at 3am without telling them what to actually do is just noise with consequences.</p><p>Here’s the Key Dashboards section written in the same casual style:</p><ul><li><strong>Key Dashboards</strong></li></ul><p>Not everyone looking at observability data needs to see the same thing, so dashboards are segmented by audience. An executive asking “are we processing payments right now” needs a completely different view than an on-call engineer who just got paged at 2am.</p><p>The <strong>Executive Dashboard</strong> is about business health at a glance. Total payment volume in real-time, transaction success rates broken down by region and processor, API availability with a 30-day trend so you can see if things are gradually degrading rather than just whether right now is green, fraud rate and how much volume got blocked, and current settlement status. No latency percentiles, no Kafka consumer lag, just the numbers a business stakeholder actually needs to answer “is the product working and are we making money.”</p><p>The <strong>Engineering Dashboard</strong> goes much deeper. This is where you’re watching API latency at p50, p95, and p99 broken down by endpoint, because aggregate latency numbers lie and you need to know which specific endpoint is slow. Error rates are broken down by service and error code, so you can distinguish between a spike in card declines (a merchant problem) and a spike in 500s (your problem). You’re also watching database QPS and replication lag, Kafka consumer lag per topic (a growing lag on the webhook topic means your delivery workers are falling behind), cache hit rates, and the circuit breaker states for every external processor integration. That last one is important, a tripped circuit breaker on Visa’s authorization endpoint is something you want to know about before merchants start calling.</p><p>The <strong>On-Call Dashboard</strong> is designed for exactly one scenario: someone just got paged and needs to orient themselves fast. It shows active incidents and their severity, how much error budget is remaining per SLO so you can immediately gauge how serious the situation is relative to your monthly budget, recent deploys and their health indicators (because the first question in any incident is “did someone just ship something”), processor health status across all card networks, and regional health with failover status. Everything on this dashboard is optimized for fast situational awareness, not deep analysis, you do the deep analysis after you’ve stopped the bleeding.</p><ul><li><strong>Synthetic Monitoring</strong></li></ul><p>Real user traffic tells you when something is broken after the fact. Synthetic monitoring is how you find out before merchants do.</p><p>The synthetic transaction monitor runs a full payment lifecycle such as authorization, capture, and refund every 5 seconds from each region, using real processor sandboxes with actual test cards. This isn’t a ping check or a health endpoint returning 200; it’s a real end-to-end payment flow hitting the actual processor integration. If latency crosses 2x the baseline or a transaction fails, an alert fires immediately. The goal is that if a processor integration silently starts degrading, or a regional network issue is causing timeouts, you know about it within seconds rather than finding out from a merchant support ticket 20 minutes later.</p><p>Canary deployments follow the same principle of catching problems early before they have blast radius. New code never goes straight to 100% of traffic, it starts at 1% and the system automatically compares error rate, latency, and payment success rate against the baseline. If any meaningful degradation is detected within 5 minutes, the deployment rolls back automatically without anyone having to make that call manually. If things look healthy, traffic shifts gradually: 1% to 5% to 25% to 50% to 100%. The slow ramp is intentional, because some bugs only show up under real load patterns and you want enough time at each stage to be confident before moving forward. A bad deploy that affects 1% of traffic for 5 minutes is a very different incident than one that affects 50% of traffic for 30 minutes.</p><h3>API Design &amp; Developer Experience</h3><ul><li><strong>API Design Principles</strong></li></ul><p>Stripe’s API is genuinely the gold standard for developer experience in fintech, and that’s not an accident, it’s the result of extremely deliberate design decisions that compound over time. The principles below are worth understanding not just as “here’s how Stripe does it” but as “here’s why these decisions matter at scale.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BvXPGrUWITb69dD9W6jbdQ.png" /></figure><p><strong>RESTful and resource-oriented</strong> is the foundation. Every entity in the system is a resource with a stable URL, and actions on that resource follow predictable HTTP conventions. Creating a payment intent is a POST to /v1/payment_intents. Retrieving one is a GET to /v1/payment_intents/:id. Actions that don&#39;t map cleanly to CRUD get their own sub-resource endpoints like /v1/payment_intents/:id/confirm and /v1/payment_intents/:id/capture. The reason this matters is predictability -- once a developer learns how one resource works, they can make reasonable guesses about how every other resource works without having to read the docs from scratch.</p><p><strong>Consistent response format</strong> is one of those things that sounds boring until you’ve used an API that doesn’t do it. Every object in the system has the same baseline fields: id, object, created, and livemode. That livemode field is particularly important for a payments API because it makes it impossible to accidentally mix up test and production data -- every single API response tells you which mode you&#39;re operating in. Errors always come back as { error: { type, code, message, param } }, which means you write your error handling logic once and it works everywhere. List endpoints always return { object: &quot;list&quot;, data: [...], has_more, url } so you always know exactly how to paginate. And expandable fields via ?expand[]=customer let developers fetch related objects in a single API call instead of chaining requests -- a huge developer experience win that also reduces unnecessary round trips.</p><p><strong>Versioning</strong> is where a lot of APIs get this wrong and Stripe gets it very right. API versions are date-based (Stripe-Version: 2026-01-01) and the version used by an account is pinned at the time the account is created, so a new version release never silently breaks existing integrations. Old versions are supported indefinitely -- not for 6 months, not until the next major release, indefinitely. Breaking changes are only ever introduced in new versions, never backported. And every version bump comes with a migration guide. The philosophy here is that Stripe takes on the maintenance burden of old API versions so that merchants never have to do an emergency migration because Stripe decided to clean up technical debt. That&#39;s a significant operational commitment but it&#39;s a big part of why developers trust the platform.</p><p><strong>Idempotency</strong> is non-negotiable for a payments API and the implementation here is clean. Every POST request can include an Idempotency-Key header with a unique key, and if you make the same request again with the same key within 24 hours, you get back the same response without the operation being executed again. This solves a genuinely hard problem: what happens when you fire off a payment request, your network drops before you get the response, and you don&#39;t know if the charge went through? Without idempotency keys you have to build complex reconciliation logic to answer that question. With them, you just retry with the same key and you&#39;re guaranteed to get the same result either way. The 24-hour window is long enough to cover any reasonable retry scenario while keeping the key storage manageable.</p><p><strong>Cursor-based pagination</strong> is the right call here and offset-based pagination is the wrong one, and it’s worth explaining why. Offset pagination (page=3&amp;per_page=25) sounds intuitive but breaks under concurrent modifications -- if a new record gets inserted while you&#39;re paginating, you either skip a record or see a duplicate depending on where it was inserted relative to your current offset. Cursor-based pagination using starting_after and ending_before anchors to a specific record ID, so it stays consistent even if records are being created or modified while you&#39;re iterating through a list. For a payments system where new transactions are being created constantly, this isn&#39;t a theoretical edge case -- it&#39;s the normal operating condition.</p><h3><strong>Wrapping This Up ^^</strong></h3><p>I love distributed systems. And honestly, you can’t love distributed systems without eventually getting obsessed with <strong>transactions</strong>. Payments are where all the hard problems show up at once like consistency vs availability, latency vs correctness, retries vs duplication, external dependencies you don’t control, and the very real fact that every bug has a dollar sign attached to it.</p><p>What makes this space interesting isn’t just the scale, it’s the constraints. You don’t get to say “eventual consistency is fine” when money is involved. You don’t get to lose data. You don’t get to guess where funds went. Everything has to be <strong>exact, explainable, and auditable</strong>, even under failure, even under retries, even under insane traffic spikes. And somehow, all of that still has to fit inside a few hundred milliseconds because a user is waiting at checkout.</p><p>A lot of this design might feel like overkill at first glance. Multiple layers of idempotency, event sourcing, double-entry ledgers, Kafka everywhere, global replication, strict compliance boundaries, i mean it’s a lot. But every piece exists because something breaks without it. Payment systems aren’t complex because engineers like complexity. They’re complex because reality forces them to be.</p><p>And the funny part is, once you zoom out, the infrastructure is not the hardest part. It’s expensive, sure, but it’s predictable. The real challenge is building a system that behaves correctly <strong>all the time</strong>, across failures, across regions, across retries, across humans making mistakes. A system where you can answer, with confidence, “where did the money go?” every single time.</p><p>That’s what makes this fun.</p><p>If you’re into backend systems, this is pretty much the deep end of the pool. You get to work on distributed consensus, fault tolerance, real-time systems, security, compliance, and machine learning all in one place. And the feedback loop is brutal but honest: either it works, or it costs money.</p><p>Anyway, this was a long one. But if you’ve made it this far, you probably get why systems like this are so fascinating.</p><p>Because at the end of the day, you’re not just moving data.</p><p>You’re moving <strong>money</strong>, and the system has to be right. Every. Single. Time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5ce2d07c616" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Agent Sandboxes at Scale: A Distributed Systems Design for AI-Driven Development]]></title>
            <link>https://medium.com/@devanshusharma658/agent-sandboxes-at-scale-a-distributed-systems-design-for-ai-driven-development-3765f4a9460c?source=rss-9043612addc6------2</link>
            <guid isPermaLink="false">https://medium.com/p/3765f4a9460c</guid>
            <dc:creator><![CDATA[Devanshusharma]]></dc:creator>
            <pubDate>Wed, 29 Apr 2026 16:22:24 GMT</pubDate>
            <atom:updated>2026-04-29T16:22:24.185Z</atom:updated>
            <content:encoded><![CDATA[<p>Designing a sandbox for an AI coding agent is one of those problems that sounds simple at first.</p><p>“Just give the model a terminal and a codebase.”</p><p>And then reality politely throws a chair at you.</p><p>An AI agent like Devin can’t just operate directly on your machine. It needs its own isolated environment like a temporary workspace where it can clone repos, inspect files, run tests, install dependencies, and make changes without breaking anything outside its little universe.</p><p>So the core idea is pretty straightforward: every agent session gets its own fresh VM or container. Think of it as handing the agent a brand-new laptop every single time. It can do whatever it wants in there, and when the session ends, the whole thing disappears.</p><p>But isolation alone isn’t enough.</p><p>The real challenge is state. AI agents don’t work in a single shot, they explore, edit, test, backtrack, and sometimes get interrupted halfway through. That means the entire workspace needs to be serializable. At any moment, you should be able to snapshot the session, pause it, resume it later, or even inspect exactly what happened. Every file change, every command, every decision should be recoverable.</p><p>Then comes synchronization, which is where things get interesting.</p><p>The user might be editing the same repository locally while the agent is working. If both sides are making changes, consistency becomes critical. You need a sync protocol that keeps the agent’s workspace aligned with the user’s editor in near real-time, without stomping over someone’s work. Silent corruption is unacceptable, computers are many things, but subtle data loss should not be one of them.</p><p>And of course, security sits underneath everything.</p><p>The agent must be completely boxed in. No host access. No cross-tenant leakage. No unexpected network adventures. Even if the model generates something… creative, the blast radius should remain exactly zero.</p><p>In practice, this means layering defenses: container isolation, restricted syscalls, network controls, filesystem boundaries, and strict permission models. Security isn’t one lock , it’s a hallway full of locked doors.</p><p>The end result is a system that feels simple to the user:</p><ul><li>Spin up an agent</li><li>Point it at a repo</li><li>Let it work</li><li>Pause whenever you want</li><li>Resume later</li><li>Review every change</li></ul><p>Under the hood, though, it’s an orchestration problem involving distributed systems, virtualization, state management, synchronization, and security engineering all pretending to be a coding assistant.</p><p>Which, honestly, is half the fun.</p><p>Before you build an AI coding sandbox, you need to be crystal clear about what “good” actually looks like.</p><p>Because “it runs code” is a very low bar. A potato connected to SSH can almost manage that.</p><p>What we really want is an environment where an AI agent can behave like a competent software engineer which clone repos, understand massive codebases, make changes, run tests, and collaborate with humans without setting the building on fire.</p><h3>What the agent should be able to do ?</h3><p>First, it needs to work with basically any repository. Public, private, tiny side project, gigantic monorepo, it shouldn’t care. Hand it a Git URL, and off it goes.</p><p>Once inside, the agent should be able to navigate enormous codebases. We’re talking millions of lines of code, enough files to make ls question its life choices.</p><p>Then comes the actual work: editing files, running builds, executing tests, using command-line tools, installing dependencies kinda the full developer experience. If a human engineer can do it in a terminal, the agent should too.</p><p>Of course, changes need to be tracked properly. Every modification should be visible, reviewable, and eventually shippable as a pull request.</p><p>“Trust me, I changed something important” is not an acceptable Git workflow.</p><h3>Collaboration matters.</h3><p>The interesting part is that the agent isn’t working alone.</p><p>Users should be able to watch changes appear almost in real time. It’s a little magical the first time you see an AI editing your code live.</p><p>But collaboration goes both ways. If the user modifies files locally, those changes need to show up in the agent’s workspace quickly. Otherwise, you’re basically running two parallel universes and hoping Git can sort out the timeline later.</p><p>And yes, conflicts will happen. Humans and AI will absolutely step on each other’s toes. The system has to detect those collisions early and resolve them safely preferably before anyone starts questioning version control as a concept.</p><p><strong>Long-running work needs persistence</strong></p><p>Agent sessions shouldn’t be fragile.</p><p>You should be able to pause an agent, save its entire state, and resume later exactly where it left off. Maybe the user closes their laptop. Maybe the model crashes. Maybe the internet decides to take a personal day.</p><p>The workspace should survive all of it.</p><p>And since one AI agent is never enough, multiple agents should be able to work on the same repository simultaneously as long as they’re isolated onto separate branches. Distributed chaos, but organized.</p><p><strong>The stuff users never see</strong></p><p>Now for the less glamorous, absolutely critical requirements.</p><p>The sandbox must be completely isolated. No host access, no peeking into other customers’ environments, no creative escape attempts.</p><p>It also needs to be fast. Cloning and preparing even a large repository should feel snappy under a minute for something substantial.</p><p>File synchronization should be nearly instant. If the user saves a file, the agent should see it within a couple of seconds. Anything slower starts feeling broken.</p><p>At scale, this system needs to support thousands of concurrent sessions. AI agents don’t exactly believe in office hours.</p><p>And perhaps most importantly, nothing gets lost. If an agent crashes, the workspace should remain intact. Every command, every edit, every action should be fully auditable.</p><p>Because when an AI rewrites half your codebase, “we’re not sure what happened” is not the kind of sentence you want to hear.</p><p>Architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pR2YY2GGBaWrhHJQd9jNxA.png" /></figure><p>The system is basically split into three clean layers.</p><p><strong>User Plane</strong> is everything the developer touches. Your editor extension, web dashboard, or CLI. It’s the front door.</p><p><strong>Control Plane</strong> is the brains of the operation. It handles session creation, workspace management, authentication, syncing, and all the behind-the-scenes orchestration.</p><p>And finally, there’s the <strong>Sandbox Pool. T</strong>he actual isolated environments where the AI agent lives, thinks, builds, tests, and occasionally questions your code formatting choices.</p><p>Now, deep diving into the core components. This is where things get interesting.</p><h4>Session Orchestrator</h4><p>Think of the Session Orchestrator as mission control. Every AI coding session passes through it.</p><p>Its entire job is to manage the lifecycle of an agent from creation to completion, with pauses, resumes, and the occasional graceful failure in between.</p><p>A typical session moves through a simple state machine:</p><pre>Session Lifecycle:<br>  REQUESTED → PROVISIONING → ACTIVE → [PAUSED ↔ ACTIVE] → COMPLETED / FAILED</pre><p>The flow is pretty straightforward:</p><ul><li>A user requests a new session.</li><li>The orchestrator grabs a sandbox from the pool (or spins up a new one).</li><li>It coordinates with the Workspace Manager to clone and prepare the repository.</li><li>Once everything is ready, the session becomes active.</li></ul><p>If the user pauses the agent, the orchestrator checkpoints the entire workspace. Later, it can restore that exact state and continue as if nothing happened.</p><p>It also handles the boring but essential stuff like timeouts, CPU and memory limits, cleanup, and lifecycle event publishing.</p><p>Basically, if the agent were an astronaut, this would be Houston.</p><pre>struct SessionRecord {<br>    session_id: UUID,<br>    user_id: UUID,<br>    org_id: UUID,<br><br>    status: SessionStatus,<br><br>    sandbox_id: UUID,<br>    workspace_id: UUID,<br><br>    created_at: Timestamp,<br>    last_active_at: Timestamp,<br>    timeout_at: Timestamp,<br><br>    resource_limits: ResourceLimits,<br><br>    // Present only when paused<br>    checkpoint_ref: Option&lt;SnapshotRef&gt;,<br>}<br><br>enum SessionStatus {<br>    Requested,<br>    Provisioning,<br>    Active,<br>    Paused,<br>    Completed,<br>    Failed,<br>}</pre><p>This record is the single source of truth for every session. If a machine dies, the control plane can reconstruct everything from here.</p><p>And that’s exactly what you want because distributed systems have a wonderful habit of failing at the least convenient moment.</p><p>Now, let’s talk about the part where the AI actually lives.</p><h4>Sandbox Manager</h4><p>This is the compute layer (the engine room). Its job is simple: give every AI agent its own isolated machine, make sure it behaves, and destroy it when the party’s over.</p><p>Not all isolation is created equal.</p><p>At the top of the food chain are <strong>Firecracker microVMs, </strong>the same tech that powers Amazon Web Services Lambda. They boot ridiculously fast, offer near-VM security, and are basically perfect for AI agents running arbitrary code.</p><p>Then there’s <strong>gVisor</strong>, which is lighter and still pretty secure.</p><p>And finally, plain old containers. Fast? Yes. Secure enough for multi-tenant untrusted code? That’s a more philosophical question.</p><p>For production, Firecracker is the obvious choice. When you’re letting an AI execute random shell commands, “pretty secure” doesn’t quite inspire confidence.</p><p>The Sandbox Manager keeps a pool of pre-warmed microVMs ready to go. That way, starting an agent feels instant instead of “go grab coffee.”</p><p>When a session starts, it grabs a VM. When the session ends, the VM gets wiped and returned to the pool or thrown away entirely, depending on your level of paranoia.</p><p>Pause and resume are especially fun. Firecracker can snapshot the entire machine, memory, disk, everything. It’s basically save states, but for software engineering.</p><p>It also enforces the usual boundaries:</p><ul><li>CPU limits, so one agent doesn’t decide to mine cryptocurrency.</li><li>Memory limits, because Java exists.</li><li>Disk quotas, because node_modules exists.</li><li>Network restrictions, because the internet is… enthusiastic.</li></ul><p>A sandbox should only talk to places it absolutely needs like Git providers, package registries, maybe a few approved APIs. Everything else gets a polite but firm “absolutely not.”</p><pre>struct SandboxSpec {<br>    sandbox_id: UUID,<br><br>    vm_type: VmType,<br>    image_id: String,<br><br>    cpu_cores: u32,<br>    memory_mb: u32,<br>    disk_gb: u32,<br><br>    network_policy: NetworkPolicy,<br>    allowed_egress: Vec&lt;CIDRRule&gt;,<br><br>    ttl: Duration,<br>}<br><br>enum VmType {<br>    Micro,<br>    Standard,<br>    Large,<br>}</pre><p>This spec defines the sandbox completely like which image to boot, how much hardware it gets, what network access it has, and how long it can live.</p><p>In other words, it’s the rental agreement for your AI’s temporary apartment.</p><h4>Workspace Manager</h4><p>Once the sandbox is ready, the Workspace Manager takes over. This is the part that turns an empty machine into an actual development environment.</p><p>Its first job is cloning the repository securely, of course and pulling credentials from a secret vault instead of leaving SSH keys lying around like it’s 2014.</p><p>But cloning isn’t a one-size-fits-all problem.</p><p>A tiny repo? Just clone the whole thing. Easy.</p><p>A medium-sized repo? Use a shallow clone. Grab the latest state now, fetch history only when needed.</p><p>A giant monorepo? Absolutely not. That’s how you end up waiting until retirement. Instead, use partial clone and sparse checkout so the agent downloads only the parts it actually cares about.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jzY3ucjigB3yyve__C8L1g.png" /></figure><p>After cloning, the Workspace Manager creates a dedicated branch for the agent. No one wants an AI committing directly to mainthat&#39;s how documentaries get made.</p><p>Then it kicks off semantic indexing in the background. This lets the agent search and understand the codebase quickly, without blocking startup.</p><p>And throughout the session, it continuously tracks the workspace state(files, diffs, branches, checkpoints, everything).</p><pre>struct WorkspaceRecord {<br>    workspace_id: UUID,<br>    repo_url: String,<br>    repo_size_bytes: u64,<br>    default_branch: String,<br>    agent_branch: String,<br>    clone_strategy: CloneStrategy,<br>    semantic_index_status: IndexStatus,<br>    last_synced_commit: String,<br>}<br><br>enum CloneStrategy {<br>    Full,<br>    Shallow,<br>    PartialSparse,<br>}</pre><p>The Workspace Manager is basically the AI’s Git-savvy personal assistant quietly handling the messy details while the agent focuses on breaking your tests in new and exciting ways.</p><h4>Semantic Index Service</h4><p>This is what makes an AI agent feel smart instead of just… aggressively recursive.</p><p>Without a semantic index, the agent would basically be doing glorified grep across your codebase. Functional, but not exactly inspiring.</p><p>Instead, we build a three-layer code intelligence stack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D2rF4kl9oB6mqoSbdOBBAw.png" /></figure><p>Each layer solves a different problem.</p><ul><li><strong>Text Search</strong> is your classic ripgrep-style lookup. Lightning fast. Perfect for exact matches, file names, or finding where a string appears.</li><li><strong>AST Index</strong> understands code structure using tools like Tree-sitter. It knows what functions, classes, and imports actually are.</li><li><strong>Embedding Index</strong> handles fuzzy, semantic queries. Things like “where is auth handled?” or “find code related to retries.”</li></ul><p>Together, they give the agent superpowers.</p><p>Need an exact symbol? Use the AST.</p><p>Need a literal string? Text search.</p><p>Need to understand intent? Embeddings.</p><pre>enum QueryMode {<br>    Text,<br>    Symbol,<br>    Semantic,<br>}<br><br>struct SearchRequest {<br>    query: String,<br>    mode: QueryMode,<br>    limit: usize,<br>}</pre><p>The really important part is incremental indexing.</p><p>When a file changes, you absolutely do not want to rebuild the entire repository. That’s the kind of decision that ruins afternoons.</p><p>Instead, a file watcher sends only the changed paths to the indexer, which updates just those files. Fast, efficient, and much kinder to CPUs everywhere.</p><p>This is the layer that lets an AI instantly jump to definitions, trace references, and understand sprawling codebases without wandering around like it’s lost in IKEA.</p><h4>Sync Engine</h4><p>Keeps the agent’s workspace in sync with the user’s local repo. This is the most complex component. we’ll Discuss it later below.</p><h4>Event Bus</h4><p>The Event Bus is the nervous system of the whole platform.</p><p>Everything talks through it.</p><p>Instead of components calling each other directly and turning your architecture into spaghetti, they simply publish events. Anyone interested can subscribe and react.</p><p>Clean, scalable, and far less likely to cause existential dread.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w4QKaYtqkUIqiBG3m9M1wg.png" /></figure><p>Events are grouped into a few major categories:</p><ul><li><strong>Session lifecycle</strong> :- session started, paused, resumed, completed.</li><li><strong>Workspace events</strong> :- repo cloned, branch created, index ready.</li><li><strong>File changes</strong> :- files created, modified, deleted.</li><li><strong>Sync events</strong> :- user pushed changes, conflicts detected, conflicts resolved.</li><li><strong>Agent actions</strong> :- file reads, writes, command executions.</li><li><strong>Audit events :- </strong>secret access, outbound network requests, security-sensitive actions.</li></ul><pre>enum EventType {<br>    SessionCreated,<br>    WorkspaceCloneComplete,<br>    FileModified,<br>    SyncConflictDetected,<br>    AgentCommandExec,<br>    AuditNetworkEgress,<br>}</pre><p>This gives you loose coupling, real-time observability, and a complete audit trail. Basically, if anything interesting happens, it goes through the bus. And in distributed systems, “interesting” usually means “important” or “slightly alarming.&quot;</p><h4>Auth &amp; ACL Service</h4><p>This is the bouncer at the club. Nothing gets in without permission.</p><p>An AI agent should only be able to do exactly what it’s allowed to do, nothing more, nothing less. “Oops, I pushed to production” is not a fun postmortem.</p><p>Permissions are layered hierarchically:</p><pre>User → Organization → Repository → Branch → Path</pre><p>That means you can get incredibly precise. Maybe an agent can edit one branch, but only inside a specific directory. Very handy when trust is still in beta.</p><p>The permission set is pretty straightforward:</p><ul><li>Can it clone the repo?</li><li>Can it read files?</li><li>Can it modify them?</li><li>Can it push changes?</li><li>Can it open a pull request?</li><li>Can it run shell commands?</li><li>Can it access the network?</li><li>Can it use stored secrets?</li></ul><pre>enum Permission {<br>    RepoClone,<br>    RepoRead,<br>    RepoWrite,<br>    RepoPush,<br>    RepoPrCreate,<br>    SandboxShell,<br>    SandboxNetwork,<br>    SecretAccess,<br>}</pre><p>Every action goes through this service before execution.</p><p>The goal is simple: the agent should have the minimum privileges necessary to do its job. No more. Because giving an AI unlimited shell access is certainly a choice , just not usually a good one.</p><h4>Secret Vault</h4><p>Secrets are where things get serious.</p><p>Git tokens, API keys, environment variables these are the keys to the kingdom, and you definitely don’t want an AI casually dropping them into a log file.</p><p>So the rule is simple: secrets never touch disk inside the sandbox. Ever.</p><p>They’re injected at runtime, either as environment variables or through temporary in-memory files mounted via tmpfs. Once the session ends, they’re gone without a trace.</p><p>Every single access is logged. If an agent reads a secret, you’ll know exactly when, why, and which session did it.</p><p>Secrets are also carefully scoped:</p><ul><li>Organization-wide secrets</li><li>User-specific secrets</li><li>Repository-specific secrets</li><li>Session-only temporary credentials</li></ul><pre>enum SecretScope {<br>    Organization,<br>    User,<br>    Repository,<br>    Session,<br>}</pre><p>Under the hood, you’d typically back this with something battle-tested like HashiCorp Vault or Amazon Web Services Secrets Manager.</p><p>Because storing plaintext API keys in a database is a great way to become very familiar with incident response.</p><p>Now we’re getting to the heart of the system: <strong>the data model</strong>.</p><p>And honestly, this is where AI coding sandboxes stop being “just containers” and start becoming real infrastructure.</p><h4>Workspace State Model</h4><p>The workspace is the single most important abstraction in the entire platform.</p><p>If the sandbox is the machine, the workspace is the machine’s soul.</p><p>It captures absolutely everything required to reconstruct an agent’s world -code, Git state, filesystem, semantic indexes, environment, processes, the whole deal.</p><p>Why does this matter?</p><p>Because agents crash. Machines reboot. Sessions get paused. Users close laptops. Distributed systems enjoy drama.</p><p>A complete workspace state means you can restore the session exactly where it left off, without losing a single byte or thought.</p><h4>The Four Layers</h4><p>A workspace isn’t just “a folder on disk.” It’s really four distinct layers stacked together.</p><p><strong>1. Git Layer</strong></p><p>This is the source of truth for the code itself.</p><p>It tracks:</p><ul><li>Which commit the session started from</li><li>The agent’s current branch</li><li>The latest commit it has made</li><li>The upstream branch being monitored</li><li>Any uncommitted changes</li><li>The agent’s commit history</li><li>Temporary stashes</li></ul><p>This layer is what makes collaboration, rebasing, and conflict resolution possible.</p><p>Without it, you’re basically doing software engineering with amnesia.</p><p><strong>2. Filesystem Layer</strong></p><p>This tracks the actual runtime state of the repository.</p><p>Which files exist, their hashes, when they were modified, how much disk is being used, and what files the agent has recently opened.</p><p>The file hashes are especially important, they’re the backbone of efficient synchronization.</p><p>No hash change? No need to sync.</p><p>Computers love hashes almost as much as programmers love complaining about build systems.</p><p><strong>3. Semantic Layer</strong></p><p>This powers code intelligence.</p><p>The semantic index is technically rebuildable, but storing its metadata saves a ton of work.</p><p>It tells us:</p><ul><li>How many files have been indexed</li><li>Whether indexing is complete</li><li>Which version of the index is active</li><li>When it was last refreshed</li></ul><p>This lets the agent search massive codebases without feeling like it’s browsing source code through a straw.</p><p><strong>4. Environment Layer</strong></p><p>This captures the runtime environment.</p><p>Installed tools, active processes, bound ports, and non-secret environment variables all live here.</p><p>Secrets are intentionally excluded, they belong in the vault, not in persisted workspace state.</p><p>That distinction tends to be important during security audits.</p><p><strong>The Full Model</strong></p><pre>#[derive(Debug, Clone, Serialize, Deserialize)]<br>pub struct WorkspaceState {<br>    pub workspace_id: Uuid,<br>    pub session_id: Uuid,<br>    pub repo_url: String,<br>    pub clone_strategy: CloneStrategy,<br><br>    pub git_state: GitState,<br>    pub fs_state: FilesystemState,<br>    pub semantic_state: SemanticState,<br>    pub env_state: EnvironmentState,<br><br>    pub created_at: DateTime&lt;Utc&gt;,<br>    pub last_synced_at: DateTime&lt;Utc&gt;,<br>    pub checkpoint_ref: Option&lt;String&gt;,<br>}<br><br>#[derive(Debug, Clone, Serialize, Deserialize)]<br>pub enum CloneStrategy {<br>    Full,<br>    Shallow,<br>    Partial,<br>}</pre><p><strong>Git State</strong></p><pre>#[derive(Debug, Clone, Serialize, Deserialize)]<br>pub struct GitState {<br>    pub base_commit: String,<br>    pub current_branch: String,<br>    pub head_commit: String,<br><br>    pub upstream_branch: String,<br>    pub upstream_head: String,<br><br>    pub dirty_files: Vec&lt;DirtyFile&gt;,<br>    pub commit_log: Vec&lt;CommitRecord&gt;,<br>    pub stash_stack: Vec&lt;String&gt;,<br>}<br><br>#[derive(Debug, Clone, Serialize, Deserialize)]<br>pub struct DirtyFile {<br>    pub path: String,<br>    pub status: FileStatus,<br>    pub diff_hash: String,<br>}<br><br>#[derive(Debug, Clone, Serialize, Deserialize)]<br>pub enum FileStatus {<br>    Modified,<br>    Added,<br>    Deleted,<br>    Renamed,<br>}<br><br>#[derive(Debug, Clone, Serialize, Deserialize)]<br>pub struct CommitRecord {<br>    pub sha: String,<br>    pub message: String,<br>    pub timestamp: DateTime&lt;Utc&gt;,<br>    pub files_changed: Vec&lt;String&gt;,<br>}</pre><p><strong>Filesystem State</strong></p><pre>#[derive(Debug, Clone, Serialize, Deserialize)]<br>pub struct FilesystemState {<br>    pub root_path: PathBuf,<br>    pub disk_usage_bytes: u64,<br><br>    pub open_files: Vec&lt;PathBuf&gt;,<br>    pub file_hashes: HashMap&lt;PathBuf, String&gt;,<br>    pub last_modified: HashMap&lt;PathBuf, DateTime&lt;Utc&gt;&gt;,<br>}</pre><p><strong>Semantic State</strong></p><pre>#[derive(Debug, Clone, Serialize, Deserialize)]<br>pub struct SemanticState {<br>    pub index_version: u64,<br>    pub indexed_files: usize,<br>    pub total_files: usize,<br><br>    pub index_status: IndexStatus,<br>    pub last_indexed_at: DateTime&lt;Utc&gt;,<br>}<br><br>#[derive(Debug, Clone, Serialize, Deserialize)]<br>pub enum IndexStatus {<br>    Building,<br>    Ready,<br>    Stale,<br>}</pre><p><strong>Environment State</strong></p><pre>#[derive(Debug, Clone, Serialize, Deserialize)]<br>pub struct EnvironmentState {<br>    pub env_vars: HashMap&lt;String, String&gt;,<br>    pub installed_tools: Vec&lt;ToolVersion&gt;,<br>    pub running_processes: Vec&lt;ProcessInfo&gt;,<br>    pub ports_in_use: Vec&lt;u16&gt;,<br>}<br><br>#[derive(Debug, Clone, Serialize, Deserialize)]<br>pub struct ToolVersion {<br>    pub name: String,<br>    pub version: String,<br>}<br><br>#[derive(Debug, Clone, Serialize, Deserialize)]<br>pub struct ProcessInfo {<br>    pub pid: u32,<br>    pub command: String,<br>    pub started_at: DateTime&lt;Utc&gt;,<br>}</pre><p><strong>Why this design works?</strong></p><p>A complete workspace snapshot gives you three superpowers:</p><ul><li><strong>Pause and resume instantly</strong></li><li><strong>Recover from crashes without data loss</strong></li><li><strong>Audit exactly what happened</strong></li></ul><p>The key idea is simple: persist the minimal source of truth, rebuild everything else lazily.</p><p>Git and filesystem state are sacred.Semantic indexes can be regenerated.Processes can be restarted.Ports can be rebound.</p><p>That’s how you build a system that’s both durable and fast.</p><p>Because nothing says “enterprise-ready” quite like surviving chaos gracefully.</p><p>Now let’s talk about the part that separates a toy demo from a real collaborative system: synchronization.</p><p>Because the moment both a human and an AI are editing the same repo, things get… spicy.</p><p><strong>Sync State Model</strong></p><p>The Sync State is the traffic controller between the user and the agent.</p><p>Its entire job is to answer one question at all times:</p><blockquote><em>“Who changed what, and are we still okay?”</em></blockquote><blockquote>Without this, collaborative coding quickly devolves into a distributed reenactment of the Spider-Man pointing meme.</blockquote><blockquote><strong>Core Responsibilities</strong></blockquote><p>The sync layer continuously tracks both sides:</p><ul><li>What the user has changed locally</li><li>What the agent has changed inside its sandbox</li><li>Whether the two views still match</li><li>Whether conflicts need human intervention</li></ul><p>It also decides how synchronization happens.</p><pre>#[derive(Debug, Clone, Serialize, Deserialize)]<br>pub enum SyncMode {<br>    GitOnly,<br>    FileWatch,<br>    Hybrid,<br>}<br><br>#[derive(Debug, Clone, Serialize, Deserialize)]<br>pub enum SyncStatus {<br>    InSync,<br>    Syncing,<br>    Conflict,<br>    Stale,<br>}</pre><ul><li><strong>GitOnly</strong> works well for slower, commit-driven workflows.</li><li><strong>FileWatch</strong> streams file changes in near real-time.</li><li><strong>Hybrid</strong> combines both, which is usually the sweet spot.</li></ul><p>Because sometimes you want low latency <em>and</em> correctness. Greedy, but reasonable.</p><p><strong>Tracking Both Worlds</strong></p><p>The system maintains two independent cursors.</p><p>One for the user:</p><pre>#[derive(Debug, Clone, Serialize, Deserialize)]<br>pub struct UserCursor {<br>    pub branch: String,<br>    pub last_known_sha: String,<br>    pub pending_events: Vec&lt;SyncEvent&gt;,<br>}</pre><p>And one for the Agent:</p><pre>#[derive(Debug, Clone, Serialize, Deserialize)]<br>pub struct AgentCursor {<br>    pub branch: String,<br>    pub last_pushed_sha: String,<br>    pub unpushed_commits: u32,<br>}</pre><p>This lets the platform know exactly where each side stands at any moment. Think of it as Git, but with trust issues.</p><p><strong>Handling Conflicts</strong></p><p>Conflicts are inevitable. Humans edit files. AI edits files.<br>Eventually, both decide the same line needs their personal attention. That’s where conflict tracking comes in.</p><pre>#[derive(Debug, Clone, Serialize, Deserialize)]<br>pub struct MergeConflict {<br>    pub path: PathBuf,<br><br>    pub user_version: String,<br>    pub agent_version: String,<br>    pub base_version: String,<br><br>    pub status: ConflictStatus,<br>    pub resolution: Option&lt;ConflictResolution&gt;,<br>}<br><br>#[derive(Debug, Clone, Serialize, Deserialize)]<br>pub enum ConflictStatus {<br>    Detected,<br>    UserReviewing,<br>    Resolved,<br>}<br><br>#[derive(Debug, Clone, Serialize, Deserialize)]<br>pub enum ConflictResolution {<br>    KeepUser,<br>    KeepAgent,<br>    Merged,<br>}</pre><p>Three hashes are stored:</p><ul><li>the shared base version,</li><li>the user’s version,</li><li>the agent’s version.</li></ul><p>That’s enough information for a proper three-way merge.</p><p>And when automatic merging isn’t safe, the human gets the final vote. As it should be. We’re not <em>that</em> brave yet.</p><p><strong>The Full Model</strong></p><pre>#[derive(Debug, Clone, Serialize, Deserialize)]<br>pub struct SyncState {<br>    pub workspace_id: Uuid,<br><br>    pub sync_mode: SyncMode,<br>    pub sync_status: SyncStatus,<br><br>    pub user_cursor: UserCursor,<br>    pub agent_cursor: AgentCursor,<br><br>    pub conflicts: Vec&lt;MergeConflict&gt;,<br>}</pre><p><strong>Why this matters ?</strong></p><p>A good sync model guarantees three things:</p><ul><li>The user never loses work.</li><li>The agent never works on stale code.</li><li>Conflicts are explicit, not surprising.</li></ul><p>And honestly, “explicit, not surprising” is a pretty good design principle for most of software engineering.</p><p><strong>Sync Event Model</strong></p><p>If the Sync State is the current snapshot, Sync Events are the history book.</p><p>Every meaningful change whether from the user, the agent, or the system itself, gets recorded as an event.</p><p>This is what makes real-time collaboration possible. It’s also what lets you replay, audit, or debug exactly what happened when things inevitably become “interesting.” Think of it as Git commits, filesystem notifications, and an audit log all rolled into one.</p><p><strong>Event Sources</strong></p><p>An event can come from three places:</p><ul><li><strong>User :- </strong>edits made in the local IDE.</li><li><strong>Agent</strong> :- actions performed inside the sandbox.</li><li><strong>System</strong> :- automatic merges, conflict detection, branch syncs, and other background magic.</li></ul><pre>#[derive(Debug, Clone, Serialize, Deserialize)]<br>pub enum EventSource {<br>    User,<br>    Agent,<br>    System,<br>}</pre><p><strong>Event types</strong></p><p>The event type tells us what actually happened.</p><pre>#[derive(Debug, Clone, Serialize, Deserialize)]<br>pub enum SyncEventType {<br>    FileModified,<br>    FileCreated,<br>    FileDeleted,<br>    FileRenamed,<br><br>    BranchPushed,<br>    BranchForcePushed,<br>    BranchDeleted,<br><br>    CommitCreated,<br>    PrCreated,<br>    PrMerged,<br><br>    ConflictDetected,<br>    ConflictResolved,<br>}</pre><p>Basically, if something important changes, it becomes an event. Because “something changed somewhere” is not exactly helpful during incident response.</p><p><strong>Event Payload</strong></p><p>Different events carry different metadata. A file modification might include a diff. A branch push might include a commit SHA. A conflict event might include both changed paths and merge metadata.</p><pre>#[derive(Debug, Clone, Serialize, Deserialize)]<br>pub struct SyncPayload {<br>    pub paths: Vec&lt;PathBuf&gt;,<br>    pub commit_sha: Option&lt;String&gt;,<br>    pub diff: Option&lt;String&gt;,<br>    pub metadata: HashMap&lt;String, String&gt;,<br>}</pre><p>Flexible enough for everything, structured enough for machines. The classic engineering compromise.</p><p>Full Model</p><pre>#[derive(Debug, Clone, Serialize, Deserialize)]<br>pub struct SyncEvent {<br>    pub event_id: Uuid,<br>    pub timestamp: DateTime&lt;Utc&gt;,<br><br>    pub source: EventSource,<br>    pub event_type: SyncEventType,<br><br>    pub payload: SyncPayload,<br>}</pre><p><strong>Why this Design Matters ?</strong></p><p>With an append-only event stream, you unlock a lot:</p><ul><li>Real-time sync between user and agent</li><li>Full auditability</li><li>Easy replay after disconnects</li><li>Time-travel debugging</li><li>Recovery after crashes</li></ul><p>It’s event sourcing, minus the usual existential crisis. Every file save, every commit, every merge conflict is captured forever which is incredibly useful, right up until you realize just how often you typo variable names.</p><p><strong>Audit Log Entry</strong></p><p>If Sync Events tell you <em>what changed</em>, the Audit Log tells you <em>who did what</em>.</p><p>And when you’re running AI agents with shell access, that’s a distinction you’ll come to appreciate. Every sensitive action gets recorded like file writes, shell commands, network requests, secret access, branch pushes, all of it.</p><p>No exceptions. Computers are terrible at remembering what they did five minutes ago.</p><p>Why it exists ?</p><p>The audit log serves three critical purposes:</p><ul><li><strong>Security</strong> :- detect suspicious behavior.</li><li><strong>Compliance</strong> :- prove what happened.</li><li><strong>Debugging</strong> :- figure out why something exploded.</li></ul><p>Because “the AI did something weird” is not actionable.</p><p>Who performed the action ?</p><p>Even entry has an actor.</p><pre>#[derive(Debug, Clone, Serialize, Deserialize)]<br>pub enum AuditActor {<br>    Agent,<br>    User,<br>    System,<br>}</pre><p>Sometimes the AI runs a command. Sometimes the user approves a merge.Sometimes the system quietly rotates credentials at 3 AM.</p><p>Everyone gets logged.</p><p><strong>What Happened ?</strong></p><p>Actions are represented as structured strings:</p><ul><li>file.write</li><li>file.delete</li><li>shell.exec</li><li>git.push</li><li>secret.access</li><li>network.egress</li></ul><p>Machines love structured names. Humans tolerate them.</p><p><strong>Did it work ?</strong></p><p>Every action ends with an outcome. Success is good. Denied is usually also good. Error is… educational.</p><p><strong>Full model</strong></p><pre>#[derive(Debug, Clone, Serialize, Deserialize)]<br>pub struct AuditEntry {<br>    pub entry_id: Uuid,<br><br>    pub session_id: Uuid,<br>    pub workspace_id: Uuid,<br><br>    pub timestamp: DateTime&lt;Utc&gt;,<br><br>    pub actor: AuditActor,<br>    pub action: String,<br>    pub resource: String,<br><br>    pub details: HashMap&lt;String, String&gt;,<br>    pub outcome: AuditOutcome,<br>}</pre><p>Why this matters ?</p><p>Audit logs are your black box recorder. When something goes wrong, this is where you look first.</p><p>Who accessed a secret?<br>Why did the agent overwrite that file?<br>What command triggered the failure?</p><p>The answers are all here. Because trusting AI is great. Verifying AI is better.</p><p><strong>Work State machine</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7j-I1YHquyupxTF5jPLROQ.png" /></figure><p><strong>Sync Protocol: Keeping Agent and User in Sync</strong></p><p>This is where things get fun. Two developers: one human, one AI. Working on the same repo without accidentally starting a small Git war.</p><p>Everything here follows a few simple rules.</p><ul><li><strong>Git is the source of truth.</strong> If it isn’t in Git, it doesn’t exist.</li><li><strong>Separate branches by default.</strong> The user and agent each get their own lane.</li><li><strong>Optimistic concurrency.</strong> Assume things will work smoothly, because pessimism is expensive.</li><li><strong>User always wins.</strong> In any messy conflict, the human gets final say.</li><li><strong>Eventually consistent.</strong> We aim for “feels instant,” not “violates the laws of distributed systems.”</li></ul><p>The goal isn’t perfect real-time synchronization, that way lies madness.</p><p>The goal is simple: the agent should always be working on code that’s fresh enough, and the user should never feel like they’re fighting their own AI.</p><h3><strong>Sync Modes</strong></h3><p>Not every workflow needs the same level of synchronization. Sometimes you’re casually collaborating; sometimes you’re basically pair programming with an AI that never asks for coffee.</p><p>So the system supports three sync modes.</p><p><strong>Mode 1: Git-Only Sync</strong></p><p>The classic, reliable option.</p><p>The user pushes code. A webhook (or polling, if webhooks decide to take the day off) notifies the system. The agent fetches, rebases, and continues working.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HX6goXf5Wo7uSdFKaVmf2Q.png" /></figure><ul><li>Latency: around 5–30 seconds</li><li>Conflict handling: normal Git merge/rebase</li><li>Best for: async workflows</li></ul><p>This is perfect when you and the agent aren’t editing the same files at the same time.</p><p><strong>Mode 2: File-Watch Sync</strong></p><p>This one feels magical.</p><p>Your editor plugin watches for file saves, computes a diff, and streams it over WebSocket. The sandbox applies the patch almost instantly. When the agent edits something, the same process happens in reverse.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*trR--CVIKm5rshu3FnPMvw.png" /></figure><ul><li>Latency: typically 1–2 seconds</li><li>Conflict handling: hash-based dirty checking</li><li>Best for: live collaboration</li></ul><p>It’s basically Google Docs, except for code, and significantly less likely to autocorrect your variable names into English words.</p><p><strong>Mode 3: Hybrid Sync (Recommended)</strong></p><p>The best of both worlds. Use file streaming for rapid edits, and fall back to Git for bigger events like branch switches, force pushes, or pull request merges.</p><ul><li>Fast during active editing</li><li>Durable for major Git operations</li><li>Automatically degrades gracefully</li></ul><p>This is the default mode, because engineers enjoy having nice things.</p><p><strong>Sync Protocol Flow (Hybrid Mode)</strong></p><p>This is the heart of real-time collaboration. Every change whether from the user or the agent passes through the same sync pipeline.</p><p>Think of it as a traffic controller for code. Lots of incoming changes, zero tolerance for crashes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iJPLyhIEy6oGyLbFmKpZYQ.png" /></figure><p>Every change, regardless of whether it originates from the user’s editor, the agent’s sandbox, a Git webhook, or a polling service, first enters the Sync Engine through the Ingest layer, where it is normalized into a standard event format. That event is then passed to the Conflict Detector, which uses file hashes and workspace metadata to determine whether the change can be safely applied. If a user saves a file, the editor plugin computes a compact diff and sends it over WebSocket to the Sync Server. The server checks whether the agent is currently modifying that file and whether the sandbox’s version still matches the expected base hash. If everything is clean, the change takes the fast path: the patch is applied directly in the sandbox, file hashes are updated, the semantic index is refreshed, and the agent is notified instantly. If both the user and the agent have edited the same file, the system performs a three-way merge using the base, user, and agent versions. Non-overlapping changes are merged automatically, while overlapping edits trigger a conflict. In that case, the workspace enters the CONFLICTED state, the agent pauses execution, and the user receives an immediate notification for manual resolution. The reverse flow works identically when the agent writes to a file, a sandbox file watcher detects the modification, computes a diff, and streams it back through the Sync Server to the editor plugin, which applies the patch locally or surfaces it for review. This architecture combines the speed of WebSocket-based live collaboration with the safety and durability of Git, ensuring both sides remain synchronized with minimal latency and robust conflict handling.</p><h3>Conflict Detection &amp; Resolution</h3><p>Conflict detection uses optimistic concurrency backed by content hashes. Every file in the workspace carries a SHA-256 hash, and before either the user or the agent writes to it, the system first checks whether the file still matches the version it originally read. If the current hash differs from the expected one, someone else has modified the file in the meantime, and a conflict is detected immediately. This is fast, simple, and incredibly effective. Tt catches races before they can corrupt state. Once a conflict is detected, the system follows a clear resolution strategy. First, it attempts an automatic three-way merge using the base, user, and agent versions; if the edits are in different parts of the file, the merge succeeds silently. If the user explicitly saves over an agent-generated change, the user’s version always takes priority. If the agent notices that its copy has gone stale before writing, it politely backs off, reloads the latest file, and recomputes its changes, machines are great at swallowing their pride. Only when both sides edit the exact same region and an automatic merge isn’t possible does the system escalate to manual resolution. In that case, the workspace enters a conflicted state, the agent pauses, and the dashboard presents both versions so the user can decide how to proceed. This approach keeps collaboration smooth most of the time while ensuring the human remains firmly in control when things get messy.</p><p><strong>Conflict resolution flow:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MuwqOje42Y1PiESBg9qS0Q.png" /></figure><p>When a conflict happens, the system follows a simple rule: solve it automatically whenever possible, and bother the human only when absolutely necessary.</p><p>First, it checks whether the changes are in completely different parts of the file. If they are, a standard three-way merge using diff3 combines both versions seamlessly, and everyone carries on as if nothing happened. If the edits overlap, the next question is whether the user is actively working on that file right now. If they are, the user immediately wins. Their version is kept, the agent&#39;s pending changes are discarded, and the agent is told to re-read the latest file before trying again. This avoids the deeply unpleasant experience of an AI overwriting code you&#39;re typing. If the user isn&#39;t actively editing and the conflict still can&#39;t be resolved automatically, the system escalates to manual resolution. The agent pauses work on that file, the dashboard notifies the user, and both versions are presented side by side. Once the user chooses how to resolve it then keep theirs, keep the agent&#39;s, or merge manually; the selected version is applied, the workspace state is updated, and the agent resumes execution. Most conflicts disappear automatically, some require the agent to gracefully step aside, and only the truly ugly ones end up in front of the user. That&#39;s exactly how it should be.</p><p><strong>Till now did you think of some edge cases ?</strong></p><ul><li><strong>User force-pushes history:</strong> This is Git’s version of pulling the rug out from under someone. The agent detects that the upstream history has diverged, resets its tracking branch to the new upstream head, and then attempts to replay any local uncommitted changes or unpublished commits on top. If replay succeeds, work continues seamlessly; if not, the user gets notified.</li><li><strong>User deletes the agent’s branch:</strong> Slightly rude, but recoverable. The session immediately moves into a conflicted state. The system pauses the agent and asks the user whether they want to terminate the session entirely or attach the agent to a different branch.</li><li><strong>Both create the same new file:</strong> Great minds think alike. Unfortunately, filesystems disagree. Since there is no common base version, this is treated as a direct conflict and sent to manual resolution.</li><li><strong>Network partition or sync server outage:</strong> The agent doesn’t panic, it just keeps coding. All outgoing sync events are queued locally, and once connectivity returns, the queued operations are replayed and reconciled against the latest remote state.</li><li><strong>Large binary file changes:</strong> Binary diffs are about as useful as a chocolate teapot. The system skips patch-based syncing entirely, compares hashes instead, and always prefers the user’s version if both sides modified the file.</li><li><strong>User switches branches:</strong> The sync engine detects the branch change through Git webhooks or polling, updates the agent’s upstream tracking reference, and rebases or relocates the workspace accordingly. No mysterious “why is the AI editing the wrong branch?” moments.</li></ul><p><strong>Isolation Architecture.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EFa8XyJXonCTJHYfaJNw9g.png" /></figure><p>The isolation architecture is built around one simple idea: every agent gets its own tiny fortress. Instead of running directly on the host, each session launches inside a dedicated Firecracker microVM. That gives us true hardware-level isolation without the heavyweight overhead of a traditional virtual machine.</p><p>Inside the microVM runs a minimal, hardened Linux kernel with small attack surface, fast boot times, and very few unnecessary components lying around. The agent itself runs as an unprivileged user with no root access, which means even if the code inside goes rogue, it can’t start rearranging the furniture. A strict seccomp filter limits which syscalls the process can make, access to /dev is almost entirely blocked except for harmless essentials like /dev/null and /dev/urandom, and the base filesystem is mounted read-only. The only writable area is an isolated overlay, typically under /home, where the repository and temporary files live. Networking is equally locked down: traffic flows through a TAP device guarded by iptables, allowing connections only to approved destinations such as Git providers, package registries, and the sync server over WebSocket. Everything else is dropped on sight. Most importantly, every tenant gets a completely separate microVM, so one customer&#39;s workload cannot peek into, interfere with, or accidentally torch another&#39;s environment. Containers are great roommates; microVMs are great locked apartments.</p><p><strong>Network Security</strong></p><p>Network security follows a very strict “default deny” philosophy. A sandbox can only talk to a tiny, carefully curated list of destinations like GitHub and GitLab for cloning and pushing code, package registries like npm and PyPI for installing dependencies, the internal sync server for real-time collaboration, and a handful of trusted internal control-plane APIs. That’s it. Everything else on the internet is simply off-limits. In particular, access to the cloud metadata endpoint (169.254.169.254) is explicitly blocked (this is absolutely critical), because leaving that open is basically handing out your cloud credentials with a complimentary bow. Access to private internal network ranges like 10.0.0.0/8 is also denied unless a specific service has been whitelisted. On the inbound side, the policy is even simpler: absolutely nothing gets in. Sandboxes never accept incoming connections, which dramatically reduces the attack surface. In other words, the agent can fetch code, install packages, and talk to the services it needs but if it suddenly decides it wants to scan the internet or poke around your VPC, it&#39;s going nowhere.</p><p><strong>Now How we going to handle secrets ?</strong></p><p>Secret handling is designed with a very simple philosophy: secrets should exist only when absolutely necessary, and disappear immediately afterward. It starts when a user stores a credential (say a Git token or API key in the Vault) scoped appropriately at the organization, user, or repository level. When an agent session needs that secret, it requests access through the control plane. Before anything is handed over, the ACL service verifies that the session is actually allowed to use it. If approved, the secret is injected directly into the sandbox, either as an environment variable for command-line tools or as a temporary file mounted in memory (using tmpfs) for tools that expect configuration files like .netrc. Crucially, the secret never touches persistent disk, not even for a moment. It&#39;s kept entirely in memory, where it can vanish without leaving forensic breadcrumbs. Once the session ends, the temporary filesystem is destroyed, taking every secret along with it. And because trust is good but verification is better, every access who requested what, when, and why is permanently recorded in the audit trail. Secrets get in, do their job, and leave no trace behind. Exactly how secrets should behave.</p><p><strong>Doing the Audit Trailing</strong></p><pre>{<br>  &quot;timestamp&quot;: &quot;2026-04-27T08:30:00Z&quot;,<br>  &quot;session_id&quot;: &quot;sess-abc123&quot;,<br>  &quot;workspace_id&quot;: &quot;ws-xyz789&quot;,<br>  &quot;actor&quot;: &quot;AGENT&quot;,<br>  &quot;action&quot;: &quot;shell.exec&quot;,<br>  &quot;command&quot;: &quot;npm install express&quot;,<br>  &quot;working_dir&quot;: &quot;/home/agent/repos/myapp&quot;,<br>  &quot;exit_code&quot;: 0,<br>  &quot;duration_ms&quot;: 3200,<br>  &quot;network_egress&quot;: [<br>    &quot;registry.npmjs.org:443&quot;<br>  ],<br>  &quot;files_modified&quot;: [<br>    &quot;package.json&quot;,<br>    &quot;package-lock.json&quot;<br>  ],<br>  &quot;outcome&quot;: &quot;SUCCESS&quot;<br>}</pre><p>Every single action the agent performs is recorded in the audit trail. If it runs a shell command, reads a secret, modifies a file, or makes a network request, there’s a permanent log entry for it. In this example, the agent executed npm install express, which took 3.2 seconds, successfully exited with code 0, contacted the npm registry, and modified both package.json and package-lock.json. This level of observability is incredibly valuable not just for security and compliance, but also for debugging. If something unexpected happens, you can reconstruct exactly what the agent did, when it did it, and what side effects it caused. It&#39;s basically a black box recorder for your AI. Airplanes have one for crashes; AI agents have one for npm install.</p><h3><strong>Designing APIs.</strong></h3><ol><li><strong>Session API: </strong>The Session API is the main entry point into the entire system. If the control plane is the brain, this is how the outside world talks to it. Every agent lifecycle operation: creation, pause, resume, termination, and auditing flows through these endpoints.</li></ol><pre>POST   /api/v1/sessions<br>GET    /api/v1/sessions/:id<br>POST   /api/v1/sessions/:id/pause<br>POST   /api/v1/sessions/:id/resume<br>DELETE /api/v1/sessions/:id<br>GET    /api/v1/sessions/:id/audit</pre><p>Creating a session spins up a brand-new isolated sandbox, clones the repository, creates the agent branch, and starts indexing the codebase. It’s the “launch sequence” for an AI coding session. Fetching a session returns its current state whether it’s initializing, active, paused, conflicted, or completed along with useful metadata like branch names, sync status, and timestamps.</p><p>Pausing a session creates a checkpoint, capturing everything needed to restore the workspace later: Git state, filesystem state, environment, and runtime metadata. Resume does exactly what you’d hope.It restores that checkpoint and drops the agent right back where it left off, ideally without existential questions. Deleting a session gracefully shuts everything down, cleans up the sandbox, revokes temporary credentials, and optionally creates a final pull request before termination.</p><p>Finally, the audit endpoint gives you the complete forensic trail of everything the agent did during its lifetime. Every shell command, file modification, network request, and secret access is there. It’s observability, compliance, and debugging all rolled into one. In distributed systems, logs are truth; in AI systems, they’re also your alibi.</p><p>2. <strong>Workspace API: </strong>The Workspace API is how the control plane peeks inside a running sandbox. Think of it as the operating panel for the agent’s live coding environment. It lets you inspect files, query Git state, and search the codebase without directly SSH-ing into anything which is nice, because SSH tends to become everyone’s “temporary solution” for about five years.</p><pre>GET    /api/v1/workspaces/:id<br>GET    /api/v1/workspaces/:id/files<br>GET    /api/v1/workspaces/:id/files/:path<br>GET    /api/v1/workspaces/:id/git/status<br>GET    /api/v1/workspaces/:id/git/log<br>GET    /api/v1/workspaces/:id/git/diff<br>POST   /api/v1/workspaces/:id/search</pre><p>GET /workspaces/:id returns the full workspace state like Git metadata, filesystem stats, semantic indexing status, environment details, and synchronization state. It&#39;s the &quot;tell me everything&quot; endpoint.</p><p>GET /files provides a paginated listing of repository contents, which is essential for large monorepos where returning 200,000 files would be... impolite. GET /files/:path reads the contents of a specific file directly from the sandbox, typically used by dashboards, editors, or debugging tools.</p><p>The Git endpoints expose the repository’s live state. git/status shows modified, staged, and untracked files. git/logreturns recent commits, usually the agent&#39;s latest work. git/diff shows the exact uncommitted changes currently sitting in the workspace.</p><p>Finally, POST /search is where things get powerful. It supports both traditional text search and semantic search. Want to find &quot;AuthMiddleware&quot;? That&#39;s a text query. Want to find &quot;where JWT tokens are validated&quot;? That&#39;s semantic. The API routes the request to the appropriate indexing tier and returns results in milliseconds.</p><p>The Workspace API gives you complete visibility into the sandbox without ever breaking isolation. Exactly the kind of power you want, and exactly the kind you don’t want developers recreating with kubectl exec.</p><p>3. <strong>Sync API (WebSocket): </strong>This is the real-time backbone of the whole system. REST APIs are great for heavyweight operations like creating sessions or fetching workspace state, but live collaboration needs something faster. That’s where WebSockets come in. Once connected, both the user’s editor and the agent’s sandbox maintain a persistent bidirectional connection, allowing file changes, conflict notifications, and activity updates to flow instantly.</p><pre>use tokio_tungstenite::connect_async;<br><br>let (ws_stream, _) = connect_async(<br>    &quot;wss://api.example.com/api/v1/sync/ws-123&quot;<br>).await?;</pre><p>Whenever the user edits a file, the editor sends a structured event to the sync server.</p><pre>use serde::{Deserialize, Serialize};<br><br>#[derive(Debug, Serialize, Deserialize)]<br>struct FileChanged {<br>    #[serde(rename = &quot;type&quot;)]<br>    event_type: String,<br>    path: String,<br>    diff: String,<br>    hash: String,<br>}<br><br>let message = FileChanged {<br>    event_type: &quot;file_changed&quot;.into(),<br>    path: &quot;crates/agent-core/src/sync.rs&quot;.into(),<br>    diff: generated_patch,<br>    hash: current_hash,<br>};</pre><p>Branch switches and conflict resolutions are sent the same way.</p><pre>#[derive(Serialize)]<br>struct BranchSwitched {<br>    r#type: String,<br>    branch: String,<br>}</pre><p>On the other side, the server pushes updates back immediately. If the agent modifies a file, the editor receives the patch and applies it locally.</p><pre>#[derive(Deserialize)]<br>struct AgentFileChanged {<br>    r#type: String,<br>    path: String,<br>    diff: String,<br>    source: String,<br>}</pre><p>If both sides collide on the same file, the server emits a conflict event containing all competing versions.</p><pre>#[derive(Deserialize)]<br>struct ConflictDetected {<br>    r#type: String,<br>    path: String,<br>    versions: ConflictVersions,<br>}</pre><p>The server also streams status updates like in_sync, syncing, or conflicted, along with live agent activity such as &quot;reading&quot;, &quot;editing&quot;, or &quot;running tests&quot;. That lets the UI show exactly what the agent is doing in real time.</p><p>In practice, this is what makes the system feel alive. Save a file, and the agent sees it instantly. The agent edits code, and your editor updates immediately. A conflict happens, and you’re notified before things get ugly. It’s basically pair programming over WebSockets. Except your partner types at superhuman speed and never asks, “Wait, what does this function do again?”</p><p>4. <strong>Agent Tool API: </strong>Inside the sandbox, the agent never directly pokes at the filesystem, shells out randomly, or manually constructs Git commands. Instead, it interacts through a carefully designed Tool API. Think of it as the agent’s operating system : a safe, structured layer between the model and the actual machine.</p><ul><li>File Operations: Most of the agent’s life revolves around reading and modifying code.</li></ul><pre>let content = tools.read_file(<br>    &quot;crates/agent-core/src/sync.rs&quot;<br>).await?;<br><br>tools.write_file(<br>    &quot;crates/agent-core/src/sync.rs&quot;,<br>    updated_content,<br>).await?;</pre><p>Search is first-class too.</p><pre>let results = tools.search_files(<br>    &quot;ConflictDetector&quot;,<br>    SearchType::Ast,<br>).await?;</pre><p>Whether it’s text search, semantic search, or AST-based symbol lookup, the agent uses the same interface.</p><ul><li>Git Operations: Git is the source of truth, so the agent gets a safe wrapper around common Git workflows.</li></ul><pre>let status = tools.git_status().await?;<br>let diff = tools.git_diff(None).await?;<br><br>tools.git_commit(<br>    &quot;Implement optimistic conflict detection&quot;<br>).await?;</pre><p>Need a branch or a push?</p><pre>tools.git_create_branch(<br>    &quot;agent/conflict-resolution&quot;<br>).await?;<br><br>tools.git_push().await?;</pre><p>And yes, even pull requests can be created programmatically.</p><ul><li>Shell Operations: And yes, even pull requests can be created programmatically.</li></ul><p>Tests, builds, package installs, linters. Classic developer activities.</p><pre>let output = tools.exec(<br>    &quot;cargo test --workspace&quot;,<br>    Some(Duration::from_secs(300)),<br>).await?;</pre><p>Long-running tasks can execute in the background.</p><pre>let pid = tools.exec_background(<br>    &quot;cargo watch -x test&quot;<br>).await?;</pre><p>And if things get weird, you can always pull the plug.</p><pre>tools.kill_process(pid).await?;</pre><p>A time-honored debugging strategy.</p><ul><li>Semantic Index Operations: This is where the magic lives.</li></ul><p>Instead of grepping blindly, the agent can reason about code structure.</p><pre>let def = tools.find_definition(<br>    &quot;SyncEngine&quot;<br>).await?;<br><br>let refs = tools.find_references(<br>    &quot;WorkspaceState&quot;<br>).await?;</pre><p>Need the full call graph?</p><pre>let graph = tools.get_call_graph(<br>    &quot;process_sync_event&quot;<br>).await?;</pre><p>Now the agent understands not just where code lives, but how it behaves.</p><h3>Now lets discuss Scalability and performance</h3><p><strong>Capacity Planning : </strong>Building an agent platform is easy. Building one that survives real users at scale ? that’s the fun part. Every subsystem has a hard performance target, and the architecture is designed backward from those numbers.</p><ul><li><strong>Concurrent Sessions (10,000+) : </strong>The platform should comfortably handle over ten thousand active agent sessions simultaneously. That means the sandbox layer can’t rely on heavyweight VMs or containers. Firecracker microVMs make this possible, and the pool scales horizontally across many hosts. Add more machines, get more capacity “beautifully boring distributed systems engineering”.</li><li><strong>Clone Time (Under 60s): </strong>Nobody wants to wait three minutes for a repository to clone. Even large 1GB repos should be ready in under a minute. The trick is aggressive optimization: pre-warmed Git object caches, shallow clones by default, and CDN-backed mirrors for popular repositories.</li><li><strong>File Sync latency ( ≤ 2s) : </strong>Edits should propagate between user and agent almost immediately. WebSockets provide a direct, persistent connection, while sync servers are deployed close to users geographically. Nobody likes collaborative editing that feels like sending mail by a raven.</li><li><strong>Semantic Search ( ≤ 500ms): </strong>Code intelligence must feel instantaneous. The vector index lives directly inside each sandbox, avoiding network round trips entirely. Updates happen incrementally as files change. Search should finish before your brain finishes asking the question.</li><li><strong>Session resume ( ≤ 10 seconds)</strong>: Pausing and resuming agents is a superpower. Firecracker snapshots restore in roughly two seconds, then workspace state, Git metadata, and semantic indexes reload immediately after. From “paused yesterday” to “coding again” in under ten seconds.</li></ul><p>Latency compounds. A slow clone, slow sync, slow search, and slow resume quickly become unbearable. But when every individual operation is fast, the entire product feels magical.</p><p>Performance isn’t a feature, it’s the foundation.</p><p><strong>Scaling Architecture</strong></p><p>At global scale, a single region won’t cut it. Users expect low latency whether they’re in New York, Berlin, or Bangalore. So the platform is deployed across multiple regions. Typically US-East, Europe, and APAC with a global load balancer sitting in front.</p><p>The load balancer handles session affinity, which is a fancy way of saying: once your session lands in a region, it stays there. Your agent, workspace, and sandbox all live together, avoiding cross-region latency and the sort of distributed systems pain that causes engineers to stare silently at dashboards.</p><p>Each region runs a fully independent stack: its own control plane, its own sandbox pool, and its own local infrastructure. That means regions can scale, fail, or recover independently. If Europe gets overloaded, US-East doesn’t even flinch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZI6qyBAhs72iji3dgv7U-Q.png" /></figure><pre>let region = load_balancer.assign_region(<br>    user.location(),<br>    RoutingStrategy::LowestLatency,<br>).await?;<br><br>control_plane(region)<br>    .create_session(request)<br>    .await?;</pre><p>Inside each region, the control plane schedules workloads onto a large pool of sandbox hosts.</p><pre>let host = sandbox_pool<br>    .select_host(ResourceRequirements::default())<br>    .await?;<br><br>host.launch_microvm(session).await?;</pre><p>Adding capacity is beautifully simple: just add more hosts to the regional sandbox pool. No migrations, no drama, no sacrificial offerings to the distributed systems gods.</p><p>This architecture gives us three huge wins: low latency, fault isolation, and near-infinite horizontal scalability. Which is exactly what you want when thousands of AI agents are simultaneously trying to cargo build the internet.</p><h3><strong>Optimization Strategies</strong></h3><p>Raw hardware helps, but smart optimizations are what make the system feel ridiculously fast. Most of the magic happens behind the scenes, shaving seconds or sometimes minutes which is off common workflows.</p><ul><li><strong>Repo Caching: </strong>Cloning large repositories over and over is wasteful. If a thousand users open the same repo, downloading those Git objects a thousand times would be… let’s call it “suboptimal.”</li></ul><p>Instead, popular repositories are pre-cached as bare Git repos on shared storage like EBS or NFS. New clones then reference that cache as an alternate object store.</p><pre>let repo = git.clone(CloneOptions {<br>    url: repo_url,<br>    reference: Some(format!(<br>        &quot;/cache/repos/{}&quot;,<br>        repo_slug<br>    )),<br>    depth: Some(1),<br>}).await?;</pre><p>Git simply hard-links or reuses existing objects, turning multi-gigabyte clones into something that often completes in just a few seconds. Your bandwidth bill also sends a thank-you card.</p><ul><li><strong>Warm pool: </strong>Starting a VM from scratch is fast. Starting one that’s already running is even faster.</li></ul><p>Each region maintains a pool of pre-booted Firecracker VMs, already loaded with the most common toolchains like Rust, Node.js, Python, Go, Java, the usual suspects.</p><pre>let vm = warm_pool.acquire(<br>    Runtime::Rust<br>).await?;</pre><p>Roughly 20% of regional capacity stays idle and ready to go. That may sound wasteful, until you realize users interpret “instant” as “working correctly.”</p><p>The pool automatically expands and contracts based on historical demand patterns, because engineers sleep better when graphs look predictable.</p><ul><li><strong>Incremental Indexing: </strong>Rebuilding a semantic index for an entire monorepo after every file edit would be spectacularly inefficient. Instead, only changed files are re-indexed. Tree-sitter reparses most files in under a millisecond.</li></ul><pre>if event.kind.is_modify() {<br>    index.update_file(&amp;event.path).await?;<br>}</pre><p>Vector embeddings are also batched through a write-ahead log, which dramatically reduces expensive embedding writes.</p><p>Tiny changes should trigger tiny work.</p><ul><li>Connection Multiplexing: Power users often run multiple agents at once. Opening a separate WebSocket for every session would quickly get messy.</li></ul><p>So the sync layer maintains a single persistent WebSocket per user and multiplexes all session traffic over it.</p><pre>socket.send(Frame::Session {<br>    session_id,<br>    payload,<br>}).await?;</pre><p>Less connection overhead, fewer TLS handshakes, and happier browsers.</p><h4>Why It Matters ?</h4><p>Performance is rarely about one giant breakthrough. It’s usually dozens of tiny optimizations stacked together.</p><p>Cache the repo. Warm the VM. Re-index only what’s changed. Reuse the connection.</p><p>Individually, they’re nice. Together, they make the platform feel almost unfairly fast.</p><h3>Failure Modes &amp; Recovery</h3><p>Distributed systems have a simple rule: everything fails eventually. Machines crash, networks split, disks fill up, and sometimes software decides today is the day. The goal isn’t preventing every failure, it’s recovering so quickly that users barely notice.</p><p><strong>1. Sandbox VM Crash</strong></p><p>MicroVMs can crash due to kernel panics, host failures, or resource exhaustion. Detection is straightforward: if heartbeats stop for more than five seconds, the control plane assumes the VM is gone.</p><p>Recovery starts immediately. The system restores the latest checkpoint, replays any uncommitted filesystem changes from the write-ahead log, and reconnects the session. In most cases, the user just sees a brief pause rather than a catastrophic meltdown.</p><p><strong>2. Sync Server Crash</strong></p><p>Realtime collaboration depends on the sync layer, so it’s constantly health-checked. If a sync node fails, traffic automatically shifts to a standby server.</p><p>During failover, sessions temporarily degrade to Git-based synchronization. Editing continues normally; only live streaming pauses. Once the sync service is back, everything catches up automatically.</p><p>Graceful degradation beats total outage every single time.</p><p><strong>3. Git Host Unreachable</strong></p><p>GitHub has a rough day. It happens.</p><p>Clone, fetch, and push operations are retried using exponential backoff. Meanwhile, the sandbox keeps operating against the local repository. Commits queue locally until connectivity returns, at which point they’re pushed automatically.</p><p>The agent doesn’t stop working just because the internet is having feelings.</p><p><strong>4. Control Plane Crash</strong></p><p>The control plane is critical, but importantly, it is not in the data path.</p><p>If Kubernetes detects a failed control plane pod, it restarts it automatically. Existing sandboxes continue running independently the entire time. Active sessions aren’t interrupted because the actual work lives inside the sandbox, not the orchestrator.</p><p>This separation is one of the architecture’s biggest strengths.</p><p><strong>5. Network Partition (Sandbox ↔ Control Plane)</strong></p><p>Sometimes the sandbox loses connectivity to the control plane. Maybe a routing issue, maybe a temporary outage, maybe the networking gods demand tribute.</p><p>The sandbox enters autonomous mode. It keeps executing, logs every action locally, and queues all outbound events. Once connectivity returns, it reconciles state and flushes the backlog.</p><p>Temporary isolation should never mean permanent damage.</p><p><strong>6. Disk Full Inside Sandbox</strong></p><p>Running out of disk space is surprisingly common, especially when someone decides to npm install the known universe.</p><p>The sandbox continuously monitors disk usage. If space gets tight, the agent is warned immediately. It can clean caches, delete temporary files, or request a larger volume when supported.</p><p>Nobody likes debugging ENOSPC at 2 AM.</p><p><strong>7. Agent Infinite Loop</strong></p><p>LLMs occasionally discover recursion the hard way.</p><p>A watchdog monitors CPU usage, execution time, and command behavior. If the agent starts chewing through resources indefinitely, the runaway process is terminated.</p><p>The user is notified, and the agent can retry with a better strategy, preferably one involving fewer accidental while-true loops.</p><p><strong>8. Corrupt Git State</strong></p><p>Repositories can become corrupted through interrupted writes, disk issues, or extremely creative Git usage.</p><p>On startup, git fsck validates repository integrity. If corruption is detected, the system performs a clean re-clone from the remote and replays the agent&#39;s local commits using the audit log.</p><p>Git is resilient, but having a backup plan is even better.</p><p><strong>The Big Idea</strong></p><p>Reliability isn’t about avoiding failure. It’s about making failure boring.</p><p>A great system treats crashes, outages, and partitions as routine events because in production, they absolutely are.</p><h3>Recovery Protocol (VM crash)</h3><p>When a sandbox VM crashes, the recovery flow needs to be automatic, fast, and ideally a little boring. Users shouldn’t have to think about infrastructure, they should just see their session come back to life.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AEiKFdkyaTvCg1f72hXSPQ.png" /></figure><p><strong>1. Detect the failure immediately</strong><br>The orchestrator continuously monitors heartbeats from every running VM. If a heartbeat goes missing for more than a few seconds, the VM is declared dead. No lengthy investigations, no committee meetings.</p><p><strong>2. Grab a fresh VM from the warm pool</strong><br>Instead of booting from scratch, the system allocates a pre-warmed Firecracker VM. This saves precious seconds and makes recovery feel nearly instant.</p><p><strong>3. Restore the workspace</strong><br>If the session uses a persistent volume, it’s attached right away. Otherwise, the repository is re-cloned automatically. Either way, the new VM gets the exact same workspace.</p><p><strong>4. Recover state using the best available method</strong><br>Recovery follows a tiered strategy:</p><ul><li><strong>Firecracker Snapshot</strong> :- the gold standard. The entire VM state is restored in roughly two seconds.</li><li><strong>Git Checkpoint + WAL Replay:- </strong>restore the last committed state, then replay uncommitted edits from the write-ahead log.</li><li><strong>Full Re-clone:- </strong>the fallback option when everything else has gone spectacularly wrong.Start with the fastest path, fall back only when necessary.</li></ul><p><strong>5. Reconnect the sync engine</strong><br>The restored VM re-establishes its WebSocket connection and re-registers with the control plane.</p><p><strong>6. Replay queued events</strong><br>Any file changes, sync updates, or pending commands that accumulated during the outage are replayed in order.</p><p><strong>7. Resume the agent</strong><br>The agent restores its last known context, including conversation state, task progress, and any in-flight operations.</p><p><strong>8. Inform the user</strong><br>Finally, the system sends a simple notification:</p><ul><li><em>“Session recovered after interruption.”</em></li></ul><p>Which is much nicer than <em>“Your VM exploded, but we handled it.”</em></p><h3>Open Questions</h3><p>Even with a solid architecture, some design decisions don’t have universally correct answers. They’re tradeoffs, and the “best” choice often depends on your workload, users, and tolerance for operational pain.</p><ul><li><strong>Should agent sessions have persistent storage?</strong><br>Keeping caches like node_modules, build artifacts, or Cargo registries across sessions could make repeat sessions dramatically faster. On the other hand, stale caches are masters of psychological warfare, I mean they fail rarely, but always at the worst possible moment. Persistent storage also expands the security surface considerably.</li><li><strong>How should large file diffs be handled?</strong><br>Generated files, lockfiles, and massive minified bundles can overwhelm a real-time sync pipeline. One approach is to exclude them entirely, similar to .gitignore. Another is to sync only hashes and let the receiving side regenerate the file locally. Your sync engine will thank you.</li><li><strong>Should multiple agents share one workspace?</strong><br>Tempting, powerful, and deeply dangerous. Multiple agents introduce coordination problems immediately like file locks, task scheduling, merge conflicts, and the very real possibility of two AIs confidently breaking the same function in different ways. It’s doable, but complexity ramps up fast.</li><li><strong>How often should checkpoints be created?</strong><br>After every commit? Every few minutes? Every file write? Frequent checkpoints make recovery nearly instantaneous, but they also increase storage and I/O costs. Too infrequent, and recovery starts feeling like archaeology.</li></ul><p>These are the kinds of questions that separate a working system from a great one. And honestly, they’re also the fun part.</p><p>Building an AI coding agent platform at scale is one of those problems that touches nearly every layer of modern systems engineering like distributed systems, virtualization, networking, storage, security, developer tooling, and a healthy amount of chaos management. What looks simple on the surface “just let an AI edit my code” is actually requires an enormous amount of carefully designed infrastructure underneath. That’s what makes it so fascinating.</p><h3><strong>Thats a Wrap!!</strong></h3><p>If you’ve made it this far, thank you for reading. I genuinely hope this deep dive gave you a clearer picture of what it takes to build something like this from the ground up. These are the kinds of systems that will define the next generation of developer tools, and we’re only getting started. Until next time. Keep building, keep breaking things thoughtfully, and, as always, trust your logs more than your instincts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3765f4a9460c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I built Git for database schemas]]></title>
            <link>https://medium.com/@devanshusharma658/i-built-git-for-database-schemas-f259ce3d3cc5?source=rss-9043612addc6------2</link>
            <guid isPermaLink="false">https://medium.com/p/f259ce3d3cc5</guid>
            <dc:creator><![CDATA[Devanshusharma]]></dc:creator>
            <pubDate>Mon, 30 Mar 2026 08:03:12 GMT</pubDate>
            <atom:updated>2026-03-30T08:03:12.393Z</atom:updated>
            <content:encoded><![CDATA[<p>Every team I’ve worked on kinda had this unspoken rule: <em>Migrations are scary</em></p><p>You write a .sql file, drop it into some folder, run it… and hope nothing breaks. And honestly, if two engineers touch the same table in the same sprint, you already know what’s coming; someone’s Monday is getting ruined. Maybe both migrations work perfectly fine on their own, but together? Chaos. One person adds a column, the other drops the table, and nobody even realizes until CI blows up.</p><p>There’s no real branching, no proper diffing, no easy way to ask, “What actually changed between last week’s schema and now?” It’s just a bunch of numbered files, and you’re sitting there hoping the order is correct.</p><p>What always bugged me is that we already solved this problem for code. Like, decades ago. With Git, you get branches, commits, diffs, and merges the whole thing. Two people can work on the same codebase at the same time, and Git will literally point out where things conflict.</p><p>But your database schema? It’s just as important. Honestly, even more dangerous to mess up. It defines the shape of your data. And still, the tooling treats it like an afterthought.</p><p>So I thought, okay, this shouldn’t be this painful. And that’s when I built Diffo.</p><p>The idea was simple: give PostgreSQL schemas the same primitives Git gives code. Branches. Commits with actual structured snapshots. Proper three-way merges with conflict detection. And instead of manually writing migrations, just generate the DDL automatically from diffs.</p><p>I wrote the whole thing in Go, backed it with Postgres for production, used an in-memory store for tests, and exposed everything through a CLI (with an HTTP API on top).</p><p>In this post, I’ll walk through the design decisions behind it. But more importantly, I’ll dive into the two parts that actually made me sweat: parsing raw SQL DDL into a structured AST using PostgreSQL’s own parser, and building a three-way merge engine that can correctly handle concurrent schema changes across branches.</p><p>What “Git for schemas” means here ? When people say “Git for X,” they usually mean: <em>named lines of history, branch tips you can move, and a merge story that says how two histories become one.</em> This project is “Git-like” in that sense. It is not pretending Postgres is a packfile, or that schema.sql is a tarball. The interesting part is <em>what you store in each commit</em> and <em>what you merge when two branches diverge</em>.</p><h4>Commits hold a real schema, not just “whatever SQL someone typed”</h4><p>A commit here is way closer to a Git tree than some random patch file and that shift matters a lot.</p><p>The main thing I store isn’t just SQL. It’s a clean, canonical in-memory version of the schema: tables, columns (with normalized types), constraints, indexes, enums… basically everything that actually defines the structure. Stuff you can <em>compare properly</em>, not just as text.</p><p>The way I think about it is:<br> “If I applied this commit to an empty database, what would the schema <em>mean</em>?”</p><p>That’s the real payload.</p><p>Now, along with that, yeah I also keep the migration SQL (both up and down). The stuff you’d actually run. But that’s not the source of truth. That part is generated.</p><p>The flow is something like:<br> schema A → you run some DDL → schema B<br> and then I just do a diff(A, B), and that diff generates the migration SQL.</p><p>So every commit ends up storing two things:</p><ul><li>the final snapshot (schema B)</li><li>the migration that explains how you got there (in proper Postgres-friendly SQL)</li></ul><p>Now you might ask why store both? Why not just pick one?</p><p>This is where things get interesting.</p><p>Snapshots make comparisons <em>honest</em>. Two engineers can write completely different-looking SQL that ends up producing the same schema. Or worse, write very similar-looking SQL that actually means different things.</p><p>If you’re just comparing raw SQL… you’re screwed. You’re basically diffing text formatting, ordering, all that noise.</p><p>But once you’re comparing structured schema state, everything changes.</p><p>Now you can say things like:<br> “Oh, this column’s type changed on both branches.”</p><p>instead of:<br> “uhh… line 847 doesn’t match???” 😭</p><h4>Branches are just names for “where history lives.”</h4><p>Branches here are honestly pretty simple, they’re just names for <em>where history lives</em>.</p><p>If you’ve used Git, it’s the same mental model. A branch is just a movable label pointing to the latest commit. The real story is that the DAG underneath commits are linked together through parent IDs.</p><p>So you’re not branching “files” or migration scripts or anything like that. You’re branching the <em>evolution of the schema itself</em>.</p><p>That shift helped me a lot while building this. Instead of thinking “what files changed?”, I started thinking “how did the schema evolve on this branch?”</p><p>So when you ask something like:<br> “What’s on main?”</p><p>What you’re really asking is:<br> “What schema does the latest commit on main represent?”</p><p>And that answer is always super clear because it’s just the snapshot stored at the tip of that branch.</p><h4>Merge is three-way on the model, not a diff of two .sql dumps</h4><p>Merging is where things usually go off the rails… so I really didn’t want it to be “open two giant .sql files and pray your diff tool makes sense” 😅Instead, merges here are proper three-way merges but on the <em>schema model</em>, not on raw SQL text. So when you try to merge two branches, the system first finds a common ancestor (the merge base). Then it basically asks two questions:</p><ul><li>how did <em>our</em> branch change the schema compared to that base?</li><li>how did <em>their</em> branch change it compared to that base?</li></ul><p>And then it tries to apply both sets of changes on top of the same base snapshot. Pretty standard three-way merge idea, but the key difference is <em>what</em> we’re merging. We’re not merging lines in a file. We’re merging actual schema objects, tables, columns, indexes, enums, all that.</p><p>And that makes conflicts way more meaningful.</p><p>So instead of some vague “line 500 conflict”, you get things like:</p><ul><li>same column, but different types on each branch</li><li>same index name, but different definitions (or even on different tables)</li><li>One branch drops a table while the other is modifying it</li></ul><p>These are basically the schema-world versions of “both people edited the same line in foo.go”.</p><p>And when changes don’t overlap? It just merges cleanly, exactly like Git does when two people edit different files.</p><p>No drama, no guesswork.</p><h4>line-diffing giant SQL is the wrong abstraction</h4><p>There’s this uncomfortable truth I kept running into: diffing giant SQL files is just the wrong abstraction.</p><p>Like, if your whole versioning strategy is “store the entire schema as one big text file,” then your diffs are always noisy. Table order changes, whitespace tweaks, random comments, harmless refactors, everything shows up. And none of it actually tells you what <em>really</em> changed.</p><p>Worse, the diff has no idea what it’s looking at. It doesn’t know what a column is. Or an index. It just sees text. Some substring changed, cool but what does that <em>mean</em>?</p><p>And that’s a huge problem if you care about automation, safe migrations, clean merges, CI checks, all that stuff. For that, you don’t want text diffs. You want <em>semantics</em>.</p><p>You want to say things like:</p><ul><li>“A column was added.”</li><li>“This column type was widened vs narrowed.”</li><li>“This index was created, then dropped.”</li><li>“An enum got a new value.”</li></ul><p>That’s the level where things actually make sense.</p><p>So when I say “Git for schemas,” what I really mean is:</p><ul><li>version the <em>meaning</em> (the schema as structured data)</li><li>generate the <em>mechanism</em> (SQL migrations) from that</li><li>and merge based on meaning, not text</li></ul><p>That way, when conflicts happen, they’re things you can actually reason about not just a giant wall of red and green in a 10,000-line SQL dump that nobody wants to touch 😭</p><h3>Designing…</h3><p>If you follow a single user action through the system, the layers start to make sense. I’ll go top-down-ish: where data lives, how the schema is represented, how you talk to the thing (CLI vs HTTP), and how history stays safe when you walk it.</p><p>High level Design:</p><figure><img alt="High Level Design" src="https://cdn-images-1.medium.com/max/1024/1*1J_OyDp0MmCqYlNJpr411Q.png" /></figure><h4>Stores: branches, commits, workspaces and two backends</h4><p>So at the core, there’s a storage layer that holds all the important stuff:</p><ul><li>branches (basically name → head commit)</li><li>commits (parents, schema snapshot, migration SQL, metadata)</li><li>and workspaces, if you’re using isolated “checkout”-like environments</li></ul><p>Pretty standard model: Branch, Commit, Workspace.</p><p>The interesting bit was how to <em>run</em> this.</p><p>I didn’t want to tie it to just one backend. So I ended up with two:</p><ul><li>a real Postgres-backed store for actual usage (with proper tables, FKs, triggers all the stuff you’d expect in production)</li><li>and an in-memory version for tests and quick local hacking</li></ul><p>And honestly, this decision paid off way more than I expected.</p><p>Because both implementations share the same interface, I had to make sure they behave the same. Same ordering, same ancestor traversal, same constraints like “you can’t delete a commit that a branch still points to,” etc.</p><p>That kind of parity forces you to be precise. And it catches a bunch of weird edge cases early instead of discovering them later in some painful integration test (or worse, in prod). Schema layer: structs in Go, snapshots on disk</p><p>Choice: The canonical schema is a handful of Go types Schema, Table, Column, indexes, enums, not “the last SQL file someone edited.”</p><p>Why: Algorithms (diff, merge, validation) need typed data, not a character stream. You normalize types (e.g., one spelling for integer vs int4) so “same column, different alias” doesn’t look like a false change.</p><p>Choice: Each commit stores its full resulting schema as a gzipped JSON envelope with a format version (e.g. { &quot;v&quot;: 1, &quot;schema&quot;: { ... } }).</p><p>Why: Portability and introspection, you can dump it, inspect it, replay it, or migrate the format later without pretending opaque binary blobs are friendly. Version v is your escape hatch when you inevitably change JSON shape. Compression keeps rows from growing stupidly large when graphs get wide. The snapshot is what makes merge base resolution reproducible: “ancestor” isn’t vibes; it’s “we have the exact structured state at that commit.”</p><p>Choice: Migrations (up/down) are derived from structural diffs between snapshots, not hand-typed as the sole source of truth inside the merge machinery.</p><p>Why: Automation stays grounded in semantics; you’re less likely to merge text that <em>claims</em> a schema the snapshot doesn’t actually represent.</p><h4>CLI vs HTTP: one brain, two front doors</h4><p>This was one of those things I didn’t want to mess up early: CLI vs HTTP.</p><p>I’ve seen systems where the CLI does one thing, the API does something slightly different, and now you’re debugging the same bug in two places… no thanks.</p><p>So I kept it simple there’s one brain, two front doors.</p><p>All the core logic lives in plain Go packages. The CLI and the HTTP server both just call into the same underlying services, storage, commit graph, and merge engine, all of that. No separate codepaths, no “this works differently over here.”</p><p>The big reason was honestly selfish: I only want to debug merge bugs <em>once</em>. Not twice, not in two slightly different implementations.</p><p>And it also naturally splits the use cases. The CLI is great for humans scripting, experimenting, doing manual flows. The HTTP API is for services (CI pipelines, control planes, health checks, programmatic merges.)</p><p>I also kept the API intentionally small. Just the basics: manage branches, look at commits, trigger merges, and some liveness/readiness endpoints. That’s it.</p><p>Because realistically, that’s what you’d automate from CI or some control system. You don’t need a massive REST API from day one.</p><p>Anything more exploratory, like initializing a repo, recording commits from DDL files, diffing schemas, garbage collection, workspace flows, that stuff feels way more natural in the CLI anyway, where you can have richer output and local config.</p><p>And the nice side effect of all this is: no surprises.</p><p>If something merges successfully through the API, it’ll merge the same way in the CLI, given the same inputs.</p><p>No more “it worked on my machine but not in prod” kind of headaches 👍</p><p>Commit graph: ancestry for merge-base and GC with guardrails</p><p>Choice: Parent links form a DAG in the happy path; the code walks ancestors from branch heads to compute reachability (merge base, garbage collection, “what’s in history”).</p><p>Why merge-base: Three-way merge needs a common ancestor snapshot in structured form, not a guess from timestamps.<br>Why GC: Once commits are unreachable from any branch head (and not pinned elsewhere), you can reclaim them using the same instinct as Git’s object reachability, except rows in SQL.</p><p>Choice: Explicit cycle detection and depth caps on graph walks.</p><p>Why: Real systems see bad data like bad imports, manual DB edits, bugs. A self-loop or a long/degenerate chain shouldn’t cause an infinite loop, stack overflow, or allocate until OOM. Failing fast with a clear “cycle” vs “history too deep” error is friendlier than a hung server. Workspace (or similar) pins can also prevent GC from deleting commits still referenced outside branch heads, another “don’t surprise the operator” decision.</p><h4>Zooming out</h4><p>If you only remember one design thread: commits store structured truth (snapshot) + derived mechanism (migrations), branches name tips, merge combines changes to the model, and storage + graph utilities exist so that story is testable, deployable, and hard to accidentally blow up on messy data. The rest is implementation noise until it isn’t and then you’re glad you split layers cleanly.</p><h3>The parser: DDL → Schema (“hard” chapter)</h3><h4>Story arc: I need a real AST, not regex</h4><p>The first time you try to “understand” SQL without a parser, you reach for regex and wish you hadn’t. Comments fool you. Strings contain semicolons. CREATE TABLE and ALTER TABLE sprawl. You invent twelve special cases, then the thirteenth shows up in code review, and you quietly delete the project.</p><p>So the real question isn’t “how do I split on ;” It’s “who already solved Postgres SQL for Postgres?” Spoiler: Postgres did.</p><h4>Choice: pg_query (same parse surface Postgres uses)</h4><p>For parsing SQL, I didn’t try to get clever, I just used pg_query (libpg_query) through Go bindings. Basically, instead of trying to interpret raw SQL myself, I let PostgreSQL’s own parser do the job and give me a proper, structured parse tree back.</p><p>That choice matters more than it sounds. My whole system is built around PostgreSQL, so if I’m accepting DDL and claiming it “means” something in my schema model, the very first step should agree with what Postgres itself considers valid or invalid. I really didn’t want to end up building some half-baked SQL parser on the side.</p><p>It’s not about being fancy, it’s about staying aligned. The most annoying failure mode in tools like this is when your tool says, “yeah, this is fine,” but psql rejects it, or even worse, subtle differences where both accept it but interpret it differently. By leaning on Postgres’s own parser, I basically sidestep that entire class of problems.</p><h3>What is the parser layer actually responsible for ?</h3><p>Once you have proper parse trees, the problem shifts nicely. You’re not dealing with raw text anymore, you’re just interpreting structure.</p><p>So instead of token juggling, you’re walking through actual statements. And real-world .sql Files are messy and it’s rarely just one statement. You loop through them, handle each one, and keep building up your internal schema state as you go.</p><p>Then comes normalization. Humans love writing int, int4, integer interchangeably but your system shouldn’t treat those as different things. So I just pick a canonical form internally. That way, diffs don’t freak out just because someone used a different synonym.</p><p>As you process everything, you’re basically building this structured in-memory model that is tables keyed by name, columns inside them, indexes, enums, all treated as proper first-class objects. It ends up looking like a graph-ish structure, and that becomes the “snapshot” for a commit that the rest of the system works with.</p><p>And then there’s the messy part: not everything in a .sql file is actually schema-changing DDL. There’s always some noise (operational queries, random statements, sometimes valid SQL) that just isn’t relevant to your model. Here, you have to be intentional. Do you ignore it? Throw an error? Support it later? The key is: you decide that explicitly.</p><p>This is where having a real AST actually pays off. You can confidently say, “yeah, I understand this node” or “nope, I’m rejecting this.” Instead of the worst-case scenario like silently skipping stuff because your regex didn’t match and now half the file just… didn’t exist.</p><h3>Edge cases that sound small until they aren’t</h3><p>Some edge cases look tiny on paper… and then they quietly ruin your day if you ignore them.</p><p>Take empty input. Sounds harmless, right? But if an empty or whitespace-only migration starts throwing errors, suddenly every caller has to special-case “no SQL.” That’s annoying and unnecessary. It’s way cleaner to just define the contract as: empty string → empty schema. It matches intuition too (no declarations, no objects).</p><p>Then there’s garbage SQL. And yeah, it <em>will</em> happen. Someone pastes half a migration from Stack Overflow, semicolons are all over the place, and now things break. In those cases, you really want a clean parse error that points to what went wrong and not some random nil pointer panic three layers deep. Wrapping the original error properly (with %w) turns out to matter a lot here. It keeps the actual cause intact for debugging, while still letting you surface a simple “can’t parse SQL” message without pretending you built a better parser than Postgres itself.</p><p>And then… CGO. This one’s less about logic and more about reality. Since libpg_query is native code, you’re now in CGO territory. That affects builds, CI, and even how contributors run tests locally. You kind of end up with a split personality: most of the codebase is clean, fast, pure Go, and then there’s the parser layer that suddenly needs a proper C toolchain.</p><p>It’s a bit annoying, but it’s honest. The trick is to embrace it early, document it, automate it in CI, and stop pretending every machine will “just work.” If you add build tags (cgo vs non-cgo), you’re basically saying: “this set of tests uses the real parser, and this other set just makes sure the rest of the pipeline doesn’t rot.” Not perfect, but way better than fighting mysterious build failures later.</p><h3>Where it’s boring, where it’s fragile</h3><p>Some parts of this system are honestly just… boring. And that’s a good thing. Walking parse trees, mapping enum nodes into your own structs, pulling out index methods and column lists, it’s all pretty mechanical. You write it once, throw a bunch of small test cases at it, and keep going until it feels numb. No surprises, no drama.</p><p>But then there’s the fragile side and this is where things get real. SQL DDL has a <em>long</em> tail of edge cases. ALTER TABLE alone feels like its own little language: adding columns, dropping them, renaming stuff, constraints, weird clause ordering… and that’s just one command. Then you get into things like partial indexes, where now you’re also carrying around predicate SQL. At some point you realize you’re never going to cover every possible combination upfront. So you pick the subset you care about, support it well, and fail loudly (and intentionally) on the rest. Because the worst thing you can do is <em>accidentally</em> accept something you don’t fully understand.</p><p>This is exactly why the “quick regex approach” dies sooner or later. You don’t discover missing cases in a design doc, you discover them when someone runs a migration at 5 pm on a Friday, and everything breaks in a way you didn’t even think was possible.</p><p>One thing that really saved me from lying to myself was round-trip testing. The scary bugs here aren’t loud failures, they’re silent drift. You parse something, serialize it, load it back… and it’s <em>almost</em> the same. Maybe a default value disappeared, or a type got slightly normalized differently, or map ordering changed something subtle. So I started being strict about it: parse DDL → snapshot → load → diff against original. That diff has to be empty. Then do it again, a snapshot of a snapshot. If that second diff isn’t empty, congrats, you’ve got a non-idempotent system that will eventually mess up someone’s merge.</p><p>It’s not glamorous testing. It feels overly paranoid… until the day it catches something like “we accidentally changed how NULL defaults serialize,” and suddenly you’re very glad it exists.</p><p>At the end of the day, parsing isn’t the flashy part of “Git for schemas.” Merges and graphs look cooler in demos. But if your AST layer is shaky or worse, everything built on top of it starts falling apart. Diffs become unreliable, migrations lie, and merges resolve the wrong state.</p><p>So yeah… real AST, not regex. That’s the foundation. Everything interesting comes after that.</p><h3>Diff + migration generation (bridge between worlds)</h3><p>There’s this awkward gap most schema tools never really solve. You can look at two states like “yesterday’s database” vs “today’s database” but production doesn’t care about that comparison in the abstract. It wants actual SQL it can run. Ideally, something safe, repeatable, and definitely not something that accidentally nukes data because the tool tried to be “smart.”</p><p>So I ended up thinking of this layer as a bridge: you take a structural diff in, and you generate migration SQL out. Sounds simple, but they’re actually two different problems that just happen to be connected.</p><p>When I say “diff,” I’m not talking about diff -u old.sql new.sql and scrolling through thousands of lines because someone reordered CREATE TABLE statements. That kind of diff is about text, not meaning.</p><p>What I’m doing instead is diffing the schema as <em>data</em>. Tables either exist or they don’t. Columns get added, dropped, or modified in specific way: type changes, nullability, defaults, whatever level of detail you care about. Indexes and enums are treated as proper objects too, not just random lines buried somewhere in a file.</p><p>That’s the whole mindset shift. You’re not producing a line-by-line patch, you’re building something like a SchemaDiff“These tables were added,” “these columns changed,” “these indexes were removed,” and so on.</p><p>And honestly, that’s what makes everything else possible. Line diffs are great when you’re reviewing text, but they’re kind of useless for understanding meaning. Two SQL files can look wildly different and still describe the same schema — or look almost identical while hiding a dangerous change.</p><p>Once you’re working with a structural diff, you can say things that actually matter. Like: “this column’s type changed,” or “this happened on both sides, so it’s a conflict.” And on top of that, you get nice practical benefits — you can group operations by table, sort them, and generate SQL in a sane order without hoping your diff chunks magically respect foreign key dependencies.</p><p>It’s not flashy, but this is the piece that actually connects “understanding the schema” to “doing something useful with it.”</p><h4>Migration generation: from “what changed” to “what to run”</h4><p>Once you have a SchemaDiff, turning that into migration SQL <em>sounds</em> like it should be trivial, like just a fancy pretty-printer. And honestly, on the happy path… it kinda is.</p><p>You just walk through the diff and start emitting statements. Create the enums or types that didn’t exist before, create new tables (being careful about ordering when foreign keys are involved), then alter existing tables, add columns, drop them, tweak types or nullability where you support it. Same for indexes: create the new ones, drop the old ones. And if a table is gone in the new state, you drop it.</p><p>That part is mostly straightforward once your diff is solid.</p><p>For the “down” migration, you basically play the whole thing in reverse. But this is where you have to be honest with yourself, reverse DDL isn’t always perfectly defined in the real world. Like, if you drop a column, what exactly is the “correct” way to bring it back? What about data? Defaults? There’s no single right answer.</p><p>So instead of pretending there is, you pick clear conventions, document them, and stay consistent. That way, users know what to expect, even if it’s not magically reversible in every edge case.</p><h4>Idempotency: “IF NOT EXISTS” is a personality trait</h4><p>Idempotency sounds like a boring word… but in migrations, it’s basically a personality trait.</p><p>Because in the real world, nothing is clean. Migrations get retried, half-applied, re-run by someone manually at 2 am, or executed in pipelines that are <em>definitely</em> not as atomic as the docs claim. So wherever Postgres gives you safety rails like IF NOT EXISTS or IF EXISTS You use them. Not blindly, but wherever they actually make sense.</p><p>The idea is simple: prefer changes that fail <em>locally and safely</em> instead of blowing up the entire deployment just because something partially ran earlier. Migrations aren’t just “what you want to do,” they’re “what you want to do, given whatever already happened before.” That’s why idempotency isn’t laziness, it’s just respecting reality.</p><p>But yeah, it has limits. Some changes just aren’t safe to auto-handle. Like changing column types when there’s already data, or shrinking a string column and that’s not something you can blindly wrap in a guard and hope for the best.</p><p>At that point, you’ve got two choices: either try to be clever (add casts, make assumptions, maybe break things), or just stop and let a human write the migration properly.</p><p>I went with the second option. It’s less “magical,” but it doesn’t come back to bite you later.</p><h4>Explicit failures: Readers respect honesty</h4><p>Here’s the part nobody likes to put on slides: not every diff can be turned into a safe, automatic migration. And pretending otherwise is how things break in really expensive ways.</p><p>Some cases are just… messy. Like foreign key cycles, if two tables depend on each other, there’s no clean linear order to create them unless you start doing multi-step tricks or deferring constraints. Or enums (Postgres is super picky there). Adding a new value at the end? Fine. But reordering, deleting, and renaming? That’s where you stop and say, “Yeah, I’m not touching this automatically.” Same with partial indexes where the WHERE clause gets weird, or defaults that aren’t simple, safe literals. At some point, the tool has to admit: this isn’t something I can guarantee.</p><p>And that’s a design choice I leaned into. If I’m not confident it’s correct, I’d rather fail loudly with a clear reason than generate SQL that <em>looks</em> fine but might wreck production. Engineers are actually okay with that. A tool that says “I can’t do this, here’s why” earns trust. A tool that guesses and gets it wrong? You stop using it real quick.</p><p>This is also where having a structural diff helps again. Instead of pointing to some random line in a SQL dump, you can say something meaningful like “enum X change isn’t supported” or “index Y has an invalid predicate.” That’s the kind of error you can actually act on.</p><p>The mental model that kept me grounded through all this was pretty simple: the schema snapshot is the <em>truth and </em>that’s what you compare, merge and reason about. The migration SQL is just the <em>mechanism</em> to move a real database along that history.</p><p>Diff is the bridge between those two. If you only had migrations, merging would be chaos. If you only had snapshots, you couldn’t actually apply anything. You need both. That bridge isn’t extra complexity and it’s what makes the whole “Git for schemas” idea actually work outside of a demo.</p><h3>The merge engine: three-way, conflicts, finalize (the second hard chapter)</h3><p>This is the part where the whole “Git for schemas” idea either clicks… or completely falls apart.</p><p>Branching is easy to explain. Merging is where things get real. In text-based systems, you get those ugly &lt;&lt;&lt;&lt;&lt;&lt;&lt; markers, and you manually fix stuff. Here, the conflicts are way more semantic and column type changes, one branch dropping a table while the other edits it, index names clashing in weird ways. And there’s always that low-key fear: what if I merged against the wrong base and nobody notices until prod?</p><p>The mental model I stuck to is intentionally simple (almost boring, but in a good way).</p><p>You start with a base schema (the common ancestor). Then you compute two diffs:<br>What <em>our</em> branch did relative to the base, and what <em>their</em> branch did relative to the base.</p><p>So instead of two final snapshots fighting each other, everything is expressed as “changes from the same starting point.”</p><p>From there, you take a copy of the base and try to apply both sets of changes. If both sides touched the same thing in incompatible ways, that’s a conflict, and you stop. If they touched different things, you just combine them and move on. That’s the happy path.</p><p>The key idea is: you’re never comparing “ours vs theirs” in isolation. You’re always asking, “What did each side try to do since we diverged?”</p><p>That’s exactly what makes Git merges feel sane, too. And once you have that, things like fast-forwards or “nothing actually changed” merges become super easy to reason about.</p><h4>The decision table (where the merge engine earns its paycheck)</h4><p>This is where the merge engine actually earns its keep. It’s not guessing, it’s basically running through a bunch of decision tables.</p><p>For tables, you’re looking at all the usual combinations: added, removed, modified. The tricky ones show up fast. Like if one branch drops a table and the other is modifying it and that’s not something you can “merge.” That’s a real conflict. Same if both branches add a table with the same name but different definitions. At that point, you stop and make the human decide.</p><p>Columns get even more interesting. Inside a table, both sides might be adding, removing, or modifying columns. If the changes don’t overlap, great!! just combine them. But if both sides touch the same column in incompatible ways (different types, nullability changes, conflicting defaults, weird add/drop combos), you flag it as a conflict. And importantly, you don’t just say “conflict”, you say <em>what kind</em> of conflict, so it’s actually debuggable.</p><p>Indexes are where I chose to be pretty strict. They’re keyed by name, so if both sides add the same index with the same definition, cool. If the definitions differ, that’s a conflict. If one side drops an index and the other adds something with the same name, also a conflict. It might feel harsh, but the alternative is silently picking one and then you end up with an index that doesn’t match what either branch intended.</p><p>Enums get their own little reconciliation logic too. If both sides just add new values (and they don’t clash), that’s the nice, easy case. But if the definitions collide in any meaningful way, you stop there as well.</p><p>And when everything <em>does</em> merge cleanly, you don’t just return “success.” You return structured results like “applied disjoint changes” or “no schema changes relative to base.” That stuff seems small, but it makes logs, UIs, and tests way cleaner because you’re not parsing vague messages, you’re dealing with actual states.</p><h4>Conflict types (the taxonomy readers secretly want)</h4><p>One thing that helped a lot was treating conflicts as <em>types</em>, not just a generic “something went wrong.”</p><p>Because when you just throw a blob of text at someone, “merge conflict,” it’s not that useful. But if you can say what kind of conflict it is, things get way clearer.</p><p>So in practice, conflicts end up looking like categories. For columns, you might have type clashes, nullability mismatches, default changes, or those annoying add/drop situations where one branch deletes a column and the other brings it back in some form. For tables, it’s stuff like both sides adding the same table differently, or one side dropping it while the other edits it, or even primary key and constraint conflicts.</p><p>Indexes are a fun one, mostly around name clashes. Same name but different definitions, or one side removing it while the other adds it back, or even binding the same index name to different tables. All of those are subtle but real problems.</p><p>Enums get their own category too if both sides disagree on what an enum looks like, that’s a proper enum_def_clash, not just a vague failure.</p><p>And this classification isn’t just for neatness, it actually matters for the product. You’re not just telling the user “hey, fix this.” You’re telling them <em>what broke</em>. That opens the door for better UX, clearer debugging, and even smarter automation later on.</p><h4>Finalize: merge pauses, human (or tool) picks a side</h4><p>When a merge is clean, life is easy, you just get a fully merged schema and move on.</p><p>But when there are conflicts, I made a very intentional choice: don’t pretend. The strict path doesn’t give you a half-baked merged result. Instead, it returns <em>no schema</em> and a clear list of conflicts, with paths like table.users, table.users.column.email, index.idx_foo, etc.</p><p>That’s on purpose. The worst thing you can do here is act like you’ve produced a “final” schema while there’s still ambiguity hiding inside.</p><p>There is a middle ground, though a partial merge. In that mode, the system applies everything that <em>doesn’t</em> conflict, and for the conflicting parts, it basically leaves them in their base state. Nothing magical, nothing guessed just “we’ll deal with this later.”</p><p>And that’s where Finalize comes in.</p><p>For every conflict, someone (a human or another tool) has to make a call: keep ours, keep theirs, or provide a manual resolution. And if it’s manual, it has to match the structure, like if you’re resolving a column conflict, you need to give a proper column definition, not some random blob.</p><p>If anything’s missing or inconsistent, Finalize just errors out. No compromises, no “close enough.” It refuses to write a fantasy schema.</p><p>This maps really nicely to how Git works in your head: you hit conflicts, you resolve them, then you commit.</p><p>The merge engine’s job is to stay boring and explicit. The actual decisions? Those are yours, and they’re recorded clearly, per conflict.</p><h4>Emotional beat: index name collision on different tables</h4><p>This was one of those cases where I <em>could’ve</em> tried to be clever… and that would’ve been a mistake.</p><p>Imagine both branches add an index called idx_same. On our side, it’s on users. On theirs, it’s on posts. From a pure SQL perspective, that might actually be fine. Different tables, different namespaces, no problem.</p><p>But in the schema model, indexes are keyed by name. So now both branches are basically saying, “This name belongs to <em>my</em> definition.” If I just merged that silently, I’d have to invent some rule like “last writer wins” or auto-renaming one of them without the user ever agreeing to it.</p><p>That’s the kind of “smart” behavior that comes back to bite you.</p><p>So instead, Diffo just stops and says: IndexNameClash. One conflict clearly surfacedindex.idx_same, with both versions preserved so you can actually see what happened and decide properly.</p><p>It’s way better to return a clear error than to ship a merge that technically works but doesn’t reflect what either branch intended.</p><p>There’s a similar vibe with something called criss-cross history. If you’ve used Git long enough, you’ve probably seen it sometimes there isn’t a clean, unique common ancestor between two branches.</p><p>In those cases, the merge engine doesn’t try to guess. It just errors out and says, “This isn’t a safe automatic merge.” You either fix the history or explicitly choose a base to merge from.</p><p>Again, same philosophy: fail loudly instead of quietly doing something arbitrary and pretending it’s correct.Optional palate cleansers: fast-forward and “no-op.”</p><p>These are the moments readers smile because it works like Git.</p><p>Fast-forward: If ours didn’t move from base and theirs has all the edits, a three-way merge should behave like “just take theirs”: the merged schema equals their tip. No conflicts, no drama, tests even describe it that way.</p><p>No-op: If base, ours, and theirs are all the same snapshot of reality, you get a clean merge where the substantive outcome is “nothing changed relative to base”, the kind of result that’s easy to skip in migration generators (identity schema → no DDL churn) and satisfying to assert in tests.</p><p>That’s the chapter arc: diff from base twice → reconcile with explicit tables → typed conflicts → pause and resolve → Finalize. The merge engine isn’t trying to be clever; it’s trying to be legible because in schema land, legibility is the safety rail.</p><h3>Ops and safety: GC, workspaces, graph limits</h3><p>This is the part you don’t think about until production reminds you of retention, isolation, and “please don’t delete something I still need.” The happy-path diff story is nice, but real systems need guardrails. You don’t want a tool that casually wipes out history just because it <em>looks</em> unused, or gets stuck walking some weird graph forever.</p><p>Garbage collection is pretty Git-like in spirit: keep everything that’s still reachable. So you start from all the branch heads that still exist, and also from any active workspaces. That second one sounds small, but it’s huge because a workspace might still be pointing to a commit even if the branch that created it is gone. If you ignore that, you risk deleting the very state someone’s actively working on. So workspaces basically act like “pins” that protect commits from being collected. And there’s a dry-run mode too, which I leaned on a lot, it shows you exactly what <em>would</em> get deleted without actually doing it, so you can sanity-check before pulling the trigger.</p><p>There are a few extra knobs to keep things sane at scale. You can avoid deleting very recent commits (so you don’t nuke something someone just created), clean up idle workspaces that nobody’s touched in a while, and paginate through commits during GC instead of trying to load everything into memory at once. None of this is flashy, but it’s the kind of stuff that makes the system feel safe instead of scary when it’s actually running in production.</p><h4>Workspaces: Isolated schema and connection semantics (high level)</h4><p>Workspaces are basically the answer to: “give me a safe place to materialize this branch’s schema without messing with anything else.” You pick a branch (or a commit), and you get an isolated environment where that schema actually exists, no stepping on shared dev or prod.</p><p>How that isolation works is intentionally flexible. In the simplest case, it’s just schema-level isolation inside the same database. Create a new schema with a generated name, point your connection there, and you’re good. In stricter setups, it could be a whole separate database or container. Same idea, just a bigger blast radius. The key is: the system doesn’t care how isolation is implemented, as long as it can provision it and tear it down cleanly.</p><p>Each workspace keeps just enough info to make this work: how to connect (ConnStr), where the isolation lives (SchemaName if you’re using schema-level isolation), and most importantly, which commit it came from (HeadCommitID). That last part acts like a pin; it tells you exactly what you’re looking at, and it also prevents GC from deleting that commit out from under you.</p><p>On top of that, there’s some boring-but-important safety logic. You don’t accidentally spin up multiple active workspaces for the same branch without a fight; there’s locking and DB constraints to enforce that. If provisioning fails halfway, it tries to clean up so you don’t leave junk behind. And teardown is treated as a real state transition, not just “hope it worked,” so you don’t end up with half-deleted environments pretending everything’s fine.</p><p>At a high level, the flow is simple: branch tip → isolated environment → connection details + schema name → pinned commit so you always know what you’re working with.</p><h4>Graph guards: depth caps and cycle errors</h4><p>Anything that walks the commit graph, finding ancestors, computing merge bases, even GC only works if you’re strict about boundaries and honest when something looks off.</p><p>So I split the failure modes very intentionally. If there’s an actual cycle in the graph (like a commit pointing to itself, or some loop in parent links), that’s a hard error ErrCommitGraphCycle. That’s not “big repo energy,” that’s just invalid data. You stop right there instead of looping forever or returning garbage. Then there’s the other case: the graph is technically fine, but it’s <em>too deep</em>. Maybe something weird happened, maybe the data is sketchy, either way, once you cross a max depth, you bail with a different error. Not because it’s wrong, but because you’re not going to burn unbounded CPU trying to prove it’s right.</p><p>That distinction matters. A broken graph and a ridiculously long but valid one aren’t the same thing but both are situations where you’d rather fail than pretend you got a meaningful answer.</p><p>And that’s kind of the theme for the whole ops side of this system. GC only deletes what’s truly unreachable (and respects workspace pins), dry-runs tell you exactly what would happen before anything is touched, workspaces give you isolated environments tied to specific commits, and graph walks have guardrails so bad data can’t turn into infinite loops or silent corruption.</p><p>Basically: if the data gets weird, the system doesn’t try to be heroic, just tells you, clearly, and stops.</p><h3>Now let’s talk about the algorithms behind this.</h3><p>This project looks like systems engineering on the surface, but a few parts quietly turn into classic algorithm problems, mostly around graphs, ordering, and merges.</p><p>Everything starts with the commit graph. Parent links are supposed to form a DAG, so the system actively checks that using a DFS with the usual gray/black states. If a node is revisited while still “in progress,” that’s a cycle → hard fail. There’s also a depth cap, because even a valid graph can be <em>too</em> deep, at some point you stop and say “this is not worth infinite CPU.” So you get two distinct failures: one for broken topology, one for “this walk is getting unreasonable.”</p><p>Once the graph is trusted, ancestry becomes predictable. Ancestors aren’t fetched randomly, it’s a clean breadth-first walk: commit, then parents, then grandparents. Within each level, everything is sorted. That tiny detail keeps behavior deterministic across storage backends and saves you from debugging “why did this test pass yesterday?” kind of issues.</p><p>Merge-base is where things get interesting. The approach is simple: take ancestors of both sides, intersect them, and then keep only the <em>minimal</em> ones, meaning no candidate is an ancestor of another. If there’s exactly one, great, that’s your merge base. If there are multiple, you’re in criss-cross history territory and the system refuses to guess. It just errors. That decision to fail instead of being clever shows up a lot in this codebase.</p><p>The actual merge follows the same philosophy. It’s a three-way merge, just not on text. You diff base → ours and base → theirs, then reconcile. Independent changes compose cleanly; overlapping incompatible ones turn into typed conflicts. Instead of vague “merge conflict” blobs, you get specific things like column type clashes or index name collisions, which makes resolution much more explicit.</p><p>Diffing itself is pretty boring in the best way. It’s just structured comparison over tables, columns, indexes, enums, essentially set operations. The complexity isn’t in the algorithm, it’s in being consistent about how things are identified and normalized.</p><p>Where ordering really matters again is migration generation. If you emit SQL in the wrong order, foreign keys will break things immediately. So table creation is driven by a topological sort over FK dependencies. If the graph has a cycle, you don’t try to be smart, you just fail and surface it. Drops run in reverse order for the same reason.</p><p>On the operational side, garbage collection is just reachability but with an important twist. You don’t just start from branch heads, you also include workspace pins. That way you never delete the commit some active sandbox is built on. It’s conceptually simple, but missing that detail would make the system feel unreliable fast.</p><p>And for SQL itself, there’s no heroics; parsing is delegated to PostgreSQL’s own parser (libpg_query). That sets a clear boundary: the system doesn’t try to <em>interpret</em> SQL differently from the database.</p><h3>What I’d do differently</h3><ul><li>Snapshots, maps, and “same meaning, different bytes.” Once commits store gzipped JSON snapshots, you live or die by whether two logically identical schemas always round-trip the same way. Go’s encoding/json already sorts map keys, which helps, but the real lesson is broader: normalization (types, nullable defaults, ordering of nested things), golden blobs checked in for no-CGO test runs, and the occasional “regenerate the golden when DDL changes” workflow. I’d bake canonical snapshot invariants into the format, for fewer surprises when diffing, hashing, or explaining “why is this commit different” to a human.</li><li>CGO vs. Fidelity is a tax you pay on purpose. Tying parsing to pg_query (and thus libpg_query + CGO for the full story) buys SQL fidelity that regexes will never give you; the tradeoff is cross-compilation, simpler CI matrices, and contributor friction. The compromise that emerged, CGO tests for the real parser, committed golden bytes so some paths can run with it, which CGO_ENABLED=0is workable but a bit apologetic. A sequel-me might either invest in a pure-Go subset parser for 80% cases, or go all-in and embrace CGO everywhere with no guilt and better tooling docs.</li><li>Merge-base isn’t a detail; it’s a product decision. Blocking on ambiguous merge bases (criss-cross histories) instead of silently picking an ancestor feels pedantic until you’ve seen the alternative: merges that <em>look</em> clean because the tool didn’t complain. I’d still make the same call fail loud, but I’d surface it in UX earlier (discovery-time, not only at merge time) so people don’t feel punished for a graph shape they didn’t know was exotic.</li><li>Postgres-first is a feature and a cage. Leaning on Postgres semantics for workspaces (schema isolation, partial unique indexes, CASCADE stories in GC dry-run) lets you move fast and be correct on the database people actually run. The lesson is honest scoping: multi-DB portability isn’t free, you’d need another isolation story, another DDL dialect, and probably lower parser fidelity or more adapters. I’d document “Postgres is the reference implementation” on day one so nobody mistakes ambition for universality.</li><li>Ops surfaces add up faster than core algorithms. Reachability GC with branch heads plus workspace pins, stale-branch previews, idle workspace teardown. None of it is glamorous, and all of it is where bugs hurt real users. If I restarted, I’d sketch the operator story (dry-run report shape, idempotency, partial failures) alongside the diff engine, not after it.</li></ul><p>So that’s the shape of it: a schema history system with real merge semantics, real operational edges, and a lot of deliberate choices where I picked clarity and predictability over clever tricks. It’s not perfect, there are rough edges I’d smooth out, abstractions I’d rethink, and definitely a few places where I wish I’d written the docs <em>before</em> forgetting why something exists.</p><p>More than anything, this was a learning exercise that got very real. You don’t actually understand diffs, graphs, retention, or isolation until you build something where hand-waving isn’t an option, where the system either behaves correctly or it doesn’t. And that pressure forces you to care about the boring parts, not just the shiny ones.</p><p>If you’re thinking about building something similar, don’t wait for a perfect idea. Pick a problem that’s annoying enough that you’ll stick with it through the unglamorous parts. That’s where most of the real learning (and most of the real systems work) actually happens.</p><p>If you’re curious or want to dig into the implementation, the repo’s here:<br> <a href="https://github.com/Devanshusharma2005/diffo">https://github.com/Devanshusharma2005/diffo</a></p><p>Thanks for sticking through the long version. If even one piece of this saves you from a week of confusion, that’s already a win. Now go break something, just do it safely: in a workspace, on a branch, with a merge base you can actually point to.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f259ce3d3cc5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a High-Performance Distributed Search System for 10,000 QPS.]]></title>
            <link>https://medium.com/@devanshusharma658/building-a-high-performance-distributed-search-system-for-10-000-qps-240e5ce48016?source=rss-9043612addc6------2</link>
            <guid isPermaLink="false">https://medium.com/p/240e5ce48016</guid>
            <dc:creator><![CDATA[Devanshusharma]]></dc:creator>
            <pubDate>Mon, 09 Feb 2026 11:39:55 GMT</pubDate>
            <atom:updated>2026-02-09T11:39:55.073Z</atom:updated>
            <content:encoded><![CDATA[<p>During my internship days at cal.com, I discovered a real passion for distributed systems, databases, and learning Golang. The last four months have been a whirlwind of reading system design blogs, diving into O’Reilly’s massive archives, and experimenting with Golang. It’s been a crazy ride of nights filled with research, coding, and deep dives into system design papers and blogs.</p><p>One day, on December 27th 2025 I was just casually talking to my sister who, by the way, isn’t from a tech background and she jokingly said, “Why don’t you build Google?” Honestly, I brushed it off at first. But then, it hit me why not try? That little comment sparked a whole new wave of motivation. I started thinking about how I could approach building something similar, even if on a smaller scale.</p><p>From that moment, I spent countless late nights researching, trying to understand what makes high-performance search engines tick. I read everything I could find about exa-scaled systems and parallel web architectures those massive systems working behind the scenes of the biggest search engines. It’s fascinating how they handle such enormous amounts of data with speed and reliability.</p><p>This journey has been intense but incredibly rewarding. I’ve learned so much about distributed systems, search algorithms, and the engineering tricks that power some of the world’s largest web systems. And now, I’m excited to share what I’ve been working on (The distributed search system using Go), the lessons I’ve learned, and the cool stuff I’ve built along the way.</p><p>So yeah, <strong>why Go?</strong></p><p>Honestly, it just felt right.</p><p>At some point while building this, I realized I was basically writing a system that lives and dies by <strong>concurrency</strong> fan-out queries, shard calls, timeouts, cancellations, the whole mess. And Go is just… built for that.</p><p>The worker-pool pattern in Go is stupidly simple. You don’t fight the language. You don’t overthink threads. You just spin up goroutines, pass stuff over channels, and things <em>work</em>. I can fire off thousands of lightweight goroutines without my laptop surrendering.</p><p>What really sold me is how boring Go makes hard things. <strong>Concurrency</strong> <em>should</em> be scary but in Go, it feels almost casual. No weird abstractions, no ceremony. Just clear code that does what you expect.</p><p>On top of that, the standard library is insanely solid. Networking, HTTP, context cancellation, profiling it’s all just… there. No dependency hell. No magic. Perfect for building something that needs to be fast, predictable, and production ready.</p><p>So yeah, I didn’t pick Go because it’s trendy or cool. I picked it because when you’re building distributed systems, Go stays out of your way and that’s exactly what you want.</p><p><strong>THE ARCHITECTURE:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0oeuy2toqzY47vCe2cD6yw.png" /></figure><h3>Phase 1: The Basics (Building a Simple Search System)</h3><p>So, for the first phase, i kept things pretty straightforward. The goal was to get a basic search up and running without overcomplicating stuff. Basically, you take some data, throw it into a single index, and then set up a simple way to search through it.</p><p>Here’s how it looked:</p><ul><li>Data Ingestion: I took a big XML dump of Wikipedia articles and processed it into a format that our search engine could understand. Think of it like cleaning and organizing the data so it’s ready to be searched.</li><li>Indexing: I used Bleve, which is like an open-source search engine library in Go. I indexed all the articles into one big index no sharding, no fancy distribution, just a single index with everything in it.</li><li>Searching: When i enter a query, the system would run the search against this big index. Since everything was in one place, it was pretty quick around ~450ms per query, give or take.</li><li>Deployment: To keep things simple, we just ran everything on one machine or a single server. No Docker, no cluster just a straightforward process.</li></ul><p>Basically, Phase 1 was about proving the concept works: i can ingest data, build an index, and search through it. It wasn’t super scalable or fast, but it was a solid starting point to see if the idea had legs.</p><h3>Phase 2: Going Distributed (Making Search Faster and Smarter)</h3><p>Once i had the basics down, it was clear that if we wanted to handle more data and get results quicker, i needed to level up. That’s where Phase 2 comes i turning the simple setup into a distributed, sharded system that can scale like crazy.</p><h3>The Big Idea</h3><p>Instead of one giant index, we splitted the data into chunks called shards so each piece can be searched independently. Think of it like dividing a huge book into chapters; you can search each chapter separately, and then combine the results.</p><h3>How I Did It ?</h3><h4>Static Pre-Sharding</h4><ul><li>I took the Wikipedia dump and sliced it into 8 separate JSONL files (each one holding a portion of the data).</li><li>The partitioning was deterministic: based on hashing each article’s title or abstract, we assigned it to one of the 8 shards. This way, the same article always ends up in the same shard.</li><li>Each shard got its own Bleve index, stored in a dedicated directory, like shard-0/, shard-1/, and so on.</li></ul><h4>Containerized Deployment</h4><ul><li>To make everything manageable, i used Docker. Each shard ran as its own container, with its own search server.</li><li>I also set up an orchestrator using Docker Compose, which spun up all 8 shard servers, along with other components like etcd for coordination and Redis for caching.</li></ul><h4>The Shard Servers</h4><ul><li>Each server had a tiny Go program that:</li><li>Started an HTTP server on a specific port.</li><li>Loaded its own Bleve index.</li><li>Listened for search requests.</li><li>Ran the search query locally and sent back the results.</li></ul><h4>Searching (Fan Out : Leveraging the power of Go)</h4><ul><li>When someone searches, the coordinator (think of it like the traffic controller) receives the query.</li><li>It then simultaneously asks all 8 shard servers for their results kind of like sending out a bunch of emails at once.</li><li>Each server works independently, searches its index, and returns the top hits.</li><li>The coordinator waits for all responses (with a timeout so it doesn’t hang), then merges the results, <strong>sorts them</strong>, and returns the top results to the user.</li></ul><h4>Keeping Track of Shards (Using etcd shard discovery)</h4><ul><li>To make sure everything is running smoothly, each shard registers itself in etcd, a distributed key-value store.</li><li>Here i leveraged the power of <strong>raft consensus algorithm</strong> and setup 3 etcd nodes inside a cluster. so that in case of failure it can use a leader election strategy.</li><li>These entries have TTL (time-to-live) leases that are periodically renewed, keeping the system aware of which shards are alive.</li><li>If a shard crashes or goes offline, its lease expires, and etcd removes it from the active list.</li><li>The coordinator constantly watches etcd for changes, so it always knows which shards are online.</li></ul><h3>Why It Works ?</h3><ul><li>Speed: Searching in parallel across multiple shards means results come back way faster around 45ms instead of hundreds.</li><li>Scalability: Adding more data? Just spin up more shards. Need more speed? Add more servers.</li><li>Fault Tolerance: If one shard crashes, the system keeps working with the remaining ones. Once the crashed shard comes back, it re-registers itself automatically.</li></ul><h3>The Upshot</h3><p>This setup made the search much faster, more scalable, and resilient. It’s a big step from a single index to a distributed system that can grow and recover on the fly.</p><h3>Phase 3 Deep Dive: Redis Caching The Cost Killer (45ms → 0.5ms p99)</h3><h3>The Duplicate Query Crisis</h3><p>In Phase 2, I faced a big problem: every time i searched for “distributed systems Golang,” I had to fan out to all 8 shards and run a full BM25 query across 24,000+ docs. That took about 45ms per shard, so total latency was around 360ms per query. And guess what? 95% of traffic was just repeat queries, so most of that compute was wasted.</p><p>Root cause: The shards were stateless no memory, no caching. Every request meant doing the full fan-out and BM25 calculation again. That’s inefficient, especially with high repeat traffic.</p><h3>The Phase 3 Insight: Caching Complete Responses</h3><p>To fix this, I cached the full serialized search responses at the coordinator level. This meant:</p><ul><li>When a query came in, we first checked Redis.</li><li>If Redis had the answer (cache hit), we returned it immediately, saving nearly all the fan-out and scoring time.</li><li>If Redis missed, we did the full fan-out, serializing the result, and stored it in Redis for next time.</li></ul><p>This simple change reduced latency from 45ms to about 0.5ms at p99 a 150x improvement.</p><p>Cold misses still took about 22ms (full fan-out plus serialization), but most queries were hits.</p><p><strong>Why Redis? Not Just a Map in Memory</strong></p><p>Using Redis instead of an in-memory map has two big reasons:</p><ol><li>Persistence (dump.rdb):</li></ol><ul><li>With in-memory maps, restarting the coordinator wipes the cache.</li><li>Redis’s dump.rdb file persists data across restarts, so the cache survives deployments and crashes.</li></ul><ol><li>Memory Management &amp; Eviction:</li></ol><ul><li>Redis can automatically evict cold keys using LRU policies, keeping the cache fresh and manageable.</li><li>Redis supports maxmemory limits, so we control how much memory is used (e.g., 256MB).</li></ul><h3>Production Realities &amp; Challenges</h3><ul><li><strong>Thundering Herd</strong>: During the Load testing, Thousands of queries hitting “Golang” simultaneously without control, this causes a huge spike on the fan-out.</li><li>Cache Stampede: To prevent multiple clients from triggering full fan-out at once, i used redis <strong>SET NX EX</strong> atomic “set if not exists” with expiration. Only one client writes the cache, others wait for it.</li><li>TTL Discipline: Setting a 5-minute TTL. Too short, and we get constant cache misses; too long, and stale data persists. 5 minutes strikes a good balance, especially since Wikipedia abstracts update yearly.</li><li>Network: Redis runs on localhost, so RTT is ~0.3ms negligible.</li></ul><p>Evidence: The dump.rdb file shows our cache is working, with hundreds of saved queries, maintaining a 93-97% hit rate.</p><h3>Cache Key Design</h3><ul><li>Key: Use sha256(&quot;distributed systems&quot;) : a 64-character hex string.</li><li>Why SHA256?</li><li>Collision-free even for billions of queries.</li><li>Fixed length, making Redis scans predictable.</li><li>Value: JSON-serialized SearchResponse, compressed with gzip (~60% smaller), saving memory.</li></ul><h3>Cache Flow (The Critical Path)</h3><ol><li>User queries &quot;distributed systems&quot;.</li><li>redis.GET cache:&lt;hash&gt; if hit (95%), return immediately (~0.5ms).</li><li>If miss, fan-out to shards (~45ms).</li><li>Serialize response + redis.SET cache:&lt;hash&gt; store for next time (~1.2ms).</li><li>Return JSON to user (~22ms total).</li></ol><p>Result:</p><ul><li>Hit: ~0.5ms latency, practically instant.</li><li>Miss: 22ms, but rare (5%).</li></ul><h3>Thundering Herd &amp; Race Condition Prevention</h3><ul><li>Without Redis NX, multiple clients might trigger full fan-out simultaneously, crashing the system.</li><li>With redis SET NX EX, only one client performs the fan-out and caches the result; others wait for the cache to populate, avoiding overload.</li></ul><h4>TTL Strategy</h4><ul><li>5 minutes is the sweet spot:</li><li>Long enough to keep high hit rates.</li><li>Short enough to refresh stale data.</li><li>Prevents cache stampedes.</li></ul><p><strong>Cache Eviction &amp; Maintenance</strong></p><ul><li>maxmemory 256MB limits Redis memory.</li><li>allkeys-lru eviction policy removes least recently used keys automatically.</li><li>Hourly dump.rdb ensures persistence across restarts.</li></ul><h3>Handling Production Edge Cases</h3><ul><li>Cache stampede? Prevented by Redis NX.</li><li>Cold start? Redis empty initially, fallback to full fan-out (~22ms).</li><li>OOM? Redis evicts cold keys automatically.</li><li>Network issues? Degradation gracefully falls back to shard fan-out.</li><li>Restarts? dump.rdb restores ~99% of cache in seconds.</li></ul><p>Most traffic hits Redis (~95%), returning responses near-instantly. The rest fall back to shard fan-out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-jQ_rgyVOBXoNufyoPW9gw.png" /></figure><h3>Phase Takeaways</h3><ul><li>Caching complete responses at the coordinator level <em>eliminates</em> redundant fan-outs.</li><li>SHA256 keys ensure collision-free, fixed-length identifiers.</li><li>Redis persistence and eviction policies keep the cache reliable and manageable.</li><li>Throttling via SET NX EX prevents overload during traffic spikes.</li><li>5-minute TTL strikes a balance between freshness and cache efficiency.</li></ul><p>Result:<br>Latency plummets to 0.5ms p99, QPS skyrockets, and the system handles high load smoothly.</p><h3>Phase 4 Deep Dive: Hot-Term Shard Affinity (The 4x Speed Boost)</h3><h3>The Real Story Behind the Shards</h3><p>In Phase 3 when we saw that 80% of queries only hit 2 out of 8 shards?<br>It turns out, most searches are pretty hot-term heavy certain keywords dominate the traffic.</p><p>Examples:</p><ul><li>&quot;distributed&quot; queries mostly hit shards 0 and 1</li><li>&quot;Golang&quot; leans toward shards 0 and 2</li><li>&quot;etcd&quot; almost always hits shard 0</li><li>&quot;neural networks&quot; mainly land on shards 1 and 3</li></ul><p>This pattern isn’t random. It’s a classic 80/20 rule: 80% of traffic is concentrated on just 2–3 shards, not all 8.</p><h3>The Old Way: Wasteful Fan-Out</h3><p>In Phase 3, every query went to all 8 shards, regardless of whether the data was there or not.<br>That meant 45ms latency every time, plus unnecessary network traffic and compute.<br>We were doing 6x more work than needed.</p><p>Goal: Cut that down to about 12ms by only touching the relevant shards.</p><h3>The Insight: Building a Routing Brain</h3><p>Create a static “hot-term” routing table at the coordinator (a simple map that tells it which shards to query for each hot term.)</p><h3>How it works:</h3><ul><li>When a query comes in, preprocess it:</li><li>Split into terms: e.g., &quot;distributed systems Golang&quot; → [&quot;distributed&quot;, &quot;systems&quot;, &quot;Golang&quot;]</li><li>Use the hot-term map.</li><li>For each term, find which shards are relevant.</li><li>Take the union of all these shard lists.</li><li>Deduplicate.</li><li>Only query those 2–3 shards instead of all 8.</li></ul><p>Result:<br>Most queries now hit just 2–3 shards, reducing latency from 45ms to about 12ms.</p><h3>Real Data &amp; Patterns</h3><p>Query logs revealed:</p><p>Hot Term shards approximate Traffic Share&quot;distributed&quot;[0,1]: 95% of such queries&quot;Golang&quot;[0,2] 87% of such queries&quot;concurrency&quot;[0,2]92%&quot;database&quot;[1,3]:89%&quot;etcd&quot;[0]:98%</p><p>Hot-term heatmap:</p><ul><li>Shard 0: &quot;distributed&quot;, &quot;etcd&quot;, &quot;raft&quot;, &quot;concurrency&quot;</li><li>Shard 1: &quot;neural&quot;, &quot;networks&quot;, &quot;ML&quot;, &quot;database&quot;</li><li>Shard 2: &quot;Golang&quot;, &quot;goroutines&quot;, &quot;channels&quot;</li></ul><h3>Architecture Diagram (simplified)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eimdwKlPK0txiC7drPZgvw.png" /></figure><p>Most queries now only involve 2 or 3 shards instead of all 8, slashing latency.</p><h3>How Query Flow Changed</h3><h4>Before and After</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NtqE4-UioY8VZ7bEXR99gw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZBIGsV-UXRkpMp2btDZw4A.png" /></figure><p>Network savings:</p><ul><li>From 8 shards to 2–3 shards for 80% of queries.</li><li>75% less shard wakeups.</li></ul><h3>Phase 4 -&gt; Traffic Breakdown &amp; Metrics</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IuQnkPyfnYTj26qdZB9QcQ.png" /></figure><h3>Dynamic Routing &amp; Etcd</h3><p>Future-proofing:</p><ul><li>Store the hot-term map in etcd.</li><li>When new hot terms emerge, update the map.</li><li>When a shard fails, remove it from the map.</li><li>Rebalance hot terms across healthy shards.</li></ul><p>Etcd keys example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ow7Q5JO3NrshtMEGMo9Q0g.png" /></figure><p>Advantages:</p><ul><li>Dynamic routing without restarting everything.</li><li>Shard failures or traffic shifts are handled smoothly.</li></ul><h3>Risks &amp; Mitigations (in progress…)</h3><p>Missed hot terms: fallback to full fan-out (20% traffic).</p><ul><li>Stale routing: update hot-term map hourly based on logs.</li><li>Shard failure: route around unhealthy shards via etcd.</li><li>Gradual rollout: test 10% traffic first, then fully switch.</li></ul><h3>Phase 5 : Deep Dive: Hybrid BM25 + Semantic Reranking</h3><h3>The Semantic Search Trap</h3><p>By now, we’ve got a blazing-fast system with smart routing and caching. But there’s a catch: pure keyword searches like &quot;neural networks Golang&quot; aren’t enough anymore.<br>They pull up papers about brain biology or neuroscience because BM25 just matches keywords. But meaning? That’s lost.</p><p>Pure vector search embedding-based also trips up:</p><ul><li>It might find “brain neurons” when you search for “neural networks” (ML), but it can also drift into unrelated topics.</li><li>No keyword anchor, so it might go off into the weeds.</li></ul><p>The solution? A hybrid approach: first, use BM25 to find the keyword candidates, then rerank with semantic understanding.</p><h3>Why Hybrid Rules</h3><p>Pure BM25 fails:</p><ul><li>Example:<br>Query: &quot;neural networks etcd sharding&quot;<br>Top results:</li></ul><ol><li>“Neural circuit” (brain biology)</li><li>“Network shard” (networking) : false positive</li><li>“Etcd config” (relevant but not top)</li></ol><p>Pure vector search:</p><ul><li>Finds “brain biology” when searching for “neural networks” close in embedding space, but irrelevant for tech docs.</li></ul><p>Hybrid approach:</p><ul><li>Step 1: BM25 finds top 200 candidates based on keywords (fast, precise).</li><li>Step 2: Get embeddings of those candidates.</li><li>Step 3: Compute cosine similarity to query embedding.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Kf3V7ZKDI9lCRbkmFmU9g.png" /></figure><ul><li>Step 4: Fuse scores:</li></ul><p>This combo delivers accurate, relevant results the best of both worlds.</p><h3>The Two-Stage Retrieval Pipeline</h3><p>Here’s how it works:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*WojOtoNQRmlyxu9OMCPIEQ.png" /></figure><p>Key point:</p><ul><li>200 candidates hits a sweet spot:</li><li>Less than 100 misses semantic neighbors</li><li>More than 500 slows embedding too much</li><li>200 covers ~87% recall, with super quick embedding</li></ul><h3>Why All-Minilm (384-dim)?</h3><ul><li>Speed: Embedding 200 docs takes just 7ms on MacBook M4.</li><li>Quality: Spearman correlation with BERT-base is 92% pretty good!</li><li>Size: Only 22MB easy to run locally in Docker.</li><li>Open: No API keys runs on localhost:11434.</li></ul><p>The flow:<br>POST to Ollama’s API with docs → get back 384-dim vectors for each doc → store in Bleve index.</p><h3>Fusion Tuning (α=0.7)</h3><p>Why 0.7?</p><ul><li>Pure BM25 (α=1.0) gives 82% recall but less semantic context.</li><li>Pure cosine (α=0.0) drifts into irrelevant docs.</li><li>α=0.7 balances keyword precision with semantic recall, giving 87% recall and 80% precision.</li></ul><p>This tuning was based on offline testing and optimizing for NDCG@10.</p><h3>Semantic Drift</h3><p>Before (Phase 4 BM25):<br>&quot;neural networks Golang&quot;</p><ul><li>Top results: “Neural circuit” (brain), “Network programming Go” (networking), “Brain net” (neuroscience) all keyword overlaps, but irrelevant.</li></ul><p>After (Phase 5 hybrid):</p><ul><li>“Deep learning” (ML)</li><li>“Neural networks” (ML)</li><li>“Transformers” (ML architecture)<br>All highly relevant, with 90%+ accuracy.</li></ul><p>Result:</p><ul><li>Beating Exa/Perplexity by 3:1 in relevance.</li><li>Precision@3: jumps to 90%.</li><li>Technical queries are now spot-on.</li></ul><h3>Embedding Pipeline in Action</h3><ul><li>Precompute: Embed all 24,000 docs once, store vectors in Bleve.</li><li>Query time: Embed the query (just 1 vector), compare with pre-stored doc vectors via cosine similarity.</li><li>Storage: 24,000 docs × 384 floats ≈ 140MB (fits comfortably in Docker).</li><li>Bleve index: Stores vectors in a field, enabling fast cosine searches.</li></ul><h3>Production Capacity Breakdown</h3><p>Let’s analyze the system component by component to understand the overall throughput:</p><p>Redis</p><ul><li>Handles approximately 10,000 QPS at 0.5ms latency</li><li>Manages around 95% of total traffic, serving as the backbone for caching and quick lookups</li></ul><p>Search Shards</p><ul><li>Each hot shard supports roughly 1,000 QPS</li><li>Only 2 shards are involved when querying top (hot) terms, effectively reducing latency</li><li>Achieves around 12ms BM25 latency per query</li></ul><p>Ollama (Embeddings)</p><ul><li>Capable of approximately 140 QPS</li><li>Processes 200 documents per batch</li><li>Throughput reaches roughly 28,000 docs/sec, enabling fast embedding retrieval</li></ul><p>Coordinator Layer</p><ul><li>Serves as the traffic orchestrator, with a maximum capacity of about 8,000 QPS in total</li></ul><h3>Final System Capacity For Now…</h3><ul><li>Stable throughput of 8,000 QPS at approximately 28ms p99 latency</li><li>This setup can handle roughly 700 million queries per day on a single deployment</li></ul><h3>Risks &amp; Mitigations</h3><ul><li>Embedding staleness: Wikipedia updates yearly, so OK.</li><li>Ollama as single point: Docker healthchecks restart if needed.</li><li>Vector quality: all-minilm is state-of-the-art for tech docs.</li><li>Graceful fallback: If Ollama down, revert to Phase 4 BM25-only.</li></ul><p>Final Takeaway.</p><p>Keyword + semantic = best of both worlds.</p><ul><li>200 candidates hits a perfect speed/recall balance.</li><li>all-minilm is fast, small, and accurate.</li><li>Precompute vectors query-time embedding is quick.</li><li>Tune fusion α=0.7 for max relevance.</li></ul><p><strong>WRAPPING UP</strong></p><p>And that’s a wrap on our journey through the (not-final phase) the ultimate hybrid search! Combined the precision of keywords with the power of semantic understanding, creating a system that’s not only lightning-fast but also razor-sharp in relevance.</p><p>With this setup, Search engine is ready to handle complex queries, deliver top-notch results in milliseconds, and scale gracefully in production. Whether we’re tackling tech docs, scientific papers, or any dense knowledge base, this hybrid magic is your secret weapon.</p><p>I’m also continuously working on adding more features and enhanching the performance.</p><p>This project is never perfect, just like every other! I’m happy to hear feedback, suggestions, or ideas to make it even better.</p><p>If you find this useful, please star the repo: <a href="https://github.com/Devanshusharma2005/distributed-search/">https://github.com/Devanshusharma2005/distributed-search/</a></p><p>Thanks for sticking with me through this deep dive. The future of search is here fast, accurate, and smarter than ever. Now go build something amazing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=240e5ce48016" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>