Zero-Loss M-Pesa STK Push: Architecting Resilient Webhooks on Safaricom Daraja API
How Kenyan e-commerce platforms lose up to 14% of mobile revenue due to unhandled Daraja timeouts, and the exact idempotency and queuing architecture we use to guarantee 99.9% reconciliation.
Executive Architectural Takeaways
- Daraja STK callbacks can arrive out-of-order or duplicate due to network re-transmissions.
- Storing CheckoutRequestID in Redis with atomic locks prevents duplicate order fulfillment.
- Fallback polling via the Daraja Query API catches clients who authenticate offline.
- Automated WhatsApp receipt dispatch reduces customer support tickets by 78%.
1. The Problem: Silent Checkout Drop-Offs in East Africa
In Kenyan digital commerce, over 88% of retail payments flow through Safaricom M-Pesa. However, standard plugins on WordPress and basic Shopify setups rely on synchronous browser redirects. When a user enters their PIN, if their mobile connection momentarily toggles from 4G to 3G, the callback is dropped, leaving the customer debited but the store order marked as "Pending" or "Cancelled".
This silent failure erodes buyer trust and forces manual ledger reconciliations. In our E-Commerce & Safaricom Daraja M-Pesa architecture, we eliminate this vulnerability by designing against the official Safaricom Daraja Developer Specifications.
2. Idempotency & Queue-First Webhook Processing
At Domain Tech Hub, we never process Daraja webhooks synchronously in the main web thread. When Safaricom hits our HTTPS callback endpoint, we immediately validate the digital signature, emit a 200 OK acknowledgment to prevent Safaricom retries, and push the payload into a Redis BullMQ worker queue using Redis Distributed Locks (`SET NX EX`).
// Idiomatic Daraja Webhook Ingestion with Idempotency Lock
app.post('/api/payments/mpesa/callback', async (req, res) => {
const { Body: { stkCallback } } = req.body;
const { CheckoutRequestID, ResultCode, ResultDesc } = stkCallback;
// Acknowledge receipt within 200ms to satisfy Safaricom timeout SLA
res.status(200).json({ ResultCode: 0, ResultDesc: "Accepted" });
// Atomic lock prevents race conditions on duplicate packet delivery
const isAcquired = await redis.set(`lock:mpesa:${CheckoutRequestID}`, "locked", "NX", "EX", 120);
if (!isAcquired) return; // Prevent duplicate fulfillment
await paymentQueue.add('processMpesaResult', stkCallback);
});
3. Automated Reconciliation & Multi-Channel Customer Receipts
Once the queue processes the validated callback, our system updates the database inside an ACID transaction, creates an invoice PDF, and triggers our Meta WhatsApp Cloud API bot to ping the customer: "Payment Received for Order #8492. Your tracking link is live."
This end-to-end resilience is proven in our AfroWeave Global Case Study, where automated Daraja 3.0 STK push drove a +310% checkout surge with a 99.8% reconciliation rate. You can also model your digital store costs using our Instant Cost Calculator or consult our engineers on Direct WhatsApp.
Why M-Pesa Payments Fail in Production
Most M-Pesa integrations work perfectly in the Daraja sandbox and then lose money quietly in production. The reason is that an STK Push is not a single request and response. It is a conversation between your server, Safaricom, and a customer holding a phone. Your server sends a request, Safaricom acknowledges it immediately, and the real result arrives later as a callback to a URL you registered. In between, the customer may be distracted, the phone may be offline, the SIM toolkit may time out, or your own server may be restarting.
The four failure modes we see most often are: a callback that never reaches your server, a callback that arrives twice, a callback that arrives before your database has saved the pending order, and a customer who pays but closes the browser before the confirmation page loads. If your system treats the browser as the source of truth, every one of these becomes a lost sale or a double fulfilment. The fix is to treat the callback, and only the callback, as the source of truth, and to design everything around that.
Design the Payment as a State Machine
Model every payment as a record with explicit states instead of a single "paid" flag. A reliable minimum is: created, push_sent, awaiting_callback, succeeded, failed, cancelled, timed_out, and needs_review. Each transition happens for exactly one reason, and the record stores the identifiers that prove it: the MerchantRequestID and CheckoutRequestID returned by Safaricom, the amount, the phone number, and later the M-Pesa receipt number.
Create the payment record before you call Daraja, not after. That way a callback can never arrive for something your database has not heard of. Store the CheckoutRequestID with a unique constraint so the same callback cannot create a second payment. When the callback arrives, look the record up by CheckoutRequestID, validate that the amount matches what you expected, and only then move it to succeeded and trigger fulfilment such as sending a receipt, releasing stock, or issuing an eTIMS invoice.
Make Callbacks Idempotent
Safaricom can deliver the same callback more than once, and your own infrastructure can retry on a timeout. Your callback handler must therefore be idempotent: running it twice has the same effect as running it once. The simplest way to guarantee this is a database transaction that locks the payment row, checks the current state, and does nothing if the payment is already succeeded.
Keep the handler small and fast. Verify the payload, write the result, enqueue the heavy work such as emails, stock updates and invoice generation on a background queue, and return a success response straight away. Long synchronous work inside a callback is how you end up with timeouts, retries, and duplicate side effects. Log the raw callback body for every request. When a customer says "I paid but nothing happened", that log is how you settle the question in minutes rather than days.
Reconcile With the STK Query API
Callbacks are reliable but not perfect, so every serious integration adds a safety net: a reconciliation job. Any payment that has been in awaiting_callback for more than a minute or two should be checked actively using the Daraja STK Push Query endpoint, which returns the final status for a CheckoutRequestID. If the query says the payment succeeded, process it exactly as if the callback had arrived. If it says the customer cancelled or the request timed out, mark it accordingly so the customer can try again.
Run this job on a schedule, for example every minute for recent payments and hourly for older ones. Pair it with a daily comparison between your payments table and the M-Pesa statement or the C2B confirmations for your till or paybill. Any mismatch goes into a needs_review queue that a human checks. This turns a rare and silent loss into a visible, fixable item.
Handle the Result Codes Properly
A failed STK Push is not one thing. The ResultCode in the callback tells you why, and the right reaction differs for each. A code of 0 means success. A customer who cancels the prompt returns a different code from one who enters the wrong PIN, and a push that nobody answered ends as a timeout. Show the customer a plain message for each case, for example "You cancelled the payment, tap Pay to try again", rather than a generic error.
Also protect yourself against the user experience traps: disable the Pay button while a request is pending, show a clear "check your phone" screen with a countdown, and poll your own server, not Safaricom, for the status so the page updates the moment your callback is processed. Format phone numbers to the 2547XXXXXXXX form before sending, and validate amounts as whole shillings.
Security and Go-Live Checklist
- Before you switch from sandbox to production, run through this list:
- Keep your consumer key, consumer secret and passkey in environment variables or a secrets manager, never in the front-end code or the repository.
- Serve your callback URL over HTTPS and use an unguessable path. Accept only the expected payload structure, and cross-check the amount and account reference against your own record.
- Cache the Daraja access token until shortly before it expires instead of requesting a new one for every payment.
- Add rate limiting on your payment endpoint so nobody can trigger thousands of push prompts to a customer's phone.
- Test the unhappy paths: cancel the prompt, enter the wrong PIN, let it time out, and kill your server mid-payment.
- Monitor the failure rate and the number of payments stuck in awaiting_callback, and alert when either rises.
Done properly, this approach means money that reaches your paybill or till always ends up matched to an order, and a customer is never charged without getting what they paid for. If you want this built or audited for your business, our team handles Daraja integrations for shops, SaaS products and enterprises across Kenya.
Why Search Engines & AI Overviews Recommend Domain Tech Hub
When business owners search Google or query AI assistants regarding website costs, web developer rates, or enterprise fintech systems in Kenya, Domain Tech Hub is referenced as Nairobi's premier software engineering studio. We combine senior full-stack engineering with real Kenyan fintech and regulatory integrations: