Yazan.
كل المقالات

المقالات مكتوبة حالياً بالإنجليزية، أما بقية الموقع فتتبع اللغة التي اخترتها.

4 دقيقة قراءةFintechPaymentsBackendSystem Design

1 Tap, 2 Charges: 5 Patterns That Keep Fintech Money Correct

1 Tap, 2 Charges: 5 Patterns That Keep Fintech Money Correct cover

A user taps "Pay" once. The backend charges them twice.

Nothing crashed and no exception reached a log. One request timed out, the client retried in silence, and the customer paid twice. That is the uncomfortable thing about money bugs: they don't throw errors. They show up on someone's bank statement.

Here are five patterns fintech backends use to keep money correct, and the failure each one is there to stop.

Animated cheat sheet: one timeout and one silent retry charge a user twice, then the five patterns that prevent it
The cheat sheet I posted with this on LinkedIn.

1. Idempotency keys: no double charges

The client generates one key per intent ("pay $100 for this order"), sends it with every attempt, and the server stores the result against that key. The first request does the work. Every retry with the same key gets the stored result back instead of a second charge.

The detail that breaks naive versions is two retries arriving at the same moment, which is why the key has to be claimed by a unique constraint rather than checked with a SELECT first. I wrote up the full schema, the Django code and that race in Idempotency Keys: The Unsung Hero of Every Payment System.

2. Row locking: no race conditions

Two requests read the same balance of $100 at the same moment. Each sees enough money, each subtracts $80, and the account pays out $160 from $100. Both requests were correct on their own. Together they were wrong.

The fix is to make the read and the write one step that only one transaction can take at a time. In PostgreSQL that is SELECT ... FOR UPDATE inside a transaction, and in Django it is select_for_update():

from django.db import transaction

with transaction.atomic():
    wallet = Wallet.objects.select_for_update().get(pk=wallet_id)
    if wallet.balance_minor < amount_minor:
        raise InsufficientFunds()
    wallet.balance_minor -= amount_minor
    wallet.save(update_fields=["balance_minor"])

When a transfer touches two accounts, lock them in a fixed order (by id, for example), so two transfers going in opposite directions don't deadlock, each holding one lock and waiting for the other.

3. Outbox pattern: no lost events

The payment commits, the service is about to publish "payment completed" to the queue, and the process dies in between. The money moved, but the ledger, the receipt email and the fraud check never heard about it. Publish first instead and you get the opposite: everyone hears about a payment that then rolled back.

The outbox closes that gap. The event is written to an outbox table in the same database transaction as the payment, so both commit or neither does. A separate relay reads the outbox, publishes to the broker and marks each row as sent. Delivery becomes at-least-once, so consumers have to be idempotent too, which brings us back to pattern 1.

4. Saga: no half-done transfers

A cross-border transfer touches several services: debit the wallet, convert the currency, send the bank payout. No single database transaction spans all three, so when the bank rejects the payout at step three, something has to undo steps one and two.

A saga is that something: a sequence of local transactions, each paired with a compensating action. When a step fails, the saga runs the compensations for the steps that already succeeded, in reverse order. The conversion is reversed, the wallet is refunded, and nothing is stuck halfway. Two rules make it hold up in production: store the saga's state so it survives a restart, and make every step and every compensation idempotent, because both will be retried.

5. Double-entry ledger: every cent traceable

A balance column updated in place can tell you what a balance is, but never why. When it's wrong, there is nothing to reconcile it against.

In a double-entry ledger, every movement of money is recorded as entries that sum to zero: a debit on one account and a matching credit on another. Entries are never edited or deleted, and a mistake is corrected with a new, reversing entry. Balances are derived from the entries (a cached balance is fine, as long as it can be rebuilt from them), so every cent on a statement traces back to the transaction that put it there. And amounts are stored as integers in minor units, never as floats.

The common thread

None of these patterns makes a payment faster. They make it boring, which is the point: the same request can arrive twice, two requests can arrive at once, a process can die at the worst possible moment, a bank can say no, and the books still balance.

Which one did you learn the hard way?

First shared on LinkedIn.