Backendcore
Transactions & isolation levels
Which anomalies each level allows — and why “check then write” needs a lock or SERIALIZABLE.
What it is and why it exists
Read Committed (Postgres default) can show non-repeatable reads and allows lost updates in read-modify-write code; Repeatable Read gives a stable snapshot but allows write skew; Serializable prevents all of these by aborting conflicting transactions (you must retry). Row locks (SELECT … FOR UPDATE), atomic updates and unique constraints fix most real bugs.
Quick prototype
Read the balance, compute, write it back.
In production, at scale
Atomic SQL updates (UPDATE … SET credits = credits − 1 WHERE credits > 0), unique constraints for idempotency, SELECT FOR UPDATE where a read must precede a write, Serializable with retry loops for complex invariants, and short transactions (never hold one open across an LLM call).
Vendors and tools
| Postgres | MVCC with Read Committed, Repeatable Read, Serializable (SSI) |
|---|---|
| SQLAlchemy / psycopg | Transaction handling in Python |
On AWS: Aurora PostgreSQL / RDS behave like Postgres; DynamoDB transactions and conditional writes for NoSQL.
How it fails
- Two concurrent requests both spend the last credit (lost update)
- Transaction held open while waiting 10 s for a model
What the interviewer asks next
Write skew example?
Two doctors on call; each transaction checks “at least one other on call” and removes itself. Both checks pass on the same snapshot, both commit, nobody is on call. Serializable or a lock on the shared rows prevents it.