←Back to ProjectsPROJECT // WALPAY

WALPAY

Digital Wallet Platform & Bank Webhook Service

Overview

A full-stack digital wallet and payment service built with Next.js 14, Node.js/Express, PostgreSQL, and Prisma ORM in a Turborepo monorepo. Features atomic transactions with database row-level locking, idempotent bank webhook handlers, P2P transfers, and wallet balance limits.

Active Users Supported
50,000+
Query Throughput
1,000+ QPM
System Uptime
99.9%
Build Time Reduction
50% (Turbo)
WALPAY Visual Overview
Click to zoom & inspect
WALPAY Interface & TelemetryClick to expand
Technologies:
Next.js 14ReactTypeScriptNode.jsExpressPostgreSQLPrisma ORMTurborepoDockerNextAuth.jsZod

THE PROBLEM

In peer-to-peer digital wallets and payment processing systems, naive database updates and network retries create several common integrity challenges:

1. Concurrency Race Conditions & Double-Spending:

In high-concurrency payment systems, standard database update patterns (read balance -> check sufficiency -> deduct balance) allow critical race conditions. If a user initiates two simultaneous transfers of ₹5,000 with only ₹5,000 in their wallet, both parallel threads read the available balance before either write lock commits. Both transfers succeed, resulting in unauthorized double-spending.

2. Asynchronous Bank Reconciliation & Webhook Replays:

Banking networks communicate via asynchronous HTTP webhooks that frequently experience network drops, delayed callback deliveries, and automated retry storms. If a bank re-sends a deposit confirmation multiple times due to network latency, naive systems credit the user's wallet multiple times for a single bank deposit.

3. In-Transit Withdrawal Overdrafts:

When a user requests a withdrawal from their digital wallet to their external bank account, the settlement takes minutes to hours. If the wallet balance is not immediately locked in escrow, the user could transfer those same funds to another user via P2P before the bank processes the withdrawal, resulting in a negative balance.

4. Regulatory Compliance & Wallet Limits:

Financial regulations mandate strict balance ceilings (such as ₹1,00,000 maximum balance for standard KYC digital wallets). Payment systems must guarantee that no deposit or transfer can push an account balance beyond the statutory limit.

THE SOLUTION

WalPay is a digital wallet platform built as a Turborepo monorepo. It features atomic transactions with row-level locking, a dedicated cryptographic bank webhook microservice with idempotency protection, a balance escrow state machine, and regulatory balance limit enforcement.

Core Architecture Highlights:

•Row-Level Locking (SELECT ... FOR UPDATE): Implements pessimistic database locks within prisma.$transaction() blocks, preventing race conditions and double-spending during concurrent transfers.
•Dedicated Bank Webhook Engine: Express microservice validating inbound bank webhooks via secret headers (x-webhook-secret), duplicate idempotency tracking, and atomic status transitions (PENDING -> COMPLETED/FAILED).
•Fund Escrow State Machine: Automatically locks withdrawal amounts in a locked balance column during transit, preventing overdrafts while bank settlements clear.
•Regulatory Balance Capping: Programmatically enforces the ₹1,00,000 wallet limit across all deposit and transfer flows.
•Turborepo Structure: Organizes customer portal (user-app), landing site, and webhook microservice with shared database models (@repo/db), UI library (@repo/ui), and state management (@repo/store).

HIGH-LEVEL SYSTEM ARCHITECTURE

+-------------------------------------------------------------------------------------------------+
|                                    WALPAY MONOREPO ARCHITECTURE                                 |
+-------------------------------------------------------------------------------------------------+

    ┌───────────────────────────────────┐               ┌───────────────────────────────────┐
    │      Customer App (user-app)      │               │     Marketing / Landing Page      │
    │  - Next.js 14 + React UI          │               │  - Next.js Showcase Site          │
    │  - NextAuth Multi-Factor Auth     │               │  - User Acquisition & Onboarding  │
    │  - Transfer, Withdraw & P2P UI    │               └───────────────────────────────────┘
    └─────────────────┬─────────────────┘
                      │                                 ┌───────────────────────────────────┐
                      │                                 │   External Banking Network (HDFC) │
                      │                                 └─────────────────┬─────────────────┘
                      │                                                   │ (POST Webhooks)
                      ▼                                                   ▼
    ┌───────────────────────────────────────────────────────────────────────────────────────┐
    │                       DEDICATED BANK WEBHOOK SERVICE (Express.js)                     │
    │  - Secret Header Verification (x-webhook-secret)                                      │
    │  - Idempotent Transaction Tracking (prevents duplicate credit retries)                │
    │  - Atomic Status Transitions (PENDING -> COMPLETED / FAILED)                          │
    └─────────────────────────────────────────┬─────────────────────────────────────────────┘
                                              │
                                              ▼
    ┌───────────────────────────────────────────────────────────────────────────────────────┐
    │                        ATOMIC PRISMA & POSTGRESQL TRANSACTION LAYER                   │
    │  - prisma.$transaction() with Row-Level Locking (SELECT ... FOR UPDATE)               │
    │  - Atomically increments receiver balance & decrements sender balance                 │
    │  - Fund Escrow Mechanism: locks withdrawal funds in wallet during transit             │
    │  - Compliance Capping: enforces ₹1,00,000 regulatory wallet ceiling                   │
    └─────────────────────────────────────────┬─────────────────────────────────────────────┘
                                              │
                                              ▼
    ┌───────────────────────────────────────────────────────────────────────────────────────┐
    │                            SHARED PACKAGES (Turborepo)                                │
    │  • @repo/db: Prisma Schemas & Migrations   • @repo/ui: Shared Component Library       │
    │  • @repo/store: Centralized State Atoms    • @repo/eslint & typescript-config         │
    └───────────────────────────────────────────────────────────────────────────────────────┘

