STAFFCHAPTER 32

Routing across providers to raise success rates

A second provider earns its keep when the first one has a bad hour, and costs you a double charge if you fall back on a guess. Classify every failure before you route, and measure the uplift against its noise

55 MINPAYMENTSUPDATED 2026-11-14
PREDICT

Lumora's provider A declines 5% of charges. Provider B declines 12% and answers 3% of calls with a 500 before charging anything. A router sends half the charges to each and does not retry. About what share of 2,000 charges is paid?

The chapter on integrating a provider built one conversation with one provider, and the one on idempotency made a retry safe against that provider. Two providers break the assumption both rely on: that the other side remembers what you did. Routing is the part of a payment system that has to decide, with two memories that do not talk to each other, whether a payment has happened.

What a second provider is for

A router is software that chooses, for each payment, which provider to send it to. Merchants add one for three reasons, and they pull in different directions.

  • Resilience. A provider has outages and slow hours. With a second one, sales continue. This is the reason that pays most clearly, and the lab shows it.
  • Success rate. Providers authorise different shares of the same cards, because of their acquiring relationships and their fraud settings. Sending a payment where it is likelier to succeed raises the paid share.
  • Price and leverage. A split of volume gives a merchant something to negotiate with, and a cheaper route is a lower cost per payment.

The AI in payments chapter explained why a success-rate router can fool itself with small samples and with declines that belong to the customer. This chapter builds the router and quantifies the cost. The build-or-partner decision, whether to own the connection to the schemes at all, is in its own chapter; here Lumora is a merchant with two partners. Routing is also the business of orchestration software, which sits in front of several providers and decides for the merchant.

Hyperswitch, the open-source orchestrator from Juspay, documents an auth-rate routing strategy in which an exploration percentage sends a share of traffic to alternative eligible processors to keep their scores current. As summarised in search results, its documentation also describes a bucket size for the recent-outcome window, and does not give one default for either setting. These are a vendor’s descriptions of its own product, from search summaries and not a read of the pagesas of 2026-11. The same vendor’s multi-objective page, as summarised in search results, scores each processor by authorisation rate times the amount left after processing cost, and promotes a cheaper processor over the success-rate leader only when that score is strictly higher. Its intelligent-routing guide advises auth-rate routing once several processors handle meaningful traffic for the same segmentas of 2026-11. The lab’s router borrows the shape: a window, an exploration share and a cost question, with none of the vendor’s code.

What a router decides

Every call to a provider ends in one of five ways, and a router that does not name them will route on the wrong one.

Outcome What the router sees Was money taken? May it try another provider?
Paid 200, success Yes No: the order is done
Declined 200, failed No Only under a rule, below
Error before charging 500, and a later check finds no charge No Yes
Lost response 500, and a later check finds a successful charge Yes No: it is paid
Unknown 500 or a timeout, and the check itself fails Cannot tell No: hold it and ask again

The mock provider has the two 500s the table separates. error_rate answers 500 before anything happens. lost_response_rate takes the charge and then answers 500. From the caller’s side they look the same, which is the point: the status code does not say whether money moved. The chapter on states called this the unknown state and gave the rule for it: ask the system that knows.

So a router has three decisions, in this order. Where does the first attempt go? What does it do with each outcome? And what does it learn from the outcome for next time?

Two memories that do not talk

Everything that makes one provider’s retries safe is held by that provider, and a second provider has none of it.

  • References. A charge reference is unique per provider. The same string sent to B is a new charge. Step 1 of the lab sends demo-0001 to both and both succeed.
  • Idempotency keys. A repeated key replays the stored answer, but only at the provider that stored it. At B the same key is new.
  • Webhooks and verification. Each provider signs and sends its own events, and its GET /charges/{reference} knows only its own charges. Verify at the provider that told you.
  • Settlement. Each provider pays you separately, on its own schedule, net of its own fee, as the settlement chapter described. Two providers mean two clearing balances to reconcile, and an order that was charged twice appears once on each report.

The order is the one thing both providers can carry. The lab puts the order id in each charge’s metadata, and derives the reference from it: ord-10210-A at one provider, ord-10210-B at the other. The rule the router enforces is then a statement about orders, not about charges: one order produces at most one successful charge across all providers. An idempotency key cannot give you that across providers (the lesson on idempotency shows why a key is a promise by one server), so your own code has to.

The safe attempt in the lab has three steps. Send the charge with its key. On a 500, send it again with the same key: if the first call charged, the provider replays the stored result, and if it did not, the retry runs the charge. If that also fails, ask the provider (GET /charges/{reference}). Only a 404, “I have no such charge”, proves nothing was taken and lets the order move to the other provider. If the check itself fails, the outcome is unknown and the order waits. This is the retry discipline of the earlier chapter with one more rule: leave the provider only on proof.

