SENIORCHAPTER 52

Inside a switch: routing, timeouts, PIN translation and stand-in

A switch holds no customer money and still decides how long every sender waits. Learn what it routes, what it times out, what it translates and what it may answer for a bank that is down, and why one slow bank is a problem for everyone who pays it

60 MINPAYMENTSUPDATED 2026-11-18
PREDICT

One receiving bank takes about 2% of a switch's transfers. Its median reply time is the same as every other bank's, but 3% of its replies never arrive inside the switch's 30-second timeout. Which describes what the switch's customers see?

You already know how a transfer looks from outside: a name enquiry, a transfer, an answer, and a status query when the answer does not come (Nigeria’s rails, payment states and refunds). You know what the messages look like on the wire (payment messages). This chapter takes the point of view of the machine in the middle.

What the switch is, and what it is not

A switch is the operator that routes payment messages between institutions that have no direct link to each other. Each institution connects once, to the switch, and the switch connects it to everyone else. That is the whole idea, and it is why the arithmetic works. The lab has 32 participants. Pairwise links would need 32 × 31 ÷ 2 = 496 connections, each with its own testing and keys. Through a switch, 32.

The switch’s public description of itself is modest. The contact-centre article of NIBSS (the Nigeria Inter-Bank Settlement System, the operator of the NIP instant payment service) lists the services under NIP as name enquiry (the source institution validates the beneficiary’s details from an account number), funds transfer by direct credit, funds transfer by direct debit (a scheduled debit instruction), transaction status query (a bank checks on a transaction it sent earlier) and balance enquiryas of 2026-11. For a credit transfer, the verbs a sending bank uses are name enquiry, transfer and status query. Behind them the switch does five jobs, and a design question hides in each.

Job What the switch does The question it forces
Route Finds the receiving institution from the message and forwards it What happens to a message for an institution that is down or unknown?
Check Applies rules it can apply without the bank: format, participant state, limits Which rules belong to the switch, and which to the bank?
Wait Holds the request open until the receiver answers or a timer fires How long, and what does each waiting request cost?
Record Writes down every message, so a later query has an answer How long is a record kept open for a late reply?
Answer Maps the receiver’s reply, or its silence, to a response code for the sender What does the sender hear when the switch does not know?
sending bankdebits its customerswitchcheck, recordtimer: 30 sno customer moneyreceiving bankowns the account1 transfer2 forward3 reply (in time)4 answertimer fires first: 97, sender must requerylate reply: recorded

What the switch does not do matters as much. In the lab’s model it holds no customer accounts, so it cannot tell whether an account is frozen, and it holds no customer money: the receiving bank credits its customer, and the banks settle their net positions later through sessions that a later chapter in this module, clearing and settlement at the switch, builds. NIBSS’s support article describes NIP as a deferred net settlement system in which funds are available in the beneficiary’s account in real time, before settlementas of 2026-11. That is the order the lab shows.

Search summaries of the Central Bank of Nigeria’s (CBN) Regulation on Instant (Inter-Bank) Electronic Funds Transfer Services in Nigeria describe an instant transfer as one whose delivery between the sending and receiving entities happens within 60 seconds, and say a receiving entity must apply the proceeds to the customer’s account within 60 seconds or, where that is impracticable, notify the sender, the beneficiary or the service provider. They give an effective date of 2 October 2018 (one entry gives 20 October). They also say the sending entity must refund a failed transaction returned by the receiving entity within 10 minutes, and one it was unable to process within one hour after the next settlement closure; that a wrongly credited transfer is reversed within one business day where funds are available; and that settlement is as agreed but no later than T+1, the next business day. Press reports add a ₦10,000 fine per item for a failed transfer not reversed within 24 hours of a complaint, and the summaries do not reconcile the 10-minute and 24-hour clocksas of 2026-11. Those are search summaries, and they do not show whether the regulation has since been amended: read the regulation before you rely on a clause. The 60 seconds is a rule about the participants and the service. It does not say what the switch’s own timer must be, and that number is the next section’s subject.

Routing is a lookup, and a session number carries a clue

Routing in the lab is a table. The participants table lists each institution’s code, its 3-digit NUBAN code and a 6-digit institution code. A name enquiry names the destination bank; the switch finds it, forwards the question and maps the answer to 00, 07 or 91. A transfer follows the same path.

The 30-digit session id is the switch’s handle on a transfer. In the lab’s model it is the sending institution’s 6-digit code, the time to the second (twelve digits) and twelve more digits that make it unique. The first transfer you read in the lab begins 900892260616…: the sender’s code, then 16 June 2026. A status query by session id therefore tells the switch who asked about what, and when, before it opens a single record. That layout is the lab’s, and a real switch’s is its operator’s to state.

Routing and settling are different tables. Owoleaf, P01 in the lab, is sponsored by B05: a message for P01 is routed to P01, but its sent and received totals settle through B05. A later chapter in this module, direct or sponsored, covers that line. Here the point is the separation: a switch that routes by one key and settles by another can change either without touching the other.

The timer is a decision about waiting

When the switch forwards a transfer it starts a timer, and when the timer fires first the switch must answer the sender with something. It has three honest choices, and two are wrong. It can say the transfer succeeded (a guess). It can say the transfer failed (a guess in the other direction). Or it can say it does not know. The lab’s 97 is the third answer, and it matches what idempotency and exactly once taught from the client’s side: a timeout means unknown.

Why unknown? Because in the lab’s model nothing tells the receiving bank that the switch gave up. It may be about to credit, or it may have a credit queued behind a slow database. The lab shows it. Of 101 transfers the switch answered 97, requery found 38 credited and 63 not. The receiving banks’ own logs show 42 credits on these transfers, all posted between 62 and 118 seconds after the request, so every reply came after the switch had given up at 30 seconds. (Requery found 38 of the 42; the last section of this chapter and step 4 return to the other four.) The sender’s bank, meanwhile, had a customer’s money debited and no answer.

A Substack commentary gives NIP’s name enquiry a 10-second timeout, describes a single 20-second end-to-end window for payment processing (the post is not consistent about its figures), and says the sending bank must send a transaction status query to resolve uncertaintyas of 2026-11. That is one writer’s account, not NIBSS’s: this chapter could not confirm any of those figures from a NIBSS document, and the lab’s 30 seconds is the lab’s own choice. When you build against a real switch, get its timer and its rules from the operator’s specification, and ask what it says about a reply that arrives after the timer.

