Payments——5 min read

Designing Idempotent Payment Webhooks in Next.js

How to handle duplicate Stripe and Khalti webhook events, verify payments, and keep payment and order states consistent when networks fail.

Person holding a credit card in front of a point-of-sale payment terminal

Integrating an online payment gateway is rarely as simple as embedding a checkout button and awaiting a redirect callback. In production environments where real money changes hands, browser redirects are fundamentally unreliable as confirmation mechanisms. A customer can close their browser window immediately after authorizing a payment, drop their cellular connection, or encounter a client-side script error before returning to your success page.

Webhooks provide the essential server-to-server confirmation channel: payment providers like Stripe and Khalti transmit asynchronous HTTP POST requests directly to your backend endpoint when an event completes. However, relying on webhooks introduces distributed state challenges. Network delays, gateway retries, and temporary connection timeouts mean that your server will inevitably receive the exact same webhook event more than once. Without explicit idempotency safeguards, duplicate events lead to duplicate database records, multiple order confirmations, and repeated digital fulfillments.

Why duplicate webhook deliveries happen

Payment providers operate on an *at-least-once* delivery guarantee. When Stripe or Khalti dispatches an event to your endpoint, the gateway expects an immediate HTTP 200 OK response within a strict timeout window (typically 5 to 10 seconds). If your server takes too long executing complex fulfillment logic, or if a network blip interrupts the response acknowledgment, the payment gateway considers the delivery failed.

To guarantee that payments are never dropped, the gateway's retry schedule immediately kicks in, resending the identical event minutes or hours later. Duplicate deliveries can also occur when multiple webhook endpoints are configured or when upstream payment systems reprocess batched transactions. Treating every incoming webhook request as a fresh transaction is a dangerous architectural mistake.

Understanding idempotency in financial workflows

An operation is idempotent if applying it multiple times produces the exact same outcome as applying it once. In a payment handler, processing an event with ID evt_12345 five times should perform the business state change exactly once and return successful HTTP acknowledgments on all subsequent attempts without mutating data again.

typescript
// Processing payment webhooks with database-level idempotency
export async function handlePaymentWebhook(event: WebhookEvent) {
  const { eventId, transactionId, amount, status } = event;

  return await prisma.$transaction(async (tx) => {
    // 1. Check if event has already been recorded
    const existingLog = await tx.webhookLog.findUnique({
      where: { eventId }
    });

    if (existingLog) {
      // Event already processed - acknowledge immediately
      return { status: "ALREADY_PROCESSED" };
    }

    // 2. Record the event log inside the transaction
    await tx.webhookLog.create({
      data: {
        eventId,
        provider: "STRIPE",
        status: "PROCESSED",
        receivedAt: new Date()
      }
    });

    // 3. Perform state transition using transaction ID constraint
    const order = await tx.order.update({
      where: { id: transactionId, paymentStatus: "PENDING" },
      data: {
        paymentStatus: "PAID",
        paidAt: new Date()
      }
    });

    return { status: "SUCCESS", orderId: order.id };
  });
}

Tracking processed events with unique database constraints

The most dependable strategy for enforcing idempotency is storing processed event identifiers in a dedicated database table (WebhookEventLog) with a UNIQUE constraint on the gateway's event ID. When a webhook arrives, the handler begins an atomic database transaction. If the event ID already exists in the log, the handler aborts further execution and immediately returns an HTTP 200 response.

By relying on relational database constraints rather than volatile in-memory flags or cache keys, your application remains resilient even when multiple serverless instances or container replicas handle concurrent requests simultaneously.

Separating payment state from service fulfillment

In complex platforms such as UseSSL, paying for a service and fulfilling that service are two entirely distinct lifecycles. When a customer purchases an SSL certificate, payment verification occurs in seconds via Stripe or Khalti. However, technical certificate issuance requires Certificate Signing Request (CSR) validation, DNS challenge verification, and external CA approval, which can take hours or days.

Conflating payment status with fulfillment status creates fragile software. If your webhook handler attempts to call upstream certificate authority APIs in the middle of processing the payment callback, any latency or downtime from the external vendor will cause the webhook to time out. The gateway will retry the payment webhook, creating confusion and potentially triggering multiple orders.

Rule of thumb: A payment webhook handler should only verify the financial transaction and record the payment state. Downstream provisioning, email delivery, and external API requests should be triggered asynchronously through independent event queues or background jobs.

Handling partial failures and database compensation

What happens when an external payment API succeeds, but your local database connection fails during the update? If your endpoint throws an unhandled error, the gateway will retry the event. However, if your handler performed a non-transactional side effect—such as dispatching an invoice email before writing to the database—retries will send duplicate emails to the customer.

To prevent partial failures from corrupting application state, wrap all database mutations in atomic transactions. External side effects—such as sending customer purchase receipts with Resend—should only run after the database transaction successfully commits. If the database update fails, rollback the transaction, log the error with structured metadata, and allow the gateway's retry schedule to safely re-trigger the handler.

Testing payment webhooks under real-world conditions

Testing payment webhooks requires more than simulating happy-path events. In our engineering workflow, we test payment integrations using the Stripe CLI and Khalti test sandboxes to specifically verify edge cases:

1. **Duplicate delivery tests:** We trigger the exact same event ID twice within a few seconds to verify that our handler returns HTTP 200 without creating duplicate order records or invoices.

2. **Out-of-order event tests:** In workflows where both payment_intent.created and payment_intent.succeeded are subscribed to, we verify that the system correctly resolves final state even if the success event arrives first.

3. **Signature verification failures:** We intentionally submit payloads with invalid cryptographic signatures to confirm that unauthorized requests are rejected with HTTP 400 before touching business logic.

Conclusion and key takeaways

Reliable payment processing is achieved not by hoping networks remain stable, but by designing software that expects retries, duplicates, and latency. By decoupling payment confirmation from technical fulfillment, verifying cryptographic signatures on every request, and enforcing database-level idempotency constraints, you build an architecture that handles high transaction volume with confidence.

Dipesh Thapa

Dipesh Thapa

Full-Stack Engineer based in Nepal, specializing in Next.js, TypeScript, Prisma, and high-performance server architectures.

Related posts

Browse all articles

Get engineering
notes

Technical case studies, engineering lessons, and notes from building real-world digital products and systems.

Logo icon

Occasional deep-dives into software architecture, database performance, payment integration, and engineering practices.

No spam · Unsubscribe anytime