Payments & APICompleted2025

E-Commerce Payment Backend

Production-grade REST API with eSewa payment integration, idempotency-safe checkout, Redis-backed concurrency guards, and structured observability.

RoleBackend Engineer
Timeline6 weeks
PublishedApril 2025
Source Code
TypeScriptNode.jsExpressPostgreSQLPrismaRedisDocker

A fully typed Express.js backend for an e-commerce platform, built with careful attention to payment correctness. The core engineering challenge was ensuring that eSewa checkout requests are safe against duplicate submissions, race conditions, and partial-failure states — all without distributed transactions.

Fig 1. Payment Request Flow
Ecommerce Backend system architecture: Client → Express API (Auth Middleware) → Payment Service (Idempotency Guard via Redis cache) → Prisma / PostgreSQL → eSewa Gateway → Webhook → Prisma update

How a checkout request flows through the idempotency guard, database lock, eSewa signature generation, and webhook verification cycle.

What We Set Out to Solve

Payment flows in e-commerce are notoriously fragile: the same checkout button can be clicked twice, network retries can replay requests, and partial failures between your database and a payment gateway leave orders in ambiguous states. This project required building a payment layer that is correct by design — idempotent, atomic, and verified end-to-end.

Architecture Highlights

  • Feature-based module structure: auth, users, products, cart, payment — each isolated with its own routes, controller, and service layer
  • Redis-backed idempotency cache (payment.cache.ts) that atomically claims in-flight payments using SETNX semantics
  • eSewa HMAC-SHA256 signature generation and response signature verification before any order is marked paid
  • Structured request logging via pino-http attached directly to the Express app
  • Centralized error handling middleware with typed AppError class carrying HTTP status and error codes
  • Dockerized with multi-stage Dockerfile and compose.yaml for deterministic local development

End-to-End Data Pipeline

Key Engineering Decisions

01

Redis Idempotency Cache for Payment Initiation

Implemented `claimPaymentInitiation`, `getPaymentInitiation`, `completePaymentInitiation`, and `clearPaymentInitiation` as a dedicated payment cache module. The API requires an `Idempotency-Key` header on every checkout request.

Rationale: Without an idempotency layer, a network timeout could cause the client to retry and charge the user twice. The Redis cache atomically claims a key for a (userId, idempotencyKey) pair using SETNX-equivalent logic. Subsequent requests with the same key either return the cached response (if completed) or return a 409 PAYMENT_INITIATION_IN_PROGRESS error.

02

HMAC-SHA256 Signature for eSewa Integration

Payment forms sent to eSewa are signed with a HMAC-SHA256 signature constructed from amount, tax, product code, and a secret key. eSewa's callback response is independently verified using `verifyEsewaResponseSignature` before trusting any payment confirmation.

Rationale: eSewa's integration requires signature verification to prevent webhook spoofing — an attacker cannot forge a successful payment callback without knowledge of the merchant secret.

03

Prisma ORM over raw SQL for PostgreSQL

All database interactions use Prisma with a seeding script (`prisma/seed.ts`) and a dedicated Prisma client singleton in `src/lib/prisma.ts`.

Rationale: Prisma's generated types provide end-to-end type safety between the database schema and the application layer, catching schema mismatches at compile time rather than at runtime.

04

Modular Feature Folder Architecture

Source code is organized as `src/modules/{auth,users,products,cart,payment}/` each containing `*.routes.ts`, `*.controller.ts`, and `*.service.ts`. Cross-cutting concerns (cache, config, errors, lib, middleware) live at `src/` root.

Rationale: Each feature module can be understood, tested, and modified independently. Adding a new domain resource (e.g. orders) requires creating a single new folder without touching other modules.

Core Code Pattern

src/modules/payment/payment.service.tsTYPESCRIPT
export const initiateEsewaPayment = async (
  orderId: string,
  userId: string,
  idempotencyKey: string
) => {
  // 1. Check if idempotency key was already completed
  const existing = await getPaymentInitiation(userId, idempotencyKey);
  if (existing) {
    if (existing.orderId !== orderId) {
      throw new AppError('Idempotency key reused for another order', 422, 'IDEMPOTENCY_KEY_REUSED');
    }
    if (existing.status === 'COMPLETED') return existing.response;
    throw new AppError('Payment already in progress', 409, 'PAYMENT_INITIATION_IN_PROGRESS');
  }

  // 2. Atomically claim the request
  const claimed = await claimPaymentInitiation(userId, idempotencyKey, orderId);
  if (!claimed) {
    throw new AppError('Payment already in progress', 409, 'PAYMENT_INITIATION_IN_PROGRESS');
  }

  // 3. Validate order & generate eSewa signature...
};

The two-step idempotency check — read then atomic claim — ensures that concurrent duplicate requests are safely rejected without initiating multiple payment flows against the eSewa gateway.

Technical Challenges & Resolutions

Challenge 1

Handling concurrent duplicate checkout requests for the same order

Resolution: Implemented a two-step idempotency check in `initiateEsewaPayment`: first check the Redis cache for an existing record; if none exists, atomically claim it. The claim fails if another process already acquired it, returning a 409 rather than initiating a second payment flow. The in-progress state prevents partial completion from being replayed.

Challenge 2

Preventing order state corruption if the eSewa gateway callback arrives before the initiation response is stored

Resolution: The idempotency state machine transitions through `PENDING → IN_PROGRESS → COMPLETED`. Webhook verification only proceeds after the idempotency record is in a claimable state, preventing out-of-order state transitions from corrupting the order record.

Challenge 3

Safely converting money between internal representation and eSewa's expected format

Resolution: All monetary amounts are stored internally in paisa (integer cents). The `toRupees()` utility converts to Nepalese Rupees with proper decimal padding before constructing the payment form, eliminating any floating-point arithmetic on money.

Measurable Outcomes

Results based on local benchmarks and integration test runs during development.

  • Zero duplicate payment initiations observed across all local and integration test runs
  • Payment signature verification catches 100% of forged webhook payloads in automated tests
  • End-to-end checkout flow (initiation → eSewa redirect → webhook → DB update) completes in under 2 seconds in local environment

E-Commerce Payment Backend

This case study documents the architecture, engineering decisions, and key challenges for E-Commerce Payment Backend. The full implementation is available in the source repository.