LLD Guide · Module 1: Foundations · Lesson 01.04
Postgres for LLD: Transactions, Row Locks and Idempotent Writes
Let the database enforce your invariants, and your concurrency bugs mostly disappear.
By Cruscible Engineering · Published
The database is the best concurrency tool you have. Most LLD bugs on Postgres come from not using it.
Chapter 4 of the LLD Guide. If a problem lists postgres under Recommended, ask for a PostgresClient in your constructor and create your schema there:
public class ParkingLotImpl implements ParkingLotContract {
private final PostgresClient db;
public ParkingLotImpl(PostgresClient db) {
this.db = db;
db.execute("""
CREATE TABLE IF NOT EXISTS spots (
id BIGSERIAL PRIMARY KEY,
floor INT NOT NULL,
kind TEXT NOT NULL CHECK (kind IN ('BIKE','CAR','TRUCK')),
plate TEXT UNIQUE
)""");
db.execute("CREATE INDEX IF NOT EXISTS spots_free ON spots (kind, floor) WHERE plate IS NULL");
}
}
1. The client in one table
| Method | Use it for |
|---|---|
execute(sql, params...) | DDL and writes where you don't need the row count |
update(sql, params...) | Writes where you do: it returns the number of rows changed |
query(sql, params...) | Many rows, as List<Map<String, Object>> |
queryOne(sql, params...) | Zero or one row, as Optional<Map<String, Object>> |
queryScalar(sql, Long.class, params...) | One value, for example a COUNT(*) |
insertReturningId(sql, params...) | An INSERT ... RETURNING id, returns Optional<Long> |
batchUpdate(sql, paramsList) | Many rows in one round trip |
transaction(tx -> { ... }) | Several statements that succeed or fail together |
Parameters use ? placeholders. Always pass values as parameters, never by concatenating strings into SQL.
💡 Tip: Values come back as JDBC types:
BIGINTasLong,INTasInteger. Read numbers throughNumber, as in((Number) row.get("floor")).intValue(), and you won't trip over the difference.
2. Constraints are invariants you get for free
Every rule in the brief that sounds like "never two of" or "always between" can usually be a constraint:
UNIQUE (plate): a vehicle can't be parked twice.CHECK (seats_left >= 0): capacity can't go negative.PRIMARY KEY,NOT NULLand foreign keys: no orphans or half-written rows.
When a write would break one, Postgres rejects it, even if two threads race. Catch the failure and turn it into the error or false the contract expects.
3. The lost update, and the one-statement fix
// ❌ Read, decide in Java, write: two threads both see the spot as free
Optional<Map<String, Object>> spot = db.queryOne("SELECT plate FROM spots WHERE id = ?", id);
if (spot.isPresent() && spot.get().get("plate") == null) {
db.execute("UPDATE spots SET plate = ? WHERE id = ?", plate, id);
}
Figure: Two transactions booking the last seat: read-then-write versus a conditional UPDATE
- Read, then write: both transactions read seats_left = 1 and both book. Two bookings for one seat.
- Conditional UPDATE: T1's UPDATE … WHERE seats_left > 0 changes 1 row; T2 waits for the row lock, re-checks, changes 0 rows and reports sold out.
Move the check into the WHERE clause and read the row count:
public boolean park(long spotId, String plate) {
int changed = db.update(
"UPDATE spots SET plate = ? WHERE id = ? AND plate IS NULL", plate, spotId);
return changed == 1; // 0: someone else got there first
}
Postgres locks the row while it updates it, so exactly one of the racing threads changes it. The same trick works for counters: UPDATE trains SET seats_left = seats_left - 1 WHERE id = ? AND seats_left > 0.
✅ Success: A conditional
UPDATEplus its row count is the simplest correct answer to most "two users want the last one" problems.
4. Transactions and SELECT ... FOR UPDATE
When the decision needs several statements, for example "find any free spot of this kind, then take it", run them in a transaction and lock the row you choose:
public Long parkAnywhere(String kind, String plate) {
return db.transaction(tx -> {
Optional<Map<String, Object>> free = tx.queryOne("""
SELECT id FROM spots
WHERE kind = ? AND plate IS NULL
ORDER BY floor, id
LIMIT 1
FOR UPDATE SKIP LOCKED""", kind);
if (free.isEmpty()) return null; // lot full for this kind
long id = ((Number) free.get().get("id")).longValue();
tx.execute("UPDATE spots SET plate = ? WHERE id = ?", plate, id);
return id;
});
}
- Use
tx, notdb, inside the callback. Only statements ontxare part of the transaction. FOR UPDATEholds the row until the transaction ends, so no one else can take it in between.SKIP LOCKEDlets a concurrent caller take the next free spot instead of waiting for this one.- Throwing inside the callback rolls everything back.
⚠️ Trap: Postgres' default isolation, Read Committed, does not stop the read-then-write race from section 3 by itself. Either lock the row (
FOR UPDATE) or put the condition in theUPDATE.
5. Idempotent writes
Many problems ask that repeating a request with the same key has no extra effect: payments, bookings, webhooks. Let a unique constraint decide:
db.execute("""
CREATE TABLE IF NOT EXISTS payments (
idempotency_key TEXT PRIMARY KEY,
amount_cents BIGINT NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT now()
)""");
public boolean charge(String key, long amountCents) {
int inserted = db.update(
"INSERT INTO payments (idempotency_key, amount_cents) VALUES (?, ?) ON CONFLICT DO NOTHING",
key, amountCents);
return inserted == 1; // 0: a duplicate, already processed
}
No Java lock and no "check if it exists first" query: the constraint makes the decision atomically.
6. Ids and counts
long id = db.insertReturningId(
"INSERT INTO rides (rider, status) VALUES (?, 'REQUESTED') RETURNING id", riderId)
.orElseThrow();
long free = db.queryScalar(
"SELECT COUNT(*) FROM spots WHERE plate IS NULL", Long.class)
.orElse(0L);
insertReturningId needs the RETURNING id clause. COUNT(*) is a BIGINT, so ask for Long.class.
7. Performance without cleverness
- Index what you filter on. The partial index
WHERE plate IS NULLabove makes finding a free spot cheap at any size. - One round trip beats five. A conditional
UPDATEis one call; read-decide-write is three. - Batch bulk writes with
batchUpdatewhen you insert many rows at once. - Keep transactions short. Don't do slow work while holding row locks.
- Don't wrap SQL in a Java lock. It serializes your threads for no benefit; Postgres already coordinates them.
Further reading
- Transaction isolation (PostgreSQL docs)
SELECT … FOR UPDATEandSKIP LOCKED: the locking clause (PostgreSQL docs)INSERT … ON CONFLICT(PostgreSQL docs)- Constraints (PostgreSQL docs)
- Explicit locking (PostgreSQL docs)
Takeaways
- Encode the brief's rules as constraints, and the database enforces them under any concurrency.
- Prefer one conditional statement plus its row count over read, decide, write.
- Use
transactionwithFOR UPDATEwhen a decision spans several statements, and only usetxinside it.
Try it yourself: Build a Parking Lot System, Build a Cab Booking System and Build a URL Shortener all run against a real Postgres.