Under Construction
Backend••20 min•88 views••

Race condition in the game backend when two requests use the same balance

Minh Khoa

Minh Khoa

Author

image.pngThe player has 100 gems, each item costs 80 gems. If two purchase requests arrive almost at the same time, the system should allow at most one purchase.

But if the balance check and the data update are handled separately, both requests can pass the check. As a result, the player receives two items, while the balance only drops from 100 to 20 gems.

This is an example of race condition. Multiple tasks access shared data, and the result depends on the order in which the processing steps interleave.

A reasonable piece of code when run sequentially

Suppose the backend processes the transaction with the following logic. This is pseudocode, with the item price determined by the server.

balance = await ReadBalance(playerId)

if balance >= 80:
    await WriteBalance(playerId, balance - 80)
    await GrantItem(playerId)

When there is only one request, the result is correct. The backend reads 100, verifies that 80 is available, writes the new balance as 20, and then grants the item.

The problem appears when a second request arrives in the time between the read step and the write step.

OrderRequest ARequest B
1Read balance 100
2Read balance 100
3Check 100 ≥ 80, valid
4Check 100 ≥ 80, valid
5Write balance 20, grant one item
6Write balance 20, grant one item

Request B calculates 100 - 80 from the data it had read earlier, then writes the value 20 to the database. It does not know that request A has just used the same balance.

The database still ends up storing 20 gems, but the inventory has increased by two items. In this example, the later write cancels out one deduction, which is often called lost update.

Why is the bug easy to miss?

If you test by buying one item, waiting for it to finish, and then buying again, the second request will read a balance of 20 and be rejected. The bug only appears when the processing steps interleave in a certain order.

Using await only keeps the order of steps within each request. While A is waiting for the database, the backend can still process B. The two requests can even run on two different backend instances.

Locking the purchase button in the interface helps reduce repeated actions. A mutex in the application can coordinate tasks within its scope. With multiple backend instances accessing the same wallet, the transaction condition needs to be protected at the place where shared data is stored.

Move the balance check into the deduction operation itself

For this example, you can use a UPDATE conditional statement so that the database checks the balance and performs the subtraction in a single operation.

Suppose using PostgreSQL at the Read Committed isolation level, each player has exactly one wallet row that already exists. The statement below is executed inside the purchase transaction.

UPDATE wallets
SET gems = gems - 80
WHERE player_id = $1
  AND gems >= 80
RETURNING gems;

The backend relies on the result of the statement.

  • One row is returned — the balance satisfies the condition and has been updated within the transaction.

  • No row is returned — the wallet does not have enough gems, and the transaction must stop.

If A updates the wallet row first, B must wait for A's transaction to finish. When A commits, PostgreSQL the condition is checked again gems >= 80 on the new data version. The balance is now 20, so B cannot update any row and does not receive the item. PostgreSQL — Read Committed

The part that decides whether to grant the item must therefore be based on the update result, rather than on a previous balance read.

Deducting gems and granting the item must both succeed

After protecting the deduction, there is still one situation to handle. The backend deducts gems successfully, but the inventory write fails.

In this example, the wallet, inventory, and purchase history are in the same database. The entire transaction is executed on the same connection, in one transaction.

  1. Open the transaction.

  2. Run the UPDATE conditional statement.

  3. If no row is updated, roll back and return an insufficient gems error.

  4. If the update succeeds, write the item to the inventory and record the purchase history.

  5. Only after the commit succeeds should the successful purchase result be returned to the client.

If the inventory or history write step fails, rollback will undo the gem deduction as well. This is the atomic property of a transaction — changes within the transaction are either all recorded or all canceled. PostgreSQL — Transactions

Adding only BEGIN and COMMIT around the original code can still allow errors to occur under Read Committed. Two transactions can still both read 100 before updating. Therefore, the transaction must be paired with an appropriate data access control method, such as the conditional update statement above.

Retry requests need idempotency

Suppose the transaction has committed, but the connection is interrupted before the client receives the response. The player sees loading or a network error and tries again.

To recognize this as the same purchase, the client sends an idempotency key and keeps the key the same when retrying. The backend stores the key along with the transaction result. When it receives the same request again, it returns the recorded result.

One way to implement this is to add a unique constraint for (player_id, idempotency_key) in the transaction table, while also writing this record in the same transaction as the wallet and inventory. If the same key is used but the purchase content is different, the backend must reject it. Stripe — Idempotent requests · PostgreSQL — Unique constraints

Two protection mechanisms for two separate situations.

ScenarioRequired mechanism
Two different purchases competing for the same balanceConcurrent update control
One purchase is retried due to a timeout or network lossIdempotency

Two requests with different idempotency keys can still compete for the same wallet. The conditional balance update statement is still necessary.

Testing with concurrent requests

With an initial balance of 100 gems and a price of 80 gems, you should test at least the following cases.

ScenarioExpected result
Two different purchases run concurrentlyOne succeeds, one is rejected. There are 20 gems left and one more item added
Inventory write fails after the gems deduction stepTransaction rollback. There are 100 gems left and no item is added
The transaction has committed but the client lost the response and then retries with the same keyReturn the previous result. Keep the gems balance and the recorded item unchanged

When testing concurrently, use separate database connections and have the requests start at the same time. For a backend running multiple instances, distribute requests across multiple instances to verify the exact scope that needs protection.