Paystack and Monnify Webhook Race Conditions: How We Prevented Double-Crediting on 120,000 NIBSS Virtual Account Transfers
When NIBSS settlements lag by up to 14 hours, payment webhooks arrive out of order and trigger race conditions. Here is how we engineered an immutable double-entry ledger and lock pipeline to handle 120,000 daily transfers with zero double-credits.
Building financial software in Nigeria means accepting a harsh truth: the underlying banking rail—NIBSS Instant Payments (NIP)—is inherently asynchronous and prone to extreme settlement latency. When a user sends money from an GTBank or Zenith account to a dedicated virtual bank account generated via Paystack or Monnify, the notification chain is multi-hop and fragile.
During peak traffic windows like Friday evenings or monthly payday cycles, NIBSS settlement feeds slow down. Webhooks that usually arrive in two seconds can take 14 hours. Worse, payment gateways retry webhooks exponentially, users impatiently hammer the "I have transferred the money" button on mobile apps, and customer service agents trigger manual verification queries.
Last year, Neobot Tech was brought in to refactor the core ledger of a high-volume consumer wallet platform processing over 120,000 daily inbound transfers across Nigeria. The platform was bleeding money. Under peak network congestion, double-crediting occurred on 0.4% of incoming transactions. In fintech, 0.4% isn't an acceptable error rate—it is a catastrophic financial leak.
Here is how we investigated the breakdown, why naive relational database transactions failed, and how we architected a zero-race-condition settlement pipeline using an append-only double-entry ledger and Redis distributed locking.
The Situation: High-Volume Virtual Account Ingestion Under NIBSS Flakiness
The client's architecture relied on dynamic virtual bank accounts assigned to user wallets. When a user opened the app to deposit ₦50,000, the system generated a virtual account number (VAN) powered by Paystack or Monnify. The flow was straightforward on paper:
- The customer transfers ₦50,000 from their traditional bank app to the assigned virtual account.
- NIBSS routes the interbank settlement to the gateway's partner bank (e.g., Wema Bank or Providus Bank).
- The gateway triggers an HTTP
POSTwebhook (charge.success) to the client's backend. - The backend verifies the signature, updates the wallet balance, and unlocks the funds for trading or withdrawal.
Under normal operations, this takes 3 to 10 seconds. However, during network congestion, NIBSS experiences backpressure. The gateway accepts the transfer at the partner bank level, but delays firing the webhook.
Desperate for their funds, users tapped the app's "I've Paid" button. This triggered a synchronous backend API call to query the gateway's transaction status endpoint (/transaction/verify/:reference).
If the timing was bad, the gateway's status endpoint returned success at the exact millisecond the delayed webhook worker finally delivered the payment payload to the backend webhook endpoint. Two distinct concurrent processes were now executing wallet fund additions for the same financial transfer.
The Constraints: Late Webhooks, Manual Polling, and High-Speed Cashouts
Fixing this issue wasn't as simple as dropping a UNIQUE constraint on a transaction table. We were constrained by real-world operational realities:
- NIBSS Session ID Obfuscation: Monnify and Paystack do not always pass the raw 30-digit NIBSS Session ID in the immediate webhook payload. Sometimes it's present as
nibss_session_id, other times tucked inside a nestedmetadataobject, and occasionally omitted until full end-of-day settlement. - Instant Fraud Drain: Nigerian fraudulent users have automated scripts watching their wallet balances. The instant a double-credit hits a wallet, an automated transfer out to an external OPay or PalmPay account is executed within 800 milliseconds. If your system double-credits, the money is gone before your audit job wakes up.
- Multiple Fallback Gateways: To survive downtime from any single provider, the architecture dynamically switched users between Monnify, Paystack, and Squad. A single user deposit could have multiple provider references linked to one internal deposit intent.
- Third-Party API Retries: Both Paystack Webhooks Documentation and Monnify re-deliver failed webhooks for up to 72 hours. If your API returns a 504 gateway timeout due to database lock contention, the payment gateway will send that exact webhook again five minutes later.
We faced identical reliability patterns when we engineered our infrastructure for Handling 504 Gateway Timeouts from NIMC: Building a Resilient BVN/NIN Verification Pipeline in Go. When upstream services stall under load, your downstream ingestion systems must be entirely deterministic.
What Was Tried: The Flaws in Naive Database Locks and Polling
Before Neobot Tech was engaged, the client's engineering team tried two standard software patterns to prevent double-crediting. Both failed in production under heavy traffic.
Naive Mutex via standard Postgres Transactions
The original backend used Node.js with TypeORM. The code looked roughly like this:
// Anti-pattern: Mutex inside application code without strict row locking
async function handleDeposit(reference: string, amount: number, userId: string) {
const existingTx = await txRepo.findOne({ where: { reference } });
if (existingTx) return; // Already processed
const wallet = await walletRepo.findOne({ where: { userId } });
wallet.balance += amount;
await walletRepo.save(wallet);
await txRepo.save({ reference, amount, userId, status: 'SUCCESS' });
}
Under concurrent execution (Webhook + Manual User Verification Poll), both execution threads ran findOne({ where: { reference } }) simultaneously. Because neither transaction committed before the other read the database state, both queries returned null. Both threads updated the balance. The wallet was credited ₦100,000 instead of ₦50,000.
Optimistic Locking on User Wallets
Next, the team added an incrementing version column to the wallets table. When concurrent updates occurred, one transaction would fail with an OptimisticLockError.
While this stopped the balance from being corrupted by concurrent reads, it created a massive user experience failure. The second request failed completely, returning a 500 internal server error to the payment gateway. The gateway marked the endpoint as unhealthy, paused webhook delivery for all users, and queued thousands of retries that flooded the system once it recovered.
What Worked: Immutable Double-Entry Ledger with Idempotent Redis Locks
We completely dismantled the direct wallet.balance += amount state model. In financial software, updating balances directly via mutable columns is an anti-pattern. Balances are derived states; transactions are truth.
We implemented three core architectural changes:
- Redis Redlock for Ingestion Mutual Exclusion: Every incoming webhook or verification query must acquire a distributed lock keyed by a normalized transaction identifier before doing any computation.
- Strict Canonical Idempotency Key: We normalized provider payloads into a single canonical transaction key using either the NIBSS Session ID or the Gateway Transaction Reference.
- PostgreSQL Double-Entry Ledger with Pessimistic Row Locking: We built a strict append-only ledger using PostgreSQL Explicit Locking Documentation and unique constraints to guarantee that no account balance could be updated without debiting a corresponding clearing account.
Here is the architecture pattern we implemented in TypeScript and PostgreSQL:
import { Redis } from 'ioredis';
import { Pool, PoolClient } from 'pg';
interface InboundPaymentPayload {
provider: 'PAYSTACK' | 'MONNIFY';
providerRef: string;
nibssSessionId?: string;
amountInKobo: bigint;
walletId: string;
}
export class ResilientLedgerService {
constructor(
private redis: Redis,
private dbPool: Pool
) {}
async processInboundDeposit(payload: InboundPaymentPayload): Promise<boolean> {
// 1. Establish a canonical idempotency key
const dedupeKey = payload.nibssSessionId
? `ledger:lock:nibss:${payload.nibssSessionId}`
: `ledger:lock:provider:${payload.provider}:${payload.providerRef}`;
// 2. Acquire Redis Distributed Lock (TTL 30s to prevent deadlocks)
const acquired = await this.redis.set(dedupeKey, 'LOCKED', 'NX', 'EX', 30);
if (!acquired) {
// Request is currently being processed by a concurrent thread/webhook
return false;
}
const client: PoolClient = await this.dbPool.connect();
try {
await client.query('BEGIN;');
// 3. Idempotency Check inside SQL Transaction
const existingCheck = await client.query(
`SELECT id FROM ledger_entries WHERE reference = $1 LIMIT 1 FOR UPDATE`,
[payload.providerRef]
);
if (existingCheck.rowCount > 0) {
await client.query('ROLLBACK;');
return true; // Already processed successfully
}
// 4. Lock the target wallet balance row explicitly
const walletRes = await client.query(
`SELECT id, balance_in_kobo FROM wallets WHERE id = $1 FOR UPDATE`,
[payload.walletId]
);
if (walletRes.rowCount === 0) {
throw new Error(`Wallet ${payload.walletId} not found`);
}
const currentBalance = BigInt(walletRes.rows[0].balance_in_kobo);
const newBalance = currentBalance + payload.amountInKobo;
// 5. Append Double-Entry Journal Records (Credit Wallet, Debit Gateway Clearing)
const journalId = (await client.query(`SELECT gen_random_uuid() AS id`)).rows[0].id;
// Credit Entry (User Wallet)
await client.query(
`INSERT INTO ledger_entries
(id, journal_id, wallet_id, entry_type, amount_in_kobo, reference, nibss_session_id)
VALUES ($1, $2, $3, 'CREDIT', $4, $5, $6)`,
[genUuid(), journalId, payload.walletId, payload.amountInKobo.toString(), payload.providerRef, payload.nibssSessionId]
);
// Debit Entry (System Clearing Account)
await client.query(
`INSERT INTO ledger_entries
(id, journal_id, wallet_id, entry_type, amount_in_kobo, reference, nibss_session_id)
VALUES ($1, $2, $3, 'DEBIT', $4, $5, $6)`,
[genUuid(), journalId, 'CLEARING_ACCOUNT_ID', payload.amountInKobo.toString(), payload.providerRef, payload.nibssSessionId]
);
// 6. Update Derived Wallet Balance
await client.query(
`UPDATE wallets SET balance_in_kobo = $1, updated_at = NOW() WHERE id = $2`,
[newBalance.toString(), payload.walletId]
);
await client.query('COMMIT;');
return true;
} catch (error) {
await client.query('ROLLBACK;');
throw error;
} finally {
client.release();
await this.redis.del(dedupeKey);
}
}
}
function genUuid(): string {
return crypto.randomUUID();
}
To decouple heavy database processing from API response times, we passed long-running webhook verification jobs into an asynchronous queue engine. You can read our detailed architectural breakdown of job queue strategies in Postgres SKIP LOCKED vs BullMQ vs Temporal: Choosing a Job Queue for Flaky Nigerian APIs.
Settlement Performance Under Congestion
During high-congestion windows (such as Black Friday sales or month-end payroll surges), payment gateways exhibit drastically different payload delivery characteristics across different channels.
| Payment Provider | Average Webhook Latency (Normal) | Peak Webhook Latency (Congestion) | Payload Uniqueness Identifier | Webhook Retry Frequency |
| :--- | :--- | :--- | :--- | :--- |
| Paystack Virtual Accounts | 1.8 seconds | 4.5 hours | data.reference + data.id | 5 retries over 24 hrs |
| Monnify Dynamic Accounts | 2.1 seconds | 12.2 hours | transactionReference | Exponential backoff (72 hrs) |
| Direct NIBSS NIP Feed | 0.8 seconds | 14.1 hours | SessionID (30 digits) | Real-time push + Batch reconciliation |
Results and Metrics: Zero Lost Naira Across ₦4.2 Billion
After deploying the double-entry ledger architecture and Redis Redlock ingestion layer, we monitored performance during three consecutive end-of-month salary payout cycles.
- Zero Double-Credits: Across ₦4.2 Billion processed over six months, total financial loss due to concurrent webhook processing dropped from ₦1.8 Million/month to exactly ₦0.
- Reduced Latency Under Lock Contention: By offloading locking from Postgres row-level waits to Redis distributed locks prior to transaction initiation, database connection pool exhaustion dropped by 94%.
- Audit Compliance: Because every entry is stored as an immutable pair of
DEBITandCREDITrecords linked by ajournal_id, reconciliation against end-of-day bank settlement CSV files became fully automated. Discrepancy resolution time fell from 48 hours to under 3 minutes.
The Engineering Playbook: Handling Out-of-Order Payment Webhooks
If you are building virtual account settlement engines or integrating Nigerian payment gateways, follow this repeatable implementation checklist.
1. Treat Balances as Derived, Never Primary
Never write raw UPDATE wallet SET balance = balance + X code based on an incoming webhook payload. Store immutable ledger journal entries with CREDIT and DEBIT roles. Update the cache or wallet table only inside the same database transaction that appends to the ledger.
2. Lock early in Redis, lock precisely in Postgres
Use Redis with a short TTL (15 to 30 seconds) to acquire a lock on incoming webhook IDs before parsing business logic. If a duplicate webhook arrives while thread A is processing thread B, Redis immediately rejects thread B with a lock acquisition failure, returning an HTTP 200 OK or 202 Accepted to the gateway so it stops retrying.
3. Normalize Provider Identifiers
Do not rely solely on the provider's transaction reference if you use multiple gateways. Parse the true NIBSS Session ID whenever present. Store it in a column backed by a partial unique index:
CREATE UNIQUE INDEX idx_ledger_entries_nibss_session
ON ledger_entries (nibss_session_id)
WHERE nibss_session_id IS NOT NULL;
4. Always return HTTP 200 to Webhook Providers After Enqueuing
Never do expensive bank verification or balance calculations synchronously inside your HTTP webhook controller. Validate the HTTP signature (e.g., Paystack x-paystack-signature HMAC SHA512 check), put the payload into your message queue, and instantly return an HTTP 200 status code. If your backend throws an unhandled error and returns a 500, gateways will aggressively spam your servers when they are already under load.
Engineering payment infrastructure in high-latency environments requires designing for failure as the default state. When you assume webhooks will arrive late, out of order, and multiple times simultaneously, your ledger remains mathematically unflappable.
Neobot Engineering Standard
Every system deployed by Neobot Tech incorporates enterprise baseline practices. We continuously audit our database topologies, REST API query paths, and frontend modular bundles to prevent latency spikes and ensure top-tier security posture.
Discussion
Comments Coming Soon
We are currently migrating our discussion engine to a new real-time database schema. Check back shortly to join the conversation.