Tracking success

A fixed split cannot notice that a provider has got worse. Tracking can. The lab’s tracker keeps the outcomes of the last 100 orders each provider handled, scores each provider by its share of them that were paid, sends the next order to the higher score, and sends every tenth order to the other provider so that it keeps a fresh score.

The numbers in the ratio come from small samples, so know their noise. A rate near 94% over 2,000 orders has a standard error of √(0.94 × 0.06 / 2,000) = 0.53 points, and the gap between two such rates 0.75 points. A difference of one point between two runs is about one and a third of that, and is not evidence. The lab prints the figure so that you do not read a result that is not there.

Two cautions from the earlier chapter apply in full. A decline is often the customer’s, so a router that scores providers on all non-successes punishes the one that was sent harder cards. The lab cannot show this, because the mock’s declines are drawn at random for every card. And the exploration share is a cost: every tenth order goes to the provider that is currently worse. Here that is worth about one point of paid share, and you will see it in step 2.

What the lab measures

Step 2 runs four strategies over 2,000 card payments replayed from the generated ledger, in two scenarios. In the steady one provider A declines 5% and B declines 12% and fails 3% of calls. In the second, A starts failing half its calls from order 1,000.

Strategy Steady: paid Degraded: paid Degraded: calls
A only 95.0% 72.2% 2,000
Split 50/50, no fallback 90.7% 77.8% 2,000
Split 50/50, safe fallback 92.0% 91.2% 2,520
Tracking, safe fallback 93.8% 91.0% 2,178

Read it from the top. In steady state the best strategy is the one that uses no router: all traffic to the better provider. Every other row pays for a worse provider’s declines. That is not an argument against routing. It is the price of insurance, and the insurance pays when A degrades: the lab’s A-only run loses 28% of orders and the split without fallback 22%, while both strategies with a safe fallback hold 91%. The fallback does the work, not the tracking. Tracking and the split with fallback paid the same share in the degraded run, within noise (91.0% and 91.2%), but tracking used 342 fewer calls: it stopped sending A the traffic that A would fail. The mock answers instantly. Against a real provider with a timeout of several seconds, a failed call is seconds that a customer waits, and the saving is in that waiting.

Re-presenting a decline elsewhere

The tempting extra is to send declined payments to the other provider too. In the mock it works wonderfully: of 101 payments A declined, B paid 91, and the paid share rises from 95.0% to 99.5%. Do not believe it.

The mock draws each decline at random, with no regard to the card. B sees a fresh draw, so it pays what its rate says, about 85%. A real decline is mostly the issuer’s decision about that card and that amount: the balance, the limit, a block. The same issuer sees the same card from the second provider and says the same. The break in step 3 puts it as a number: if the second try is declined with probability q, a fallback recovers 86 payments at q = 0 and 9 at q = 0.9.

Card schemes also make rules about it. The tokenisation chapter taught the soft and hard declines and the schemes’ retry limits for renewals; the same rules cover any reattempt of a declined authorisation, wherever it is sent. What the search results showed about Visa and Mastercard is limited and partly vendor-sourced, so it is stated narrowly.

A Visa document titled “Updates to rules for declined transaction resubmission and use of authorization response codes” appeared in search results. The search summary of it says that the notice is dated 3 September 2020 and that Visa updated its rules effective 17 April 2021; processors’ pages say that that acquirers must manage reattempts according to categories of decline response code, and that Category 1 declines (the issuer will not approve) are hard declines with no reattempts. This build did not read the document itself, and the search results did not return the current Visa Core Rules text for the sectionas of 2026-11. PayPal’s help page, a vendor’s account and not Visa’s rulebook, says that Visa evaluates a reattempt using data that includes the acquirer, the acquirer identifier, the card acceptor ID, the token or card number and the amount, that it matches by credential (token to token, card number to card number), and that soft declines may be reattempted up to 20 times in 30 daysas of 2026-11. Another processor’s page, Payway’s, gives the soft-decline limit as 15 reattempts in 30 days. The sources disagree (15 against 20) and may describe different versions of the rule, so check the current Visa Core Rules and your acquirer’s guideas of 2026-11. For Mastercard, a TD bulletin found by search says that a change effective 7 November 2022 lowered a Mastercard threshold for excessive unsuccessful attempts to 10 on the same card (previously 20). Other processor pages give a different start date for that change, and one describes a threshold of 35 declined attempts within 30 days from 2024 in some markets. The sources disagree, may describe different programmes, regions or dates, and no result was Mastercard’s own textas of 2026-11.

What follows for a router is narrow. Two sources say Visa’s evaluation uses the acquirer among other fields, and none of the results says whether trying a second acquirer starts a new count. Do not assume it does. A router should keep its own count of attempts per card across providers and treat the schemes’ limits as a ceiling on all of them together. It should never re-present a decline the issuer marked final. And it should give the customer a different path, another card or a bank transfer, before it gives them a fourth attempt.

What Nigerian rules bound the design

Routing across two providers is a merchant’s design, and two pieces of CBN regulation bear on it. What was confirmed is thin.

The CBN’s Guidelines on Operations of Electronic Payment Channels in Nigeria (2020) appeared in search results, and the summary of the CBN’s text says they supersede the 2016 guidelines of the same name. A law firm’s newsletter says they were published on 31 May 2020 and took effect on 8 June 2020as of 2026-11. A policy tracker’s summary, which this build could not check against the CBN’s text, says that the guidelines require domestic transactions to be routed through a local switch within Nigeria. It is the only source found for that routing rule, so treat the rule as unverified until you have read the provisionas of 2026-11. If it holds, it would bear on what “send it to the other provider” means for a domestic card, since the route would still pass through a Nigerian switch. Read the provisions before you design around it.

The CBN’s Regulatory Framework for Non-Bank Acquiring in Nigeria was issued by circular in May 2021. Law-firm and press summaries of it say that a non-bank acquirer must be a CBN-licensed switching company or another company the CBN approves, and that non-bank acquirers may not acquire transactions of merchants that are not registered in Nigeriaas of 2026-11. For a merchant like Lumora the practical question is about its two partners: whether each holds the authority its role needs (licences in Nigeria lays out the categories). Whether a merchant’s own router needs any approval, and what changes if a company routes other merchants’ payments as its business, are questions that the search results did not answer. Ask counsel before the second kind of design.

Price against success

The cheapest route is not always the cheapest outcome. Take Lumora’s illustrative ₦500 recharge with a ₦25 margin, the figures of the pricing chapter. Provider A takes 1% (₦5). Suppose B takes 0.8% (₦4) and authorises fewer payments. B saves ₦1 per charge. If a failed charge is a lost sale, each point of authorisation rate it gives up costs 0.01 × ₦25 = ₦0.25 of expected margin. The saving cancels out at 1 / 0.25 = 4 points. A gap of 5 points costs 0.05 × ₦25 = ₦1.25, more than the ₦1 saved. The assumption does the work. Customers who try again, or pay another way, make a failed charge cheaper than a lost sale, and the break-even moves to a wider gap. Measure the retry rate before you use the sum, and put the real fees in; the lab’s two providers charge the same 1%, so it cannot test this.

Where it goes wrong

Falling back on a 500. The 500 is not proof of anything. The break at the end of the lab charges 86 orders twice. Ask the provider, then move.

Reporting paid or failed from the last call. In the naive run 18 orders were charged at A, declined at B, and reported to the customer as failed. The customer paid and was told they had not.

A fresh reference or key at the second provider with no link to the first. Neither provider can see the other’s charge. Put the order id in the metadata and in the reference, and check “one successful charge per order” on a schedule against both providers’ reports (reconciliation is where a double charge is found if the router missed it).

Routing on a rate nobody can distinguish from noise. A one-point gap over 2,000 orders is inside the error. Use a window, a minimum sample and an exploration share, and report the noise next to the result.

Treating a decline as the provider’s fault. It rewards the provider that was sent easy cards and starves the one that got hard ones.

Retrying declines until one works. Schemes count reattempts, customers see every one, and the recovery you measured in a mock does not exist for a real card.

Concentration without a fallback. A router that learns A is best sends it everything. If A fails, the exploration share is all that is working at B. Keep B warm and watch its connection, certificates and limits.

LAB Route 2,000 charges across two providers, and double-charge a customer ~50 MIN
YOU NEEDPython 3.9 or later (standard library only)labs/finance with the data generated (python3 generate.py, then python3 cards.py)Three terminals: one for each provider and one for the scriptsNo Docker, no packages

You work in labs/finance. You run two copies of the mock provider and write four small files: router.py, run_routes.py, declines.py and doublecharge.py. The data is generated at seed 42 and scale 0.1, with cards.py run, so your numbers match the ones below. Money is integer kobo. The providers’ rates, faults and fees are the mock’s and are illustrative: not any real provider’s, a scheme’s or the CBN’s.

The mock draws its random faults from a seeded generator, so a script’s output is reproducible only if the providers have not served other calls since they started. Before each script from step 2 on, stop both providers (Ctrl-C) and start them again with the two commands in step 1. If you do not, your counts will differ by a few orders and the story will not.

1. Start two providers and look at what they share. In the first terminal start provider A. In the second start provider B on its own port and with its own state file. Without --state, B would write to A’s state and the two would be one provider.

