Fintech

BVN/NIN Verification Failures: Building a Fault-Tolerant Identity Cascade in Node.js

C
Chidi OkekeVP of Frontend Engineering
October 26, 202617 min read
BVN/NIN Verification Failures: Building a Fault-Tolerant Identity Cascade in Node.js

When NIBSS or NIMC endpoints time out during peak hours, user onboarding stalls. Here is how we engineered a multi-provider fallback cascade with fuzzy name matching to achieve 99.9% identity verification uptime.

On a Friday evening at 5:30 PM in Lagos, traffic on your payment app spikes as workers receive end-of-month salary alerts. Users download your app, enter their phone number, and type in their Bank Verification Number (BVN) or Virtual National Identification Number (vNIN) to pass Tier-1 onboarding. Then your logs turn red.

The primary NIBSS (Nigeria Inter-Bank Settlement System) bridge endpoint suddenly jumps from an 800ms response time to a 14-second tail latency before dropping connections with HTTP 504 Gateway Timeouts. Your single-provider verification wrapper throws an unhandled rejection, and 38% of your new user registrations fail within two hours. Users abandon the app, complaining on X (formerly Twitter) that your platform "does not work."

Relying on a single vendor or direct upstream connectivity for Central Bank of Nigeria (CBN) mandated KYC verification is a strategy destined for downtime. Aggregators like Prembly, IdentityPass, Youverify, and Smile Identity route requests to the same underlying government databases—NIBSS for BVN and NIMC for NIN—which routinely experience downstream throttles and maintenance windows.

To build a high-conversion onboarding flow, you must implement an identity cascade: an architecture that routes around vendor outages, handles asymmetric response formats, caches non-sensitive matching tokens, and uses fuzzy string comparison to evaluate name mismatches caused by cultural naming conventions.


The Architecture of a Resilient Identity Cascade

A resilient verification engine relies on three operational tiers:

  1. Primary Circuit-Broken Provider: Route real-time requests through your lowest-cost provider wrapped in a circuit breaker.
  2. Secondary Fallback Provider: If the primary circuit trips or exceeds a tight 3000ms threshold, immediately attempt a execution path through a secondary provider.
  3. Asynchronous Verification Queue: If all real-time providers fail or time out, save the encrypted payload, return an HTTP 202 Accepted with a PENDING_VERIFICATION status to the frontend, and process the verification via a background worker with exponential backoff.

Here is how provider strategies compare under typical Nigerian infrastructure conditions:

| Operational Metric | Single API Direct Route | Multi-Vendor Sync Fallback | Async Fallback Cascade | | :--- | :--- | :--- | :--- | | P99 Latency (Normal) | 850ms | 920ms | 880ms | | P99 Latency (Outage) | Timeout (15,000ms+) | 3,400ms | 2,900ms (Client gets 202) | | Failure Rate during NIBSS Blip | ~40% - 60% | ~8% - 12% | < 0.5% | | Cost Optimization | Low | Medium | High | | Compliance Complexity | Low | Medium | High (Requires Audit Logging) |

Notice how the Async Fallback Cascade decouples identity verification from user session HTTP request/response lifecycles, ensuring user drop-off remains negligible even when NIMC or NIBSS suffer prolonged outages.


Step 1: Solving the "Name Mismatch" Problem with Fuzzy Matching

One major reason for false-positive identity rejections in Nigeria is rigid string comparison (===).

If NIBSS returns ADEBAYO OLUMIDE SUNDAY and the user inputs Olumide S. Adebayo, exact string matching fails immediately. CBN compliance regulations require high-confidence verification, but throwing away real customers because of middle-name omissions or transposed first/last names damages unit economics.

We solve this by combining string normalization, token sorting, and the Jaro-Winkler distance algorithm using the natural library.

// nameMatcher.ts
import { JaroWinklerDistance } from "natural";

interface NameMatchResult {
  isMatch: boolean;
  score: number;
  reason?: string;
}

/**
 * Normalizes strings by removing titles, special characters, and converting to uppercase.
 */
