Skip to main content

Part of topic: Next.js Architecture, Kotlin Multiplatform & Mobile Engineering

Fits by Aliv: Building Kenya-First E-Commerce with Asynchronous Payment-Safe Workflows

Fits by Aliv: Building Kenya-First E-Commerce with Asynchronous Payment-Safe Workflows

March 5, 2025 3 min read NestJS, Flutter, M-Pesa, E-Commerce, PostgreSQL, BullMQ, Resilience

Fits by Aliv: Building Kenya-First E-Commerce with Asynchronous Payment-Safe Workflows is a Developer Journal article by Ancel Ajanga on https://ancel.co.ke. Engineering e-commerce for emerging markets: soft inventory reservations, idempotent M-Pesa Daraja STK push callbacks, and bounded background reconciliation. It focuses on: Standard shopping carts fail under asynchronous payment rails like M-Pesa. Ancel Ajanga (Senior Software Engineer) authored this piece from production engineering work.

Engineering e-commerce for emerging markets: soft inventory reservations, idempotent M-Pesa Daraja STK push callbacks, and bounded background reconciliation.

Who this is for

Mobile and backend engineers building e-commerce systems in markets where mobile money (M-Pesa) is asynchronous, mobile data is intermittent, and inventory overselling must be prevented.

Problem

Standard shopping carts fail under asynchronous payment rails like M-Pesa. If inventory is decremented before payment, abandoned carts lock out genuine buyers; if decremented after payment confirmation, items oversell when two customers pay simultaneously.

Business outcome

A resilient commerce architecture featuring 15-minute soft inventory locks with automatic Redis TTL expiry, idempotent webhook ingestion, and background reconciliation.

Metrics

  • Zero duplicate order creations during payment callback retries
  • 15-minute automated inventory reservation releases via BullMQ
  • Full audit logging for M-Pesa transaction IDs and checkout requests

E-commerce architectures designed in Silicon Valley make fundamental assumptions that crumble in emerging markets. They assume customers pay with instant credit cards, possess reliable fiber broadband, and hold items in carts with synchronous checkout confirmation.

In Kenya, commerce runs on **M-Pesa**.

M-Pesa is an asynchronous payment rail: the backend triggers an STK Push, the customer's phone receives a SIM prompt, they enter their PIN, and Safaricom transmits a callback seconds or minutes later. If your e-commerce platform is not engineered around this asynchronous lifecycle, you will either suffer rampant inventory overselling or lock up your stock with abandoned carts.

I built Fits by Aliv (a curated thrift/sustainable fashion platform) with a **NestJS backend and Flutter mobile client** specifically to solve these emerging-market payment and inventory challenges.

The Problem: The Payment-Inventory Conundrum

In sustainable fashion and one-of-a-kind thrift items, every item has an inventory count of exactly **one**. This creates a severe dilemma: - **Scenario A (Deduct on Checkout Initiation)**: If you mark an item sold the moment the user clicks "Pay with M-Pesa", a customer who cancels the PIN prompt or walks away locks that item forever, costing the merchant sales. - **Scenario B (Deduct on Payment Callback)**: If you wait until Safaricom's webhook confirms payment, two shoppers can trigger STK prompts for the same dress simultaneously. Both enter their PINs, both get charged, and the merchant now has an angry customer and an impossible refund dilemma.

## The Architectural Solution: 15-Minute Soft Reservations with BullMQ

Fits by Aliv resolves this dilemma using **Soft Inventory Reservations backed by Redis and BullMQ**:

. User Initiates Checkout  -->  Reserve item in Redis with 15m TTL
2. Enqueue BullMQ Job       -->  Scheduled for +15m release if unpaid
3. Trigger M-Pesa STK Push  -->  Customer receives PIN prompt
4. Safaricom Webhook        -->  Verify signature, settle order, cancel release job

1. When a shopper clicks checkout, the backend attempts to acquire a soft reservation on the item ID in Redis. If the item is already reserved, the second shopper receives an immediate message: "Another shopper is currently checking out this item. If they do not complete payment within 10 minutes, it will become available." 2. Concurrently, a delayed job is scheduled in **BullMQ** with a 15-minute timer. 3. If Safaricom's payment callback arrives successfully within the window: - The order status transitions to `PAID`. - The item is marked permanently sold in PostgreSQL. - The delayed release job is cancelled. 4. If the customer cancels the prompt or the 15-minute timer expires without a callback: - The BullMQ worker fires, releases the Redis reservation, and notifies the client via WebSocket that the cart has expired.

ypescript
async function initiateMpesaCheckout(userId: string, itemId: string, phone: string) {
  // 1. Acquire atomic soft reservation in Redis
  const acquired = await redis.set(`item:reserve:${itemId}`, userId, 'EX', 900, 'NX');
  if (!acquired) {
    throw new ConflictException("Item is currently reserved by another customer");
  }

  // 2. Schedule automatic release worker
  await reservationQueue.add(
    'release-unpaid-item',
    { itemId, userId },
    { delay: 15 * 60 * 1000, jobId: `release:${itemId}` }
  );

  // 3. Initiate Daraja STK Push
  return await mpesaService.triggerStkPush({ phone, itemId });
}

Defensive Webhook Handling & Idempotency

Safaricom's Daraja gateway can deliver the same payment confirmation webhook multiple times during cellular network fluctuations. - **Raw Signature Validation**: Callbacks are verified against Safaricom's secret certificate. - **Idempotency Locks**: The incoming `MpesaReceiptNumber` is saved with a database unique constraint. If a duplicate callback arrives with the same receipt, the server returns an immediate `200 OK` without dispatching duplicate orders or balance credits. - **Zero Client Trust**: The Flutter mobile client never dictates payment state. The mobile app displays a pending spinner and polls only the authoritative backend state until the webhook settles the transaction.

Key Engineering Takeaways

1. **Design for Asynchronous Payment Rails**: Never assume payment is synchronous. Treat checkout initiation, payment authorization, and settlement as discrete state machine steps. 2. **Soft Locks Prevent Stock Collision**: Using atomic Redis locks with bounded TTLs allows you to protect unique inventory without locking database tables. 3. **Idempotency Protects Financial State**: Network retries are inevitable. Ensuring every webhook handler checks an idempotency key guarantees you will never create duplicate orders.

Explore the Fits by Aliv Project Page or see my other [full-stack and mobile projects](/projects).

Trade-offs

Chose soft reservations with background release queues over strict database table locks to keep browsing and checkout fast without holding open database transactions during slow mobile money user input.

Challenges faced

Safely handling delayed, out-of-order, or replayed M-Pesa STK push callbacks from Safaricom Daraja without trusting client-side transaction assertions.