cd labs/finance
ls data/finance.sqlite >/dev/null 2>&1 || (python3 generate.py && python3 cards.py)
python3 mock_provider.py --port 8101 --decline-rate 0.05 --fresh --quiet
cd labs/finance
python3 mock_provider.py --port 8104 --decline-rate 0.12 --error-rate 0.03 --state data/provider2.sqlite --fresh --quiet

In the third terminal read each provider’s faults, then send the same charge, with the same reference and the same Idempotency-Key, to A twice and to B once.

cd labs/finance
for p in 8101 8104; do curl -s localhost:$p/admin/faults | python3 -c "import json,sys; f=json.load(sys.stdin)['faults']; print({k: f[k] for k in ('decline_rate', 'error_rate', 'lost_response_rate')})"; done
H='Authorization: Bearer sk_test_owoleaf_mock'
B='{"reference":"demo-0001","amount_kobo":50000,"customer_ref":"C0000042","card_number":"5061000000001234"}'
echo "--- A, first"; curl -s -i -H "$H" -H 'Idempotency-Key: demo-0001' -d "$B" localhost:8101/charges | grep -E "HTTP|Idempotent|\"status\"|\"reference\""
echo "--- A, same key again"; curl -s -i -H "$H" -H 'Idempotency-Key: demo-0001' -d "$B" localhost:8101/charges | grep -E "HTTP|Idempotent|\"status\"|\"reference\""
echo "--- B, same key and reference"; curl -s -i -H "$H" -H 'Idempotency-Key: demo-0001' -d "$B" localhost:8104/charges | grep -E "HTTP|Idempotent|\"status\"|\"reference\""
for p in 8101 8104; do curl -s -H "$H" "localhost:$p/charges?status=success" | python3 -c "import json,sys; print(len(json.load(sys.stdin)['charges']), 'successful charge(s)')"; done
{'decline_rate': 0.05, 'error_rate': 0.0, 'lost_response_rate': 0.0}
{'decline_rate': 0.12, 'error_rate': 0.03, 'lost_response_rate': 0.0}
--- A, first
HTTP/1.0 200 OK
Idempotent-Replayed: false
    "reference": "demo-0001",
    "status": "success",
--- A, same key again
HTTP/1.0 200 OK
Idempotent-Replayed: true
    "reference": "demo-0001",
    "status": "success",
--- B, same key and reference
HTTP/1.0 200 OK
Idempotent-Replayed: false
    "reference": "demo-0001",
    "status": "success",
1 successful charge(s)
1 successful charge(s)

The second call to A is a replay, so A took the money once. The same reference and key at B are new, so B took it too: the customer has been charged twice, by two providers that each did the right thing. Nothing in either provider can stop that. Stop both providers and start them again before step 2.

2. Write the router and run four strategies. Save router.py. It has the HTTP calls, the replay of the first 2,000 card fundings as orders, the safe attempt (key, same key again, then ask), a tracker over the last 100 orders, and the choice of first provider.

"""Two providers, a router and an honest ledger of what each order cost. Money is integer kobo.

Provider A is on port 8101, provider B on 8104. Each keeps its own state: a reference or an
Idempotency-Key that one provider has seen means nothing to the other.
"""
import json
import sqlite3
import urllib.error
import urllib.request
from collections import deque

PORTS = {"A": 8101, "B": 8104}
HEAD = {"Authorization": "Bearer sk_test_owoleaf_mock", "Content-Type": "application/json"}
CARD = "5061000000001234"          # the last four (1234) are not a test card, so the fault rates decide


def call(p, method, path, body=None, key=None):
    """One HTTP call to provider p. Returns (status, json). Status 0 means no answer at all."""
    head = dict(HEAD, **({"Idempotency-Key": key} if key else {}))
    data = json.dumps(body).encode() if body is not None else None
    req = urllib.request.Request(f"http://127.0.0.1:{PORTS[p]}{path}", data=data, method=method, headers=head)
    try:
        with urllib.request.urlopen(req, timeout=10) as r:
            return r.status, json.load(r)
    except urllib.error.HTTPError as e:
        return e.code, json.load(e)
    except OSError:
        return 0, {}


def orders(n, path="data/finance.sqlite"):
    """The first n card fundings in the generated ledger, replayed as orders: (order id, customer, amount)."""
    db = sqlite3.connect(path)
    return db.execute("""SELECT 'ord-' || t.id, c.ref, t.amount_kobo FROM transactions t
                         JOIN customers c ON c.id = t.customer_id
                         WHERE t.kind = 'funding_card' ORDER BY t.id LIMIT ?""", (n,)).fetchall()


