Fintech

Reconciling Flaky NIBSS Virtual Account Transfers: Building an Immutable Ledger in Node.js and PostgreSQL

A
Adebayo FalojuPrincipal Systems Architect
October 30, 202617 min read
Reconciling Flaky NIBSS Virtual Account Transfers: Building an Immutable Ledger in Node.js and PostgreSQL

When NIBSS bank transfers hang for hours during network flaps, naive balance updates cause duplicate credits and balance drifts. Here is how to architect an immutable double-entry ledger engine in Node.js and PostgreSQL that handles out-of-order webhooks and delayed bank settlements cleanly.

It is Friday at 6:15 PM in Lagos. Bank traffic spikes as millions of users top up their wallet accounts for weekend spending. A customer transfers ₦100,000 from GTBank to a virtual account hosted by Wema Bank or Providus Bank for your digital app. The customer's GTBank app displays a successful transaction notice containing a 30-digit NIBSS Instant Payment (NIP) session ID.

Inside your API backend, nothing happens for 45 minutes. The virtual account provider's webhook payload was dropped due to network congestion along the telco routes. At 7:00 PM, your retry worker executes a polling query against the provider's API. The endpoint responds with status: "PENDING" and response code 09 (In-System Transfer Pending). At 7:15 PM, the delayed webhook finally hits your server with status: "SUCCESS". Two seconds later, your scheduled polling job finishes a background run and receives status: "SUCCESS" from the re-queried REST endpoint.

If your engine uses naive balance updates like UPDATE wallets SET balance = balance + 100000 WHERE user_id = 42, one of two things just occurred: you either credited the user twice (₦200,000) because both execution threads processed the event simultaneously, or your system entered a race condition that threw an unhandled exception and left the customer wallet uncredited. The user starts spamming your support desk on WhatsApp while your finance team spends Saturday morning reconciling missing funds against CSV statements.

Mutating a single balance column on a user table for payment settlements is architectural suicide in Sub-Saharan Africa. Between NIBSS switch delays, partner bank webhooks arriving out of order, and retried API responses, you must build financial systems around immutable double-entry accounting ledgers and atomic database locks.

The Failure Mode of Stateful Balance Columns

When developers build their first fintech integration in Nigeria, they usually design a schema with a single user table:

-- DO NOT DO THIS IN PRODUCTION
CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    email VARCHAR(255),
    wallet_balance NUMERIC(15, 2) DEFAULT 0.00
);

This design breaks down under real-world conditions for three reasons:

  1. Lack of Auditability: If wallet_balance is 150000.00, there is no database-level proof of how it reached that figure without parsing unstructured application logs.
  2. Race Conditions: Two concurrent HTTP requests reading wallet_balance, calculating 150000 + 100000, and writing 250000 back will overwrite intermediate state, causing silent money leaks.
  3. Inability to Reconcile Non-Final States: NIBSS transfer status codes like 91 (Beneficiary Bank Not Available) or 09 (Pending) often transition to 00 (Success) hours after the initial attempt. A single balance integer cannot represent pending holds, clearings, or chargeback reversals.

To solve this, we throw away mutating state updates and implement a double-entry ledger. Every naira that moves through your system must be represented by at least two ledger entries: a debit from a source account and an equal credit to a destination account.

Designing the Double-Entry Schema in PostgreSQL

In standard double-entry bookkeeping, the fundamental accounting equation must always hold:

$$\text{Assets} = \text{Liabilities} + \text{Equity}$$

From your system's perspective, money sitting in your platform's operational bank account is an Asset. Money you owe to your users (their wallet balance) is a Liability. When a user transfers ₦100,000 into their virtual account:

  • Your clearing/bank account (Asset) increases by ₦100,000 (Debit).
  • The user's wallet account (Liability) increases by ₦100,000 (Credit).

Here is the schema required to support bulletproof ledger transactions in PostgreSQL:

CREATE TYPE account_type AS ENUM ('ASSET', 'LIABILITY', 'EQUITY', 'REVENUE', 'EXPENSE');
CREATE TYPE ledger_entry_direction AS ENUM ('DEBIT', 'CREDIT');
CREATE TYPE transaction_status AS ENUM ('PENDING', 'POSTED', 'VOIDED');

CREATE TABLE accounts (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    name VARCHAR(100) NOT NULL,
    type account_type NOT NULL,
    currency VARCHAR(3) NOT NULL DEFAULT 'NGN',
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE TABLE ledger_transactions (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    idempotency_key VARCHAR(255) UNIQUE NOT NULL,
    nip_session_id VARCHAR(30) UNIQUE,
    description TEXT NOT NULL,
    status transaction_status NOT NULL DEFAULT 'PENDING',
    posted_at TIMESTAMPTZ,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE TABLE ledger_entries (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    transaction_id UUID NOT NULL REFERENCES ledger_transactions(id) ON DELETE RESTRICT,
    account_id UUID NOT NULL REFERENCES accounts(id) ON DELETE RESTRICT,
    direction ledger_entry_direction NOT NULL,
    amount NUMERIC(18, 4) NOT NULL CHECK (amount > 0),
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Indexing for fast balance aggregations and lookups
CREATE INDEX idx_entries_account_id ON ledger_entries(account_id);
CREATE INDEX idx_transactions_nip_session ON ledger_transactions(nip_session_id);

Notice the strict database constraint: amount must be greater than zero. Direction (DEBIT or CREDIT) determines the sign during aggregation, preventing confusing negative amounts.

To ensure our ledger never goes out of balance, we use a PostgreSQL trigger or transactional application checks to guarantee that for any transaction_id, the sum of DEBIT entries strictly equals the sum of CREDIT entries.

Implementing the Reconciliation Engine in Node.js

When receiving a virtual account webhook from a provider (like Monnify, Flutterwave, or Paystack), your HTTP endpoint must remain thin. Validate the HMAC signature, parse the NIP Session ID, insert the raw event into a background processing table, and respond immediately with HTTP 200. Processing the settlement synchronously inside the webhook request lifecycle is an anti-pattern; if the connection drops midway, the sender retries while your database state is halfway written.

If you deal with network instability across multiple telcos, pair this with a reliable background processing system. We previously wrote about why Telco API Failures in Nigeria: Ditch Celery for a Go Transactional Outbox Engine is essential for handling low-level carrier network drops reliably.

Below is a complete, production-grade Node.js service using pg (node-postgres) that handles virtual account top-up settlements atomically using explicit database locks (PostgreSQL Concurrency Control Docs).

import { Pool, PoolClient } from 'pg';

interface VirtualAccountDepositPayload {
  providerRef: string;
  nipSessionId: string;
  userAccountId: string; // The user's liability account UUID
  clearingAccountId: string; // Your bank account asset UUID
  amountNaira: number;
}

export class LedgerService {
  constructor(private pool: Pool) {}

  /**
   * Settles a incoming NIBSS bank transfer into the double-entry ledger.
   * Idempotent based on NIP Session ID.
   */
  async processVirtualAccountDeposit(payload: VirtualAccountDepositPayload): Promise<string> {
    const client: PoolClient = await this.pool.connect();

    try {
      await client.query('BEGIN ISOLATION LEVEL READ COMMITTED');

      // 1. Check if this NIP session ID has already been recorded
      const existingTx = await client.query(
        `SELECT id, status FROM ledger_transactions WHERE nip_session_id = $1 FOR UPDATE`,
        [payload.nipSessionId]
      );

      if (existingTx.rowCount > 0) {
        await client.query('COMMIT');
        return existingTx.rows[0].id; // Already processed, drop execution safely
      }

      // 2. Create the Ledger Transaction
      const idempotencyKey = `VA_TOPUP_${payload.nipSessionId}`;
      const txResult = await client.query(
        `INSERT INTO ledger_transactions (idempotency_key, nip_session_id, description, status, posted_at)
         VALUES ($1, $2, $3, 'POSTED', NOW())
         RETURNING id`,
        [idempotencyKey, payload.nipSessionId, `NIBSS Transfer - Ref: ${payload.providerRef}`]
      );

      const transactionId = txResult.rows[0].id;
      const amount = payload.amountNaira;

      // 3. Insert DEBIT entry (Asset Account - Bank Clearing)
      await client.query(
        `INSERT INTO ledger_entries (transaction_id, account_id, direction, amount)
         VALUES ($1, $2, 'DEBIT', $3)`,
        [transactionId, payload.clearingAccountId, amount]
      );

      // 4. Insert CREDIT entry (Liability Account - User Wallet)
      await client.query(
        `INSERT INTO ledger_entries (transaction_id, account_id, direction, amount)
         VALUES ($1, $2, 'CREDIT', $3)`,
        [transactionId, payload.userAccountId, amount]
      );

      await client.query('COMMIT');
      return transactionId;
    } catch (error) {
      await client.query('ROLLBACK');
      throw error;
    } finally {
      client.release();
    }
  }

  /**
   * Calculates the current real-time balance for an account by aggregating entries.
   */
  async getAccountBalance(accountId: string): Promise<number> {
    const query = `
      SELECT 
        a.type,
        COALESCE(SUM(CASE WHEN le.direction = 'DEBIT' THEN le.amount ELSE 0 END), 0) as total_debits,
        COALESCE(SUM(CASE WHEN le.direction = 'CREDIT' THEN le.amount ELSE 0 END), 0) as total_credits
      FROM accounts a
      LEFT JOIN ledger_entries le ON a.id = le.account_id
      WHERE a.id = $1
      GROUP BY a.id, a.type;
    `;

    const res = await this.pool.query(query, [accountId]);
    if (res.rowCount === 0) throw new Error('Account not found');

    const { type, total_debits, total_credits } = res.rows[0];
    const debits = parseFloat(total_debits);
    const credits = parseFloat(total_credits);

    // For Asset accounts, Debits increase balance.
    // For Liability accounts, Credits increase balance.
    if (type === 'ASSET' || type === 'EXPENSE') {
      return debits - credits;
    } else {
      return credits - debits;
    }
  }
}

When operating at high concurrency, using distributed locking mechanisms alongside SQL transactions is essential. If you rely on Redis keys for fast deduplication prior to database operations, take a look at Paystack Webhook Retries: Why Redis Idempotency Keys Drop Payments Under Network Flaps to avoid dropping incoming webhook records when network connectivity flaps.

Handling Unsettled States and Cron Reconciliation

NIBSS Instant Payments are not always instant. When an outbound transfer moves through the switch, it passes through three stages:

  1. Originating Bank -> NIBSS Switch
  2. NIBSS Switch -> Beneficiary Bank
  3. Beneficiary Bank -> Virtual Account Webhook

If step 2 times out, NIBSS returns response code 09 (Pending). The provider's webhook will either not fire or fire with a pending status. To reconcile these hung funds, you must implement an asynchronous poll-and-settle worker that runs on a schedule.

| NIBSS Code | Provider Status | Action Required | | :--- | :--- | :--- | | 00 | SUCCESS | Post transaction to ledger immediately (DEBIT Clearing, CREDIT User Wallet). | | 09 | PENDING | Create a transaction in PENDING status. Do NOT insert ledger entries yet. | | 91 | FAILED / TIMEOUT | Retry query every 15 minutes up to 24 hours. Void transaction if confirmed failed. | | 51 | INSUFFICIENT_FUNDS | Mark transaction VOIDED. No entries written. |

Here is how you handle delayed transition updates when the polling worker finally receives a SUCCESS confirmation for a previously PENDING transaction:

-- Complete a pending transaction safely
BEGIN;

UPDATE ledger_transactions 
SET status = 'POSTED', posted_at = NOW() 
WHERE id = '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d' 
  AND status = 'PENDING';

-- Only insert entries if the row update affected exactly 1 row
INSERT INTO ledger_entries (transaction_id, account_id, direction, amount)
VALUES 
  ('9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d', 'clearing-account-uuid', 'DEBIT', 100000.00),
  ('9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d', 'user-wallet-account-uuid', 'CREDIT', 100000.00);

COMMIT;

By ensuring that UPDATE ... WHERE status = 'PENDING' checks state explicitly, you prevent concurrent execution workers from writing duplicate entries for transactions that transitioned while the worker was running.

For a deeper reading on architectural structures governing ledger balance designs, see Martin Fowler's Accounting Patterns.

Common Pitfalls in Virtual Account Reconciliation

1. Deduplicating on Provider Reference Instead of NIP Session ID

Virtual account providers (Monnify, Paystack, Providus) generate their own transaction references (e.g., MNFY_202603301234). However, if a user sends money, the provider might issue multiple internal attempt references for a single incoming bank transfer retry. Always use the NIP Session ID (a 30-character identifier generated by NIBSS) as your primary idempotency key. It is the only globally unique identifier guaranteed across the entire Nigerian banking network.

2. Performing Mutable Updates for Refunds or Reversals

When a bank transfer is recalled due to a duplicate credit or fraudulent dispute, engineers often attempt to run DELETE FROM ledger_entries or update historical transaction rows. Never delete or update existing ledger entries. To reverse an incorrect ₦100,000 credit:

  1. Create a new transaction titled REVERSAL_NIP_SESSION_ID.
  2. Write a DEBIT entry against the User's Wallet (Liability) for ₦100,000.
  3. Write a CREDIT entry against the Reversal/Dispute Account (Asset) for ₦100,000.

This keeps your audit history completely clean and matches real-world bank accounting standards.

3. Summing Entries on Every Read Without Materialized Views

Calculating a wallet balance using SUM(CASE WHEN ...) on a table with 50 million ledger_entries will stall your API queries. To maintain sub-millisecond response times:

  • Cache account balances in Redis or maintain a account_balances summary table updated inside the same database transaction.
  • Periodically run a nightly integrity job that re-calculates SUM(entries) and compares it against your cached summary table to ensure 0% drift.

FAQ

What happens if a user's wallet balance goes negative due to a bank reversal?

If a NIBSS transfer was initially reported as SUCCESS by your bank partner but later recalled due to an interbank settlement reversal, executing a reversal ledger entry will push the user's liability account balance below zero. This accurately reflects real life: the user owes your platform money. You should lock withdrawals on the account until subsequent deposits cover the negative balance.

How do we handle provider fee deductions on bank transfers?

If your virtual account provider charges ₦50 per deposit, your double-entry transaction will contain three or four entries instead of two:

  • DEBIT Clearing Account (Asset): ₦100,000
  • CREDIT User Wallet Account (Liability): ₦99,950
  • CREDIT Provider Fee Revenue/Expense Account: ₦50

The sum of debits (₦100,000) still strictly equals the sum of credits (₦99,950 + ₦50).

Why not use PostgreSQL SERIALIZABLE isolation level for all payment operations?

While SERIALIZABLE isolation prevents read and write anomalies automatically, PostgreSQL enforces it using Serialization Anomaly checks that throw 40001 serialization failure exceptions under high concurrency. In a high-throughput Lagos payment engine, handling constant application-level retries adds latency. READ COMMITTED combined with explicit row locking (FOR UPDATE) on key parent records provides superior throughput while retaining absolute mathematical correctness.

Should we store monetary values as floating-point numbers or integers?

Never use float or double types for currency. Floating-point arithmetic produces rounding errors (e.g., 0.1 + 0.2 = 0.30000000000000004). Store currency in PostgreSQL as NUMERIC(18, 4) or as integer kobo/cents (e.g., ₦100.00 stored as 10000).

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.

Tags:#Fintech#Node.js#PostgreSQL#NIBSS#Payments#Architecture

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.