What a stall costs

A request waiting for a reply holds something: a connection, a worker, a record. How many of them are held at once is the arrival rate times how long each waits. Take an illustrative bank that receives 100 requests a second. Normally each is held for 1 second. Suppose 3% of them stall for 30 seconds. The mean hold is 0.97 × 1 + 0.03 × 30 = 0.97 + 0.90 = 1.87 seconds, so about 100 × 1.87 = 187 requests are in flight for that bank, against 100 without stalls. The 3% of requests that stall hold 90 of those 187 slots. If every bank shares one pool of workers, that bank takes 87 extra slots from everyone else.

Two controls follow, and the lessons on timeouts, bulkheads and tail latency show them in a simulation. A bulkhead caps the number of requests one destination may hold, so one bank’s stall cannot take the whole pool. A per-participant timeout shortens the wait for a bank whose healthy replies are quick and whose bad ones never come. Running a switch and when a bank or a switch goes down, two later chapters in this module, add the circuit breaker and the alert that fires on it.

Setting a timeout from the data

You cannot set a timeout from the average. You set it from what a healthy reply looks like and what a stall costs. In the lab the replies that do arrive take up to 8,395 ms at the very slowest, so a timeout beneath about 8.4 seconds starts turning healthy replies into unknowns. How many it turns depends on the number you choose, and step 4 of the lab counts them. The shape is the lesson: below the healthy tail every second you shave turns good transfers into unknowns, and above it you save nothing for the healthy and a lot for the stalls.

A per-participant timeout beats a global one when banks differ. B19’s slowest healthy reply was 5,892 ms, so a 5-second timeout for B19 alone costs one healthy transfer and saves 25 seconds on each of its 11 stalls. What it does not do is change what B19 does with the request: a bank that was about to credit still credits. The timeout moves the sender’s answer earlier. It does not make the outcome known.

Reading a tail without fooling yourself

Averages hide stalls. 101 stalls in 17,998 transfers is 0.56%, and the median reply does not move, yet they are 13.1% of all the seconds senders waited. That is why a switch reports percentiles per receiving bank and not one network average. The 99th percentile (p99) is the reply time that 99 of every 100 beat.

A small count needs care. F02 shows 2 stalls in 124 transfers (1.61%) and P01 3 in 252 (1.19%), against 0.44% for the rest of the network once the Thursday incident is left out. Is that a slow bank or a run of luck? The lab computes the chance of seeing at least that many if the bank behaved like everyone else, and multiplies by the 32 participants you could have looked at, since you looked at all of them. For B19 that comes to about 7 in a million. For F02 and P01 it comes to more than 1, which means that among 32 banks you should expect to find a bank or two that look like this by luck: not proved. Report them as nothing yet. Report B19 as a problem. This is a judgment about a sample, and the lab’s data is generated, but the method is the same on real data.

PIN translation: re-encrypting a PIN without seeing it

Most of this chapter is about account-to-account transfers, which carry no PIN: the sending bank authenticates its own customer before it sends the message (authenticating the payer covers how). A card payment at a terminal is different. The customer types a PIN, and the issuing bank, not the acquirer, must verify it. The acquiring side and the issuing side do not share a key, and the switch sits between them.

A payment-security guide in the search results describes the flow like this: the terminal encrypts the PIN block, the acquirer’s hardware security module (HSM, a tamper-resistant device that holds keys and does the cryptography) converts it to the network’s key, and the network’s HSM converts it again to the issuer’s key, so that clear PINs and keys stay inside certified hardware. Vendor and cloud documentation in the same results call the keys between organisations zone keys. These are secondary sources, not the standard itselfas of 2026-11. The PCI Security Standards Council (PCI SSC) has a PIN Security standard page that describes the standard as covering the secure management, processing and transmission of PIN data at ATMs and point-of-sale terminals, including the lifecycle of cryptographic keys. Search results also showed a PCI SSC post announcing version 3.1 of its PIN Security Requirements and Testing Procedures, and a Visa notice dating v3.1 to March 2021. This chapter could not confirm that no later version exists, so check the council’s site for the current oneas of 2026-11..

Two design facts follow, both from the problem and not from any one vendor. First, a PIN block is the PIN arranged in a fixed layout (in some layouts combined with part of the card number) and then encrypted. The switch has the HSM re-encrypt it from the acquirer’s key to the issuer’s key, so the clear PIN never exists outside the HSM. Second, that is why a switch with a card function typically needs a hardware module and a key-management process audited against a standard: a switch that could see a clear PIN would be an extremely valuable target.

The lab does not implement PIN translation, for two reasons. Python’s standard library has no block cipher, and a hand-rolled one would teach the wrong lesson. And clear PINs must not appear in code or logs, even test ones. What you do get is the property to test: after a translation, no log line, error message or message trace may contain anything from which a PIN could be recovered. When you review a switch, that is the first thing to grep for.

Stand-in: answering for a bank that is down

When a receiving bank cannot be reached, the switch has the sender waiting and nothing to say. The simplest answer is a quick refusal: 91, beneficiary bank not available. The alternative is stand-in: the switch decides on the bank’s behalf, using rules the bank gave it beforehand, and tells the bank afterwards.

Stand-in is best known on the card side. Visa’s 2020 announcement of its Smarter Stand-In Processing, as summarised in search results, says the service approves or declines payments on behalf of issuers when their systems are offline, building on Visa’s existing stand-in capability by using deep learning on past transactions down to the cardholder level. The figure Visa gives for it, matching issuers’ own decisions about 95% of the time, is Visa’s own claim from its own testsas of 2026-11. Payment messages described the advice that follows: a message that reports what the stand-in decided, so the issuer’s books catch up.

Whether NIP has an equivalent for transfers is not something this chapter could confirm. The searches found NIBSS’s list of NIP services and a commentator’s account of the timeout, and no description of a stand-in. Treat what follows as the lab’s design exercise, not a description of any operator.

The useful question is what a switch may decide and what it may not. A rule of thumb that holds up: the switch may decide what it can compute from its own data, and what the bank delegated in advance with limits it set. It may not decide anything that depends on data only the bank holds.