def attempt(p, order, cust, amount, safe=True):
    """Try one order at provider p. Returns (outcome, calls) where outcome is
    paid, declined, error (nothing was charged) or unknown (we cannot tell)."""
    ref = f"{order}-{p}"                     # one reference per order and provider
    body = {"reference": ref, "amount_kobo": amount, "customer_ref": cust,
            "card_number": CARD, "metadata": {"order": order}}
    calls = 1
    st, out = call(p, "POST", "/charges", body, key=ref if safe else None)
    if st == 500 and safe:                   # the same key again: a replay if the charge was made
        calls += 1
        st, out = call(p, "POST", "/charges", body, key=ref)
    if st == 500 and safe:                   # still 500: ask the provider what it did before going elsewhere
        calls += 1
        vst, vout = call(p, "GET", f"/charges/{ref}")
        if vst == 404:
            return "error", calls
        if vst != 200:
            return "unknown", calls
        st, out = 200, vout
    if st == 200:
        return ("paid" if out["charge"]["status"] == "success" else "declined"), calls
    return "error", calls


class Tracker:
    """Success rate over the last `window` orders each provider handled."""
    def __init__(self, window=100):
        self.w = {p: deque(maxlen=window) for p in PORTS}

    def rate(self, p):
        return sum(self.w[p]) / len(self.w[p]) if self.w[p] else 1.0

    def record(self, p, ok):
        self.w[p].append(1 if ok else 0)


def first_choice(strategy, i, tracker):
    if strategy == "A only":
        return "A"
    if strategy.startswith("split"):
        return "A" if i % 2 == 0 else "B"
    leader = max(PORTS, key=lambda p: (tracker.rate(p), p == "A"))   # ties go to A
    other = "B" if leader == "A" else "A"
    return other if i % 10 == 9 else leader                          # every tenth order explores

Save run_routes.py. For each scenario and strategy it resets both providers, replays the 2,000 orders and counts what was paid. In the second scenario provider A starts failing half its calls at order 1,000.

import math
import router as r

N = 2000
STRATEGIES = ["A only", "split 50/50", "split 50/50 + fallback", "tracking + fallback"]
SCENARIOS = {"steady": None, "A degrades at order 1,000": {"error_rate": 0.5}}


def run(strategy, degrade, orders):
    for p in r.PORTS:
        r.call(p, "POST", "/admin/reset")
    r.call("A", "POST", "/admin/faults", {"error_rate": 0.0})
    tr, paid, calls, first_b, fallbacks = r.Tracker(), 0, 0, 0, 0
    for i, (order, cust, amount) in enumerate(orders):
        if degrade and i == 1000:
            r.call("A", "POST", "/admin/faults", degrade)
        p = r.first_choice(strategy, i, tr)
        first_b += p == "B"
        out, c = r.attempt(p, order, cust, amount, safe="fallback" in strategy)
        calls += c
        tr.record(p, out == "paid")
        if out == "error" and "fallback" in strategy:
            q = "B" if p == "A" else "A"
            out, c = r.attempt(q, order, cust, amount, safe=True)
            calls += c
            tr.record(q, out == "paid")
            fallbacks += 1
        paid += out == "paid"
    return dict(paid=paid, calls=calls, first_b=first_b, fallbacks=fallbacks)


orders = r.orders(N)
print(f"{len(orders):,} orders replayed from the generated card fundings")
print(f"A: {r.call('A', 'GET', '/admin/faults')[1]['faults']['decline_rate']} decline rate; "
      f"B: {r.call('B', 'GET', '/admin/faults')[1]['faults']['decline_rate']} decline rate, "
      f"{r.call('B', 'GET', '/admin/faults')[1]['faults']['error_rate']} error rate")
for name, degrade in SCENARIOS.items():
    print(f"\nscenario: {name}")
    print(f"{'strategy':<26}{'paid':>7}{'paid %':>9}{'not paid':>10}{'calls':>8}{'first to B':>12}{'fallbacks':>11}")
    for s in STRATEGIES:
        x = run(s, degrade, orders)
        print(f"{s:<26}{x['paid']:>7,}{x['paid'] / N * 100:>8.1f}%{N - x['paid']:>10,}{x['calls']:>8,}{x['first_b']:>12,}{x['fallbacks']:>11,}")

se = math.sqrt(0.94 * 0.06 / N) * 100
print(f"\none standard error of a rate near 94% over {N:,} orders is {se:.2f} points; of the gap between two runs, {se * math.sqrt(2):.2f}")

Stop both providers (Ctrl-C in their two terminals) and start them again, with the same two commands as step 1. The mock’s random draws start from the same place only on a fresh start. Then run the script in the third terminal.

cd labs/finance
python3 mock_provider.py --port 8101 --decline-rate 0.05 --fresh --quiet
cd labs/finance
python3 mock_provider.py --port 8104 --decline-rate 0.12 --error-rate 0.03 --state data/provider2.sqlite --fresh --quiet
python3 run_routes.py

It takes about 90 seconds, because every charge is a real HTTP call.

2,000 orders replayed from the generated card fundings
A: 0.05 decline rate; B: 0.12 decline rate, 0.03 error rate

