Fintech

Resolving NIP Ghost Credits: Building an Idempotent Bank Transfer Ledger Engine in Go

O
Oluwaseun AlabiTechnical Director
October 22, 202619 min read
Resolving NIP Ghost Credits: Building an Idempotent Bank Transfer Ledger Engine in Go

Bank transfers account for the majority of digital payment volume in Nigeria, but NIBSS timeouts and delayed provider webhooks frequently trigger ghost credits and duplicate wallet updates. Here is how we build a deterministic, zero-phantom-credit ledger in Go using NIP Session IDs.

Resolving NIP Ghost Credits: Building an Idempotent Bank Transfer Ledger Engine in Go

It is 4:45 PM on a Friday payday in Lagos. A customer opens your mobile app, generates a temporary virtual account, and pushes ₦250,000 from their GTBank app to complete a high-value purchase.

Behind the scenes, GTBank routes the fund transfer through the NIBSS Instant Payment (NIP) switch to your payment partner's settlement bank (say, Wema or Providus). NIBSS processes the debit, but the acknowledgement connection back to GTBank times out. GTBank flags the transfer as pending. Meanwhile, your payment provider's webhook engine catches the inbound credit 12 minutes late due to queue backpressure, sending a charge.success HTTP POST request to your backend.

Your API receives the webhook, credits the user's wallet, and marks the transaction as complete. But at 5:15 PM, GTBank’s automated reconciliation system retries the stalled NIP packet. The payment provider processes the incoming instruction again and fires a second webhook—this time with a different internal payment reference ID, but carrying the exact same 30-digit NIP Session ID.

If your engine matches payments on provider-generated transaction references instead of the underlying NIBSS Session ID, your ledger will double-credit the customer’s wallet. The user promptly withdraws ₦500,000. Your risk ops team notices the ₦250,000 balance shortfall during midnight reconciliation. You have just suffered a ghost credit.

In Nigerian financial infrastructure, bank transfers account for over 80% of digital transaction volume. Yet, engineers frequently treat bank transfer webhooks like card payments. They are not the same. NIBSS is an asynchronous, multi-hop interbank messaging protocol, and building a system that relies solely on payment aggregator callback payloads will eventually bleed your company's capital.

Here is how to design and build a production-grade, deterministic NIP ledger matching engine in Go that prevents double-crediting, survives dropped webhooks, and automatically reconciles T+1 bank settlement files.


Deconstructing NIP Session IDs and Provider Webhook Payloads

Every single electronic funds transfer traversing the Nigerian banking network is assigned a unique 30-digit numeric string by the originating bank known as the NIP Session ID. This ID is the single source of truth across the entire interbank ecosystem.

A standard NIP Session ID follows a strict layout:

  • Digits 1–6: Originating Bank Financial Institution Code (e.g., 000013 for GTBank, 000011 for First Bank).
  • Digits 7–12: Date stamp formatted as YYMMDD (e.g., 241025).
  • Digits 13–24: Channel Code + System Sequence Identifier.
  • Digits 25–30: Unique incremental transaction sequence number.

Regardless of whether a user pays into a dynamic virtual account provided by Paystack, Flutterwave, or Monnify, the core clearing network always stamps the same 30-digit NIP Session ID on the transfer packet.

Aggregators wrap this raw NIP packet in their own JSON structures. When building a multi-provider fallback system, relying on provider-specific IDs like paystack_trx_9812379 or monnify_MNFY_88123 is dangerous because if a provider retries or re-routes an incoming payment across multiple upstream switching banks, those provider IDs change. The NIP Session ID does not.

Let us look at how different provider payloads expose this critical identifier:

| Provider | Raw Webhook Field Path for NIP Session ID | Example Field Value | | :--- | :--- | :--- | | Paystack | data.authorization.nir_session_id or data.id | 000013241025164201000192837401 | | Monnify | eventData.paymentMetaData.nipSessionId | 000011241025091244109283746152 | | Wema / Alat Direct | originator.sessionId | 000035241025110239000182736412 | | Interswitch / Quickteller | Response.Transaction.NIPSessionID | 000002241025121102981273645120 |

If your system collects PII during account generation, ensure you read our guide on Blind Indexing for NDPR Compliance: Why Encrypted BVNs Break Postgres Indexes and How HMAC-SHA256 Fixes It to securely correlate user identities without breaking database query performance.


Designing the Multi-Phase Ledger State Machine

To eliminate ghost credits, your ledger must decouple receiving a payload from committing funds to an available user balance. We model inbound transfer settlement using a 5-state deterministic state machine:

[ WEBHOOK RECEIVED ] 
         │
         ▼
  ┌──────────────┐      Session ID Exists?      ┌───────────────────────┐
  │ PENDING_MATCH │────────────────────────────►│ FLAGGED_DUPLICATE     │
  └──────────────┘              YES             │ (Audit log, no credit)│
         │                                      └───────────────────────┘
         │ NO
         ▼
  ┌──────────────┐      Amount Match?           ┌───────────────────────┐
  │   MATCHED    │────────────────────────────►│ DISCREPANCY_HOLD      │
  └──────────────┘              NO              │ (Requires Ops review) │
         │                                      └───────────────────────┘
         │ YES
         ▼
  ┌──────────────┐      T+1 Bank Settlement     ┌───────────────────────┐
  │   COMMITTED  │────────────────────────────►│ SETTLED               │
  └──────────────┘        CSV Ingested          └───────────────────────┘

Database Schema (PostgreSQL)

We enforce constraints directly at the database layer using raw SQL. We do not trust application code to enforce uniqueness under high concurrency; database table constraints are mandatory.

CREATE TABLE accounts (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID NOT NULL,
    account_number VARCHAR(10) UNIQUE NOT NULL,
    balance_kobo BIGINT NOT NULL DEFAULT 0 CHECK (balance_kobo >= 0),
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE TABLE nip_transactions (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    nip_session_id VARCHAR(30) UNIQUE NOT NULL, -- Enforces NIP-level idempotency
    provider_reference VARCHAR(100) NOT NULL,
    account_number VARCHAR(10) NOT NULL REFERENCES accounts(account_number),
    amount_kobo BIGINT NOT NULL CHECK (amount_kobo > 0),
    status VARCHAR(30) NOT NULL DEFAULT 'PENDING_MATCH',
    originating_bank_code VARCHAR(10) NOT NULL,
    raw_payload JSONB NOT NULL,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE TABLE ledger_entries (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    transaction_id UUID NOT NULL REFERENCES nip_transactions(id),
    account_id UUID NOT NULL REFERENCES accounts(id),
    entry_type VARCHAR(10) NOT NULL CHECK (entry_type IN ('CREDIT', 'DEBIT')),
    amount_kobo BIGINT NOT NULL,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX idx_nip_transactions_session_id ON nip_transactions(nip_session_id);
CREATE INDEX idx_nip_transactions_status ON nip_transactions(status);

Notice that balance_kobo and amount_kobo are stored as 64-bit integers (BIGINT). Never store currency values as floating-point numbers (FLOAT or NUMERIC without fixed scale). Floating-point arithmetic errors will accumulate rounding drift over millions of transactions.


Step-by-Step Implementation in Go

Now, let us build the core ingestion service in Go. This service must acquire an explicit transaction lock, perform an idempotent insertion on the 30-digit NIP Session ID, credit the wallet, and record double-entry ledger rows atomically.

If you want to understand how PostgreSQL lock mechanisms perform under extreme load, check our deep-dive analysis on Handling 500 Webhooks/Sec: Redis Mutexes vs Postgres Advisory Locks for Paystack Idempotency.

Here is the complete production-grade matching implementation in Go using standard library tools and lib/pq drivers.

package ledger

import (
	"context"
	"database/sql"
	"encoding/json"
	"errors"
	"fmt"
	"log"
	"regexp"
	"strings"
	time"
)

var nipSessionIDRegex = regexp.MustCompile(`^[0-9]{30}$`)

var (
	ErrInvalidSessionID = errors.New("invalid NIP session ID format")
	ErrDuplicateTransfer = errors.New("transaction with this NIP session ID already processed")
	ErrAccountNotFound  = errors.New("destination account number does not exist")
)

type WebhookPayload struct {
	ProviderRef         string `json:"provider_reference"`
	NIPSessionID        string `json:"nip_session_id"`
	AccountNumber       string `json:"account_number"`
	AmountInKobo        int64  `json:"amount_kobo"`
	OriginatingBankCode string `json:"originating_bank_code"`
}

type Engine struct {
	db *sql.DB
}

NewEngine(db *sql.DB) *Engine {
	return &Engine{db: db}
}

// ProcessInboundTransfer handles incoming bank credit events with full database transaction isolation
func (e *Engine) ProcessInboundTransfer(ctx context.Context, payload WebhookPayload, rawJSON []byte) error {
	// 1. Strict Validation of NIP Session ID
	cleanSessionID := strings.TrimSpace(payload.NIPSessionID)
	if !nipSessionIDRegex.MatchString(cleanSessionID) {
		return fmt.Errorf("%w: got '%s'", ErrInvalidSessionID, cleanSessionID)
	}

	// 2. Begin Serializable or Read Committed DB Transaction
	tx, err := e.db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelReadCommitted})
	if err != nil {
		return fmt.Errorf("failed to initiate transaction: %w", err)
	}
	defer tx.Rollback()

	// 3. Insert transaction record with ON CONFLICT DO NOTHING to guarantee idempotency at the DB level
	var transactionID string
	query := `
		INSERT INTO nip_transactions (
			nip_session_id, provider_reference, account_number, amount_kobo, status, originating_bank_code, raw_payload
		)
		VALUES ($1, $2, $3, $4, 'MATCHED', $5, $6)
		ON CONFLICT (nip_session_id) DO NOTHING
		RETURNING id;
	`

	err = tx.QueryRowContext(ctx, query, 
		cleanSessionID, 
		payload.ProviderRef, 
		payload.AccountNumber, 
		payload.AmountInKobo, 
		payload.OriginatingBankCode, 
		rawJSON,
	).Scan(&transactionID)

	if err != nil {
		if errors.Is(err, sql.ErrNoRows) {
			// ON CONFLICT triggered — this NIP Session ID was already ingested!
			log.Printf("[WARN] Duplicate NIP webhook blocked for Session ID: %s", cleanSessionID)
			return ErrDuplicateTransfer
		}
		return fmt.Errorf("failed to record nip transaction: %w", err)
	}

	// 4. Lock and retrieve user account (FOR UPDATE prevents race conditions on user balance)
	var accountID string
	var currentBalance int64
	accQuery := `
		SELECT id, balance_kobo 
		FROM accounts 
		WHERE account_number = $1 
		FOR UPDATE;
	`
	err = tx.QueryRowContext(ctx, accQuery, payload.AccountNumber).Scan(&accountID, &currentBalance)
	if err != nil {
		if errors.Is(err, sql.ErrNoRows) {
			return ErrAccountNotFound
		}
		return fmt.Errorf("failed to lock account: %w", err)
	}

	// 5. Atomic Balance Update
	updateAccQuery := `
		UPDATE accounts 
		SET balance_kobo = balance_kobo + $1 
		WHERE id = $2;
	`
	_, err = tx.ExecContext(ctx, updateAccQuery, payload.AmountInKobo, accountID)
	if err != nil {
		return fmt.Errorf("failed to update account balance: %w", err)
	}

	// 6. Write Double-Entry Ledger Entry
	ledgerQuery := `
		INSERT INTO ledger_entries (transaction_id, account_id, entry_type, amount_kobo)
		VALUES ($1, $2, 'CREDIT', $3);
	`
	_, err = tx.ExecContext(ctx, ledgerQuery, transactionID, accountID, payload.AmountInKobo)
	if err != nil {
		return fmt.Errorf("failed to insert ledger entry: %w", err)
	}

	// 7. Commit Transaction cleanly
	if err := tx.Commit(); err != nil {
		return fmt.Errorf("failed to commit transaction: %w", err)
	}

	log.Printf("[SUCCESS] Successfully credited %d kobo to account %s (NIP: %s)", payload.AmountInKobo, payload.AccountNumber, cleanSessionID)
	return nil
}

Handling Nightly Settlement File Audits (T+1 CSV Processing)

In Nigeria, webhooks fail. Internet service providers go down, switching banks experience downtime, and aggregators silently drop callbacks. According to operational guidelines set by the Central Bank of Nigeria (CBN), switching nodes must settle payment service providers on a T+1 schedule.

Every morning at 2:00 AM, your payment partner drops a CSV settlement report on an SFTP server containing all completed bank transfers cleared through NIBSS for the previous day. To guarantee zero dropped credits, you must implement an automated reconciliation loop that runs against this file.

Here is how the automated T+1 processor works:

  1. Fetch and Parse Settlement CSV: Stream lines into memory using Go’s encoding/csv package.
  2. Look Up Session ID: Query nip_transactions using the CSV row's NIP Session ID.
  3. Handle Missing Webhooks (Orphaned Credits): If the record does not exist in your database, execute ProcessInboundTransfer automatically to credit the customer's wallet. This catches funds that were transferred by the customer but whose webhooks failed to deliver.
  4. Handle Discrepancies: If the record exists, verify that amount_kobo on the settlement CSV matches the DB record precisely. If there is a mismatch (e.g., bank charges deducted upstream), flag the row status as DISCREPANCY_HOLD and send an alert to Risk Ops.
// ReconcileSettlementRow checks a T+1 CSV row against local ledger records
func (e *Engine) ReconcileSettlementRow(ctx context.Context, csvSessionID, csvAccount string, csvAmountKobo int64) error {
	var dbAmount int64
	var status string

	query := `SELECT amount_kobo, status FROM nip_transactions WHERE nip_session_id = $1`
	err := e.db.QueryRowContext(ctx, query, csvSessionID).Scan(&dbAmount, &status)

	switch {
	case errors.Is(err, sql.ErrNoRows):
		// Webhook was missed entirely! Re-inject transaction automatically.
		log.Printf("[RECONCILIATION] Unprocessed settlement found for NIP %s. Processing now...", csvSessionID)
		payload := WebhookPayload{
			ProviderRef:         "T1_SETTLEMENT_RECOVERY",
			NIPSessionID:        csvSessionID,
			AccountNumber:       csvAccount,
			AmountInKobo:        csvAmountKobo,
			OriginatingBankCode: csvSessionID[0:6], // Extract first 6 digits as bank code
		}
		return e.ProcessInboundTransfer(ctx, payload, []byte(`{"source":"T+1_csv"}`))

	case err != nil:
		return fmt.Errorf("database error during reconciliation: %w", err)

	default:
		// Record exists. Ensure amounts match exactly.
		if dbAmount != csvAmountKobo {
			log.Printf("[CRITICAL] Amount mismatch for Session ID %s! DB: %d, CSV: %d", csvSessionID, dbAmount, csvAmountKobo)
			_, updateErr := e.db.ExecContext(ctx, `UPDATE nip_transactions SET status = 'DISCREPANCY_HOLD' WHERE nip_session_id = $1`, csvSessionID)
			return updateErr
		}
		// Mark status as verified settlement
		_, updateErr := e.db.ExecContext(ctx, `UPDATE nip_transactions SET status = 'SETTLED' WHERE nip_session_id = $1`, csvSessionID)
		return updateErr
	}
}

For official specifications on interbank processing windows, refer to the NIBSS NIP Operational Guidelines.


Common Pitfalls in Bank Transfer Implementations

1. Truncating or Formatting NIP Session IDs as Numbers

Never parse a NIP Session ID into a standard JavaScript Number or Go int64. A 30-digit integer exceeds standard 64-bit integer limits (2^63 - 1 is 19 digits). Standard JSON parsers in dynamically typed languages will silently truncate or round the final 11 digits, turning distinct session IDs into identical strings and causing legitimate transfers to get rejected as duplicates. Always store, parse, and validate NIP Session IDs strictly as fixed 30-character strings.

2. Using Non-Atomic Balance Updates

Running SELECT balance FROM accounts in application code, adding the incoming amount in Go runtime code, and then calling UPDATE accounts SET balance = newBalance introduces race conditions. If two webhooks hit different microservice instances simultaneously, instance B will overwrite the write performed by instance A. Always execute balance modifications directly inside PostgreSQL using UPDATE accounts SET balance_kobo = balance_kobo + $1 WHERE id = $2 within a SELECT ... FOR UPDATE row-locking block.

3. Relying on Provider Webhooks for Real-Time Order Release

Do not hold user checkouts open for 30 minutes waiting for a bank transfer webhook. Webhook delivery latency over NIBSS fluctuates heavily based on interbank network load. Always advise users to complete bank transfers asynchronously while displaying clear status polling in your frontend UI.


Frequently Asked Questions

What happens if a customer sends less than the expected transaction amount?

When a user transfers an incorrect amount (e.g., sending ₦4,000 for a ₦5,000 order), your webhook parser should still record the transaction in nip_transactions using the actual kobo amount received. Credit the user's main wallet balance in kobo, but mark the order status as PARTIALLY_PAID. Never drop or discard a transfer webhook simply because the amount does not match an order expectation.

What if a payment provider does not send the 30-digit NIP Session ID in the webhook?

While modern Nigerian gateways provide the NIP Session ID in webhook callbacks, older aggregators or custom direct-to-bank integrations may omit it in raw payloads. In such cases, contact the payment gateway's support team immediately to enable NIP Session ID pass-through on your account. If unavailable, issue an instant synchronous API query to the provider’s GET /transactions/:id verification endpoint upon webhook receipt—the full verification payload usually exposes the NIP Session ID even when the raw webhook drops it.

How should we handle chargebacks and bank-initiated NIP reversals?

When a originating bank issues an official claim for an erroneous transfer (e.g., due to fraud or systemic bank error), NIBSS issues an interbank recall instruction. You should never auto-debit a customer balance below zero without audit logs. Record a dedicated DEBIT row in ledger_entries with a reference to the recall mandate ID. If the account lacks sufficient balance, transition the user account to a FROZEN_NEGATIVE_BALANCE state and flag it for manual compliance ops review.


To build resilient fintech products in high-volume environments, relying on happy-path network conditions is a recipe for balance sheet loss. Enforcing strict database constraints on 30-digit NIP Session IDs, isolating ledger writes inside DB transactions, and backing up webhooks with T+1 settlement file matching guarantees that every Naira entering your system is accounted for.

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#Go#Payments#PostgreSQL#Architecture#Nigeria

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.