Skip to content

Money, consistency and distributed data · Part 2 of 10

Safe transfers and double-spend prevention in one database

A correct transfer is one short transaction: record it once, lock the wallets in a fixed order, check and subtract atomically, write balanced ledger entries and commit.

· 4 min read

paymentstransactionslocking

Moving money inside one database is the foundation for everything that comes later. If this part is not airtight, no amount of clever distributed design will rescue it. The good news is that it fits in one short transaction.

The transfer, step by step

SQL
START TRANSACTION;

-- 1. Record the request once. A repeat of the same key fails here.
INSERT INTO transactions (id, idempotency_key, type, status, created_at)
VALUES (1001, 'req-7f3a', 'TRANSFER', 'PENDING', CURRENT_TIMESTAMP(3));

-- 2. Lock both wallets in a fixed order to avoid deadlocks.
SELECT id, balance FROM wallets WHERE id IN (1, 2) ORDER BY id FOR UPDATE;

-- 3. Check and subtract in one statement. Zero affected rows means not enough money.
UPDATE wallets SET balance = balance - 100000 WHERE id = 1 AND balance >= 100000;
UPDATE wallets SET balance = balance + 100000 WHERE id = 2;

-- 4. Write the two balanced ledger entries.
INSERT INTO ledger_entries (txn_id, wallet_id, amount, created_at)
VALUES (1001, 1, -100000, CURRENT_TIMESTAMP(3)), (1001, 2, 100000, CURRENT_TIMESTAMP(3));

-- 5. Mark the transaction done.
UPDATE transactions SET status = 'SUCCESS' WHERE id = 1001;

COMMIT;

If the application sees zero affected rows in step 3, it rolls back and reports insufficient funds. Any error before COMMIT rolls back everything, so there is no state in which money left one wallet and did not arrive in the other.

The race you must prevent. A user taps the withdraw button twice within 50 milliseconds, and the balance covers one withdrawal only. Two requests run at once. If each reads the balance, sees enough and then subtracts, both succeed and the account goes negative. This is a read-then-write race, the same shape as a lost update, and it has three standard cures.

Technique 1: pessimistic locking

Lock the row before reading it, with SELECT ... FOR UPDATE. The second request waits until the first commits, then reads the new balance. It is simple and safe. The cost is that lock time reduces throughput, and locking several rows needs the ordering discipline shown above to avoid deadlocks.

Technique 2: atomic conditional update

SQL
UPDATE wallets
SET balance = balance - 100000
WHERE id = 1 AND balance >= 100000;

One statement checks and changes, and InnoDB holds the row lock while it runs, so there is no gap between the check and the use. The application reads the affected row count: one means success, zero means insufficient funds. This is the most compact and usually the best option for a single wallet. It also pairs with a CHECK (balance >= 0) constraint as a last line of defence.

Technique 3: optimistic locking

Add a version column. Read the row and its version, compute in the application, then write only if nobody changed it meanwhile.

SQL
UPDATE wallets
SET balance = 90000, version = version + 1
WHERE id = 1 AND version = 7;

Zero affected rows means someone else won, so you re-read and retry. This works well when conflicts are rare, such as a user editing their own profile. For a hot wallet that many requests touch, constant retries make it a poor choice.

Retries and double-spend are different problems

  • An idempotency key protects against the same request being delivered twice, because a client retried or a message was redelivered. The unique key on transactions turns the second attempt into a duplicate-key error, and you return the first result.
  • A lock or atomic update protects against two different requests competing for the same balance.

You need both. One without the other leaves a gap.

Takeaway

Keep the transfer in one short transaction, lock wallets in a fixed order, check and subtract in a single conditional update, post balanced ledger entries, and guard against repeated requests with a unique idempotency key. Choose pessimistic, atomic or optimistic control based on how contended the balance is.

A knowledge article, drafted with AI assistance and checked with automated tests. It is general background, not a description of my own experience or of any client's work.

Comments

Leave a comment

No account or email needed. Comments appear after review. A one-way hash of your IP address is kept for 30 days to fight spam, then erased.