scenario: steady
strategy                     paid   paid %  not paid   calls  first to B  fallbacks
A only                      1,899    95.0%       101   2,000           0          0
split 50/50                 1,814    90.7%       186   2,000       1,000          0
split 50/50 + fallback      1,841    92.0%       159   2,033       1,000          0
tracking + fallback         1,875    93.8%       125   2,007         204          0

scenario: A degrades at order 1,000
strategy                     paid   paid %  not paid   calls  first to B  fallbacks
A only                      1,445    72.2%       555   2,000           0          0
split 50/50                 1,557    77.8%       443   2,000       1,000          0
split 50/50 + fallback      1,824    91.2%       176   2,520       1,000        120
tracking + fallback         1,819    91.0%       181   2,178         990         40

one standard error of a rate near 94% over 2,000 orders is 0.53 points; of the gap between two runs, 0.75

The first table is the steady case. A alone pays 95.0%, the best of the four, and a fixed split pays 90.7%: the average of 95% and B’s 85.4%, as the prediction said. The safe fallback adds 1.3 points back by recovering B’s errors, 2,033 calls for 2,000 orders. Tracking pays 93.8%, 1.2 points under A alone, against a gap noise of 0.75: about what the 200 exploration orders at B should cost (200 orders at about 10 points less is 20 orders, 1.0 point). In the second table A has failed half its calls since order 1,000. A alone pays 72.2% and the split without fallback 77.8%. Both strategies with a safe fallback hold about 91%, and tracking gets there in 2,178 calls against 2,520, because by the end 990 orders in all went to B first. fallbacks is 0 in the steady table because the same-key retry at B recovers all its 3% errors before an order has to move.

3. Re-present declines at the other provider. Stop both providers and start them again. Save declines.py, which sends every order to A, and sends A’s declines, and only those, to B.

import math
import router as r

N = 2000
orders = r.orders(N)
for p in r.PORTS:
    r.call(p, "POST", "/admin/reset")
r.call("A", "POST", "/admin/faults", {"error_rate": 0.0, "lost_response_rate": 0.0})

stats = dict(paid_first=0, declined_first=0, paid_on_second=0, errors=0)
for order, cust, amount in orders:
    out, _ = r.attempt("A", order, cust, amount)
    if out == "paid":
        stats["paid_first"] += 1
    elif out == "declined":
        stats["declined_first"] += 1
        out2, _ = r.attempt("B", order, cust, amount)      # re-present the declined payment to the other provider
        stats["paid_on_second"] += out2 == "paid"
    else:
        stats["errors"] += 1
d, s = stats["declined_first"], stats["paid_on_second"]
print(f"declined at A: {d}; paid when re-presented at B: {s} ({s / d * 100:.1f}%)")
print("B pays about 85% of what it is sent (0.97 x 0.88), whoever the card belongs to: the mock draws every decline afresh")
print(f"paid overall: {stats['paid_first'] + s:,} of {N:,}  (A alone paid {stats['paid_first']:,})")

# What if a decline belonged to the card, not the provider? q = chance the second try is declined too.
# (a model: 0.85 is B's rate from above, q is the assumption)
print(f"\n{'q':>5}{'recovered of the declines':>28}{'orders paid':>14}{'paid %':>9}")
for q in (0.0, 0.5, 0.9, 1.0):
    rec = round(d * 0.85 * (1 - q))
    paid = stats["paid_first"] + rec
    print(f"{q:>5.1f}{rec:>28,}{paid:>14,}{paid / N * 100:>8.1f}%")
se = math.sqrt(0.95 * 0.05 / N) * 100
print(f"\none standard error of a 95% rate over {N:,} orders is {se:.2f} points")

Stop both providers and start them again with the two commands from step 1, then run the script in the third terminal.

cd labs/finance
python3 mock_provider.py --port 8101 --decline-rate 0.05 --fresh --quiet
cd labs/finance
python3 mock_provider.py --port 8104 --decline-rate 0.12 --error-rate 0.03 --state data/provider2.sqlite --fresh --quiet
python3 declines.py
declined at A: 101; paid when re-presented at B: 91 (90.1%)
B pays about 85% of what it is sent (0.97 x 0.88), whoever the card belongs to: the mock draws every decline afresh
paid overall: 1,990 of 2,000  (A alone paid 1,899)

    q   recovered of the declines   orders paid   paid %
  0.0                          86         1,985    99.2%
  0.5                          43         1,942    97.1%
  0.9                           9         1,908    95.4%
  1.0                           0         1,899    95.0%

one standard error of a 95% rate over 2,000 orders is 0.49 points

