{"canonical_url":"https://engineer.company/glossary/transaction/","content_markdown":"# Transaction\n\n## What it is\n\nA transaction is a group of changes that a database applies as one unit: either\nall of them take effect, or none of them does. People write database transaction\nwhen they need to keep it apart from a payment, which shares the word. The\nPostgreSQL tutorial describes a transaction as something that \"bundles multiple\nsteps into a single, all-or-nothing operation\", and nothing in between is\nvisible to anyone else.\n\nIn PostgreSQL a transaction opens with `BEGIN` and ends with `COMMIT`, which\nmakes its changes permanent and visible to other sessions, or with `ROLLBACK`,\nwhich throws them away. A statement sent on its own still runs inside one:\nPostgreSQL wraps it in an implicit `BEGIN` and, if it succeeds, an implicit\n`COMMIT`. A long transaction can set a `SAVEPOINT` and later return to it with\n`ROLLBACK TO`, discarding the work done since while keeping everything before\nit.\n\nThe guarantees a transaction gives are summed up as ACID. Atomicity means a\ntransaction completes as one unit or not at all, and no half-finished result\nsurvives a crash. Consistency means the constraints declared on the data hold\nonce it commits, and a transaction that would leave one broken is rolled back\ninstead. Isolation means its changes stay invisible to concurrent transactions\nuntil it commits. Durability means a committed change survives a crash of the\nserver.\n\nIsolation comes in levels, and the SQL standard defines four: Read Uncommitted,\nRead Committed, Repeatable Read and Serializable. PostgreSQL starts every\ntransaction at Read Committed unless told otherwise, and its Read Uncommitted\nbehaves exactly like Read Committed. At Read Committed each statement sees the\ndata committed before that statement began, so two queries in the same\ntransaction may see different numbers. At Repeatable Read the whole transaction\nworks from one snapshot, taken when its first statement other than a\ntransaction-control statement runs. Serializable goes further and makes\nconcurrent transactions produce the same result as if they had run one after\nanother.\n\n## Why it matters\n\nAlmost every action worth recording touches more than one row. An order is a row\nin one table, a decrement in another and an entry in a ledger. Without a\ntransaction, a crash, a timeout or a failed constraint between the second and\nthe third statement leaves an order whose stock was never taken, or stock taken\nfor an order that does not exist. Someone then finds it in a report and repairs\nit by hand. With a transaction that half state never exists for anyone to see,\nand the database, not the application, is what guarantees it.\n\nThe second reason is concurrency. Two requests that arrive together run side by\nside, and the isolation level decides what each one sees while locks decide\nwhich one waits. This is where teams are most often surprised: wrapping code in\n`BEGIN` and `COMMIT` does not on its own stop two requests from reading the same\nbalance and both spending it. At Read Committed each statement reads what was\ncommitted when it started, so a check made in one statement and a write made in\nthe next can be separated by another session's commit. The check has to lock the\nrow first or become part of the write.\n\nTransactions also have a cost, and it is paid in time. Row locks taken by\n`UPDATE`, `DELETE` and `SELECT ... FOR UPDATE` normally last until the transaction\nends; rolling back to a savepoint releases locks acquired after that savepoint.\nA session that wants a conflicting lock must wait unless a timeout, cancellation\nor deadlock resolution stops it. An open transaction also stops `VACUUM` from\nremoving old row versions it might still need to see, so a transaction left open\nfor hours lets tables bloat. The design question is never only whether to use a\ntransaction. It is where its edges go and how little happens between them.\n\nFinally, an ordinary local database transaction does not by itself include\nexternal effects. A call to a payment provider, an email or a message published\nto a separate queue is not undone by rolling back the database. Coordinating\nother systems needs an additional design; a surrounding `BEGIN` is not enough.\nDeciding what sits inside the boundary, and how the outside world hears about a\ncommit, is most of the work of designing one.\n\n## What it looks like in practice\n\nA member of a loyalty scheme spends 250 points on a cinema voucher. Three things\nhave to happen together: the wallet loses the points, the ledger records why,\nand the redemption is created. Written as one transaction it looks like this:\n\n```sql\nBEGIN;\n\nUPDATE wallet\nSET    points = points - 250\nWHERE  member_id = 42\nAND    points \u003e= 250\nRETURNING points;\n-- no row back: not enough points, so ROLLBACK and stop here\n\nINSERT INTO points_entry (member_id, delta, reason)\nVALUES (42, -250, 'redeemed: cinema voucher');\n\nINSERT INTO redemption (member_id, reward_id)\nVALUES (42, 7);\n\nCOMMIT;\n```\n\nThe `UPDATE` takes a row lock on member 42's wallet. Until `COMMIT`, any other\nsession that reads the wallet still sees the old balance, because row locks do\nnot block readers and uncommitted changes are invisible. A second redemption for\nthe same member, sent from another tab a moment later, reaches its own `UPDATE`\nand waits. When the first transaction commits, PostgreSQL at Read Committed\nevaluates the second one's `WHERE` clause again against the row as it now\nstands. If only 100 points are left, the condition fails, no row comes back, and\nthe second request rolls back without having written anything. If instead the\nlast `INSERT` fails, say because reward 7 has been withdrawn and a foreign key\nrefuses it, the client rolls back and the points are exactly where they were.\n\nThis is the shape of the\n[loyalty wallet with leagues and badges](/portfolio/built-a-loyalty-wallet-leagues-and-badges/).\nEvery change to a wallet there takes a row lock on it before reading it, so a\nsecond request waits for the first to finish instead of racing it, and because\nthe wallet lives in the same database as everything else, a balance and what it\npaid for are committed together or not at all. The page is open about the price:\nrow locking is the slower answer, and members wait their turn rather than spend\nthe same points twice.\n\nThe note on\n[selling the last ticket exactly once](/notes/selling-limited-stock-without-overselling/)\nputs the same tool under a flash sale. Its fix makes the stock check and the\ndecrement one conditional `UPDATE`, because a lock held while the application\nthinks between a `SELECT` and an `UPDATE` makes the next buyer wait for every\nmillisecond of it. First on its list for the rest of the work is keeping\neverything external out of the transaction: a payment call, an HTTP request or a\npublished message belongs before it or after it.\n\n## Where it goes wrong\n\n**A session sits idle in a transaction and everything behind it waits.** An\napplication opens a transaction, updates a row, and then waits for a slow API,\nfor a user's next click, or for a worker that crashed without ever sending\n`COMMIT`. Its locks stay, and with timeouts disabled PostgreSQL makes a session\nthat wants a conflicting lock wait indefinitely unless it detects a deadlock\nor the wait is cancelled. The documentation calls holding a transaction open\nwhile waiting for user input a bad idea. `pg_stat_activity` shows these sessions\nwith the state `idle in transaction`, and `xact_start` says when the transaction\nbegan:\n\n```sql\nSELECT pid, now() - xact_start AS open_for, state, query\nFROM pg_stat_activity\nWHERE state LIKE 'idle in transaction%'\nORDER BY xact_start;\n```\n\nMove the slow work out of the transaction, and give the server a limit so a\nforgotten one cannot hold locks for hours. `idle_in_transaction_session_timeout`\nends any session left idle inside an open transaction for longer than its value.\nIts default is 0, which disables it, so it has to be set, for example for the\napplication's role with\n`ALTER ROLE app SET idle_in_transaction_session_timeout = '30s';`.\n\n**Two requests both spend the same balance.** The code reads a value in one\nstatement, decides in the application, and writes the result in another. Two\nsessions read the same number, both pass the check, and both write, so one\nchange silently overwrites the other. A surrounding `BEGIN` does not prevent it\nat Read Committed. Make the check part of the write with a condition in the\n`UPDATE`, as in the example above, or lock the row before reading it with\n`SELECT ... FOR UPDATE`, which makes the second session wait for the first.\n\n**Errors appear under load at Repeatable Read or Serializable.** At these levels\nPostgreSQL refuses a transaction that would break the level's promise and\nreports a serialization failure, SQLSTATE `40001`, with messages such as\n`could not serialize access due to concurrent update`. This is the design\nworking, not a bug, and the documentation states that applications using these\nlevels must be prepared to retry. Catch `40001` and run the whole transaction\nagain from `BEGIN`, including its reads, since the decision it made was based on\ndata that has since changed. Retrying only the statement that failed repeats the\nmistake.\n\n**Two transactions deadlock.** One locks order 1 and then order 2, another locks\norder 2 and then order 1, and each waits for the other. PostgreSQL detects the\ncycle and aborts one of the transactions so the other can finish, and which one\nit picks is hard to predict. The documented defence is to have every code path\nacquire locks in the same order, for example by updating rows in ascending order\nof their primary key, and to retry a transaction that was aborted for a\ndeadlock.\n\n**An email goes out for an order that was rolled back.** The application sends a\nconfirmation or publishes an event from inside the transaction, and then a later\nstatement fails. The rollback removes the order, but nothing can unsend the\nemail. Record the message in an outbox table in the same transaction as the\nchange it describes, and let a separate process send it once the commit has\nhappened. The message then exists exactly when the order does.\n\n## Further reading\n\n- [Transactions](https://www.postgresql.org/docs/current/tutorial-transactions.html)\n  — the PostgreSQL tutorial chapter: all-or-nothing behaviour, implicit\n  transactions and savepoints, shown on a bank transfer.\n- [Transaction Isolation](https://www.postgresql.org/docs/current/transaction-iso.html)\n  — the four standard levels, what each one sees in PostgreSQL, and the\n  serialization failures that call for a retry.\n- [Explicit Locking](https://www.postgresql.org/docs/current/explicit-locking.html)\n  — row and table locks, how long they are held, and how deadlocks are detected\n  and avoided.\n- [Client Connection Defaults](https://www.postgresql.org/docs/current/runtime-config-client.html)\n  — `default_transaction_isolation`, `idle_in_transaction_session_timeout`,\n  `lock_timeout` and the other limits on a session.\n- [Routine Vacuuming](https://www.postgresql.org/docs/current/routine-vacuuming.html)\n  — why old row versions stay while any transaction might still see them, and\n  what long open transactions do to cleanup.\n\n\u003chttps://engineer.company/glossary/transaction/\u003e\n","date_modified":"2026-11-09T21:50:25Z","description":"How a database transaction makes several changes count as one: commit and rollback, isolation levels, row locks, and five ways transactions go wrong.","formats":{"gemtext":"https://engineer.company/glossary/transaction/index.gmi","gopher":"https://engineer.company/glossary/transaction/gophermap","html":"https://engineer.company/glossary/transaction/","json":"https://engineer.company/glossary/transaction/index.json","markdown":"https://engineer.company/glossary/transaction/index.md","pdf":"https://engineer.company/glossary/transaction/index.pdf"},"kind":"page","language":"en","title":"What is a transaction?","url":"https://engineer.company/glossary/transaction/","version":1}