Hi!
Skip to main content
← Back to Writing

The Art of Idempotency in Banking Systems

In e-commerce, a double-charge is an annoyance. In banking, it's a catastrophe. If a system processes a $1M wire transfer twice because of a network timeout, people get fired.

This is why Idempotency is the single most important concept I teach junior engineers.

The Network Lie

We often write code assuming the network is reliable:

async function transfer(amount: number) {
  await api.post('/transfer', { amount });
  // We assume if this line is reached, it worked.
}

But what if the response packet gets lost? The server processed the request, but the client thinks it failed. The client retries. Now we have two transfers.

The Idempotency Key

The solution is deceptively simple: The Idempotency Key.

Every state-changing request must carry a unique ID (usually a UUID v4) generated by the client. The server tracks these keys.

  1. Client generates key = uuid()
  2. Client sends POST /transfer with Idempotency-Key: key
  3. Server checks Redis: "Have I seen this key?"
  4. No: Process transaction, save result, return 200.
  5. Yes: Return the saved result immediately. Do not re-process.

Storage Strategy

Where do you store these keys?

For high-volume banking systems at Bank Mega, we use a tiered approach:

  1. Redis (TTL 24h): Fast lookups for immediate retries.
  2. PostgreSQL (Permanent): Audit trail for dispute resolution.

The Hard Part: Concurrency

The real challenge is the race condition. What if two requests with the same key arrive at the exact same millisecond?

If you just check-then-set, both might pass. You need atomic operations.

INSERT INTO idempotency_keys (key, user_id) 
VALUES ($1, $2) 
ON CONFLICT (key) DO NOTHING;

If the INSERT returns 0 rows affected, another thread beat you to it. Abort and wait for the result.

Conclusion

Reliability isn't about preventing errors; errors are inevitable. Reliability is about handling them deterministically. Idempotency turns "maybe it happened" into "it happened exactly once."