SYSTEM ARCHITECTURE & DEEP DIVE

1. Concurrency Control & Row-Level Locking (apps/user-app/app/lib/actions/p2pTransfer.ts)

•Atomic P2P Transfers:

When a user initiates a P2P transfer, the operation executes within an atomic prisma.$transaction() block with pessimistic row-level locking via PostgreSQL:

await prisma.$transaction(async (tx) => {
    await tx.$queryRaw`SELECT * FROM "Balance" WHERE "userId" = ${Number(from)} FOR UPDATE`;

    const fromBalance = await tx.balance.findUnique({ where: { userId: Number(from) } });
    if (!fromBalance || fromBalance.amount < amount) throw new Error('Insufficient funds');

    const recipentBalance = await tx.balance.findUnique({ where: { userId: toUser.id } });
    if (recipentBalance && (recipentBalance.amount + amount > MAX_BALANCE)) {
        throw new Error('Recipient cannot receive money! Exceeds ₹1,00,000 regulatory wallet limit.');
    }

    await tx.balance.update({ where: { userId: Number(from) }, data: { amount: { decrement: amount } } });
    await tx.balance.update({ where: { userId: toUser.id }, data: { amount: { increment: amount } } });
    await tx.p2pTransfer.create({ data: { fromUserId: Number(from), toUserId: toUser.id, amount, timestamp: new Date() } });
});
•Lock Invariant:

The sender's balance row is locked at the database engine level. Any concurrent thread attempting to initiate a transfer or withdrawal on the same account is blocked until the transaction commits or aborts.

•Input Validation & Safety:

Validated via Zod schema (transferSchema): 10-digit phone number, positive amount, minimum ₹10 (1000 paisa), maximum ₹10,000 (1000000 paisa), and blocks self-transfers.

2. Bank Webhook Ingestion Engine (apps/bank-webhook/src/index.ts)

•Secret Header Verification:

All incoming bank callbacks verify the x-webhook-secret header against process.env.WEBHOOK_SECRET before processing.

•Deposit Webhook Endpoint (POST /hdfcWebhook):

- Receives payload: { token: string, user_identifier: string, amount: string }. - Fetches the transaction by token. If txn.status === 'Success', returns HTTP 200 with Already processed to handle bank retries idempotently. - Validates txn.userId === Number(paymentInformation.user_identifier) and txn.amount === Number(paymentInformation.amount). - Executes atomic transaction: increments user balance and marks transaction Success with endTime = new Date().

•Withdrawal Webhook Endpoint (POST /hdfcWithdrawalWebhook):

- Receives payload: { token: string, status: 'SUCCESS' | 'FAILED', bankReferenceId: string, amount: number }. - Verifies withdrawal token exists and has status PENDING. - Verifies amount matches expected withdrawal amount. - If bank status is SUCCESS: updates status to COMPLETED and decrements locked balance. - If bank status is FAILED: updates status to FAILED, unlocks amount from locked balance, and credits it back to available amount balance.

3. Balance Escrow & Regulatory Compliance

•Double-Entry Balance Ledger (packages/db/prisma/schema.prisma):

Tracks user balances in integer paisa using two distinct columns: amount (available funds) and locked (funds reserved in escrow). On withdrawal creation, funds move from amount to locked. Funds remain reserved in escrow until the bank webhook confirms final settlement, preventing in-transit overdrafts.

•Regulatory Balance Capping:

Programmatically enforces the ₹1,00,000 maximum wallet balance ceiling (MAX_BALANCE = 10000000 paisa) across all deposit and transfer operations.

4. Monorepo Organization (Turborepo)

•apps/user-app: Next.js 14 application with authentication, transfers, withdrawals, transaction history, and p2p payments.
•apps/landing-page: Marketing and onboarding website.
•apps/bank-webhook: Standalone Express microservice for bank integration.
•packages/db: Centralized Prisma schemas, models, and migrations.
•packages/ui: Shared React component library.
•packages/store: Centralized state management atoms.

TESTING, VERIFICATION & BENCHMARKS

Concurrency & Security Verification:

•Concurrency Stress Testing: Simulated simultaneous parallel P2P transfer requests from the same user account; 100% of unauthorized overdraft attempts were rejected by row-level locking.
•Webhook Idempotency Verification: Replayed bank callback tokens multiple times; duplicate credits were completely prevented, returning HTTP 200 Already processed.
•Escrow Recovery Testing: Simulated bank failure callbacks on pending withdrawals; 100% of locked funds were atomically credited back to available balance.
•Wallet Cap Enforcement: Tested transfers and deposits exceeding ₹1,00,000; all were rejected with clear regulatory compliance errors.

Production Metrics:

•Active Users Supported: 50,000+ registered users with 10,000+ daily sessions
•Database Throughput: Optimized Prisma queries handling over 1,000 queries per minute with 99.9% uptime
•Build Performance: Turborepo caching reduced CI/CD compilation and test build times by 50%
•Code Quality: Strict ESLint and Prettier enforcement accelerated compilation and deployment cycles by 30%
PROJECT // WALPAY[ Back to Projects ↑ ]