What it is
A database stores durable facts. Constraints express rules such as unique identifiers or valid references. A transaction groups changes so they commit together or roll back together; concurrency behavior still depends on isolation and the operations you choose.
Why you need it
If creating an order and reserving its stock can drift apart, users can pay for inventory the system did not reserve. Correctness should hold even when two requests arrive together.
How it works
- Define the facts and invariants the database must preserve.
- Choose constraints and atomic operations that enforce them.
- Commit related changes together where a single transaction can cover them.
- Handle conflicts, failures, and external effects explicitly.
Reserve stock inside a transaction
BEGIN;
UPDATE products SET stock = stock - 1
WHERE id = :product_id AND stock > 0;
-- Application checks that exactly one row changed.
-- Otherwise ROLLBACK and report no stock.
INSERT INTO reservations (id, product_id) VALUES (:id, :product_id);
COMMIT;Use bound parameters. This sketch requires an existing schema and explicit affected-row handling. The database transaction cannot atomically include a third-party payment call.
Good practices and why
- Enforce invariants in the authoritative store and test concurrent attempts.
- Use a stable operation identity when retries could otherwise duplicate business effects.
Common mistakes
- Reading stock and later decrementing it without concurrency protection.
- Assuming the word transaction makes every isolation or external-effect problem disappear.
Try it yourself
Model two customers competing for one item. Describe the affected-row results and when each reservation may be created.
What a successful result looks like
At most one reservation succeeds, stock never becomes negative, and failures cannot leave a partial local update.
0 / 6000 characters · Saved on this device. Do not include passwords or private data.
Check your understanding
Answer the understanding check correctly to record exercise completion.
Related interview practice
- Two customers. One item left. ↗
- Two editors save. One loses their changes. ↗
- Both transactions are waiting for each other. ↗
These scenarios add constraints and follow-up questions to the concepts you just learned.
Further reading
Selected primary references · reviewed 2026-10-09. Examples are educational; use your framework’s documented integration guidance when building a deployed system.