惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

B
Blog RSS Feed
量子位
Recent Announcements
Recent Announcements
T
The Blog of Author Tim Ferriss
美团技术团队
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Blog — PlanetScale
Blog — PlanetScale
H
Help Net Security
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
博客园 - Franky
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
宝玉的分享
宝玉的分享
大猫的无限游戏
大猫的无限游戏
V
Visual Studio Blog
博客园 - 聂微东
aimingoo的专栏
aimingoo的专栏
Microsoft Security Blog
Microsoft Security Blog
U
Unit 42
J
Java Code Geeks
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
IT之家
IT之家
Hugging Face - Blog
Hugging Face - Blog
腾讯CDC
L
LangChain Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
MpesaBooks — devto
sharkflow lt · 2026-04-29 · via DEV Community

sharkflow ltd

{
  "title": "Building M-Pesa Accounting Software: The Technical Stack Behind MpesaBooks",
  "content": "# Building M-Pesa Accounting Software: The Technical Stack Behind MpesaBooks\n\nKenya processes over $320 billion annually through M-Pesa. Yet most SMEs still reconcile these transactions in spreadsheets.\n\nThat's the problem MpesaBooks solves. But here's what most people don't realize: building M-Pesa accounting software isn't just about connecting to an API. It's about designing systems that survive on African mobile networks, handle concurrency at scale, and make sense of chaotic cash flow patterns.\n\nThis is how we built it.\n\n## The Core Challenge: M-Pesa Isn't a Ledger\n\nM-Pesa transactions are notifications. Notifications that arrive out of order, sometimes duplicate, sometimes late. A customer sends you 500 KES. You get notified 30 seconds later. Then again 2 minutes later (network hiccup). Meanwhile, your accountant needs to see your cash position *right now*.\n\nTraditional accounting software assumes instant, sequential transactions. M-Pesa assumes none of this.\n\nSo we built around three principles:\n1. **Idempotency first** — Every transaction is a unique event\n2. **Eventually consistent** — Real-time is nice; correct is essential\n3. **Network-first** — Assume phones will drop, reconnect, and retry\n\n## API Design: Webhook Reliability Over Perfection\n\nWe use M-Pesa's C2B (Customer to Business) webhook system. Here's the flow:\n\n```

javascript\n// Our webhook receiver — first line of defense\napp.post('/mpesa/callback', async (req, res) => {\n  const transaction = req.body;\n  \n  // Step 1: Acknowledge immediately (before processing)\n  res.status(200).json({ \n    ResultCode: 0, \n    ResultDesc: 'Accepted'\n  });\n  \n  // Step 2: Queue async (don't process in the request)\n  await queue.add('process-mpesa-txn', transaction, {\n    attempts: 5,\n    backoff: {\n      type: 'exponential',\n      delay: 2000\n    }\n  });\n});\n

```\n\nWhy this pattern? M-Pesa expects a response within 30 seconds. If we're slow, it retries. If we acknowledge first, then process in the background, we never lose a transaction.\n\nWe use Bull queues (backed by Redis) for this. On Heroku? AWS SQS works too. The point: decouple receipt from processing.\n\n## Database Design: Events Over Entities\n\nWe store transactions as immutable events, not mutable records.\n\n```

sql\n-- The source of truth: raw M-Pesa notifications\nCREATE TABLE mpesa_events (\n  id UUID PRIMARY KEY,\n  merchant_request_id VARCHAR(255) UNIQUE NOT NULL,\n  checkout_request_id VARCHAR(255),\n  mpesa_receipt_number VARCHAR(100) UNIQUE,\n  amount DECIMAL(15, 2) NOT NULL,\n  phone_number VARCHAR(20) NOT NULL,\n  transaction_timestamp TIMESTAMP NOT NULL,\n  received_at TIMESTAMP DEFAULT NOW(),\n  raw_payload JSONB,\n  idempotency_key VARCHAR(255) UNIQUE,\n  status ENUM('pending', 'processed', 'failed', 'reversed'),\n  created_at TIMESTAMP DEFAULT NOW()\n);\n\n-- Derived: account ledger (rebuilt from events)\nCREATE TABLE account_ledger (\n  id UUID PRIMARY KEY,\n  business_id UUID REFERENCES businesses(id),\n  mpesa_event_id UUID REFERENCES mpesa_events(id),\n  debit DECIMAL(15, 2),\n  credit DECIMAL(15, 2),\n  balance DECIMAL(15, 2),\n  posted_at TIMESTAMP,\n  created_at TIMESTAMP DEFAULT NOW(),\n  INDEX (business_id, posted_at)\n);\n

```\n\nWhy separate tables? **Auditability + Flexibility**.\n\nIf M-Pesa sends a reversal (refund), it arrives as a new event with a reference to the original `mpesa_receipt_number`. We don't delete or update the original transaction. We add a new event and let the ledger rebuild itself.\n\n```

javascript\n// Processing a transaction\nconst processTransaction = async (mpesaEvent) => {\n  const db = await getConnection();\n  \n  try {\n    await db.transaction(async (trx) => {\n      // Check if already processed\n      const existing = await trx('mpesa_events')\n        .where('mpesa_receipt_number', mpesaEvent.mpesa_receipt_number)\n        .first();\n      \n      if (existing) {\n        return; // Idempotent — don't reprocess\n      }\n      \n      // Insert the event\n      const [eventId] = await trx('mpesa_events').insert({\n        mpesa_receipt_number: mpesaEvent.mpesa_receipt_number,\n        amount: mpesaEvent.amount,\n        phone_number: mpesaEvent.phone_number,\n        transaction_timestamp: mpesaEvent.transaction_date,\n        raw_payload: mpesaEvent,\n        status: 'processed'\n      });\n      \n      // Append to ledger\n      await trx('account_ledger').insert({\n        mpesa_event_id: eventId,\n        business_id: mpesaEvent.business_id,\n        credit: mpesaEvent.amount,\n        posted_at: new Date()\n      });\n      \n      // Trigger balance recalculation\n      await recalculateBalance(trx, mpesaEvent.business_id

Enter fullscreen mode Exit fullscreen mode