Track: APIs and back end · Lesson 36 of 41 · 17 min

Databases in depth: migrations, transactions and race conditions

What breaks at the data level: migrations on live data, partial writes without transactions, double charges under parallel requests — and how QA catches it.

Data outlives code

Code can be rolled back in a minute. Corrupted data can't. That makes schema changes and concurrent data access a high-risk area worth testing on its own.

Migrations

A migration is a script that changes the schema or the data (add a column, split a table, recompute a field).

Check Why
On a copy of the data close to production volume Everything is fast on 100 rows; on 10 million it can lock the table for an hour
Old records after the migration A new NOT NULL column — what happens to existing rows?
Rollback (down migration) Can you go back without losing data?
Version compatibility During deployment the old code runs against the new schema
Encodings and locales Accents, apostrophes and emoji aren't mangled

Tip: before a migration, save control queries (counts and sums on key tables) and compare them afterwards — any mismatch shows up immediately (SQL examples).

Transactions

"Pay for an order" is several changes: debit the balance, change the status, record the payment. Without a transaction, a failure in the middle leaves the data half-changed.

How to check: force the second step to fail (invalid data, a disabled dependency, a mocked error) and look in the database — are there any partial changes left?

Race conditions

A race condition when debiting a balanceRequest ARequest Bread balance = 100read balance = 100100 ≥ 80 → ok100 ≥ 80 → okwrite balance = 20write balance = 20160 debited from a balance of 100
A race condition when debiting a balance. Two requests read the same balance before the other one updates it — and both debit successfully. Protection: a row lock, an atomic update or an idempotency key.

Two requests read a balance of 100 at the same time, both debit 80, both save 20 — and money appears out of thin air. Typical race spots:

  • debiting a balance, bonus points, limits;
  • the last item in stock;
  • a single-use promo code;
  • a double click on "Pay";
  • email uniqueness during simultaneous sign-ups.

How to reproduce:

from concurrent.futures import ThreadPoolExecutor

def apply_once():
    return api.post(f"/carts/{cart_id}/promo", json={"code": "ONE-TIME-50"}, token=token).status_code

with ThreadPoolExecutor(max_workers=10) as ex:
    codes = list(ex.map(lambda _: apply_once(), range(10)))

assert codes.count(200) == 1        # a single-use code is applied exactly once

By hand: two browser tabs and near-simultaneous clicks, or Burp Repeater / Postman Runner with parallel requests.

What development does (and what QA checks)

Protection Check
Unique indexes Parallel sign-ups with the same email → one account, the other gets an error
Row locks (SELECT … FOR UPDATE) Parallel debits never produce a negative balance
Optimistic locking (version) A stale update → 409
Idempotency keys A repeated request → the same result

Backups

A separate, rarely tested scenario: does the database actually restore from a backup, and how long does it take? A backup nobody has restored from is just hope.

The same principles in an event queue: async systems.

Key takeaways

  • Test migrations on realistic data volumes, together with old records and rollback.
  • A failure in the middle of an operation must not leave partial changes — that's the transaction check.
  • Races are reproduced with parallel requests; a one-time action must happen exactly once.

Check yourself

  1. 1. 10 parallel requests apply a single-use promo code and 3 get a 200. This is…

  2. 2. Why test a migration on a large data volume?

  3. 3. How do you check that payment runs in a transaction?

Practice: SQL for testers