Preventing Duplicate Payments After USSD Timeouts in Kenyan Banking

Content authorBy EGSPublished onReading time12 min read
Two software engineers in a modern office discuss project plans while pointing at a whiteboard filled with handwritten diagrams and notes.

A USSD timeout ends the customer's session while the payment instruction behind it continues. Duplicate debits happen when the bank treats session loss as payment failure and lets the customer start again. The fix is a bank-generated payment reference and authoritative status recovery before any new attempt.

Payment state must outlive the session

The session is a conversation, and the payment is a record. When the conversation drops, the record keeps existing in whatever state the core banking system and the switch left it in. That's why a timeout tells you the customer stopped seeing the screen.

Payment functionality is now the norm on these channels. The Central Bank of Kenya's Banking Sector Innovation Survey 2025 found that 92 percent of institutions offered payment services inside their mobile banking solution when app and USSD are counted together.

So the channel where sessions break most easily is also the channel carrying real debits for almost every bank in the market. If your USSD code can move money, the session layer and the payment layer need separate lifecycles in your design, with separate storage and separate expiry rules. A session can die in 30 seconds. A pending instruction at the switch can stay unresolved for minutes, and your customer will redial inside that window.

Where can a timeout occur?

Infographic depicting a financial workflow with interconnected steps, rounded cards, and arrows, in a clean fintech design.

A single payment can time out at three points, and each one demands a different response from the bank. Follow one customer paying a bill through your USSD menu. The session can break while they're still entering a Personal Identification Number (PIN) or after the instruction leaves your system for the switch. It can also break after the money has already moved and only the display is missing.

Safaricom's own payment stack already encodes this distinction. The Daraja result codes include 1037 for DS timeout where the phone is unreachable, which is a different outcome from 1032, a cancellation by the user.

Read that carefully and the design implication is unavoidable. The upstream platform distinguishes "we never heard back" from "the customer said no," so a bank that collapses both into one generic "transaction failed" screen is destroying information it was handed. Generic failure messages are where duplicate debits are born.

Before authorization permits a safe restart

No financial instruction exists until authorization completes, so a restart here is safe. The customer entered an amount and a PIN, and nothing reached the ledger or the switch. Your system can confirm that by checking whether a reference was ever created and submitted.

Stripe documents the same boundary in its own Application Programming Interface (API). Idempotent results are saved only after execution of an endpoint begins, so requests that fail validation can be retried freely.

The useful inference for a USSD menu is that your safe-restart check should be a positive lookup. Prove that no submission record exists for that customer with the same amount and beneficiary in the last few minutes before you let the menu offer a fresh payment.

After submission requires status recovery

A submitted instruction is unknown, not failed, and the bank must resolve it before allowing anything new. Once the request leaves your orchestration layer, the outcome sits with the switch or the mobile money platform, and only a status query answers it.

Safaricom's asynchronous design makes this explicit. The initial POST response only confirms acceptance for processing, while the settlement outcome arrives later on the result callback.

Which means an acknowledgment in your logs is not evidence of anything financial. Treat every submitted reference as blocking: the customer who redials gets a status check against that reference, and the menu refuses a second instruction for the same amount and beneficiary until the first one resolves.

After completion requires confirmation recovery

Money moves and the customer believes nothing happened. This is the most expensive of the three cases, because the only thing missing is a screen. The ledger already posted and the beneficiary already received value, so the customer is about to pay twice.

Callback handling is where this breaks in practice. In Daraja, a failed STK callback has no CallbackMetadata key at all, and that asymmetry is a leading cause of 500 errors on callback endpoints.

A callback endpoint that throws an error on a shape it didn't expect leaves your system holding a stale pending record for a payment that completed. The returning customer then sees "pending" and retries. Defensive parsing of callbacks is duplicate prevention.

Start building your financial platform?

Speak with EGS engineers about open banking, payment infrastructure, cloud systems, and enterprise software.

Get in Touch →

References preserve one payment intent

One bank-generated payment reference, created before submission and independent of the session identifier, is what holds the payment together. Session IDs die with the session. A reference created at authorization survives the redial and the support investigation three days later.

Kenya's regulator has been pushing the sector toward exactly this kind of end-to-end identification. The Central Bank of Kenya's National Payments Strategy 2022-2025 sets out adoption of ISO 20022 across the payment sector as a priority for interoperability and data quality.

Standards work like that only pays off inside the bank if your own channel generates and carries a single identifier through every hop. One reference should answer what the customer authorized and what support can see now.

Repeated requests must remain idempotent

A retry carrying the same payment reference must return the recorded outcome and never repeat the debit. That's the whole contract. The second request reads the stored result rather than creating a new financial effect.

Stripe's implementation is the reference model most engineering teams already know. Keys are up to 255 characters and are pruned after at least 24 hours, with incoming parameters compared against the original request to catch misuse.