B paid 91 of A’s 101 declines, so the paid share goes from 94.95% (1,899 of 2,000) to 99.5%. B is not special: it pays about 85% of any charge, because the mock draws each decline afresh. The table is the same fallback under an assumption the mock does not make: if q is the chance that the second try is declined as well, the recovery falls from 86 payments at q = 0 to 9 at q = 0.9 and none at q = 1, and the paid share falls with it, back to A’s alone. The real q is not in the mock. It depends on why the issuer declined, so measure it on your own data before you count the uplift, and read the scheme text on reattempts first.

Break the router: make it fall back on any failure and let the provider lose some responses. Stop both providers and start them again, then save doublecharge.py. It sets lost_response_rate to 0.05 on both providers, so that one call in twenty takes the money and answers 500. It then runs the naive router (a new reference at B, no key, no check) and the safe one over the same 2,000 orders, and asks both providers what they actually charged.

import router as r

N = 2000
orders = r.orders(N)


def run(safe):
    for p in r.PORTS:
        r.call(p, "POST", "/admin/reset")
        r.call(p, "POST", "/admin/faults", {"lost_response_rate": 0.05})   # the charge is made, the reply is a 500
    r.call("A", "POST", "/admin/faults", {"error_rate": 0.0})
    paid, paid_orders = 0, set()
    for order, cust, amount in orders:
        out, _ = r.attempt("A", order, cust, amount, safe)
        if out in ("error", "unknown"):                                    # the naive router goes to B on any failure
            out, _ = r.attempt("B", order, cust, amount, safe)
        paid += out == "paid"
        if out == "paid":
            paid_orders.add(order)
    seen = {}
    for p in r.PORTS:                                                      # what each provider says it took
        for c in r.call(p, "GET", "/charges?status=success")[1]["charges"]:
            seen.setdefault(c["metadata"]["order"], []).append((p, c["amount_kobo"]))
    twice = {o: v for o, v in seen.items() if len(v) > 1}
    return paid, len(seen), twice, len(set(seen) - paid_orders)


for safe in (False, True):
    paid, charged, twice, told_failed = run(safe)
    extra = sum(v[1][1] for v in twice.values())
    label = "same key, verify, then fall back" if safe else "naive: new reference, other provider"
    print(f"{label}")
    print(f"   orders the router reports paid: {paid:,}; orders with a successful charge: {charged:,}; charged twice: {len(twice)}")
    print(f"   money taken twice: ₦{extra // 100:,}.{extra % 100:02d}; charged but the router says not paid: {told_failed}")
    if twice:
        o, v = next(iter(sorted(twice.items())))
        print(f"   first example: {o} charged at {v[0][0]} and at {v[1][0]}, {v[0][1]:,} kobo each")

Stop both providers and start them again with the two commands from step 1, then run the script in the third terminal.

cd labs/finance
python3 mock_provider.py --port 8101 --decline-rate 0.05 --fresh --quiet
cd labs/finance
python3 mock_provider.py --port 8104 --decline-rate 0.12 --error-rate 0.03 --state data/provider2.sqlite --fresh --quiet
python3 doublecharge.py

It prints this:

naive: new reference, other provider
   orders the router reports paid: 1,886; orders with a successful charge: 1,904; charged twice: 86
   money taken twice: ₦741,204.00; charged but the router says not paid: 18
   first example: ord-1007 charged at A and at B, 457,200 kobo each
same key, verify, then fall back
   orders the router reports paid: 1,908; orders with a successful charge: 1,908; charged twice: 0
   money taken twice: ₦0.00; charged but the router says not paid: 0

The naive router charged 86 orders twice, taking ₦741,204.00 more than it should, and 18 more orders were charged at A, declined at B and shown to the customer as failed. The router believes it paid 1,886 orders and the providers took money for 1,904. The safe router retried A with the same key, got the stored result back, asked when it had to, and charged no order twice. Its 1,908 paid orders match the 1,908 charged, and the same 2,000 orders, the same lost responses and the same second provider produced no double charge. Only the rule about unknowns changed.

ARTEFACT Write a routing policy change record ~45 MIN
YOU PRODUCERouting policy change record

Template

# Routing policy change: <short name>
Author <payments engineer> · Approver <head of payments> · Date <date> · Decision needed by <date>

## Current rule
<Steps in order: where the first attempt goes, what each outcome does, what is learned.>

## Proposed change
<The new steps in order. Out of scope: <what this change does not touch>.>

## Evidence
| Rule | Orders | Paid | Paid % | Calls |
|---|---|---|---|---|
Noise: one standard error of the gap is <points>. The gap is <n> times it.
What this evidence cannot see: <for example real issuer declines>.

## Guard against double charges
Rule: one order, at most one successful charge across all providers.
How it is enforced: <reference, key, verification>. How it is checked: <report, schedule>.
Unknown outcome: <what is held, who asks again, for how long>.