The switch may The switch may not
Refuse a number that fails its own check digit (07) Return a name: the name is the bank’s data
Answer 91 at once instead of holding the sender 30 seconds Answer 00 for a credit the bank has not made
Accept a credit up to a cap the bank set, and send an advice Decide whether an account is frozen or closed
Keep an outage log the bank can reconcile later Raise its own cap, or accept without logging the advice

The lab measures two of these. For name enquiries it asks: if every destination were unreachable, what could the switch decide alone? A number’s check digit depends only on the bank’s 3-digit code and the nine digits before it (the account numbers and identifiers chapter in this module builds the full test). Of the 403 enquiries the data ended in 07, 325 fail the check digit and need no bank, and 78 pass it: those are closed accounts, which only the bank knows. For transfers it replays the real outage first. B07, a large bank, was down on Wednesday from 11:02 to 11:49, and in that window 11 name enquiries got 91, and so did 4 transfers worth ₦98,995. All four were to saved beneficiaries, so the senders had no fresh name enquiry to warn them, and all four accounts were active. A stand-in capped at ₦20,000 would have accepted three of them. Four transfers cannot size a cap, so the step then asks what accepting and advising would cost if B07 had been unreachable all week. A cap of ₦20,000 would have accepted 818 of its 1,046 transfers, worth ₦6,234,187, and the bank would later have refused 3 of them, worth ₦22,826, because the accounts were frozen or closed. Each of those is a sender’s customer debited, an acceptance the switch gave, and a return later. A lower cap shrinks both the number and the value, since the bad accounts are few and their amounts vary. What a cap does not remove is the return itself.

Stand-in is therefore a transfer of risk, and someone has to agree to carry it before the outage. A cap the bank set, a log of every decision and an advice stream the bank must acknowledge are what make it a delegation and not a guess.

Where it goes wrong

One timeout for every bank. The timer is set once, for the slowest healthy bank, and a stall at a fast bank holds its slot for 30 seconds. Set it per participant, from each bank’s own healthy tail, and review it when the tail moves.

Treating the timeout as a failure. A switch that answers 97 and records “failed” has told the sender it may reverse. In the lab 42 of 101 had been credited (a status query found 38; four senders never asked). The status stays open until a query or a late reply resolves it, and the record must stay open long enough: requeries in the lab came between 1 and 30.9 minutes after the request, and 11 of the 101 were never requeried. Four of those eleven had been credited by the receiving bank, and the switch never learned. The next chapters cover what that does to a settlement.

Ignoring the late reply. A reply that arrives after the timer is information. A switch that drops it relies on the sender’s requery to learn what its own receiver already said.

A shared pool. Without a bulkhead, the slow bank’s stalls take slots from everyone. The arithmetic above gives 87 extra slots for one bank.

Stand-in without an advice trail. The switch accepts on a bank’s behalf and the bank never hears. The bank’s books and the switch’s differ, and a reconciliation chapter’s whole job begins.

Quoting an average. A network mean wait cannot show a 30-second stall on 3% of one bank’s transfers. Report percentiles and stall rates per receiving bank.

What the lab cannot tell you

The lab’s switch is a model. Its timeout, response codes, fees and limits are illustrative, and the generator gives every healthy reply the same distribution, so a real slow bank would look different (a slow median, not only a tail). Search found no public architecture document from a Nigerian switch operator describing its internal timers, queues or stand-in, so the chapter states none. The real figures belong to the operator’s specification and the CBN’s documents, which participants receive from the operator and which this chapter did not read.

LAB Build a small switch, replay the week through it, find the slow bank and test a stand-in ~60 MIN
YOU NEEDPython 3.9 or later (standard library only)labs/finance with rails.pyNo Docker, no packagesNo sqlite3 command needed

You work in labs/finance. Save each script below next to rails.py with the name shown. The scripts import switch.py, so run them from that folder. They read data/rails.sqlite and never write to it. The week is a model: its codes, the 30-second timeout and every rule are illustrative.

1. Generate the week and read one transfer as the switch saw it.

cd labs/finance
python3 rails.py
python3 check.py --rails-only

rails.py takes about a second and prints:

32 participants, 22,835 accounts, 17,998 transfers, 12,158 name enquiries, 136 status queries
21 settlement sessions, 125 batch files, 193 RTGS payments, 3,412 USSD sessions, 3,453 PSB postings
planted (answers/rails_truth.csv): credited_without_settlement 4, customer_fee_not_charged 6, customer_reversed_twice 3, levy_not_charged 5, mmo_trust_shortfall 1, participant_limit 4, participant_outage 1, psb_cash_out_fee_not_posted 1, psb_cash_out_posted_twice 1, reversed_after_late_success 4, same_number_two_banks 8, switch_incident 1, telco_record_missing 12

check.py --rails-only prints:

rails week: 17,998 transfers, 21 settlement sessions, 22,835 accounts; checks 21-25 run
OK: all invariants hold

The third line names the planted breaks. Do not open data/answers/ yet. Seed 42 gives the same numbers every time.

Now save one_transfer.py. It picks the first transfer to B19 that the switch answered 97 and requery later found credited.

import sqlite3

db = sqlite3.connect("data/rails.sqlite")
db.row_factory = sqlite3.Row
t = db.execute("""SELECT * FROM transfers WHERE dest = 'B19' AND first_response = '97' AND final_status = '00'
                  ORDER BY at LIMIT 1""").fetchone()
print("transfer:", {k: t[k] for k in ("session_id", "at", "src", "dest", "amount_kobo", "first_response",
                                      "latency_ms", "final_status", "final_at", "settlement_session")})
ne = db.execute("SELECT * FROM name_enquiries WHERE id = ?", (t["name_enquiry_id"],)).fetchone()
print("name enquiry:", {k: ne[k] for k in ("id", "at", "response", "latency_ms")})
for q in db.execute("SELECT at, asked_by, response FROM tsq WHERE session_id = ? ORDER BY at", (t["session_id"],)):
    print("status query:", dict(q))
for b in db.execute("SELECT institution, direction, status, posted_at FROM bank_log WHERE session_id = ? ORDER BY posted_at",
                    (t["session_id"],)):
    print("bank log:", dict(b))
