0
Challenge · 29Correct & Fast

Transactions & ACID

Dataused in ~80% of apps

Recording one DevLog like is two writes: a row in `likes`, and a bump to `posts.like_count`. Do them as two separate calls and there is a window where the server crashes, the network drops, or your app throws between them — and the count is now permanently wrong, forever, with no error anywhere to tell you. A transaction is the only thing standing between "probably fine" and "provably correct."

Core idea. A transaction groups one or more statements into a single, indivisible unit: either every statement in it takes effect, or none do. ACID is the four-letter guarantee Postgres makes about that unit — Atomicity (all or nothing), Consistency (every constraint still holds when it's done), Isolation (concurrent transactions don't see each other's half-finished work), and Durability (once it says COMMIT, that data survives a crash a millisecond later).
Playground, this isn't a screenshot
Ending instep 1 / 4
likes (post_id=1)
1 row
posts.like_count (id=1)
1

Open a transaction. Nothing is written yet - this just marks "what follows is one unit."

The rule: everything between BEGIN and COMMIT is one indivisible unit. Either every statement in it takes effect, or - on ROLLBACK, a crash, or a dropped connection - none of them do. There is no in-between state where the like exists but the counter does not.
↑ play a little first, then dig in