Researching database concepts
I need to provide a clear explanation of several database concepts, including ACID properties, isolation levels, anomalies, and more. I’ll cover differences between Postgres and MySQL while keeping it concise but comprehensive. Examples in SQL and pseudo code will be included, especially around isolation levels like read committed and serializable. I want to discuss MVCC basics, various lock types, tuning strategies, deadlock detection, idempotency keys, and the saga/outbox pattern. A scenario about e-commerce orders could help illustrate these concepts effectively.
1) What a database transaction is
A transaction groups multiple reads/writes into one logical unit of work. The database guarantees that either all changes become visible, or none do.
Example (money transfer):
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT; -- or ROLLBACK on error
If the app crashes after the first update, the DB rolls back so balances don’t diverge.
2) ACID (what the database promises)
A — Atomicity
“All or nothing.” If any statement fails, the whole transaction can roll back.
C — Consistency
Transactions move the DB from one valid state to another, enforcing constraints (FKs, CHECKs, triggers).
Example: a CHECK(balance >= 0) prevents overdrafts—transaction fails instead of committing invalid data.
I — Isolation
Concurrent transactions behave as if they ran alone (to varying degrees depending on isolation level).
D — Durability
Once committed, changes survive crashes (via WAL/redo logs, fsync, replication).
3) Isolation levels + anomalies (what can go wrong)
Isolation levels define which anomalies are allowed under concurrency.
Common anomalies
- Dirty read: read uncommitted data from another transaction.
- Non-repeatable read: read the same row twice and get different values (someone else committed in between).
- Phantom read: rerun a query and get new/missing rows because another tx inserted/deleted matching rows.
- Lost update: two tx read same value, both write back, later write overwrites earlier.
- Write skew (important under snapshot isolation): two tx make decisions based on a snapshot, individually “valid,” but combined violate an invariant.
Typical SQL isolation levels
READ UNCOMMITTED
- Allows dirty reads (many DBs effectively don’t implement true dirty reads; e.g., PostgreSQL treats it as READ COMMITTED).
READ COMMITTED (common default)
- Prevents dirty reads.
- Allows non-repeatable reads and phantoms.
Example (non-repeatable read):
Tx1:
BEGIN;
SELECT balance FROM accounts WHERE id=1; -- sees 100
-- later...
SELECT balance FROM accounts WHERE id=1; -- might see 50 after Tx2 commits
COMMIT;
Tx2 (between Tx1 reads):
BEGIN;
UPDATE accounts SET balance=50 WHERE id=1;
COMMIT;
REPEATABLE READ
- Guarantees repeated reads of the same row return the same value (typically via snapshot).
- Phantoms may or may not be prevented depending on DB/implementation (e.g., InnoDB uses next-key locks; PostgreSQL uses snapshot semantics and still needs predicate locks for true serializability).
- Can still allow write skew under snapshot isolation.
Write skew example (classic “at least one doctor on call”):
- Constraint: at least 1 row in
on_call must remain.
Tx1 and Tx2 both run concurrently:
-- both read: there are 2 doctors on call
SELECT COUNT(*) FROM on_call WHERE on_call=true; -- returns 2
-- each turns off a different doctor
UPDATE on_call SET on_call=false WHERE doctor_id=1; -- Tx1
UPDATE on_call SET on_call=false WHERE doctor_id=2; -- Tx2
Both commit → count becomes 0 (invariant broken), even though each tx saw “2”.
SERIALIZABLE
- Strongest: outcome equivalent to some serial order of transactions.
- Prevents dirty/non-repeatable/phantom reads and write skew.
- May abort transactions with a serialization failure; application must retry.
4) MVCC (Multi-Version Concurrency Control)
MVCC is how many DBs provide high read concurrency without blocking writers (and vice versa).
Idea: Updates don’t overwrite in-place for readers. Instead, each row has versions; readers see a snapshot appropriate for their transaction.
- Readers usually don’t block writers.
- Writers still need coordination (locks) to avoid conflicting updates.
- Old row versions are cleaned up later (vacuum/garbage collection).
Example intuition:
- Tx1 starts at time T=10, sees “balance=100”.
- Tx2 commits an update at T=12, sets balance to 50.
- Tx1 still sees the T=10 version until it commits/ends (under snapshot-based levels).
5) Locking + tuning (how to reduce contention)
Even with MVCC, locks matter for correctness and for write/write conflicts.
Common lock patterns
Practical lock tuning tips
- Keep transactions short
- Do not hold locks while making network calls or doing slow computations.
- Touch rows in a consistent order
- e.g., always lock accounts in increasing
id to reduce deadlocks.
- Use proper indexes
- Without an index, an update might scan/lock many rows.
- Choose the right locking read
- Avoid “read-modify-write” without protection
- Use atomic updates:
UPDATE counters SET value = value + 1 WHERE id=1;
- Or optimistic concurrency:
UPDATE doc
SET content = ..., version = version + 1
WHERE id = 1 AND version = 7; -- fails if someone else updated
6) Deadlocks (what they are and how to handle)
A deadlock happens when Tx1 holds a lock Tx2 needs, while Tx2 holds a lock Tx1 needs. Neither can proceed.
Example:
- Tx1 locks row A, then wants row B.
- Tx2 locks row B, then wants row A.
Most DBs detect deadlocks and abort one transaction.
How to prevent/mitigate:
- Lock ordering: always acquire locks in the same order.
- Narrow lock scope: lock only what you need.
- Retry on deadlock: treat it as a normal transient error.
- Reduce isolation/locking where safe (carefully).
7) Idempotency keys (safe retries for APIs)
In real systems, clients retry requests (timeouts, 502s). Without idempotency, retries can duplicate side effects (double charge, double order).
Pattern
Client sends Idempotency-Key: <uuid> for a “create” operation. Server stores the key with the outcome; repeated requests return the same result.
Minimal schema idea:
CREATE TABLE idempotency_keys (
key TEXT PRIMARY KEY,
response_json TEXT NOT NULL,
created_at TIMESTAMP NOT NULL
);
Usage (simplified):
- Start transaction.
- Insert key; if conflict, fetch stored response and return it.
- Perform action (e.g., create order).
- Store response tied to key.
- Commit.
Or enforce uniqueness directly on the business object:
CREATE UNIQUE INDEX uniq_order_request ON orders(request_id);
Then:
INSERT INTO orders(request_id, user_id, total) VALUES (...);
-- on conflict: select existing order and return it
8) Distributed workflows: Sagas + Outbox (when one DB tx isn’t enough)
A single database transaction cannot atomically update multiple services (without 2PC, which is complex and often avoided). Instead, use patterns that embrace eventual consistency.
Saga pattern (orchestration or choreography)
A saga is a sequence of local transactions with compensating actions if a later step fails.
Example: placing an order across services
- OrderService: create order =
PENDING
- PaymentService: charge card
- InventoryService: reserve stock
- OrderService: mark order =
CONFIRMED
If inventory reservation fails after payment succeeds:
- Run compensation: refund payment
- Mark order =
CANCELLED
Key points:
- Each step is a local DB transaction.
- You need retries, timeouts, and compensation logic.
- Design operations to be idempotent (see above).
Transactional Outbox pattern (reliable event publication)
Problem: “update DB then publish message” can fail between steps, causing lost or duplicated events.
Solution: write business changes and an “outbox event” in the same DB transaction, then publish asynchronously.
Schema:
CREATE TABLE outbox (
id BIGSERIAL PRIMARY KEY,
topic TEXT NOT NULL,
key TEXT NOT NULL,
payload JSONB NOT NULL,
published_at TIMESTAMP NULL
);
In one transaction:
BEGIN;
UPDATE orders SET status='CONFIRMED' WHERE id=123;
INSERT INTO outbox(topic, key, payload)
VALUES ('orders', '123', '{"type":"OrderConfirmed","orderId":123}');
COMMIT;
A separate publisher process:
- Polls
outbox WHERE published_at IS NULL
- Publishes to Kafka/Rabbit/etc.
- Marks
published_at = now() (or deletes row)
This gives “atomic DB state change + guaranteed event record,” making messaging robust.
(Variants: CDC-based outbox using WAL/binlog, exactly-once-ish delivery with dedupe downstream.)
9) Practical selection guide
- Default OLTP app: READ COMMITTED + targeted locking (
FOR UPDATE) where needed.
- Strong invariants across rows (no write skew): SERIALIZABLE (and retry on serialization failures) or explicit locking strategies.
- High-throughput queues:
SKIP LOCKED workers + short tx.
- Distributed workflows: Saga + outbox; avoid pretending you have a single global transaction.
If you tell me which database you’re targeting (PostgreSQL/MySQL/SQL Server/Oracle) and a concrete workflow (e.g., “reserve inventory then charge”), I can map the exact isolation semantics and show the recommended SQL patterns for that engine.