python3 one_transfer.py
transfer: {'session_id': '900892260616172353625556593151', 'at': '2026-06-16T17:23:53+01:00', 'src': 'B07', 'dest': 'B19', 'amount_kobo': 527600, 'first_response': '97', 'latency_ms': 30000, 'final_status': '00', 'final_at': '2026-06-16T17:43:53+01:00', 'settlement_session': '20260616-4'}
name enquiry: {'id': 'NE0003211', 'at': '2026-06-16T17:23:02+01:00', 'response': '00', 'latency_ms': 333}
status query: {'at': '2026-06-16T17:43:53+01:00', 'asked_by': 'B07', 'response': '00'}
bank log: {'institution': 'B07', 'direction': 'out', 'status': 'completed', 'posted_at': '2026-06-16T17:23:53+01:00'}
bank log: {'institution': 'B19', 'direction': 'in', 'status': 'credited', 'posted_at': '2026-06-16T17:25:34.569000+01:00'}

This is ₦5,276.00 (527,600 kobo) from B07 to B19. The switch gave up at 30,000 ms and answered 97. B19 credited the customer at 17:25:34, about 102 seconds after the request. B07 did not ask until 17:43:53, 20 minutes after the request, so its customer was debited and unsure for that long. The first six digits of the session id are B07’s institution code. The money settles in session 20260616-4. About a third of transfers have no name enquiry at all, because the sender reused a saved beneficiary’s earlier one and name_enquiry_id is empty; the first stalled transfer happens not to be one of them.

2. Build the switch and replay every message through it. Save switch.py. It holds only what a switch holds: the participants, their outage windows and, as a stand-in for the banks, an account table the banks own. It routes, applies one timeout per participant and maps what comes back to a code.

"""A small switch for the rails week. Standard library only. Illustrative rules, not NIBSS's."""
import datetime as dt
import sqlite3

DB = "data/rails.sqlite"
DEFAULT_TIMEOUT_MS = 30_000            # the lab's timeout; the real one is NIBSS's to state


def when(text):
    return dt.datetime.fromisoformat(text)


class Switch:
    def __init__(self, db_path=DB, timeouts=None, default_timeout_ms=DEFAULT_TIMEOUT_MS):
        db = sqlite3.connect(db_path)
        # What the switch holds: who the participants are, and when each is down.
        self.nuban_code = dict(db.execute("SELECT code, nuban_code FROM participants"))
        self.down = [(who, when(a), when(b)) for who, a, b in
                     db.execute("SELECT who, start_at, end_at FROM outages WHERE who <> 'switch'")]
        # What only the banks hold: their accounts. The switch asks; it does not keep them.
        self.bank_accounts = {(inst, no): status for no, inst, status in
                              db.execute("SELECT account_no, institution, status FROM accounts")}
        self.timeouts = timeouts or {}
        self.default_timeout_ms = default_timeout_ms

    def is_down(self, bank, at):
        return any(who == bank and a <= at < b for who, a, b in self.down)

    def timeout_for(self, bank):
        return self.timeouts.get(bank, self.default_timeout_ms)

    def name_enquiry(self, at, dest, number):
        """Route a name enquiry to the destination bank and map its answer to a code."""
        if self.is_down(dest, at):
            return "91"
        status = self.bank_accounts.get((dest, number))
        return "00" if status and status != "closed" else "07"

    def transfer(self, at, dest, number, reply_ms):
        """Route a transfer. reply_ms is how long the receiving bank takes to answer: the one
        input the switch cannot know in advance. Returns (code, how long the sender waited)."""
        if self.is_down(dest, at):
            return "91", 0
        limit = self.timeout_for(dest)
        if reply_ms >= limit:
            return "97", limit                       # give up; the bank may still credit
        state = self.bank_accounts.get((dest, number))
        if state == "closed":
            return "07", reply_ms                    # a closed account is refused at transfer too
        if state == "frozen":
            return "57", reply_ms
        return "00", reply_ms

Then replay.py, which feeds the week’s messages in and compares the switch’s answer with the one the data recorded.

import sqlite3
from collections import Counter
from switch import Switch, DB, when

db = sqlite3.connect(DB)
sw = Switch()

diff = Counter()
n = 0
for at, dest, number, recorded in db.execute("SELECT at, dest, account_no, response FROM name_enquiries"):
    n += 1
    mine = sw.name_enquiry(when(at), dest, number)
    if mine != recorded:
        diff[(recorded, mine)] += 1
print(f"name enquiries replayed: {n:,}; differ: {sum(diff.values())} {dict(diff)}")

diff = Counter()
n = 0
for at, dest, number, latency, recorded in db.execute(
        "SELECT at, dest, credit_account, latency_ms, first_response FROM transfers"):
    n += 1
    mine, _wait = sw.transfer(when(at), dest, number, latency)
    if mine != recorded:
        diff[(recorded, mine)] += 1
print(f"transfers replayed:      {n:,}; differ: {sum(diff.values())} {dict(diff)}")

print()
print("the transfers the switch could not reproduce, by what the data says:")
for row in db.execute("""SELECT first_response, src, MIN(substr(at, 1, 16)), MAX(substr(at, 1, 16)), COUNT(*)
                         FROM transfers WHERE first_response = '51' GROUP BY 1, 2"""):
    print(" ", row)
python3 replay.py
name enquiries replayed: 12,158; differ: 1 {('07', '91'): 1}
transfers replayed:      17,998; differ: 4 {('51', '00'): 4}

the transfers the switch could not reproduce, by what the data says:
  ('51', 'B13', '2026-06-19T12:16', '2026-06-19T12:18', 4)

Your small switch reproduces 12,157 of the 12,158 name enquiries and 17,994 of the 17,998 transfers from three things: the destination’s state (a down bank is 91, a closed account 07, a frozen one 57), the receiving bank’s reply time and one timer, and that includes every 91 in B07’s Wednesday outage. For a timed-out row the recorded latency is the 30,000 ms the sender waited, not the bank’s reply time; the replay treats it as a reply that did not beat the timer, so >= is the rule. The one name enquiry it misses was answered 07 inside B07’s outage window, where the switch says 91: a mistyped number, which fails its own check digit, so the switch could refuse it without the bank. Step 5 returns to that. The four transfers it cannot reproduce are 51 answers to transfers from B13 on Friday 19 June, recorded from 12:16 to 12:18:13, all before the 12:19:00 top-up. A 51 is a decision about the sender’s position, which the switch’s messages do not carry: the lab declines when B13’s net debit in the open session at that moment would pass its collateral. How that limit works is the subject of the chapters on how banks settle with each other and on clearing and settlement at the switch.

