<?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 Suresh Kumar Katikala on Medium]]></title>
        <description><![CDATA[Stories by Suresh Kumar Katikala on Medium]]></description>
        <link>https://medium.com/@sureshkumarkatikala?source=rss-924a9adb0ead------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*HH9MlyTH-275Hw_J</url>
            <title>Stories by Suresh Kumar Katikala on Medium</title>
            <link>https://medium.com/@sureshkumarkatikala?source=rss-924a9adb0ead------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 21:50:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sureshkumarkatikala/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 Payment Gateway Orchestration Layer: A System Design Deep Dive]]></title>
            <link>https://medium.com/@sureshkumarkatikala/building-a-payment-gateway-orchestration-layer-a-system-design-deep-dive-209878f20fdc?source=rss-924a9adb0ead------2</link>
            <guid isPermaLink="false">https://medium.com/p/209878f20fdc</guid>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[payment-gateway]]></category>
            <category><![CDATA[fintech]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[payments]]></category>
            <dc:creator><![CDATA[Suresh Kumar Katikala]]></dc:creator>
            <pubDate>Thu, 29 Jan 2026 20:21:37 GMT</pubDate>
            <atom:updated>2026-01-29T20:37:45.214Z</atom:updated>
            <content:encoded><![CDATA[<h4>What happens between “Pay Now” and “Payment Successful”? Here’s the complete behind-the-scenes breakdown.</h4><p>When you’re building a platform that accepts payments across multiple providers — Stripe, Razorpay, Payoneer — things get complex fast. Each gateway has different APIs, different webhook formats, and different quirks.</p><p>In this article, I’ll walk you through how I built a unified payment gateway orchestration layer that handles all of this complexity behind a single, clean abstraction.</p><h3>The Problem</h3><p>Imagine you’re building an e-commerce platform that needs to support multiple payment gateways. Your challenges include:</p><ul><li>Different APIs: Stripe uses one format, Razorpay uses another</li><li>Async webhooks: Payment confirmations arrive asynchronously and can be delayed</li><li>Reliability concerns: Webhooks can fail, duplicate, or never arrive at all</li><li>Consistency: You need a single source of truth for payment status</li><li>Scale: The system needs to handle thousands of concurrent payments</li></ul><p>The solution? A unified orchestration layer that abstracts all payment providers behind a single interface.</p><h3>The Architecture</h3><p>Here’s the high-level view of what we’re building:</p><pre>┌─────────────┐     ┌─────────────┐     ┌─────────────┐     ┌─────────────┐<br>│   CLIENT    │     │   PAYMENT   │     │   PAYMENT   │     │  DOWNSTREAM │<br>│   (Web/App) │────▶│   GATEWAY   │────▶│   GATEWAYS  │────▶│  SERVICES   │<br>│             │◀────│   SERVICE   │◀────│(Stripe/Rzp) │     │  (Wallet)   │<br>└─────────────┘     └──────┬──────┘     └─────────────┘     └─────────────┘<br>                           │<br>                           ▼<br>                    ┌─────────────┐<br>                    │    KAFKA    │<br>                    │  (Webhooks) │<br>                    └─────────────┘</pre><h4>The Complete Flow</h4><p><em>PHASE 1: Token Generation</em></p><p>When a user clicks “Pay Now,” the frontend doesn’t talk directly to Stripe or Razorpay. Instead, it asks our backend to create a payment session.</p><pre>Frontend                 Backend PG Service                Gateway<br>    │                          │                              │<br>    │  POST /createPayment     │                              │<br>    │  { amount, currency,     │                              │<br>    │    orderId, gateway }    │                              │<br>    │─────────────────────────▶│                              │<br>    │                          │   POST /v1/orders            │<br>    │                          │   { amount, currency }       │<br>    │                          │─────────────────────────────▶│<br>    │                          │                              │<br>    │                          │   { order_id: &quot;xyz123&quot; }     │<br>    │                          │◀─────────────────────────────│<br>    │                          │                              │<br>    │                          │  Save to DB: status=INITIATED│<br>    │                          │                              │<br>    │  { token: &quot;xyz123&quot; }     │                              │<br>    │◀─────────────────────────│                              │</pre><p>What happens here:</p><ol><li>Frontend sends payment details (amount, currency, order ID) to our backend</li><li>Backend calls the payment gateway’s API to create an order</li><li>Gateway returns an order ID (this becomes our “token”)</li><li>Backend saves the transaction to our database with status “INITIATED”</li><li>Token is returned to the frontend</li></ol><p>The token is essentially a session ID that links the frontend payment popup to our backend record. This is crucial for tracking the payment through its entire lifecycle.</p><p><em>PHASE 2: Payment Popup</em></p><p>Frontend receives the token and initializes the gateway’s SDK:</p><pre>const razorpay = new Razorpay({<br>order_id: token, // Token from backend<br>amount: 100000,<br>handler: (response) =&gt; {<br>startPolling(); // Start checking for status<br>}<br>});<br>razorpay.open(); // Opens payment popup</pre><p>The user sees a hosted payment page from the gateway. They select their payment method — credit card, debit card, UPI, net banking — and complete the payment.</p><p>Here’s the key insight: The frontend doesn’t know immediately if the payment succeeded. The gateway processes the payment and sends a webhook to our backend <em>asynchronously</em>. So the frontend starts polling our backend every few seconds:</p><p><em>PHASE 3: Webhook Processing via Kafka</em></p><p>This is where it gets interesting. When the payment completes on the gateway side, they send a webhook to our system. But instead of processing it synchronously, we publish it to Kafka.</p><pre>Razorpay                    Webhook Handler              Kafka<br>    │                              │                       │<br>    │  POST /webhook               │                       │<br>    │  { event: &quot;payment.captured&quot;,│                       │<br>    │    payment_id, order_id,     │                       │<br>    │    amount, method }          │                       │<br>    │─────────────────────────────▶│                       │<br>    │                              │                       │<br>    │                              │  Publish to topic     │<br>    │                              │  &quot;webhook.razorpay&quot;   │<br>    │                              │──────────────────────▶│<br>    │                              │                       │</pre><p>Why Kafka instead of direct processing?</p><ol><li>Durability: If our service is down, events are stored in Kafka and processed when we’re back up</li><li>Retry capability: Failed processing can be retried automatically</li><li>Decoupling: The webhook handler responds immediately; processing happens separately</li><li>Scalability: We can add more consumers if needed</li></ol><p><em>PHASE 4: Validation &amp; Status Update</em></p><p>Our Kafka consumer picks up the webhook event and processes it. But here’s the critical part: we never trust the webhook data blindly.</p><pre>Kafka Consumer        Backend PG Service                Razorpay API<br>    │                          │                              │<br>    │  Consume webhook event   │                              │<br>    │─────────────────────────▶│                              │<br>    │                          │                              │<br>    │                          │  1. Find record in DB        │<br>    │                          │     by order_id              │<br>    │                          │                              │<br>    │                          │  2. Check: already processed?│<br>    │                          │     if status=SUCCESS, skip  │<br>    │                          │                              │<br>    │                          │  3. GET /v1/payments/{id}    │<br>    │                          │─────────────────────────────▶│<br>    │                          │                              │<br>    │                          │  { status, amount, order_id }│<br>    │                          │◀─────────────────────────────│<br>    │                          │                              │<br>    │                          │  4. Validate:                │<br>    │                          │     ✓ Status = captured      │<br>    │                          │     ✓ Amount matches DB      │<br>    │                          │     ✓ Order ID matches       │<br>    │                          │                              │<br>    │                          │  5. Update DB: status=SUCCESS│<br>    │                          │     (with row locking)       │</pre><p>Why re-validate with the gateway API?</p><p>Webhooks can be spoofed. An attacker could send a fake webhook claiming a payment succeeded. By calling the gateway’s API directly, we verify the payment status from the source of truth.</p><p>Once validated, we:</p><ol><li>Update our database status to “SUCCESS”</li><li>Publish an event to the wallet service to credit funds</li><li>The wallet service adds the amount to the customer’s account</li></ol><p>Meanwhile, the frontend’s polling finally sees status: SUCCESS and shows the confirmation screen.</p><p><em>Handling Edge Cases</em></p><p>Real-world systems need to handle failures gracefully. Here are the key edge cases and how we solve them.</p><h3>Duplicate Webhooks</h3><p>The same webhook might arrive multiple times (network retries, gateway bugs, etc.). If we process each one, we’d credit funds multiple times.</p><p>Solution: <em>Idempotency + Row Locking</em></p><pre>BEGIN TRANSACTION;<br><br>-- Lock the row to prevent concurrent updates<br>SELECT * FROM payments WHERE id = ? FOR UPDATE;<br><br>-- Check if already processed<br>-- If status is already SUCCESS, we skip<br>IF status = &#39;SUCCESS&#39; THEN<br>    ROLLBACK;<br>    RETURN;<br>END IF;<br><br>-- Process the payment<br>UPDATE payments SET status = &#39;SUCCESS&#39; WHERE id = ?;<br><br>COMMIT;</pre><p>The SELECT FOR UPDATE ensures that even if two webhook processors try to handle the same payment simultaneously, only one will succeed. The other will see status = SUCCESS and skip.</p><h3>Missing Webhooks</h3><p>Sometimes webhooks never arrive. The payment completed on the gateway, but our system doesn’t know about it. The customer is stuck on “Processing…”</p><p>Solution: <em>Scheduled Reconciliation Job</em></p><p>We run a cron job every 30 minutes that:</p><ol><li>Finds all payments stuck in “INITIATED” status for more than 30 minutes</li><li>Calls the gateway API directly to check their actual status</li><li>Updates our database accordingly</li></ol><pre>async function reconcilePayments() {<br>    // Find stuck payments<br>    const stuckPayments = await db.query(`<br>        SELECT * FROM payments <br>        WHERE status = &#39;INITIATED&#39; <br>        AND created_at &lt; NOW() - INTERVAL 30 MINUTE<br>    `);<br>    <br>    for (const payment of stuckPayments) {<br>        // Check with gateway<br>        const gatewayStatus = await gateway.getOrder(payment.external_id);<br>        <br>        if (gatewayStatus === &#39;captured&#39;) {<br>            await processSuccessfulPayment(payment);<br>        } else if (gatewayStatus === &#39;failed&#39;) {<br>            await markPaymentFailed(payment);<br>        }<br>        // If still pending on gateway, leave it alone<br>    }<br>}</pre><p><em>The Gateway Abstraction</em></p><p>One of the most valuable architectural decisions was abstracting payment gateways behind a common interface.</p><pre>           ┌───────────────────────────┐<br>           │    Payment Controller     │<br>           │    (Routes by gateway_id) │<br>           └─────────────┬─────────────┘<br>                         │<br>         ┌───────────────┼───────────────┐<br>         │               │               │<br>         ▼               ▼               ▼<br>  ┌────────────┐  ┌────────────┐  ┌────────────┐<br>  │   Stripe   │  │  Razorpay  │  │  Payoneer  │<br>  │  Service   │  │  Service   │  │  Service   │<br>  └────────────┘  └────────────┘  └────────────┘</pre><p>Each gateway service implements the same interface:</p><pre>interface PaymentService {<br>    createPayment(body: PaymentBody): Promise&lt;PaymentResponse&gt;;<br>    handleWebhook(event: WebhookEvent): Promise&lt;void&gt;;<br>    refund(paymentId: string, amount: number): Promise&lt;RefundResponse&gt;;<br>}</pre><p>Adding a new payment gateway is now trivial: just implement one new service class. The controller, Kafka consumers, database layer, and wallet integration all stay exactly the same.</p><h4>Tech Stack</h4><p><strong>Runtime</strong><br> Node.js + TypeScript</p><p><strong>API</strong><br> Express.js</p><p><strong>Messaging</strong><br> Apache Kafka</p><p><strong>Database</strong><br> MySQL</p><p><strong>Validation</strong><br> Joi</p><p><strong>Monitoring</strong><br> Elastic APM</p><h3>Key Takeaways</h3><p>If you’re building a payment system, here are the principles that matter most:</p><p>1. Never trust webhooks blindly</p><p>Always verify with the payment gateway’s API before crediting funds. Webhooks can be spoofed, replayed, or tampered with.</p><p>2. Event-driven beats synchronous</p><p>Using Kafka (or similar) for webhook processing gives you durability, retries, and decoupling. Your webhook endpoint stays fast; processing happens asynchronously.</p><p>3. Idempotency is non-negotiable</p><p>Duplicate webhooks will happen. Your system must handle them gracefully without double-crediting.</p><p>4. Plan for webhook failures</p><p>Have a reconciliation job that catches payments where webhooks never arrived. No customer should get stuck in “processing” forever.</p><p>5. Abstract early</p><p>Building a gateway abstraction from day one makes adding new payment providers trivial. The investment pays off quickly.</p><h3>Conclusion</h3><p>Building a payment orchestration layer is about more than just integrating APIs. It’s about handling the messy reality of distributed systems: async communication, failures, duplicates, and edge cases.</p><p>The architecture I’ve described here — token-based sessions, Kafka-driven webhooks, double validation, and gateway abstraction — has proven reliable in production handling significant transaction volume.</p><p>The beauty of this design is that the core infrastructure stays stable. Whether you’re adding a new payment method, a new gateway, or scaling to 10x the volume, the fundamentals don’t change.</p><p><em>What’s your biggest challenge with payment integrations? I’d love to hear about it in the comments</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=209878f20fdc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>