function cleanNameString(name: string): string {
  return name
    .toUpperCase()
    .replace(/\b(MR|MRS|MS|DR|CHIEF|PASTOR|ALHAJI)\b/g, "")
    .replace(/[^A-Z\s]/g, "")
    .replace(/\s+/g, " ")
    .trim();
}

/**
 * Tokenizes and sorts names alphabetically to ignore first/last name transposition.
 */
function tokenSort(name: string): string {
  return cleanNameString(name).split(" ").sort().join(" ");
}

export function verifyNameMatch(
  inputName: string,
  returnedName: string,
  threshold = 0.85
): NameMatchResult {
  const cleanInput = cleanNameString(inputName);
  const cleanReturned = cleanNameString(returnedName);

  // Direct exact match after normalization
  if (cleanInput === cleanReturned) {
    return { isMatch: true, score: 1.0 };
  }

  // Token sort comparison (Handles "Adebayo Olumide" vs "Olumide Adebayo")
  const sortedInput = tokenSort(cleanInput);
  const sortedReturned = tokenSort(cleanReturned);
  
  if (sortedInput === sortedReturned) {
    return { isMatch: true, score: 0.98 };
  }

  // Calculate Jaro-Winkler similarity on sorted tokens
  const score = JaroWinklerDistance(sortedInput, sortedReturned, {});

  if (score >= threshold) {
    return { isMatch: true, score };
  }

  return {
    isMatch: false,
    score,
    reason: `Similarity score ${score.toFixed(2)} below threshold ${threshold}`,
  };
}

Step 2: Implementing the Multi-Provider Cascade with Opossum Circuit Breakers

Next, we write the orchestration service. We use opossum to wrap upstream provider network requests in circuit breakers. If Vendor A fails 50% of its last 10 requests within a 30-second window, its circuit trips, and requests immediately route to Vendor B without waiting for timeout timeouts.

For details on handling high-throughput locking scenarios for payment pipelines, see our previous engineering deep dive on Handling 500 Webhooks/Sec: Redis Mutexes vs Postgres Advisory Locks for Paystack Idempotency.

// identityCascade.ts
import CircuitBreaker from "opossum";
import axios from "axios";
import { verifyNameMatch } from "./nameMatcher";
import { createCipheriv, randomBytes } from "crypto";

interface IdentityVerificationRequest {
  bvn?: string;
  vnin?: string;
  firstName: string;
  lastName: string;
  dob: string; // YYYY-MM-DD
}

interface VerificationResponse {
  status: "VERIFIED" | "FAILED" | "PENDING";
  providerUsed?: string;
  matchScore?: number;
  reference: string;
}

const circuitOptions = {
  timeout: 3000, // 3 seconds timeout before failing over
  errorThresholdPercentage: 50,
  resetTimeout: 30000, // Wait 30s before attempting to close circuit
};

async function callPrimaryVendor(payload: IdentityVerificationRequest) {
  const response = await axios.post(
    "https://api.primary-vendor.co/v1/kyc/bvn",
    {
      bvn_number: payload.bvn,
    },
    {
      headers: { Authorization: `Bearer ${process.env.PRIMARY_VENDOR_KEY}` },
      timeout: 2800,
    }
  );
  return {
    fullName: `${response.data.data.first_name} ${response.data.data.last_name}`,
    dob: response.data.data.date_of_birth,
  };
}

async function callSecondaryVendor(payload: IdentityVerificationRequest) {
  const response = await axios.post(
    "https://api.secondary-vendor.ng/api/v3/identity/bvn/verify",
    {
      number: payload.bvn,
    },
    {
      headers: { "x-api-key": process.env.SECONDARY_VENDOR_KEY! },
      timeout: 2800,
    }
  );
  return {
    fullName: response.data.identity.full_name,
    dob: response.data.identity.dob,
  };
}

const primaryBreaker = new CircuitBreaker(callPrimaryVendor, circuitOptions);
const secondaryBreaker = new CircuitBreaker(callSecondaryVendor, circuitOptions);