3. Find the slow bank. Save latency.py. It computes percentiles per receiving bank, lists who waited on the worst one, and asks whether each outlier could be chance.

import math
import sqlite3
from collections import defaultdict

db = sqlite3.connect("data/rails.sqlite")
by_dest = defaultdict(list)
for dest, latency in db.execute("SELECT dest, latency_ms FROM transfers"):
    by_dest[dest].append(latency)


def pct(sorted_values, p):
    """Nearest-rank percentile: the value at or below which p% of the sample falls."""
    k = max(0, -(-len(sorted_values) * p // 100) - 1)
    return sorted_values[int(k)]


rows = []
for dest, values in by_dest.items():
    values.sort()
    stalls = sum(v >= 30_000 for v in values)
    rows.append((100 * stalls / len(values), dest, len(values), pct(values, 50), pct(values, 95),
                 pct(values, 99), stalls))
rows.sort(reverse=True)
print(f"{'dest':<5} {'n':>5} {'p50 ms':>7} {'p95 ms':>7} {'p99 ms':>7} {'stalls':>6} {'stall %':>8}")
for rate, dest, n, p50, p95, p99, stalls in rows[:6]:
    print(f"{dest:<5} {n:>5} {p50:>7,} {p95:>7,} {p99:>7,} {stalls:>6} {rate:>7.2f}%")
all_values = sorted(v for vs in by_dest.values() for v in vs)
stalls = sum(v >= 30_000 for v in all_values)
print(f"{'all':<5} {len(all_values):>5} {pct(all_values, 50):>7,} {pct(all_values, 95):>7,} "
      f"{pct(all_values, 99):>7,} {stalls:>6} {100 * stalls / len(all_values):>7.2f}%")

print()
print("who waited 30 s on B19:")
rows = db.execute("""SELECT src, COUNT(*) FROM transfers
                     WHERE dest = 'B19' AND latency_ms >= 30000 GROUP BY src ORDER BY 2 DESC, 1""").fetchall()
print(f"  {sum(n for _, n in rows)} stalled transfers from {len(rows)} different sending institutions")
print("  " + ", ".join(f"{s} {n}" for s, n in rows))

print()
print("is a bank's stall count more than chance? (switch incident left out)")
INCIDENT = ("2026-06-18T15:20:00+01:00", "2026-06-18T15:34:00+01:00")
rows = db.execute("""SELECT dest, COUNT(*), SUM(latency_ms >= 30000) FROM transfers
                     WHERE NOT (at >= ? AND at < ?) GROUP BY dest""", INCIDENT).fetchall()
total_n, total_s = sum(r[1] for r in rows), sum(r[2] for r in rows)


def tail(n, k, p):
    """P(at least k stalls in n transfers) if every transfer stalls with probability p."""
    return sum(math.comb(n, i) * p ** i * (1 - p) ** (n - i) for i in range(k, n + 1))


print(f"  {'dest':<5} {'n':>5} {'stalls':>6} {'rest of network':>16} {'chance':>10} {'x 32 banks':>11}")
for dest, n, s in sorted(rows, key=lambda r: -r[2] / r[1])[:3]:
    p = (total_s - s) / (total_n - n)
    print(f"  {dest:<5} {n:>5} {s:>6} {100 * p:>15.2f}% {tail(n, s, p):>10.1e} {32 * tail(n, s, p):>11.1e}")
python3 latency.py
dest      n  p50 ms  p95 ms  p99 ms stalls  stall %
B19     348   1,038   3,088  30,000     11    3.16%
F02     124     968   2,673  30,000      2    1.61%
P01     252     966   2,353  30,000      3    1.19%
B24     346     980   2,375  30,000      4    1.16%
B13     362   1,024   2,273  30,000      4    1.10%
B09     684     987   2,278   5,436      6    0.88%
all   17998     994   2,323   3,604    101    0.56%

who waited 30 s on B19:
  11 stalled transfers from 10 different sending institutions
  B07 2, B01 1, B02 1, B10 1, B11 1, B12 1, B16 1, B20 1, B21 1, M02 1

is a bank's stall count more than chance? (switch incident left out)
  dest      n stalls  rest of network     chance  x 32 banks
  B19     347     11            0.40%    2.2e-07     6.9e-06
  F02     124      2            0.44%    1.1e-01     3.4e+00
  P01     252      3            0.44%    1.0e-01     3.2e+00

B19’s median (1,038 ms) is the network’s (994 ms). Only its tail differs: 3.16% of its transfers wait the full 30 seconds, and its 99th percentile is 30,000 ms. Its 11 stalls come from ten different senders. The last block drops the 14-minute switch incident on Thursday afternoon, in which 20 of 46 transfers stalled, to thirteen different banks, and asks about chance. B19’s 11 stalls in 347 transfers are far beyond what a 0.40% rate would give (the multiplied figure, about 7 in a million). F02’s 2 in 124 and P01’s 3 in 252 are not: multiplied by 32, the figures are above 1, so a bank or two looking like that is what chance gives, and you would not act. The P-values need the data’s baseline rate to be right, which is an assumption you can change.

4. Price the timeout, and see how long a record has to stay open. Save timeouts.py. It replays the week with different timers and counts two things: healthy transfers made unknown, and seconds senders waited.

import sqlite3
from switch import Switch, DB, when

db = sqlite3.connect(DB)
rows = db.execute("SELECT at, dest, credit_account, latency_ms, first_response FROM transfers").fetchall()


def run(label, switch):
    stalled = good_made_unknown = wait_ms = 0
    for at, dest, number, latency, recorded in rows:
        code, wait = switch.transfer(when(at), dest, number, latency)
        wait_ms += wait
        if code == "97":
            stalled += 1
            good_made_unknown += recorded == "00"      # answered 00 in the data, now unknown
    print(f"{label:<28} {stalled:>5} {good_made_unknown:>9} {wait_ms / 1000:>12,.0f}")


print(f"{'timeout':<28} {'97 sent':>5} {'good ones':>9} {'sender wait':>12}")
print(f"{'':<28} {'':>5} {'made 97':>9} {'(seconds)':>12}")
for t in (2_000, 3_000, 5_000, 10_000, 30_000):
    run(f"every bank {t // 1000} s", Switch(default_timeout_ms=t))
run("B19 5 s, others 30 s", Switch(timeouts={"B19": 5_000}))

base = Switch()
waits = [base.transfer(when(at), dest, number, latency)[1] for at, dest, number, latency, _ in rows]
stall_wait = sum(w for w in waits if w >= base.default_timeout_ms)
print()
print(f"stalls: {sum(w >= base.default_timeout_ms for w in waits)} of {len(waits):,} transfers "
      f"({100 * sum(w >= base.default_timeout_ms for w in waits) / len(waits):.2f}%), "
      f"{stall_wait / 1000:,.0f} of {sum(waits) / 1000:,.0f} seconds waited ({100 * stall_wait / sum(waits):.1f}%)")
python3 timeouts.py
timeout                      97 sent good ones  sender wait
                                     made 97    (seconds)
every bank 2 s                1474      1365       19,445
every bank 3 s                 327       224       20,195
every bank 5 s                 111        10       20,527
every bank 10 s                101         0       21,040
every bank 30 s                101         0       23,060
B19 5 s, others 30 s           102         1       22,784

stalls: 101 of 17,998 transfers (0.56%), 3,030 of 23,060 seconds waited (13.1%)

A 2-second timeout for everyone saves about 3,600 seconds of waiting and makes 1,365 healthy transfers answer 97, each now needing a requery. At 5 seconds the cost falls to 10. Only the 101 real stalls are ever answered 97 from 10 seconds up, and the longer wait costs 2,020 seconds more than the 10-second row: the sum of the 101 stalls’ extra 20 seconds. The B19-only row saves 276 seconds (11 stalls × 25 seconds, plus 0.9 of a second from the one healthy reply cut off at 5 seconds) and costs one healthy transfer, B19’s slowest healthy reply at 5,892 ms. The 101 stalls are 0.56% of transfers and 13.1% of the seconds waited.

Then late.py, which asks how long the switch must keep a timed-out record open.

import sqlite3
from switch import when

db = sqlite3.connect("data/rails.sqlite")
stalls = db.execute("""SELECT session_id, at, final_status FROM transfers
                       WHERE first_response = '97' ORDER BY at""").fetchall()
print(f"{len(stalls)} transfers answered 97; final status after requery: "
      f"{sum(s[2] == '00' for s in stalls)} credited (00), {sum(s[2] == '97' for s in stalls)} not")

credit_gap, first_tsq, last_tsq, never_asked = [], [], [], 0
for sid, at, final in stalls:
    t0 = when(at)
    posted = db.execute("""SELECT posted_at FROM bank_log WHERE session_id = ? AND direction = 'in'""", (sid,)).fetchone()
    if posted:
        credit_gap.append((when(posted[0]) - t0).total_seconds())
    asks = sorted(when(a) for a, in db.execute("SELECT at FROM tsq WHERE session_id = ?", (sid,)))
    if asks:
        first_tsq.append((asks[0] - t0).total_seconds())
        last_tsq.append((asks[-1] - t0).total_seconds())
    else:
        never_asked += 1
print(f"receiver posted the credit {min(credit_gap):.0f} to {max(credit_gap):.0f} s after the request "
      f"({len(credit_gap)} credits; the switch gave up at 30 s)")
print(f"first requery {min(first_tsq) / 60:.1f} to {max(first_tsq) / 60:.1f} minutes after the request; "
      f"last requery up to {max(last_tsq) / 60:.1f} minutes")
print(f"never requeried: {never_asked} of {len(stalls)}")
credited_never = db.execute("""SELECT COUNT(*) FROM transfers t WHERE first_response='97' AND final_status='97'
        AND EXISTS (SELECT 1 FROM bank_log b WHERE b.session_id=t.session_id AND b.direction='in')""").fetchone()[0]
print(f"credited by the receiver but the switch still says 97: {credited_never}")
python3 late.py
101 transfers answered 97; final status after requery: 38 credited (00), 63 not
receiver posted the credit 62 to 118 s after the request (42 credits; the switch gave up at 30 s)
first requery 1.0 to 30.0 minutes after the request; last requery up to 30.9 minutes
never requeried: 11 of 101
credited by the receiver but the switch still says 97: 4

The receiver credited 42 of the 101 timed-out transfers, all 62 to 118 seconds after the request, more than 30 seconds after the switch gave up. Requery found 38 of them. The other four were never requeried: the receiver has credited a customer and the switch’s record still says 97, so they will not settle. A record kept open for about 31 minutes would have covered every requery in the week. Whether to accept a late reply from the bank instead of waiting for a query is a design choice you would take to the operator.

One bank’s developer documentation (Providus Bank’s, read here only through a search summary) recommends a status requery for 15 minutes to confirm the final status of a NIP transferas of 2026-11. That is one bank’s guidance for its integrators, not a rule of the scheme; the lab’s senders go to 30 minutes.

5. Test a stand-in. Save stand_in.py. It answers every name enquiry as if the destination were down, deciding only what the switch can compute, then replays B07’s real outage and prices accepting its transfers under a cap.

import sqlite3
from collections import Counter
from switch import Switch, DB, when

WEIGHTS = [3, 7, 3, 3, 7, 3, 3, 7, 3, 3, 7, 3]      # the lab's check-digit weights (illustrative)
db = sqlite3.connect(DB)
sw = Switch()


def check_digit_ok(bank, number):
    """What the switch can decide with no help from a down bank: the number's own arithmetic."""
    if len(number) != 10 or not number.isdigit():
        return False
    total = sum(int(d) * w for d, w in zip(sw.nuban_code[bank] + number[:9], WEIGHTS))
    return str((10 - total % 10) % 10) == number[9]


def stand_in_name_enquiry(bank, number):
    """The bank is unreachable. 07 only when the arithmetic says so; never a name, never 00."""
    return "07" if not check_digit_ok(bank, number) else "91"


tally = Counter()
for dest, number, recorded in db.execute("SELECT dest, account_no, response FROM name_enquiries"):
    tally[(stand_in_name_enquiry(dest, number), recorded)] += 1
print("name enquiries answered as if every destination were down:")
print(f"  switch says 07 alone, bank would say 07: {tally[('07', '07')]:>6,}   (decided correctly)")
print(f"  switch says 07 alone, bank would say 00: {tally[('07', '00')]:>6,}   (decided wrongly)")
print(f"  switch says 91, bank would say 07:       {tally[('91', '07')]:>6,}   (closed accounts: only the bank knows)")
print(f"  switch says 91, bank would say 00:       {tally[('91', '00')]:>6,}")


print()
print("the real outage, B07 down Wednesday 11:02-11:49:")
start, end = db.execute("SELECT start_at, end_at FROM outages WHERE who = 'B07'").fetchone()
print("  name enquiries to B07 in the window:", dict(db.execute(
    "SELECT response, COUNT(*) FROM name_enquiries WHERE dest = 'B07' AND at >= ? AND at < ? GROUP BY 1", (start, end))))
status = {no: st for no, st in db.execute("SELECT account_no, status FROM accounts WHERE institution = 'B07'")}
out = db.execute("""SELECT substr(at, 12, 8), src, amount_kobo, credit_account, name_enquiry_id FROM transfers
                    WHERE dest = 'B07' AND first_response = '91' ORDER BY at""").fetchall()
print(f"  transfers answered 91: {len(out)}, worth ₦{sum(r[2] for r in out) // 100:,}")
for t, src, amount, number, ne in out:
    print(f"    {t} from {src}: ₦{amount // 100:>9,}  account {status[number]:<7} name enquiry: {ne or 'none (saved beneficiary)'}")
print(f"  a stand-in capped at ₦20,000 would have accepted {sum(r[2] <= 2_000_000 for r in out)} of the {len(out)}")


# A bigger sample for sizing a cap: accept and advise, up to a cap the bank set in advance.
def stand_in_transfer(amount_kobo, cap_kobo):
    return "accept_and_advise" if amount_kobo <= cap_kobo else "91"


print()
print("every transfer to B07 that week, as if it had been down all week (what the stand-in accepts, what the bank returns):")
rows = db.execute("""SELECT amount_kobo, credit_account FROM transfers
                     WHERE dest = 'B07' AND first_response IN ('00', '57', '07')""").fetchall()
print(f"  {'cap':>12} {'accepted':>9} {'value accepted':>16} {'bank refuses later':>19} {'value to return':>16}")
for cap_naira in (5_000, 20_000, 100_000, 10_000_000):
    acc = [(a, n) for a, n in rows if stand_in_transfer(a, cap_naira * 100) == "accept_and_advise"]
    back = [(a, n) for a, n in acc if status[n] in ("frozen", "closed")]
    print(f"  {'₦' + format(cap_naira, ','):>12} {len(acc):>9} {'₦' + format(sum(a for a, _ in acc) // 100, ','):>16} "
          f"{len(back):>19} {'₦' + format(sum(a for a, _ in back) // 100, ','):>16}")
python3 stand_in.py
name enquiries answered as if every destination were down:
  switch says 07 alone, bank would say 07:    325   (decided correctly)
  switch says 07 alone, bank would say 00:      0   (decided wrongly)
  switch says 91, bank would say 07:           78   (closed accounts: only the bank knows)
  switch says 91, bank would say 00:       11,744

the real outage, B07 down Wednesday 11:02-11:49:
  name enquiries to B07 in the window: {'07': 1, '91': 11}
  transfers answered 91: 4, worth ₦98,995
    11:29:37 from B03: ₦    3,308  account active  name enquiry: none (saved beneficiary)
    11:34:21 from B17: ₦   83,579  account active  name enquiry: none (saved beneficiary)
    11:37:03 from B12: ₦   11,282  account active  name enquiry: none (saved beneficiary)
    11:39:05 from B10: ₦      826  account active  name enquiry: none (saved beneficiary)
  a stand-in capped at ₦20,000 would have accepted 3 of the 4

every transfer to B07 that week, as if it had been down all week (what the stand-in accepts, what the bank returns):
           cap  accepted   value accepted  bank refuses later  value to return
        ₦5,000       324         ₦967,924                   0               ₦0
       ₦20,000       818       ₦6,234,187                   3          ₦22,826
      ₦100,000      1033      ₦14,239,279                   5         ₦133,416
   ₦10,000,000      1046      ₦18,340,514                   5         ₦133,416

The arithmetic alone settles 325 of the 403 07 answers, with no wrong decision. The other 78 pass the check digit and are closed accounts: a stand-in has to say 91. The real outage is small: B07’s 91s reached 11 name enquiries and 4 transfers, all to saved beneficiaries, so a sender who skips the name enquiry learns of an outage only when the transfer fails. Four transfers cannot size a cap, so the second table runs the whole week as if B07 had been down throughout. There the cap does change the return: at ₦5,000 none of B07’s transfers would have gone to a bad account, at ₦20,000 three would (₦22,826) and at ₦100,000 five would (₦133,416, two to frozen accounts and three to closed). A lower cap reduces the amount the switch has told senders is done (₦967,924 at ₦5,000 against ₦18,340,514 with no practical cap). The one 07 name enquiry in the outage window is the sort the switch could answer alone. Values are in whole naira, with the kobo dropped. The account states are the generator’s, not a real bank’s.

Set B19’s timeout to 1 second, below its median, and replay only its transfers:

python3 - <<'PY'
import sqlite3
from switch import Switch, DB, when
db = sqlite3.connect(DB)
sw = Switch(timeouts={"B19": 1_000})
n = sum(sw.transfer(when(at), d, no, lat)[0] == "97"
        for at, d, no, lat in db.execute("SELECT at, dest, credit_account, latency_ms FROM transfers WHERE dest = 'B19'"))
print(n, "of 348 transfers to B19 answered 97")
PY

It prints 182 of 348 transfers to B19 answered 97. A timeout under the bank’s own median turns about half of its healthy transfers into unknowns, and each one now needs a requery, a late-reply path and a customer who is told “pending”. The switch has kept every sender from waiting 30 seconds and created 182 unknowns where there were 11 stalls. Try 3,000 and 5,000 and find where the count stops falling.

ARTEFACT Write the timeout and stand-in policy ~50 MIN
YOU PRODUCESwitch timeout and stand-in policy

Template

# Timeout and stand-in policy: <switch>
Written by <switch engineer> · Reviewed by <participants' forum> · Approved by <head of switch operations> · Version <n>, <date> · Next review <date>

## Purpose and scope
<What this policy decides. Message types in scope, and what is out of scope.>

## Timeout per participant
Rule: <how a participant's timeout comes from its measured healthy replies>. Default until measured: <seconds>.
| Participant | Median | p99 | Slowest healthy reply | Timeout | Good transfers made unknown (replay) | Review on |
|---|---|---|---|---|---|---|
A timeout means unknown. The switch answers <code>, keeps the record open and never records failed.

## When a participant is slow or down
| Situation | Switch answers | Sender must |
|---|---|---|

## Stand-in
Applies only when: <condition>. Off unless the participant has signed a delegation.
May decide: <list>. May not decide: <list>.
Cap: set by <the participant>, never by the switch. Advice sent: <when, to whom, acknowledged how>.

## Late-reply window
Record stays open <minutes>, because <measured requery times>. A late reply is <recorded, shown to the sender>. A credit nobody asked about is <flagged to whom, by when>.

## Telling participants
<Notice of each change: what, to whom, how long before, the replay figures attached, who can object.>

## Assumptions and how this could be wrong
<Each guess with its value. One way the policy fails, and the measurement that would show it.>

## Review and decision needed
Owner: <name>. Next review: <date>. Brought forward if: <figure and level>. Decision needed now: <approve / amend, by when>.
WORKED EXAMPLE

At a real switch the switch engineer writes this policy, the participants’ forum reviews it and the head of switch operations approves it. Here Ajibola writes it and Azeezat checks the figures.

Timeout. Rule: a participant earns its own timeout only when its stalls are more than chance (B19 alone, in the lab’s chance table). The timeout is its slowest healthy reply in the last full week, rounded down to a whole second, and counted by replay before it goes live; everyone else keeps 30 seconds. B19’s slowest healthy reply was 5,892 ms, so its timeout is 5 seconds. Replay: one good transfer made 97, and senders wait 276 fewer seconds in the week. Cutting every bank to a shorter timeout does not pay: 5 seconds for every bank would make 10 good transfers unknown, and 3 seconds would make 224.

Slow or down. Slow: at the timeout the switch answers 97, unknown, and the bank may still credit. In the week the receivers credited 42 of 101 timed-out transfers, 62 to 118 seconds after the request. Down: 91 at once. Stand-in never answers for a slow bank.

Stand-in. Name enquiries: 07 only when the check digit fails (325 of 403 07 answers, none wrong), otherwise 91, because 78 closed accounts pass the check. Transfers: accept and advise only under a cap the participant has signed. B07 has signed none (an assumption), so its Wednesday outage gets 91 (4 transfers, ₦98,995).

Late replies. Records stay open 35 minutes: the last requery came at 30.9 minutes, and the four minutes of margin are an assumption. Four of the 11 transfers never requeried had been credited, so the switch flags any such credit to the sender when the window closes.

Telling participants. Written notice to the forum and B19 before the change, with replay figures; B19 may object.

Could be wrong: the lab gives every healthy reply one distribution. Weekly replay showing more than one good B19 transfer made unknown would show it.

Decision needed: approval by the head of switch operations this month; review in four weeks.

Now you

A month later B19 has fixed its fault and its stalls have stopped. The participants’ forum asks the switch to cut the default timeout for all 32 participants from 30 seconds to 3, saying senders would wait far less. Separately, B07, after its Wednesday outage, asks for stand-in on transfers with a cap of ₦100,000. F02 and P01 still show a few stalls, which the chance table calls nothing yet.

You are the switch engineer. Write the policy. Use step 4 to answer the forum: what a 3-second default would cost, and when a participant earns its own timeout. Use step 5 to answer B07: what the cap would accept, what the bank would return, and what the policy says about it. Set the late-reply window from step 4’s requery times, and say how you tell participants.

The head of switch operations will read it to decide whether to change the default and whether to accept B07’s delegation. The forum reviews it first.

Self-check

DECIDE

Ajibola and Azeezat have the lab's numbers: B19's median is normal, its p99 is the full 30 seconds, its stalls reach ten different senders, and its slowest healthy reply was 5,892 ms. A bank's help desk calls every day. The switch has one global 30-second timeout and a shared worker pool. They must decide what changes this week.

READING
  1. DOC
    Regulation on Instant (Inter-Bank) Electronic Funds Transfer Services in Nigeria (CBN, 2018) Central Bank of Nigeria, 2018

    The regulator's own text on the 60-second rule, name enquiry and the duties of sending and receiving parties. Read it for what is required of participants and what is left to the operator, such as the switch's own timer. This chapter rests on search summaries of it, so check each clause.

  2. DOC
    What are the Services under NIP that customers can utilize? (NIBSS support article) NIBSS

    The operator's own list of NIP's services: name enquiry, direct credit, direct debit, transaction status query and balance enquiry. Read it as the surface a sending bank sees; it gives no timers or codes.

  3. DOC
    How does Settlement happen on the service? (NIBSS support article) NIBSS

    NIBSS's short description of NIP as a deferred net settlement system, with funds available to the beneficiary before settlement. It is why a late credit on a timed-out transfer matters to settlement. It gives no timers.

  4. DOC
    PIN Security standard (PCI Security Standards Council) PCI Security Standards Council

    The standards body's own page for the PIN Security Requirements and Testing Procedures, which govern how PIN blocks and keys are handled, including translation by a switch. Check the council's site for the current version before you rely on any requirement; this chapter could not confirm which is current.

  5. POST
    Visa harnesses real-time deep learning to enhance transaction processing (Visa, 2020) Visa, 2020

    A card scheme's own announcement of stand-in processing, which approves or declines for an issuer whose systems are offline. Read it for the idea of deciding on a bank's behalf and treat the performance figures as Visa's claims, not independent results.

  6. DOC
    Get NIP transaction status (Providus Bank developer documentation) Providus Bank

    One bank's own guidance for requerying a NIP transfer, the sending bank's side of the timeout. Read it to see how a bank documents the status query for its own integrators; it is one bank's practice, not the scheme's rule.

  7. POST
    National Payment Stack: why? (Open Africa podcast, Substack) Open Africa

    A commentary that describes NIP's timeout and status query and the move to the National Payment Stack. It is commentary, not NIBSS: read it for the questions to put to the operator, and confirm each claim with NIBSS.

All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: Clearing and settlement at the switch: files, netting and settlement risk →