Your retention window has to cover the longest realistic redial gap, which for a Kenyan USSD customer who loses network and tries again after lunch is hours rather than seconds. Back the check with a unique database constraint on the reference, because a check-then-insert in application code loses to two concurrent requests arriving in the same millisecond.

Returning customers need status-first journeys

A customer who redials should see their unresolved payment before they see the menu. Put the recent instruction first, with its state and its reference, and let them choose to check status or wait. The new payment option comes after that, and only after.

The platform layer already enforces something similar. Daraja returns result code 1001 for "unable to lock subscriber" when a concurrent session exists for that customer.

If Safaricom's own switch refuses to run two overlapping instructions for one subscriber, a bank menu that happily accepts a second attempt is less careful than the rail underneath it. Build your menu to mirror that refusal, in language the customer understands rather than a numeric code.

Notifications must reflect final state

Messages must name the real state and never describe a timeout as a failure. "Your payment is being processed, reference ABC123, we'll confirm by SMS" is accurate. "Transaction failed, please try again" is an instruction to create a duplicate.

Production M-Pesa integrations are built around an explicit transaction state machine covering initiated, pending, success. The same machine also includes failed and reversed, alongside idempotency handling for duplicate callbacks.

Your customer messaging should expose those same states rather than flattening them into two. I'd go further: the pending message is the single highest-leverage string in the whole journey, because it's the one sent at the exact moment the customer is deciding whether to dial again.

A restart table governs every outcome

Every known state needs a predetermined response, written down before launch and implemented as a rule rather than a judgment call. Stripe's guidance for interrupted checkouts is to reuse the same PaymentIntent rather than create a new one, because the object state tracks prior attempts for that cart or session.

StateCustomer messageStatus checkNew payment allowedReference stays active
No submission foundStart againNone neededYesNo
Submitted, pendingBeing processed, confirm by SMSAutomatic, every 30 secondsNoYes
Pending beyond 5 minutesStill processing, support notifiedAutomatic plus manual queryNoYes
CompletedPaid, with receipt detailRead stored resultYes, as a separate paymentClosed
Failed at switchNot completed, no debitConfirmed failure onlyYesClosed
ReversedRefunded, with timingLedger confirmationYesClosed

Two rules make the table work in production. Only an authoritative status response closes a pending reference, and no automated path converts "unknown" into "failed" without a confirmed query result.

Start building your financial platform?

Speak with EGS engineers about open banking, payment infrastructure, cloud systems, and enterprise software.

Get in Touch →

Recovery protects trust and operations

Deterministic recovery cuts disputed debits at the source, and the cost of not having it is measured in customers who give up rather than complain. Kenyan evidence on redress is sobering. Innovations for Poverty Action's Financial Consumer Protection Survey found that only 43 percent of people who lost money in the past 12 months sought redress at all, and 9 percent of those cases were never resolved.

Apply that ratio to duplicate debits on your channel and the complaint volume in your dashboard is a fraction of the actual incidents. The rest become quiet attrition and a channel reputation you can't see in a ticket queue.

Clean recovery also changes your operations. Support stops reconstructing events from fragments when every instruction carries one reference with a full state history, and finance stops hunting matched pairs in end-of-day files.

Tests must reproduce interrupted journeys

Recovery rules that haven't been tested under real interruption are assumptions. The evidence you need is a set of controlled scenarios that show suppressed duplicates and the trace a support agent can pull afterward.

Regulated institutions are already formalizing this. Amazon Web Services describes how Nationwide Building Society integrated controlled fault injection experiments into its cloud infrastructure to demonstrate resilience to regulators.

The part worth borrowing is the framing. These teams treat failure testing as evidence they can show a supervisor, which is precisely the posture a Kenyan bank needs when the Central Bank asks why a customer was debited twice. Write your timeout scenarios as a documented suite with expected outcomes, and keep the results.

Redial tests verify duplicate suppression

Redial testing proves that a second dial cannot create a second debit. Test the customer who redials three seconds after the drop and the one who redials twenty minutes later, during pending processing and after completion.

Concurrency is the case teams skip. High-concurrency environments allow identical retries to hit the processing layer in the same millisecond, which bypasses check-then-insert logic before the first write commits.

So fire simultaneous requests with the same reference and assert that exactly one ledger entry exists afterward. A test that sends them sequentially will pass while your production code is still broken.

Delay tests expose uncertain outcomes

Slow responses create the pending states that duplicate payments feed on, so inject them deliberately. Delay the core banking response and the callback, one at a time, and confirm that the pending instruction stays blocked from resubmission.

Tooling for this is routine now. Fault injection using Toxiproxy in a pipeline can add 5 seconds of latency between a payment orchestrator and a mock gateway to validate behavior.