export class IdentityService {
  public async verifyCustomer(
    req: IdentityVerificationRequest,
    reference: string
  ): Promise<VerificationResponse> {
    let rawData = null;
    let providerUsed = "";

    // Try Primary Provider
    try {
      rawData = await primaryBreaker.fire(req);
      providerUsed = "PRIMARY_VENDOR";
    } catch (primaryErr) {
      console.warn(`[KYC Failover] Primary vendor failed. Routing to secondary. Reason: ${(primaryErr as Error).message}`);
      
      // Try Secondary Provider
      try {
        rawData = await secondaryBreaker.fire(req);
        providerUsed = "SECONDARY_VENDOR";
      } catch (secondaryErr) {
        console.error(`[KYC Failover] Both providers failed. Falling back to Async processing.`);
        return {
          status: "PENDING",
          reference,
        };
      }
    }

    // Verify Name Match
    const inputFullName = `${req.firstName} ${req.lastName}`;
    const matchResult = verifyNameMatch(inputFullName, rawData.fullName);

    if (!matchResult.isMatch) {
      return {
        status: "FAILED",
        providerUsed,
        matchScore: matchResult.score,
        reference,
      };
    }

    // Verify Date of Birth
    if (req.dob !== rawData.dob) {
      return {
        status: "FAILED",
        providerUsed,
        matchScore: matchResult.score,
        reference,
      };
    }

    return {
      status: "VERIFIED",
      providerUsed,
      matchScore: matchResult.score,
      reference,
    };
  }
}

Step 3: Asynchronous Retries with Encrypted BullMQ Processing

When both real-time providers trip their breakers, we do not throw an HTTP 500 error. Instead, we offload the job to a BullMQ Redis queue.

However, storing unencrypted BVN and NIN values in Redis exposes you to regulatory non-compliance with the Nigeria Data Protection Act (NDPA) and CBN IT standards. Always encrypt sensitive payload fields using AES-256-GCM before putting them on a Redis instance.

// kycWorker.ts
import { Worker, Queue } from "bullmq";
import Redis from "ioredis";
import { createCipheriv, createDecipheriv, randomBytes } from "crypto";
import { IdentityService } from "./identityCascade";

const redisConnection = new Redis(process.env.REDIS_URL!);
export const kycQueue = new Queue("kyc-fallback-queue", { connection: redisConnection });

const ALGORITHM = "aes-256-gcm";
const ENCRYPTION_KEY = Buffer.from(process.env.ENCRYPTION_KEY_HEX!, "hex"); // Must be 32 bytes

export function encryptPayload(text: string): { iv: string; encryptedData: string; tag: string } {
  const iv = randomBytes(12);
  const cipher = createCipheriv(ALGORITHM, ENCRYPTION_KEY, iv);
  let encrypted = cipher.update(text, "utf8", "hex");
  encrypted += cipher.final("hex");
  return {
    iv: iv.toString("hex"),
    encryptedData: encrypted,
    tag: cipher.getAuthTag().toString("hex"),
  };
}

export function decryptPayload(encrypted: { iv: string; encryptedData: string; tag: string }): string {
  const decipher = createDecipheriv(ALGORITHM, ENCRYPTION_KEY, Buffer.from(encrypted.iv, "hex"));
  decipher.setAuthTag(Buffer.from(encrypted.tag, "hex"));
  let decrypted = decipher.update(encrypted.encryptedData, "hex", "utf8");
  decrypted += decipher.final("utf8");
  return decrypted;
}

// Background Worker Setup
const identityService = new IdentityService();

const worker = new Worker(
  "kyc-fallback-queue",
  async (job) => {
    console.log(`[Worker] Processing delayed KYC job: ${job.id}`);
    const decryptedPayloadString = decryptPayload(job.data.encryptedPayload);
    const payload = JSON.parse(decryptedPayloadString);

    const result = await identityService.verifyCustomer(payload, job.data.reference);

    if (result.status === "PENDING") {
      // Re-queue job with exponential backoff if upstream remains unavailable
      throw new Error("Upstream providers still unresponsive. Retrying...");
    }

    // Update database record and trigger webhook / push notification to app
    await updateCustomerKYCStatus(job.data.reference, result);
  },
  {
    connection: redisConnection,
    limiter: {
      max: 10, // Max 10 requests per second to avoid triggering vendor rate limits
      duration: 1000,
    },
  }
);