## Failover rule
<When an order may leave provider A, on what proof, and when it may not.>

## Rollout and rollback
Rollout: <share of orders, duration, what must hold before widening>
Rollback: <the switch, who may use it, what traffic does after it>

## How this could be wrong
<One way, and the number that would show it.>

## Approval
Written by <name, role>. Approved by <name, role> on <date>. Reviewed with <finance operations>.
WORKED EXAMPLE

At a real company a payments engineer writes this record and the head of payments signs it. Mojisola writes this one for Lumora Mobile after the Friday double charges.

Routing policy change: safe failover. Author Mojisola, payments engineering · Approver head of payments · Date 23 November 2026 · Decision needed by 27 November: start the three-day trial.

Current rule. Send every order to A. On any 500 or timeout, send it to B under a new reference, with no key and no check.

Proposed change. Send to A with a key. On a 500, retry once with the same key. If that fails, ask A for the charge by reference. Only a 404 moves the order to B. If the check fails, hold the order and ask again. Out of scope: re-presenting declines at B, and any split of volume.

Evidence. One replay of 2,000 orders, with one call in twenty losing its response at both providers. Current rule: the router reports 1,886 paid, the providers took money for 1,904, 86 orders were charged twice (₦741,204.00 taken twice) and 18 were charged and shown as failed. Proposed rule: 1,908 paid, 1,908 charged, none twice. The paid gap is 22 orders, 1.1 points, against a noise of 0.75 for the gap between two rates, about one and a half times the noise. The case rests on the double-charge counts, not the rates. The replay is one run against a mock, which cannot see real issuer declines.

Guard. The reference is the order id plus the provider. A daily check against both providers’ reports looks for any order with two successful charges.

Rollout and rollback. Assumption: one order in ten for three days, widened only if the check finds no double charge. Rollback is the flag that sends everything to A with no failover, not the old rule, which is the fault.

How this could be wrong. If B’s real 500s differ from the mock’s, held orders could pile up. A hold queue above a day’s work would show it.

Now you

You are a payments engineer at Ojaline, the marketplace that delivers in nine cities. Checkout sends card payments to two providers with a 50/50 split and a safe fallback. You want to move to success-rate tracking with a safe fallback. Treat the lab’s step 2 rows as your own replay of 2,000 orders: split with fallback paid 92.0% in 2,033 calls (steady) and 91.2% in 2,520 (degraded); tracking paid 93.8% in 2,007 calls and 91.0% in 2,178. Use the 0.75-point noise line the lab printed. Say what the change does not touch, and choose the trial size and the rollback yourself. Your head of payments will read the record and decide whether the trial starts. Both of you need to see how the order is protected from a double charge.

Self-check

DECIDE

Lumora Mobile's two providers differ: B is cheaper per charge and authorises a few points fewer. Mojisola must ship the first version of the router before the airtime season. Boma wants the cheaper route used when it is safe, and the board wants no repeat of the Friday double charges. Nobody has measured how much of Lumora's declines belong to the cards. Which first version does she ship?

READING
  1. DOC
    Auth rate based routing (Hyperswitch documentation) Juspay (Hyperswitch)

    A vendor's own description of success-rate routing with exploration and a recent-outcome window. Read how the window and the exploration share are set. Its improvement claims are the vendor's, from its own traffic, so use the page for the design and not for the numbers.

  2. DOC
    Updates to rules for declined transaction resubmission and use of authorization response codes (Visa) Visa, 2021

    Visa's own notice of the 2021 change to how declines are categorised and reattempted. Read the categories and what an acquirer must do. This build saw it only through search results, so read it for the exact text and check the current Visa Core Rules.

  3. DOC
    How to avoid excessive retries penalties (PayPal) PayPal

    A processor's explanation of Visa's reattempt categories, the fields Visa uses to match a reattempt and the limit it states. A vendor's account, not a rulebook; compare its limit with the other processors' before you quote one.

  4. DOC
    Guidelines on Operations of Electronic Payment Channels in Nigeria (CBN, 2020) Central Bank of Nigeria, 2020

    The CBN's channel rules. Read the sections on switching and on acquirers to check whether domestic card transactions must pass through a local switch, which this chapter could confirm only through a summary.

  5. DOC
    Regulatory Framework for Non-Bank Acquiring in Nigeria (CBN, 2021) Central Bank of Nigeria, 2021

    Who may process and settle merchants' card transactions besides banks, and the standards they work to. Read it before you add a provider, to see what role that provider must be authorised for.

  6. POST
    An overview of the CBN's Regulatory Framework for Non-Bank Acquiring Aelex, 2021

    A law firm's summary of the 2021 framework. Read it for a quick map of the participants. It is a secondary account, and the CBN's own text decides a question.

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: Other African markets: Kenya, Ghana, South Africa, Egypt →