Latency is the cheapest fault to simulate and the closest to what Kenyan customers actually experience on a congested evening. If your retry and timeout settings have never been exercised against a slow dependency, they're configuration.

Disconnect tests preserve transaction evidence

Cut each link and check what survives. Break the connection between the USSD gateway and your application and between the mobile money platform and your callback endpoint, then verify restart behavior and the records left behind.

Safaricom built for this case. When Daraja cannot reach your ResultURL, it calls your TimeoutURL instead, which signals a problem with your server's availability.

That endpoint is frequently stubbed and forgotten. Test it properly, because it's the only signal you'll get that an instruction resolved somewhere you couldn't see, and your reconciliation window depends on catching it.

Operator timing must be verified directly

Get current production timing constraints in writing from each operator and aggregator, because the numbers differ by network. Africa's Talking documents that a Safaricom session runs 180 seconds but times out after 30 seconds of customer inactivity, while Airtel applies a 15 second application response timeout and a 60 second customer response window.

Those gaps matter directly. A recovery design tuned to a 30 second customer window behaves differently on a network that allows 60, and an orchestration call that comfortably returns in 12 seconds will be cut off by Airtel's application response limit.

Confirm session duration and response deadlines for Safaricom and Airtel as they stand today, since published figures age and aggregator settings vary by account. Assume nothing is shared across networks until someone at the operator confirms it.

EGS can review the recovery design

If you're investigating duplicate debits now or preparing a USSD launch, an independent review of the recovery design is the fastest way to find where your channel converts a timeout into a second debit. EGS assesses existing and new channels across recovery rules and the evidence your support teams can retrieve after an incident.

That review covers the specifics this article has worked through: whether your payment reference is generated independently of the session and whether retries carrying that reference are genuinely idempotent under concurrency.

Talk to EGS about USSD payment recovery and the engineering changes needed to address duplicate-payment risk.

Start building your financial platform?

Speak with EGS engineers about open banking, payment infrastructure, cloud systems, and enterprise software.

Get in Touch →

Don’t start another payment immediately. Keep the amount, beneficiary, and approximate time, then ask the bank to check the payment reference and authoritative status. If no submission exists, a new attempt is safe. If the instruction is pending or complete, wait for confirmation or receipt details before paying again.

Support should search by the bank-generated payment reference, then compare the customer’s session record, submitted request, switch response, callback, and ledger entry. Matching timestamps and references show whether one instruction was retried or two payment intents were created. The investigation should end with a confirmed financial state.

A bank should retain the payment reference, session identifier, customer and beneficiary details, amount, authorization time, submission time, state changes, outbound messages, switch responses, callbacks, and ledger identifiers. These records let support reconstruct the payment without relying on the customer’s recollection or incomplete USSD screen history.

Escalate a payment when it remains pending beyond the bank’s documented recovery threshold, such as five minutes in the article’s restart table, or when status queries fail. Keep the reference blocked while operations investigate. Escalation must not convert an unknown outcome into failure or permit a second debit.

Reconciliation should query the switch or mobile money platform with the original payment reference and compare that result with the core ledger. If the payment completed, update the stored state and receipt data without creating another debit. If the result remains unresolved, keep the reference pending and continue controlled follow-up.

Schedule a Meeting

Book a time that works best for you

You Might Also Like

Discover more insights and articles

A project manager in business casual attire discusses a document intake process with a team in a modern office, focusing on a large monitor.

Bank document intake workflow: A readiness checklist

This article gives you a checkpoint-by-checkpoint method for testing a document intake process before you turn it on. It includes a worksheet structure you can copy into a spreadsheet and the evidence each control needs to produce.

Two business partners collaborate on configuring a POS terminal in a modern office, surrounded by payment devices and colleagues.

EthioPay for Ethiopian Banks: Turn Readiness into a Delivery Plan

This article explains how an Ethiopian bank moves from "we want to participate" to a dated, costed integration plan for the country's domestic card scheme and instant payment rails. It covers service selection and a phased release sequence.

A modern smartphone displaying a mobile banking app lies on a wooden desk, surrounded by abstract payment cards and a notebook.

AfriGO Card Readiness: Plan Your Nigerian Bank’s Rollout

This article is a readiness guide for moving from "we're considering it" to a controlled pilot on Nigeria's domestic card rails. It covers role definition and launch scope, then maps the transaction flow so you can assess systems and assign requirement ownership through the workstream matrix that holds the whole program together.

A professional seated at a desk uses a smartphone and payment card, engaged in online banking in a bright, modern office.

G2P Payments in Africa: Build Reliable Social Payment Infrastructure

This article traces the full lifecycle of a government social payment in Africa, from eligibility approval through to reconciliation and investigation evidence. It assigns operational ownership at each system boundary and sets out how to control exceptions and assisted access.