High-Concurrency Engineering: Distributed Locking & Race Condition Prevention in African Fintech
How to engineer bulletproof transaction boundaries, PostgreSQL row-level locks, and Redis distributed leases to prevent double-spends and inventory over-allocations.

Kelvin Agyare Yeboah
Founder & Lead Engineer, Zoharix

1. The Anatomy of a High-Concurrency Flash Drop
Imagine this scenario: A major concert at the Accra International Conference Centre announces tickets on [Z-Events](https://z-events.zoharix.tech). Exactly 500 Early Bird passes are listed.
Within the first 3 seconds of opening the gate, 3,200 concurrent HTTP requests hit your checkout reservation endpoint.
If your backend executes a naïve read-modify-write query: ```sql -- NAÏVE IMPLEMENTATION: RACE CONDITION GUARANTEED SELECT remaining_count FROM ticket_tiers WHERE id = 'early-bird'; -- App checks: remaining_count > 0 (e.g. 5 tickets left) -- 50 threads pass the check simultaneously! UPDATE ticket_tiers SET remaining_count = remaining_count - 1 WHERE id = 'early-bird'; ```
Within milliseconds, your database commits 50 tickets when only 5 existed. You have oversold capacity, angry attendees are turned away at the door, and refund reconciliations create nightmare accounting headaches.
2. Solution Level 1: Atomic Database Constraints
The first line of defense is strict relational database constraints at the storage engine level:
-- Atomic decrements with hardware-level row locks
UPDATE ticket_tiers
SET remaining_count = remaining_count - 1,
version = version + 1
WHERE id = 'early-bird'
AND remaining_count >= 1
RETURNING remaining_count, version;By incorporating the condition `remaining_count >= 1` directly into the `UPDATE` statement, PostgreSQL acquires a row-level write lock. Only transactions that decrement while the count is strictly positive will return rows.
3. Solution Level 2: Distributed Leases with Redis
When checkout involves asynchronous Mobile Money USSD authorization prompts (which take 30 to 90 seconds for user PIN input), you cannot hold an open PostgreSQL database transaction lock without starving your connection pool.
Instead, we engineer **Distributed Reservation Leases** in Redis with automatic TTL expiration:
const redis = new Redis(process.env.REDIS_URL!);
export async function reserveTicketWithLease( tierId: string, userId: string, leaseSeconds = 600 ): Promise<{ success: boolean; leaseId?: string }> { const leaseId = `lease:${tierId}:${userId}:${Date.now()}`; // Lua script ensures atomic inventory decrement and lease issuance const luaScript = ` local available = tonumber(redis.call('get', KEYS[1]) or '0') if available >= 1 then redis.call('decr', KEYS[1]) redis.call('set', KEYS[2], ARGV[1], 'EX', ARGV[2]) return 1 else return 0 end `;
const result = await redis.eval( luaScript, 2, `inventory:${tierId}`, `lease:${tierId}:${userId}`, leaseId, leaseSeconds );
return { success: result === 1, leaseId: result === 1 ? leaseId : undefined, }; } ```
If the buyer fails to enter their MoMo PIN within 10 minutes, the Redis key expires, an automated inventory recovery worker restocks the pool, and no human intervention is needed.
4. Idempotency Keys on Payment Callbacks
Telecom gateways in Africa frequently retry webhooks when network latency causes their initial delivery acknowledgement to time out.
Every single transaction on Z-Events carries an **Idempotency Key**: - Generated from the SHA-256 hash of `telcoTransactionId + amount + accountReference`. - Written to an isolated ledger with a unique database index. - If a duplicate callback arrives 10 seconds later, the server returns `HTTP 200 OK` immediately without re-crediting or re-issuing duplicate tickets.
Read our practical implementation breakdown in the [Behind the Build: Payment Rails log](/insights/building-z-events-payment-rails).

Explore Z-Events Platform
Sub-second Mobile Money ticketing, instant WhatsApp tickets, and offline gate operations built in Accra for the continent.