async function updateCustomerKYCStatus(ref: string, result: any) {
  // Implementation updates core database ledger status
  // For transactional consistency during user state updates, refer to our ledger pattern guide:
  // /blog/resolving-nip-ghost-credits-building-an-idempotent-bank-transfer-ledger-engine-i-mvk5ah6uavgj
}

Common Pitfalls When Implementing Identity Engines in Nigeria

1. Storing Raw 11-Digit NIN Strings

Under the Central Bank of Nigeria guidelines and NIMC security requirements, application systems are prohibited from saving raw 11-digit National Identification Numbers in databases without user authorization tokenization. Always demand the Virtual NIN (vNIN), which is generated via the *346*3*NIN*AgentCode# USSD string or the NIMC mobile application. The vNIN is enterprise-specific and dynamically expires.

2. Not Accounting for Vendor Rate Limits and Burst Throttles

Aggregators set strict TPS (Transactions Per Second) caps. When your app goes viral or runs an acquisition push, sending 200 concurrent HTTP requests to a vendor endpoint will trigger HTTP 429 Too Many Requests. Enforce local rate limiting in your Node.js application layer using Redis token buckets before requests leave your server boundary.

3. Trusting Status Codes Over Payload Attributes

Some identity aggregators return HTTP 200 OK even when the downstream verification attempt actually failed. The body might contain { "success": false, "message": "NIBSS Database Unreachable" }. If your application code checks only response.status === 200, you will inadvertently mark users as verified or throw invalid database exceptions. Always validate structural fields in the response body using a runtime schema validator like Zod.

4. Cache Eviction Oversights for Failed Matches

Caching successful match responses (e.g. mapping SHA256(bvn + dob) to identity metadata) saves money on repeat API calls. But never cache failure responses long-term. If a vendor returns an error because of a temporary downstream network hiccup, caching that failure means the user remains permanently blocked until manual support intervention.


Frequently Asked Questions

How does CBN require fintechs to handle vNIN vs raw NIN?

CBN compliance frameworks prohibit raw NIN storage on commercial application servers. Fintechs must collect the 16-character alphanumeric vNIN, which is generated using your enterprise's NIMC Agent ID. Upstream aggregators validate this vNIN against NIMC servers to return demographic records.

What Jaro-Winkler threshold works best for Nigerian names?

A match threshold between 0.82 and 0.88 provides optimal precision and recall. A score of 1.0 represents an exact string match. Dropping below 0.80 risks matching totally different individuals with common regional names, while setting it above 0.92 causes false rejections due to minor typographical errors or omitted middle names.

How long should we keep a user in a PENDING_VERIFICATION status?

You should allow background workers up to 24 hours to resolve identity verification. Most NIBSS or NIMC maintenance windows resolve within 1 to 4 hours. Once the job succeeds or reaches its final retry limit, alert the user via push notification or WhatsApp messaging.

Why do we encrypt payload fields before putting them into Redis queues?

Redis instances are frequently configured without at-rest encryption or are stored in shared cluster nodes. Storing raw identity records like BVNs, phone numbers, and home addresses in plaintext opens your infrastructure to massive security penalties under the NDPA if Redis logs or dumps leak.


Next Steps for Your Production KYC Architecture

To ensure your identity pipeline is ready for production:

  1. Replace hardcoded API timeouts with explicit, short-circuiting HTTP clients like Axios configured with opossum breakers.
  2. Implement Jaro-Winkler name normalization to eliminate human-induced drop-offs caused by ordering discrepancies.
  3. Encrypt sensitive identity tokens at rest before queuing background tasks using AES-256-GCM encryption.
  4. Expose clear client-side polling or WebSocket updates so users are aware when their verification moves from pending to confirmed.

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#TypeScript#KYC#Nigeria#System Architecture#Redis

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.