<?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 Shivam Tripathi on Medium]]></title>
        <description><![CDATA[Stories by Shivam Tripathi on Medium]]></description>
        <link>https://medium.com/@shivt681?source=rss-a79301a41587------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_Q6AyxDtOXwDcVIcCxSwag.jpeg</url>
            <title>Stories by Shivam Tripathi on Medium</title>
            <link>https://medium.com/@shivt681?source=rss-a79301a41587------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 18:09:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shivt681/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[Building a Production-Ready Email Notification System: A Complete System Design Guide]]></title>
            <link>https://medium.com/@shivt681/building-a-production-ready-email-notification-system-a-complete-system-design-guide-21e9d9ea883f?source=rss-a79301a41587------2</link>
            <guid isPermaLink="false">https://medium.com/p/21e9d9ea883f</guid>
            <category><![CDATA[system-designing]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Shivam Tripathi]]></dc:creator>
            <pubDate>Thu, 16 Jul 2026 16:58:17 GMT</pubDate>
            <atom:updated>2026-07-16T16:58:17.778Z</atom:updated>
            <content:encoded><![CDATA[<p>When developers first build an application, sending emails usually seems like one of the simplest features. A few lines of code, an SMTP server, and the email is delivered.</p><pre>send_email(user.email, &quot;Welcome!&quot;)</pre><p>It works perfectly during development.</p><p>But as your application grows, that simple function quickly becomes one of the most critical parts of your infrastructure.</p><p>Imagine your application needs to handle:</p><ul><li>User registration emails</li><li>Login alerts</li><li>Password reset links</li><li>OTP verification</li><li>Subscription confirmations</li><li>Payment receipts</li><li>Invoice generation</li><li>Monthly reports</li><li>Marketing campaigns</li><li>Security notifications</li></ul><p>Now imagine thousands of users performing these actions simultaneously. Would you still send emails directly from your API?</p><p>The answer is <strong>no</strong>.</p><p>A production-grade email system is not simply an SMTP connection — it’s a distributed, event-driven service designed for reliability, scalability, observability, and fault tolerance.</p><p>In this article, we’ll explore how large-scale systems design and implement email notification services and the architectural principles that make them resilient.</p><h3>Why Email is a System Design Problem</h3><p>Let’s consider a simple example.</p><p>A user purchases a premium subscription.</p><p>Naively, your application might perform the following sequence:</p><pre>Receive Request<br>      │<br>Process Payment<br>      │<br>Generate Invoice<br>      │<br>Send Email<br>      │<br>Return Success</pre><p>This looks reasonable until something goes wrong.</p><p>What happens if:</p><ul><li>The email provider is temporarily unavailable?</li><li>Network latency increases?</li><li>SMTP takes 15 seconds to respond?</li><li>The email service returns a timeout?</li><li>The email API is rate-limited?</li></ul><p>Your user has already paid, but now they’re waiting for an email to be sent before receiving a response.</p><p>Even worse, if the email fails, should the payment also fail?</p><p>Obviously not.</p><p>Email delivery should never become the bottleneck for business-critical workflows.</p><h3>Core Design Principle</h3><p>One of the most important principles in distributed systems is:</p><blockquote><strong><em>Business transactions and notifications should be loosely coupled.</em></strong></blockquote><p>A purchase should complete successfully even if email delivery experiences temporary issues.</p><p>Instead of coupling them together, they should communicate through events.</p><h3>Evolution of Email Architecture</h3><h3>Level 1 — Direct SMTP</h3><p>Most applications begin here.</p><pre>Application<br>      │<br>      ▼<br>SMTP Server<br>      │<br>      ▼<br>Recipient</pre><p>The application opens an SMTP connection, authenticates, and sends the email.</p><p>Advantages:</p><ul><li>Easy to implement</li><li>Minimal infrastructure</li><li>Suitable for internal tools</li></ul><p>Limitations:</p><ul><li>Slow response times</li><li>No retries</li><li>No analytics</li><li>Poor scalability</li><li>Weak monitoring</li><li>Limited deliverability</li></ul><p>This approach works for hobby projects but quickly becomes insufficient in production.</p><h3>Level 2 — Email Service Provider</h3><p>Instead of talking directly to an SMTP server, applications communicate with specialized email providers.</p><pre>Application<br>      │<br>REST API<br>      │<br>Email Provider<br>      │<br>Recipient</pre><p>Popular providers include SendGrid, Amazon SES, Mailgun, Postmark, Resend, and Azure Communication Services Email.</p><p>These providers handle:</p><ul><li>SMTP infrastructure</li><li>IP reputation</li><li>Spam filtering</li><li>Retry mechanisms</li><li>Delivery optimization</li><li>Analytics</li><li>Bounce management</li><li>Webhooks</li></ul><p>This significantly improves deliverability while reducing operational complexity.</p><h3>Why Asynchronous Processing Matters</h3><p>Imagine an e-commerce platform receiving 10,000 orders in one hour.</p><p>Each order generates:</p><ul><li>Order confirmation</li><li>Invoice</li><li>Shipping notification</li><li>Loyalty points update</li></ul><p>If each email takes just two seconds to send, synchronous processing quickly becomes a bottleneck.</p><p>Instead, modern systems decouple request processing from email delivery.</p><pre>User Request<br>      │<br>Business Logic<br>      │<br>Save Transaction<br>      │<br>Publish Email Event<br>      │<br>Return Success</pre><p>The user receives an immediate response while email delivery happens independently.</p><h3>Queue-Based Architecture</h3><p>A queue is the foundation of every scalable notification system.</p><pre>API Server<br>                    │<br>                    ▼<br>             Message Queue<br>                    │<br>         ┌──────────┴──────────┐<br>         ▼                     ▼<br>Email Worker 1          Email Worker 2<br>         ▼                     ▼<br>      Email Provider      Email Provider</pre><p>Popular technologies include:</p><ul><li>Azure Service Bus</li><li>RabbitMQ</li><li>Kafka</li><li>AWS SQS</li><li>Redis Streams</li><li>Google Pub/Sub</li></ul><p>Queues provide several critical guarantees:</p><ul><li>Reliability</li><li>Decoupling</li><li>Load leveling</li><li>Scalability</li><li>Retry support</li></ul><p>Even if your email provider is temporarily unavailable, requests continue entering the queue while workers process them once the provider recovers.</p><h3>Event-Driven Architecture</h3><p>Large systems rarely call an Email Service directly.</p><p>Instead, they publish business events.</p><pre>Subscription Purchased<br>            │<br>            ▼<br>        Event Bus<br>            │<br> ┌──────────┼──────────┐<br> ▼          ▼          ▼<br>Billing   Analytics   Email</pre><p>This architecture provides loose coupling.</p><p>The Payment Service never needs to know who is consuming the event.</p><p>Today only the Email Service may consume it.</p><p>Tomorrow additional services can subscribe:</p><ul><li>CRM</li><li>Recommendation Engine</li><li>Audit Service</li><li>Fraud Detection</li><li>Analytics Platform</li></ul><p>No changes are required in the Payment Service.</p><p>This is one of the biggest advantages of event-driven architectures.</p><h3>Designing an Email Microservice</h3><p>Instead of scattering email logic across your application, create a dedicated Email Service.</p><p>Its responsibilities include:</p><ul><li>Rendering templates</li><li>Sending emails</li><li>Managing retries</li><li>Processing webhooks</li><li>Tracking delivery status</li><li>Handling attachments</li><li>Logging events</li><li>Recording analytics</li></ul><p>A typical API might look like:</p><pre>sendEmail(<br>    recipient,<br>    template,<br>    variables,<br>    attachments<br>)</pre><p>Business services no longer care how emails are delivered — they simply publish events.</p><h3>Template Management</h3><p>Hardcoding HTML inside source code quickly becomes unmanageable.</p><p>A better structure is:</p><pre>templates/<br>    welcome.html<br>    invoice.html<br>    otp.html<br>    subscription.html<br>    password_reset.html</pre><p>Templates contain placeholders:</p><pre>Hello {{name}}</pre><pre>Thank you for purchasing {{plan}}.</pre><pre>Amount Paid: {{amount}}</pre><p>The Email Service injects the required data before sending.</p><p>Benefits include:</p><ul><li>Easier maintenance</li><li>Localization</li><li>A/B testing</li><li>Versioning</li><li>Collaboration with design teams</li></ul><h3>Transactional vs Marketing Emails</h3><p>Not every email should be treated equally.</p><h3>Transactional Emails</h3><p>These are essential for product functionality.</p><p>Examples:</p><ul><li>OTP</li><li>Password Reset</li><li>Login Alert</li><li>Invoice</li><li>Receipt</li><li>Subscription Confirmation</li></ul><p>These require extremely high delivery guarantees.</p><h3>Marketing Emails</h3><p>Examples include:</p><ul><li>Product announcements</li><li>Newsletters</li><li>Promotions</li><li>Offers</li></ul><p>These require:</p><ul><li>User consent</li><li>Unsubscribe links</li><li>Campaign analytics</li><li>Compliance with privacy regulations</li></ul><p>Separating these two categories prevents marketing traffic from affecting critical transactional emails.</p><h3>Retry Strategy</h3><p>Failures are inevitable.</p><p>Network interruptions.</p><p>Provider outages.</p><p>Temporary rate limits.</p><p>Your retry mechanism should distinguish between temporary and permanent failures.</p><p>A common exponential backoff strategy looks like:</p><pre>Attempt 1</pre><pre>↓</pre><pre>Retry after 1 minute</pre><pre>↓</pre><pre>Retry after 5 minutes</pre><pre>↓</pre><pre>Retry after 15 minutes</pre><pre>↓</pre><pre>Retry after 30 minutes</pre><pre>↓</pre><pre>Dead Letter Queue</pre><p>Permanent failures such as invalid email addresses should never be retried endlessly.</p><h3>Dead Letter Queue (DLQ)</h3><p>After multiple unsuccessful attempts, failed messages should be moved into a Dead Letter Queue.</p><pre>Queue</pre><pre>↓</pre><pre>Worker</pre><pre>↓</pre><pre>Failure</pre><pre>↓</pre><pre>Retry</pre><pre>↓</pre><pre>Failure</pre><pre>↓</pre><pre>Retry</pre><pre>↓</pre><pre>DLQ</pre><p>This allows engineers to inspect problematic messages without blocking the rest of the system.</p><p>DLQs are an essential component of resilient distributed systems.</p><h3>Email Status Tracking</h3><p>Production systems track every email.</p><p>A typical lifecycle is:</p><pre>Queued</pre><pre>↓</pre><pre>Processing</pre><pre>↓</pre><pre>Sent</pre><pre>↓</pre><pre>Delivered</pre><pre>↓</pre><pre>Opened</pre><pre>↓</pre><pre>Clicked</pre><p>Other possible states include:</p><ul><li>Failed</li><li>Deferred</li><li>Bounced</li><li>Spam Complaint</li><li>Unsubscribed</li></ul><p>This information becomes invaluable for debugging customer issues and measuring system health.</p><h3>Webhooks</h3><p>Modern email providers send asynchronous callbacks whenever something happens.</p><p>Examples include:</p><ul><li>Delivered</li><li>Opened</li><li>Clicked</li><li>Bounced</li><li>Dropped</li><li>Spam Complaint</li></ul><pre>Email Provider</pre><pre>↓</pre><pre>Webhook</pre><pre>↓</pre><pre>Your API</pre><pre>↓</pre><pre>Update Database</pre><p>Without webhooks, your application has no visibility into what happened after an email was accepted by the provider.</p><h3>Security Considerations</h3><p>A production email system should never expose credentials inside source code.</p><p>Instead:</p><ul><li>Store API keys in Azure Key Vault or another secrets manager.</li><li>Rotate credentials regularly.</li><li>Encrypt sensitive configuration.</li><li>Validate recipient addresses.</li><li>Limit attachment size and file types.</li><li>Sanitize template variables.</li><li>Protect against email header injection.</li></ul><h3>Email Authentication</h3><p>To maximize inbox placement, configure your domain with:</p><ul><li><strong>SPF</strong> — Defines which servers may send emails on behalf of your domain.</li><li><strong>DKIM</strong> — Cryptographically signs outgoing messages.</li><li><strong>DMARC</strong> — Specifies how receiving servers should handle authentication failures.</li></ul><p>Without these records, legitimate emails often land in spam folders.</p><h3>Observability</h3><p>One of the biggest mistakes teams make is assuming that “accepted by the provider” means “delivered.”</p><p>A mature email platform exposes operational metrics such as:</p><ul><li>Emails queued</li><li>Emails sent</li><li>Delivery rate</li><li>Bounce rate</li><li>Open rate</li><li>Click-through rate</li><li>Retry count</li><li>Queue depth</li><li>Average processing latency</li><li>Worker utilization</li><li>Failed deliveries</li></ul><p>These metrics should be integrated with centralized monitoring tools such as Azure Monitor, Application Insights, Prometheus, Grafana, or Datadog.</p><h3>Scalability</h3><p>Suppose your application grows from sending 100 emails per day to one million.</p><p>The architecture should scale horizontally.</p><pre>Queue</pre><pre>      ┌─────────────┼─────────────┐<br>      ▼             ▼             ▼</pre><pre> Worker 1      Worker 2      Worker 3</pre><pre>      ▼             ▼             ▼</pre><pre> Email Provider Cluster</pre><p>Adding more workers increases throughput without changing business logic.</p><p>This is horizontal scalability in action.</p><h3>Idempotency</h3><p>Distributed systems must assume that duplicate events can occur. Imagine a payment service retries publishing an event due to a timeout. Without idempotency, the customer may receive two invoices.</p><p>To prevent duplicates:</p><ul><li>Assign every email request a unique message ID.</li><li>Store processed message IDs.</li><li>Ignore repeated events with the same identifier.</li></ul><p>Idempotency is critical for reliable event processing.</p><h3>High Availability</h3><p>Production systems should avoid a single point of failure.</p><p>Strategies include:</p><ul><li>Multiple worker instances</li><li>Queue replication</li><li>Provider failover</li><li>Health checks</li><li>Auto-scaling</li><li>Circuit breakers</li><li>Bulkhead isolation</li></ul><p>If one worker crashes, another should continue processing queued emails.</p><h3>A Production-Ready Architecture</h3><p>Putting everything together, a modern email platform looks like this:</p><pre>User Action<br>                     │<br>                     ▼<br>              Business Service<br>                     │<br>                     ▼<br>          Persist Business Transaction<br>                     │<br>                     ▼<br>           Publish Email Event<br>                     │<br>                     ▼<br>               Message Queue<br>                     │<br>         ┌───────────┴───────────┐<br>         ▼                       ▼<br>   Email Worker 1         Email Worker 2<br>         │                       │<br>         └───────────┬───────────┘<br>                     ▼<br>          Template Rendering Engine<br>                     │<br>                     ▼<br>            Secret Manager / Vault<br>                     │<br>                     ▼<br>            Email Provider API<br>                     │<br>                     ▼<br>             Recipient Mail Server<br>                     │<br>                     ▼<br>            Delivery Webhooks<br>                     │<br>                     ▼<br>          Email Status Database<br>                     │<br>                     ▼<br>      Monitoring &amp; Observability</pre><p>This architecture is:</p><ul><li>Loosely coupled</li><li>Highly scalable</li><li>Fault tolerant</li><li>Observable</li><li>Secure</li><li>Easy to extend</li><li>Resilient to failures</li></ul><h3>Final Thoughts</h3><p>Email is often treated as a secondary feature, but in reality, it is a distributed system that sits at the intersection of user experience, infrastructure, security, and reliability.</p><p>By embracing asynchronous processing, event-driven communication, message queues, retries, idempotency, observability, and proper authentication, you can transform a simple notification feature into a robust platform capable of supporting millions of users.</p><p>The next time you write sendEmail(), remember that in production, it&#39;s rarely just a function call. Behind it lies a carefully designed system that ensures every message reaches the right user, at the right time, even when parts of the infrastructure inevitably fail.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21e9d9ea883f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Zomato, Uber, and Razorpay Handle Millions of Payments Without Losing a Rupee — And How You Can…]]></title>
            <link>https://medium.com/@shivt681/how-zomato-uber-and-razorpay-handle-millions-of-payments-without-losing-a-rupee-and-how-you-can-a14777ddfa46?source=rss-a79301a41587------2</link>
            <guid isPermaLink="false">https://medium.com/p/a14777ddfa46</guid>
            <category><![CDATA[fintech]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Shivam Tripathi]]></dc:creator>
            <pubDate>Wed, 15 Jul 2026 19:03:58 GMT</pubDate>
            <atom:updated>2026-07-15T19:03:58.237Z</atom:updated>
            <content:encoded><![CDATA[<h3>How Zomato, Uber, and Razorpay Handle Millions of Payments Without Losing a Rupee — And How You Can Too</h3><blockquote>How money actually moves when someone clicks “Pay Now” — and how companies like Zomato, Uber, and Razorpay built systems that never lose a rupee. Written for everyone from complete beginners to engineers architecting at scale.</blockquote><p><strong>📖 ~35 min read · ⚡ Beginner → Advanced · No prior payments knowledge required</strong></p><p>There’s a moment every developer hits with payments. The test transaction works. The demo works. You ship it. Three weeks later, a customer says they were charged twice. Another paid successfully but never got access. A third has money deducted from their bank, but your database shows nothing.</p><p>Payment bugs are different from other bugs. They cost real money, they destroy trust instantly, and — here’s the important part — they’re almost never <em>coding</em> mistakes. They’re <em>understanding</em> mistakes. The developer treated a payment like a simple request-and-response, when it’s actually a multi-step conversation between five different parties, any of whom can go silent at any moment.</p><p>This guide fixes the understanding. We’ll walk through how payments actually work, compare every major payment provider honestly, explain the architecture that keeps production systems safe, and study how Zomato, Razorpay, and Uber solved these problems at massive scale. Code appears only where it genuinely helps — the rest is explained the way a senior engineer would explain it to you over coffee.</p><h3>What This Guide Covers</h3><ol><li>How a Payment Actually Works — The Story of ₹500</li><li>The One Mental Model That Prevents Most Payment Bugs</li><li>Meet the Payment Providers — Who to Use and When</li><li>The Architecture of a Trustworthy Payment System</li><li>Webhooks — How Your App Finds Out What Really Happened</li><li>Security — What You’re Responsible For (And What You’re Not)</li><li>Case Study: Zomato — Surviving the Dinner Rush</li><li>Case Study: Razorpay — The IPL Outage That Taught Indian Fintech a Lesson</li><li>Case Study: Uber — Charging for a Ride Before Knowing the Price</li><li>Scaling to Millions of Users — The Patterns That Matter</li><li>The Go-Live Checklist</li></ol><h3>1. How a Payment Actually Works — The Story of ₹500</h3><p>Let’s follow a single payment from start to finish. Imagine a customer named Priya ordering food worth ₹500 on your app.</p><h3>The Cast of Characters</h3><p>Before the story, meet the players. Every online payment involves at least five parties:</p><p><strong>Priya (the customer)</strong> — has a card, wants food.</p><p><strong>You (the merchant)</strong> — built the app, want the ₹500.</p><p><strong>The payment gateway</strong> — the middleman service (Razorpay, Stripe, LawPay) that securely handles card details so you never have to. Think of it as a professional courier who specializes in transporting money — bonded, insured, and legally certified.</p><p><strong>The card network</strong> — Visa, Mastercard, RuPay. These are the <em>roads</em> the money travels on. They don’t hold the money; they route it.</p><p><strong>The issuing bank</strong> — the bank that gave Priya her card (say, HDFC). This is the only party that can actually say “yes” or “no” to the payment, because they’re the ones holding Priya’s money.</p><h3>The Journey, Step by Step</h3><p><strong>Step 1 — Priya types her card number.</strong> Here’s the first thing most beginners get wrong: her card number should <em>never</em> reach your server. Instead, the input box she’s typing into isn’t really yours — it’s a secure iframe embedded in your page, served directly by the payment gateway. This is called a <strong>Hosted Field</strong>. To Priya, it looks like your checkout page. Technically, she’s typing directly into Razorpay’s (or Stripe’s) system.</p><p><em>Why does this matter?</em> Because if card numbers touched your server, you’d be legally responsible for protecting them under a strict security standard called PCI DSS — which involves audits, penetration tests, and costs that can run into tens of thousands of dollars a year. Hosted Fields make that entire burden the gateway’s problem, not yours.</p><p><strong>Step 2 — The gateway gives you a token.</strong> Instead of the card number, the gateway hands your app a one-time token — a random string like tok_8f3kx92m. This token is useless to a thief: it works exactly once, only with your secret key, and expires in minutes. It&#39;s like a valet ticket — it represents the car, but you can&#39;t drive off with just the ticket.</p><p><strong>Step 3 — Your server asks the gateway to charge.</strong> Your backend takes the token and says: “Charge ₹500 against this token.” Critically, that ₹500 figure must come from <em>your database</em> — never from what the browser sends. (We’ll see why in the security section. Spoiler: a mildly curious user with browser dev tools can change any number the browser sends.)</p><p><strong>Step 4 — The authorization chain.</strong> The gateway forwards the request through the card network to HDFC Bank. HDFC checks: Does Priya have ₹500? Is this card reported stolen? Does this purchase look like fraud? If everything’s fine, HDFC places a <em>hold</em> on ₹500 in her account. Note carefully: <strong>no money has moved yet</strong>. It’s reserved, like a hotel room booking.</p><p><strong>Step 5 — You get an answer… sort of.</strong> The gateway replies to your server: “Looks good so far.” Most developers treat this as the finish line. <strong>It is not.</strong> It’s a progress update. The payment can still fail after this — the bank can reverse it, a 3D Secure verification can time out, Priya’s app can crash mid-flow.</p><p><strong>Step 6 — The webhook: the real answer.</strong> Seconds or minutes later, the gateway sends a message to a special URL on your server — a <strong>webhook</strong> — saying definitively: “Payment succeeded” or “Payment failed.” <em>This</em> is the finish line. This is the only message you should trust to release the food order.</p><p><strong>Step 7 — You fulfil the order.</strong> Your server verifies the webhook is genuinely from the gateway (not a forger), updates the database, and tells the restaurant to start cooking.</p><p>Total elapsed time: usually 2–5 seconds. Number of independent systems involved: at least five. Number of places it can fail: all of them.</p><h3>Authorization vs. Capture — The Hotel Booking Analogy</h3><p>One more concept, because it shapes real product decisions. Most gateways split a payment into two phases:</p><ul><li><strong>Authorization</strong> = reserving the money (the hotel holds your room)</li><li><strong>Capture</strong> = actually taking the money (you check out and pay)</li></ul><p>Why separate them? Because sometimes you don’t know the final amount when the customer commits. Uber authorizes an <em>estimated</em> fare when you book, and captures the <em>actual</em> fare when the trip ends. An online store authorizes when you order and captures when the item ships — so if they can’t fulfil, they simply release the hold instead of processing a refund.</p><p>If your product has any gap between “customer commits” and “final price known,” this two-step flow is the answer — and knowing it exists will save you from building an awkward charge-then-refund system.</p><h3>2. The One Mental Model That Prevents Most Payment Bugs</h3><p>If you remember only one thing from this article, make it this:</p><blockquote><strong><em>A payment is not a request and a response. It is a state machine.</em></strong></blockquote><p>A request-response mindset says: “I called the charge API, it returned success, we’re done.” That mindset produces the bugs from the introduction — double charges, missing fulfillments, ghost payments.</p><p>The state machine mindset says: a payment is an object that moves through defined states, and each state change comes from a verified event:</p><pre>PENDING → PROCESSING → SUCCEEDED → (maybe) REFUNDED<br>                    ↘  FAILED</pre><p>Three rules follow naturally from this model, and they prevent nearly every classic payment bug:</p><p><strong>Rule 1 — Only move forward.</strong> A payment marked SUCCEEDED can never go back to PENDING. So when a late, out-of-order “failed” event arrives for a payment you’ve already confirmed (this genuinely happens — Razorpay explicitly does not guarantee event order), you ignore it. Without this rule, a stale event silently un-pays a paid order.</p><p><strong>Rule 2 — Every event might arrive twice.</strong> Payment gateways guarantee <em>at-least-once</em> delivery of webhooks, not <em>exactly-once</em>. If your server was slow to respond, the gateway resends the same event. If handling “payment succeeded” twice ships two products, that’s your bug, not theirs. The fix is called <strong>idempotency</strong> — designing every operation so running it twice has the same effect as running it once. In practice: every event carries a unique ID; you record processed IDs in your database; if you’ve seen an ID before, you skip it.</p><p><strong>Rule 3 — The webhook is the source of truth.</strong> Not the frontend callback (the user can close the tab). Not the redirect URL (a user can type ?status=success into any URL themselves). Only the cryptographically verified webhook.</p><p>Idempotency deserves one more analogy because it’s the most under-appreciated concept in payments. Think of an elevator button: pressing it five times doesn’t summon five elevators. The system is designed so repeated identical requests produce a single effect. Your payment system needs the same property at three layers — when your server calls the gateway (send an “idempotency key” so a network-retry doesn’t double-charge), when webhooks arrive (skip already-seen event IDs), and in your database itself (a uniqueness rule that makes duplicate records physically impossible to insert).</p><h3>3. Meet the Payment Providers — Who to Use and When</h3><p>There’s no single “best” gateway — there’s the right gateway for your geography, industry, and scale. Here’s the honest breakdown.</p><h3>Stripe — The Default Choice for Most of the World</h3><p>Stripe processes roughly <strong>$1.9 trillion a year</strong> and handles over 500 million API requests per day. For most new applications outside India, it’s the correct default — not because it’s the cheapest, but because it removes the most friction and its documentation genuinely sets the industry standard.</p><p><strong>What makes it great:</strong> You can create an account and accept a test payment within an hour — no merchant account paperwork, no sales calls. Its checkout component automatically handles cards, Apple Pay, Google Pay, and bank authentication steps without extra work from you. And as your product grows, Stripe grows with it: subscriptions (Billing), marketplace payouts (Connect), fraud detection (Radar) are all in the same ecosystem.</p><p><strong>The honest downsides:</strong> The 2.9% + $0.30 fee is real money at scale — a business doing $10M a year pays roughly $290,000 in fees. Stripe can also freeze accounts it flags as high-risk, sometimes with painfully slow resolution. And for Indian businesses, its local payment method support doesn’t match Razorpay’s.</p><p><strong>Choose Stripe when:</strong> you’re building a global SaaS, subscription product, or marketplace, and you want the smoothest path from zero to production.</p><h3>Razorpay — Non-Negotiable for India</h3><p>If your customers pay in rupees, this decision is essentially made for you. Over half of India’s digital payments happen through <strong>UPI</strong> — a real-time bank transfer system with no card involved at all — and Razorpay’s UPI, Netbanking, wallet, and EMI support is the most complete in the market. Zomato, Swiggy, and CRED all route Indian payments through it.</p><p><strong>What makes it great:</strong> One integration covers every way an Indian customer wants to pay. Its ML-based “smart routing” automatically sends each transaction to the bank gateway most likely to approve it (more on this in the case study — the results are remarkable). It also handles India-specific regulatory requirements like RBI card tokenization out of the box.</p><p><strong>The honest downsides:</strong> It’s India-first, so international coverage is limited. Business verification takes longer than Stripe’s instant signup. And one crucial technical quirk: Razorpay does not guarantee webhook events arrive in order — which is exactly why the state machine model from section 2 isn’t optional.</p><p><strong>One workflow difference worth knowing:</strong> Unlike Stripe, Razorpay requires you to create an “Order” on your server <em>before</em> the customer pays. That order ID becomes the thread connecting the whole transaction — a helpful discipline, honestly, because it forces the server-first flow that’s correct anyway.</p><p><strong>Choose Razorpay when:</strong> your customers are in India. Full stop.</p><h3>LawPay — A Lesson in Why Industry-Specific Gateways Exist</h3><p>LawPay looks like a niche product until you understand <em>why</em> it exists — and the reason is a beautiful illustration of how payments and law intertwine.</p><p>US law firms hold client money (settlements, retainers, escrow) in special accounts called <strong>IOLTA trust accounts</strong>. Bar association ethics rules say client money and the firm’s own money must never mix — not even by a few cents. Now here’s the problem: when a client pays through Stripe, Stripe deducts its processing fee <em>from the deposited amount</em>. If that deposit goes into a trust account, the fee deduction has just mixed firm money with client money. That’s a bar violation. Lawyers have faced discipline for exactly this.</p><p>LawPay’s entire architecture exists to solve this one problem: it deposits the <em>full</em> client payment into the trust account and charges all processing fees separately to the firm’s operating account. That’s why it’s approved by all 50 US state bars and processes over $10 billion a year for 150,000+ legal professionals.</p><p>Technically, it works like the others: Hosted Fields collect card or bank details securely, your server charges using a token, webhooks confirm the result. One elegant detail — the same token flow works for both credit cards and eCheck (bank transfer) payments, so your backend doesn’t care which one the client chose.</p><p><strong>Choose LawPay when:</strong> you’re building anything that handles payments for law firms. This isn’t a preference — it’s compliance. The broader lesson: before picking a gateway, always check whether your industry has regulatory constraints a general-purpose provider can’t satisfy.</p><h3>The Rest of the Field, Briefly</h3><p><strong>PayPal</strong> — 400M+ users who already trust it and have money stored in it. Adding a PayPal button can lift conversions meaningfully (Nielsen research suggests up to 44% in some markets). But its developer API is clunky and it redirects users away from your site. Use it as a <em>supplementary</em> button next to your main checkout — not as your primary integration.</p><p><strong>Braintree</strong> — owned by PayPal, and essentially “PayPal with a proper developer API.” One SDK accepts both cards and PayPal. Uber, Airbnb, and Dropbox use it. Choose it when you want native PayPal acceptance without a second integration, or need marketplace split payments.</p><p><strong>Adyen</strong> — the enterprise heavyweight behind Spotify, eBay, and McDonald’s. It owns its entire pipeline (gateway, processor, acquirer, fraud engine), which means higher approval rates and volume-based pricing. But there’s no self-service signup — it’s a sales process, a minimum monthly invoice, and a serious integration effort. Choose it when you’re processing millions per year across multiple countries and have a dedicated payments team.</p><p><strong>Square</strong> — the champion of small businesses that need a physical card reader <em>and</em> an online checkout, with no monthly fees. A restaurant with a counter and a website is the perfect Square customer. Developers wanting deep customization will find it limiting.</p><h3>The Decision Table</h3><p>Your Situation Use This Why Global SaaS / subscriptions <strong>Stripe</strong> Best overall developer experience and ecosystem Customers in India <strong>Razorpay</strong> Only complete UPI + Indian payment stack Legal industry software <strong>LawPay</strong> Trust account compliance — legally required Marketplace with seller payouts <strong>Stripe Connect</strong> or <strong>Braintree</strong> Built for multi-party money flows Want PayPal + cards together <strong>Braintree</strong> One SDK, both methods Enterprise, multi-country, high volume <strong>Adyen</strong> Direct bank relationships, volume pricing Small shop, counter + online <strong>Square</strong> Simplest hardware-to-web setup</p><blockquote><strong><em>One strategic note before moving on:</em></strong><em> serious payment systems eventually run </em>more than one<em> gateway. Keep that thought — it’s the heart of the Zomato case study.</em></blockquote><h3>4. The Architecture of a Trustworthy Payment System</h3><p>Whatever gateway you choose, the shape of a correct payment backend is always the same. Here it is as a picture:</p><pre>Customer&#39;s browser<br>   │  (card details go straight to the gateway via Hosted Fields —<br>   │   your code only ever sees a token)<br>   ▼<br>Your backend<br>   │  1. Look up the price in YOUR database<br>   │  2. Attach an idempotency key<br>   │  3. Ask the gateway to charge<br>   ▼<br>Payment gateway  →  card network  →  customer&#39;s bank<br>   │<br>   │  ...seconds or minutes later...<br>   ▼<br>Your webhook endpoint<br>   │  1. Verify the message is really from the gateway<br>   │  2. Check: have we seen this event before? (skip if yes)<br>   │  3. Hand it to a background queue and reply &quot;received&quot; instantly<br>   ▼<br>Background worker<br>   │  Update the database → grant access → send the email<br>   ▼<br>Your database (the permanent record)</pre><p>Every piece exists for a specific reason, and it’s worth being able to explain each one:</p><p><strong>Why Hosted Fields?</strong> So card data never touches your systems, keeping you out of expensive security-audit territory (more in section 6).</p><p><strong>Why does the price come from your database?</strong> Because anything the browser sends can be edited by the user. A price in a request body is a <em>suggestion</em>; a price in your database is a fact.</p><p><strong>Why an idempotency key?</strong> So that when a network hiccup makes your server retry a charge, the gateway recognizes “I’ve already done this exact request” and doesn’t charge twice.</p><p><strong>Why does the webhook handler pass work to a queue instead of doing it directly?</strong> Two reasons. First, gateways expect a fast acknowledgment (Stripe gives you 30 seconds) — if your handler is busy sending emails, it might time out, and the gateway will think delivery failed and retry, creating duplicate work. Second, a queue means that if your email service is down, the payment record still gets saved and the email retries later. The payment’s success shouldn’t depend on every downstream system being healthy at that exact second.</p><p><strong>Why a traditional SQL database (like PostgreSQL) rather than a trendy NoSQL store?</strong> Because payments demand <em>strong consistency</em> — the guarantee that a record is either fully written or not written at all, never half-written, and that two simultaneous updates can’t silently overwrite each other. SQL databases have provided these guarantees (called ACID) for decades. Payment records are the last place to experiment.</p><p>The only table design worth showing, because it encodes two ideas in structure itself:</p><pre>CREATE TABLE transactions (<br>  id               UUID PRIMARY KEY,<br>  order_id         UUID NOT NULL,<br>  gateway_txn_id   VARCHAR UNIQUE,     -- one gateway charge = one row, enforced by the DB<br>  idempotency_key  VARCHAR UNIQUE,     -- duplicates physically impossible to insert<br>  amount           INTEGER NOT NULL,   -- in the smallest unit: paise/cents, never decimals<br>  status           VARCHAR DEFAULT &#39;pending&#39;,<br>  created_at       TIMESTAMPTZ DEFAULT NOW()<br>);</pre><p>Two details reward attention. The UNIQUE constraints mean duplicate charges aren&#39;t prevented by careful code — they&#39;re prevented by the database refusing the insert. Defense in structure beats defense in logic. And amounts are stored as whole integers of the smallest unit (₹500 = 50000 paise) because computers famously cannot do decimal math precisely — 0.1 + 0.2 does not equal 0.3 in most programming languages, and payment systems have lost real money to that quirk.</p><h3>5. Webhooks — How Your App Finds Out What Really Happened</h3><p>Webhooks deserve their own section because they’re the most misunderstood — and most critical — part of any payment integration.</p><p><strong>What a webhook is, in plain terms:</strong> you give the gateway a URL on your server. Whenever something happens to a payment — succeeded, failed, refunded, disputed — the gateway sends an HTTP message to that URL. It’s the gateway calling <em>you</em>, instead of you repeatedly asking the gateway “is it done yet?”</p><p><strong>Why they exist at all:</strong> because the final result of a payment can arrive after the customer is gone. Priya’s phone dies right after she authorizes the UPI payment. Her money left her account — but your frontend never got the memo, because the app was dead. Without webhooks, you’d have her money and no record of it. With webhooks, the gateway tells your <em>server</em> directly, regardless of what happened to her phone.</p><p>Five rules govern webhook handling. Learn them once and you’re ahead of most implementations in production today:</p><p><strong>1. Verify every signature.</strong> Your webhook URL is just a URL — anyone who discovers it can send a fake “payment succeeded” message and get free products. Every gateway signs its messages cryptographically (using a shared secret only you two know). Checking that signature is 3–5 lines of code with the gateway’s library, and skipping it is the single most dangerous shortcut in payments.</p><p><strong>2. Expect duplicates.</strong> As covered in the mental model: at-least-once delivery means the same event may arrive twice. Track event IDs; skip what you’ve seen.</p><p><strong>3. Acknowledge fast, work later.</strong> Reply “received” immediately; do the actual database updates and emails in a background job.</p><p><strong>4. Expect disorder.</strong> Especially with Razorpay, events can arrive out of chronological sequence. Your state machine rules (only move forward) handle this automatically.</p><p><strong>5. Watch your failures.</strong> Events that repeatedly fail processing should land in a “dead letter queue” — a holding pen for problem events. Here’s the reframe that makes teams take it seriously: <em>every item in that queue is money in an unknown state.</em> A failed webhook might be an unfulfilled paid order or an unprocessed refund. Monitor it like you monitor revenue, because it is revenue.</p><p><strong>And one safety net beneath everything: daily reconciliation.</strong> Once a day, an automated job asks the gateway “list every successful payment from yesterday” and compares against your database. Any payment the gateway knows about but you don’t means a webhook slipped through every defense — and the job fixes it automatically. Accountants have done exactly this, by hand, for centuries; you’re just automating a very old and very wise practice. In the case studies below, you’ll see this isn’t paranoia — even the best-engineered systems miss events.</p><h3>6. Security — What You’re Responsible For (And What You’re Not)</h3><p>Payment security sounds intimidating, but the modern division of labor is actually generous to you — <em>if</em> you set things up correctly.</p><p><strong>PCI DSS</strong> is the global security standard for anyone touching card data. Compliance comes in tiers, and your integration choice determines which tier you land in:</p><ul><li><strong>Use Hosted Fields / Stripe Elements</strong> (card data never touches your systems) → you’re in the lightest tier: an annual self-assessment questionnaire. A form. That’s it.</li><li><strong>Handle raw card data on your server</strong> → the heaviest tier: annual audits, penetration tests, quarterly scans, costs easily exceeding $50,000/year.</li></ul><p>The entire reason Hosted Fields exist is to put you in the first bucket. There is almost never a good reason for a normal application to be in the second.</p><p>Beyond PCI, your actual responsibilities fit in a short list:</p><p><strong>Prices come from your database.</strong> Worth repeating because it’s the most commonly exploited beginner mistake. If your API accepts an amount from the browser, a user can open dev tools, change ₹4,999 to ₹1, and buy your premium plan for one rupee. The gateway won’t stop them — from its perspective, you asked to charge ₹1 and it charged ₹1.</p><p><strong>Secrets live in a secrets manager, never in code.</strong> Your gateway secret key can charge and refund money. If it’s committed to a git repository — even a private one — treat it as leaked. Automated bots scan public repos for payment keys within <em>minutes</em> of a push.</p><p><strong>Never log sensitive data.</strong> Card numbers, tokens, bank accounts — none of it belongs in your logs, error messages, or analytics. Logs get shipped to third-party tools, shared in Slack during debugging, and retained for years. A card number in a log file is a breach waiting to be discovered.</p><p><strong>Rate-limit your payment endpoints.</strong> There’s an attack called <em>card testing</em>: fraudsters with a stolen list of card numbers use someone’s checkout page to test which cards still work, firing hundreds of small charges. If your endpoint allows unlimited attempts, congratulations — you’re their free testing lab, and the resulting chargebacks and gateway penalties land on you. A simple limit (say, ten attempts per user per 15 minutes) shuts this down.</p><p><strong>Use HTTPS everywhere.</strong> Including webhooks. This should go without saying in 2025+, so we’ll leave it at that.</p><h3>7. Case Study: Zomato — Surviving the Dinner Rush</h3><p><strong>The setting:</strong> Zomato processes millions of food orders daily across 800+ Indian cities. Demand isn’t smooth — it’s two daily tidal waves, at lunch and dinner, where volume multiplies within minutes. And food delivery is uniquely unforgiving of payment failure: nobody re-attempts a failed dinner order patiently. They open the competitor’s app.</p><p><strong>The problem:</strong> in its early architecture, one payment gateway handled everything. Which meant every gateway outage, every bank downtime, every degraded UPI provider became a <em>complete checkout outage</em> for Zomato — always, by Murphy’s law, during peak hours.</p><p><strong>The solution — never depend on one gateway:</strong> Zomato’s payment service integrates with multiple gateways simultaneously — Razorpay, PayU, Cashfree, Stripe among them — with order confirmation and payment recording handled atomically so records stay consistent across their microservices. Which gateway handles a given payment depends on the country and the payment method the customer chose.</p><p>Conceptually, their routing layer answers three questions for every single transaction:</p><ol><li><strong>What’s the payment method?</strong> UPI payments route to whichever gateway has the strongest UPI performance; cards may route elsewhere entirely.</li><li><strong>How healthy is each gateway right now?</strong> Not “is it up according to its status page” — but “what’s its actual success rate and response time over the last sixty seconds of <em>our own</em> traffic?” The system continuously measures reality rather than trusting promises.</li><li><strong>If the first choice fails, who’s next?</strong> Every payment has a fallback chain. If the primary gateway errors or slows down, the payment silently retries through the second gateway. Priya never sees a failure — she sees a payment that took two seconds longer.</li></ol><p>It’s an airline booking philosophy applied to payments: never one route to the destination; always a rebooking path ready before the disruption happens.</p><p><strong>The refund lesson hiding inside:</strong> food delivery generates constant refunds (restaurant runs out of an item, order cancelled in the allowed window). Zomato’s rule is one worth adopting universally: <em>refunds always flow back through the same gateway that took the original payment</em>, matched by transaction ID, protected by the same idempotency discipline so a retried refund can’t pay a customer twice.</p><p><strong>What you should copy — even as a solo developer:</strong> you don’t need three gateways on launch day. But you should build the <em>seam</em> for them from day one. Concretely: never call a gateway’s API directly from your business logic. Put one thin layer — a PaymentService — between your app and the gateway, so your code says &quot;charge this order&quot; and only that one layer knows <em>how</em>. It costs perhaps an afternoon now. Retrofitting it into a live system with money flowing through it costs weeks of terrifying migration work. Every scaled company either built this seam early or painfully wished they had.</p><h3>8. Case Study: Razorpay — The IPL Outage That Taught Indian Fintech a Lesson</h3><p>This is one of the most instructive failure stories in Indian fintech, told openly by Razorpay’s own engineering team — which is exactly why it’s worth studying.</p><p><strong>The setting:</strong> the Indian Premier League is India’s biggest sporting event, with tens of millions watching. And minutes before every match, food delivery apps and gaming platforms launch flash sales, all funnelling payments through Razorpay <em>at the same moment</em>.</p><p><strong>The failure:</strong> during IPL 2019, Razorpay went down three days in a row. The specific reason is the lesson: their traffic would leap from a baseline of 200 requests per second to <strong>1,500 requests per second within seconds</strong> of a match starting. Their AWS infrastructure was configured to autoscale — but autoscaling took 3–4 minutes to bring new servers online. The flood arrived in seconds; the reinforcements arrived in minutes. The system drowned in the gap.</p><p>That gap — <em>reactive scaling versus instantaneous demand</em> — is a general truth about traffic bursts, not a Razorpay quirk. Autoscaling handles gradual growth beautifully. It cannot handle a vertical wall of traffic.</p><p><strong>Fix #1 — Stop reacting; start anticipating.</strong> Razorpay built a system where merchants declare expected peak traffic <em>in advance</em> (“our flash sale starts at 7:25pm, expect 800 TPS”). Before the event, everything — servers, queues, caches — is pre-scaled to the declared peak plus a safety buffer, then scaled back down afterwards. The mindset shift: treat a known traffic event like a scheduled deployment, not a surprise to react to. If you know your marketing campaign fires at 6pm, your infrastructure should be ready at 5:45.</p><p><strong>Fix #2 — Let a machine choose the route.</strong> The subtler problem: during these bursts, <em>the banks’ own systems</em> degraded under load too. Razorpay had always rerouted payments away from struggling banks — but a human changed those routing rules manually. At 1,500 requests per second, human-speed decisions are uselessly slow.</p><p>So they built an ML system that watches every payment succeed or fail in real time, across dimensions like card type, card network (Visa/Mastercard/RuPay), and issuing bank. For each new payment, it computes the probability of success through each available banking route and automatically sends the payment down the most promising one. The published result: <strong>a 60% improvement in payment success rates</strong> during burst events. Behind every payment on a big match night, a model is quietly picking the healthiest road through India’s banking infrastructure.</p><p><strong>Fix #3 — Solve the “two writes” problem properly.</strong> As Razorpay broke their original monolithic system into microservices, they hit a classic distributed-systems trap. When a payment succeeds, you must do two things: save it to your database <em>and</em> announce it (via a message stream like Kafka) so other services — notifications, analytics, settlements — can react. But those are two separate systems, and you cannot make two systems atomic by wishing. If you save to the database and then crash before announcing, other services never learn the payment happened. Announce first and then fail to save, and you’ve told the world about a payment you have no record of. Either way: silent inconsistency, with money involved.</p><p>Their answer is a pattern every payments engineer should know by name: the <strong>Transactional Outbox</strong>. Instead of writing to two systems, write twice to <em>one</em> — the payment record and a small “message to announce later” row go into the same database, in the same atomic transaction, so both exist or neither does. A separate background process then reads pending announcements from that outbox table and publishes them, retrying as long as it takes. If the messaging system is down for an hour, no announcement is lost — it’s sitting safely in the database, waiting. Razorpay liked the pattern enough to build and open-source their own library (“Outboxer”) for it.</p><p>The everyday analogy: don’t hand a letter directly to a courier who might not show up — drop it in your own outbox, where it physically exists until someone reliably collects it.</p><p><strong>The takeaways, compressed:</strong> pre-scale for what you can predict; automate decisions that must happen faster than humans can think; and when one action must update two systems, use the outbox pattern instead of hoping both calls succeed.</p><h3>9. Case Study: Uber — Charging for a Ride Before Knowing the Price</h3><p><strong>The setting:</strong> Uber runs tens of millions of trips a day across 70+ countries, and its payment problem is structurally unusual: <em>the price isn’t known when the customer commits.</em> The fare depends on route, time, and surge pricing — none finalized until the trip ends. And the customer must not be asked to pull out their phone and approve a charge at the destination.</p><p><strong>The elegant answer — authorization holds.</strong> Remember the hotel-booking concept from section 1? Uber’s checkout is its purest real-world expression. When you request a ride, Uber’s payment system evaluates the situation and — guided by its risk engine — either places an <em>authorization hold</em> for the estimated fare (money reserved, not taken) or, for riskier profiles, charges upfront. The trip happens. The final fare is computed. Then Uber <em>captures</em> the actual amount against the hold — which can legitimately be less than what was authorized, with the difference automatically released back to the rider.</p><p>No end-of-trip payment screen, no risk of a rider whose card fails after the service is already delivered. The two-phase payment model isn’t a technicality here — it’s what makes the entire “get out of the car and walk away” experience possible.</p><p><strong>The gatekeeper — a risk engine with half a second to decide.</strong> Before any hold is placed, Uber’s risk system must answer “should we let this trip happen at all?” — in a fraction of a second, invisibly. It weighs the rider’s payment history, account age, device signals, and velocity patterns (many trips from one device or card in a short window is a classic stolen-card signature — fraudsters famously resell “discounted” rides booked on stolen cards). The output isn’t just yes/no; it actively <em>chooses the payment strategy</em> — hold versus upfront charge — per transaction, per rider.</p><p>The takeaway generalizes well beyond ride-hailing: risk isn’t a bolt-on fraud filter that runs after checkout. In mature systems, risk assessment <em>shapes</em> the checkout flow itself.</p><p><strong>The nervous system — events, not phone calls.</strong> Underneath, Uber’s payment platform is built as microservices communicating through <strong>Apache Kafka</strong>, a stream-processing backbone carrying billions of messages daily. The design philosophy matters more than the tool: services <em>announce events</em> (“trip completed,” “payment captured”) rather than calling each other directly and waiting for replies.</p><p>Why is that better at scale? Because direct calls create chains of dependency — if the receipts service is slow, and payments calls it directly, payments becomes slow, and everything upstream of payments follows. With event streams, the payment service announces “captured” and moves on; receipts, ledgers, and analytics each consume that event at their own pace. If a downstream provider goes down entirely, its transactions queue for retry rather than failing the ride. One slow component degrades gracefully instead of toppling dominoes.</p><p><strong>The masterclass — migrating payment code with zero downtime.</strong> One more Uber technique deserves its own paragraph because you may someday need it. When Uber rebuilt their authorization system, they faced the scariest task in payments: replacing live money-handling code without breaking anything. Their method, called <strong>shadow mode</strong>: keep the old system serving real traffic, and cache every request it sends to payment providers along with every response it receives. Then <em>replay</em> that same traffic against the new system — which builds its requests and computes its state transitions, but never actually contacts the providers (responses are replayed from cache instead, since you can’t charge a card twice for a test). Compare the two systems’ behavior, side by side, on real production traffic.</p><p>Running this for a few days surfaced <em>dozens</em> of subtle mismatches and edge cases in the new system — every one of them caught before a single real customer was affected. The principle applies to any high-stakes migration: never cut over cold; run both, compare relentlessly, and switch only when the shadows match.</p><h3>10. Scaling to Millions of Users — The Patterns That Matter</h3><p>A recalibration first, because the numbers surprise people: a million transactions per day averages only about <strong>12 per second</strong>. Even dramatic flash sales peak around 500–1,500 per second — figures a modest, well-configured setup can serve. Payments is not a raw-throughput problem.</p><p>The real challenges at scale are <strong>correctness under pressure</strong> and <strong>surviving other people’s failures</strong>. Four patterns cover most of it — three you’ve already met in the case studies:</p><p><strong>Pre-scale for predictable spikes</strong> <em>(Razorpay’s lesson)</em>. Autoscaling reacts in minutes; bursts arrive in seconds. For any traffic event you can foresee, scale up beforehand.</p><p><strong>Multi-gateway with health-based routing</strong> <em>(Zomato’s lesson)</em>. One gateway is one point of failure. The abstraction seam costs an afternoon early and weeks later.</p><p><strong>The transactional outbox</strong> <em>(Razorpay’s lesson)</em>. Whenever one action must update your database <em>and</em> notify other systems, write both to the database atomically and publish asynchronously.</p><p><strong>Circuit breakers</strong> <em>(the one new idea)</em>. Named after the electrical device, and behaving the same way. When a gateway starts failing, the naive system keeps sending requests, each waiting out a long timeout — tying up resources until the caller itself collapses. This is how one provider’s bad hour becomes <em>your</em> outage. A circuit breaker watches the failure rate, and past a threshold it “trips”: requests fail instantly (or reroute to a backup) instead of queuing up to wait for a corpse. Periodically it lets one test request through; when the gateway recovers, the circuit closes and normal flow resumes. The counterintuitive wisdom: at scale, <em>failing fast is a feature</em>. A system that immediately says “primary is down, using backup” is far healthier than one that makes every customer wait 30 seconds to learn the same thing.</p><p>And beneath all four, the humble safety net from section 5 — <strong>daily reconciliation</strong> — quietly catches whatever slips past everything else. Scale doesn’t change that; it just raises the price of skipping it.</p><h3>11. The Go-Live Checklist</h3><p>Before your first real transaction, walk this list. Every line traces back to a failure mode covered in this guide — none of it is theoretical.</p><p><strong>Foundations</strong></p><ul><li>✅ Card inputs use Hosted Fields / gateway elements — card data never touches your code</li><li>✅ Every charge amount is read from your database, never from the request</li><li>✅ Secret keys live in a secrets manager, not in the codebase</li><li>✅ Payment endpoints are rate-limited against card-testing attacks</li></ul><p><strong>The state machine</strong></p><ul><li>✅ Payment statuses only move forward — stale events can’t overwrite terminal states</li><li>✅ Idempotency keys accompany every charge request</li><li>✅ Database uniqueness constraints make duplicate transactions impossible to insert</li><li>✅ Amounts stored as integers of the smallest unit — no decimals, ever</li></ul><p><strong>Webhooks</strong></p><ul><li>✅ Signature verified on every event, no exceptions</li><li>✅ Event IDs tracked; duplicates skipped</li><li>✅ Handler acknowledges instantly; real work happens in a background queue</li><li>✅ Dead letter queue exists — and someone actually monitors it</li><li>✅ Daily reconciliation job compares gateway records against your database</li></ul><p><strong>Test the failures, not just the success</strong></p><ul><li>✅ A declined card produces a clear, human-readable error</li><li>✅ The same payment submitted twice results in exactly one charge</li><li>✅ A replayed webhook does not double-fulfil</li><li>✅ A deliberately “missed” webhook is caught by reconciliation</li><li>✅ 3D Secure / bank-authentication flows complete properly on real mobile devices</li></ul><p><strong>Operations</strong></p><ul><li>✅ Alert fires when the webhook endpoint starts erroring</li><li>✅ Alert fires when payment failure rates spike (gateway trouble — or an attack)</li><li>✅ A written runbook exists for: gateway outage, account freeze, chargeback surge</li><li>✅ If you have a backup gateway, the failover has actually been tested</li></ul><h3>Closing Thoughts</h3><p>Strip away the provider names and the architecture diagrams, and this entire guide reduces to a handful of durable ideas:</p><p><strong>A payment is a state machine, not an API call.</strong> Hold that model and the strange behaviors — duplicate events, out-of-order arrivals, payments confirmed after the customer left — stop being edge cases and become expected inputs your design already handles.</p><p><strong>Trust only the verified webhook.</strong> Not the frontend, not the redirect URL, not the optimistic first response.</p><p><strong>Idempotency everywhere.</strong> Every request retried, every event redelivered, every job re-run must land in the same final state.</p><p><strong>Prices from your database. Secrets in a vault. Nothing sensitive in logs.</strong></p><p><strong>Design for failure, because failure is scheduled.</strong> Zomato assumes gateways will go down and routes around them. Razorpay assumes traffic will spike faster than machines can react and scales ahead of it. Uber assumes providers will fail mid-ride and queues rather than crashes. None of them were being pessimistic — they were being accurate.</p><p>The companies moving billions learned these lessons through outages, incident reviews, and expensive mistakes. You get to learn them from an article. Build the boring, correct foundation first — the state machine, the webhook discipline, the reconciliation job — and payments transform from the scariest part of your product into one of the most dependable.</p><p>That’s the whole secret. Now go build it.</p><p><em>Case study material drawn from the Razorpay Engineering Blog, Uber Engineering Blog, and publicly documented system design analyses. Provider details reflect publicly available documentation as of 2025–2026.</em></p><p><em>Covers: Stripe · Razorpay · LawPay · PayPal · Braintree · Adyen · Square</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a14777ddfa46" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>