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

MethodUse 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: BIGINT as Long, INT as Integer. Read numbers through Number, 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:

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

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 UPDATE plus 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;
    });
}

⚠️ 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 the UPDATE.

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

Further reading

Takeaways

Try it yourself: Build a Parking Lot System, Build a Cab Booking System and Build a URL Shortener all run against a real Postgres.