---
title: "Database Transactions and ACID Explained"
url: https://www.khanwaseem.com/blog/database/database-transactions-and-acid
author: "khan Waseem"
published: 2026-12-06
updated: 2026-12-06
topics: ["Database", "Blog"]
description: "Learn what database transactions are, what ACID really means, how isolation levels work and how to stop race conditions, with tested PostgreSQL and Node.js examples."
---

# Database Transactions and ACID Explained

Table of Contents

[Toggle](#)

- [Introduction:](#introduction)
- [Your First Transaction:](#your-first-transaction)[Undoing with ROLLBACK:](#undoing-with-rollback)

- [What Does ACID Mean?](#what-does-acid-mean)[1. Atomicity: all or nothing](#1-atomicity-all-or-nothing)
- [2. Consistency: rules are never broken](#2-consistency-rules-are-never-broken)
- [3. Isolation: transactions don’t step on each other](#3-isolation-transactions-dont-step-on-each-other)
- [4. Durability: committed means saved](#4-durability-committed-means-saved)

- [Savepoints: Undo Part of a Transaction](#savepoints-undo-part-of-a-transaction)
- [Isolation: The Problems It Prevents](#isolation-the-problems-it-prevents)
- [Isolation Levels:](#isolation-levels)
- [A Real Race Condition: The Last Phone in Stock](#a-real-race-condition-the-last-phone-in-stock)[The buggy version: read, then write](#the-buggy-version-read-then-write)
- [Fix 1: Lock the row with SELECT … FOR UPDATE](#fix-1-lock-the-row-with-select-%e2%80%a6-for-update)
- [Fix 2: Do the check inside one atomic UPDATE](#fix-2-do-the-check-inside-one-atomic-update)
- [Fix 3: Use the SERIALIZABLE isolation level](#fix-3-use-the-serializable-isolation-level)

- [Using Transactions Correctly in Node.js:](#using-transactions-correctly-in-nodejs)
- [Common Mistakes to Avoid:](#common-mistakes-to-avoid)[1. Believing a transaction prevents all race conditions:](#1-believing-a-transaction-prevents-all-race-conditions)
- [2. Long transactions:](#2-long-transactions)
- [3. Forgetting to retry:](#3-forgetting-to-retry)
- [4. Locking rows in different orders:](#4-locking-rows-in-different-orders)
- [5. Missing constraints:](#5-missing-constraints)

- [Conclusion:](#conclusion)

## Introduction:

In the last database lesson, [SQL Joins Explained with Examples](https://blog.khanwaseem.com/sql-joins-explained/), we read data from several tables at once. Today we look at the other side: **changing** data safely.

Think of a bank transfer. Aisha sends ₹200 to Rahul. In SQL that is two steps: take ₹200 out of Aisha’s account, and add ₹200 to Rahul’s account. What if the server crashes right after the first step? Aisha has lost ₹200 and Rahul never got it. The money has vanished.

A **transaction** prevents this. It groups several statements into **one unit of work**: either **all** of them happen, or **none** of them do. In this lesson you will learn how transactions work, what the famous **ACID** properties mean, how isolation levels protect you from other users, and how to fix a real race condition. Every example was run on PostgreSQL 16, and the outputs shown are real.

## Your First Transaction:

Let’s create a small accounts table:

```php
CREATE TABLE accounts (
  id      INT PRIMARY KEY,
  owner   TEXT NOT NULL,
  balance NUMERIC(12,2) NOT NULL CHECK (balance >= 0)
);

INSERT INTO accounts VALUES (1, 'Aisha', 1000), (2, 'Rahul', 500);Code language: PHP (php)
```

A transaction starts with `BEGIN` and ends with `COMMIT` (save everything) or `ROLLBACK` (undo everything):

```
BEGIN;
UPDATE accounts SET balance = balance - 200 WHERE id = 1;
UPDATE accounts SET balance = balance + 200 WHERE id = 2;
COMMIT;

SELECT * FROM accounts ORDER BY id;
--  id | owner | balance
-- ----+-------+---------
--   1 | Aisha |  800.00
--   2 | Rahul |  700.00
```

Both changes were saved together.

### Undoing with ROLLBACK:

```
BEGIN;
UPDATE accounts SET balance = balance - 300 WHERE id = 1;
SELECT * FROM accounts ORDER BY id;
--   1 | Aisha |  500.00    <- inside the transaction, we see the change
--   2 | Rahul |  700.00
ROLLBACK;

SELECT * FROM accounts ORDER BY id;
--   1 | Aisha |  800.00    <- back to the old value
--   2 | Rahul |  700.00
```

Nothing from the rolled-back transaction remains.

By the way, if you run a single statement without `BEGIN`, the database still wraps it in its own tiny transaction and commits it immediately. This is called **autocommit**.

## What Does ACID Mean?

ACID is the set of four promises a transaction gives you.

### 1. Atomicity: all or nothing

The transaction cannot half-happen. If any step fails, or the server crashes before `COMMIT`, the database undoes everything. Our transfer either moves the money completely or not at all.

### 2. Consistency: rules are never broken

A transaction takes the database from one valid state to another valid state. “Valid” means all your rules hold: primary keys, foreign keys, `NOT NULL`, `CHECK` constraints and so on.

Our table has the rule `CHECK (balance >= 0)`. Watch what happens when a transfer would make Aisha’s balance negative:

```javascript
BEGIN;
UPDATE accounts SET balance = balance + 5000 WHERE id = 2;
UPDATE accounts SET balance = balance - 5000 WHERE id = 1;
-- ERROR:  new row for relation "accounts" violates check constraint "accounts_balance_check"
-- DETAIL:  Failing row contains (1, Aisha, -4200.00).
SELECT * FROM accounts;
-- ERROR:  current transaction is aborted, commands ignored until end of transaction block
COMMIT;
-- ROLLBACK

SELECT * FROM accounts ORDER BY id;
--   1 | Aisha |  800.00
--   2 | Rahul |  700.00Code language: JavaScript (javascript)
```

Look at three things here:

- The **first** update (adding ₹5,000 to Rahul) worked on its own. Without a transaction, Rahul would have received free money.

- After the error, PostgreSQL refuses every command until the transaction ends.

- Even though we typed `COMMIT`, PostgreSQL answered `ROLLBACK`. The whole transaction was undone, and both balances are unchanged.

### 3. Isolation: transactions don’t step on each other

Many users run transactions at the same time. Isolation means each transaction behaves as if it were alone, at least to a certain level. This is the trickiest property, and we will spend most of this lesson on it.

### 4. Durability: committed means saved

Once the database says `COMMIT`, the data survives a crash or a power cut. Databases do this with a **write-ahead log (WAL)**: before reporting success, the change is written to a log file on disk. After a crash, the database replays the log.

## Savepoints: Undo Part of a Transaction

Sometimes you want to undo only the last few steps, not the whole transaction. A **savepoint** marks a point you can roll back to:

```
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
SAVEPOINT before_bonus;
UPDATE accounts SET balance = balance + 999 WHERE id = 2;   -- oops
ROLLBACK TO SAVEPOINT before_bonus;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;

SELECT * FROM accounts ORDER BY id;
--   1 | Aisha |  700.00
--   2 | Rahul |  800.00
```

The ₹999 mistake was undone, and the rest of the transaction was saved.

## Isolation: The Problems It Prevents

When transactions run at the same time, a few classic problems can appear:

- **Dirty read:** you read data that another transaction changed but has **not committed yet**. If it rolls back, you read something that never existed.

- **Non-repeatable read:** you read the same row twice in one transaction and get **different values**, because someone committed a change in between.

- **Phantom read:** you run the same query twice and **new rows appear** (or disappear), because someone inserted or deleted rows.

- **Lost update:** two transactions read a value, both change it, and one change silently overwrites the other.

## Isolation Levels:

The SQL standard defines four isolation levels. Higher levels prevent more problems but can be slower or make transactions fail more often:

- **Read Uncommitted:** may allow dirty reads.

- **Read Committed:** you only see committed data. Each statement sees the latest committed data. This is the **default in PostgreSQL**.

- **Repeatable Read:** the whole transaction sees one snapshot of the data, taken at its first query.

- **Serializable:** the result is the same as if the transactions ran one after another.

You choose the level when you start the transaction:

```
BEGIN ISOLATION LEVEL REPEATABLE READ;
```

We tested how PostgreSQL behaves with two connections, `A` and `B`, both looking at a row whose value starts at 1.

**Read Uncommitted.** A changed the value to 99 but did not commit. B, using `READ UNCOMMITTED`, still read **1**. PostgreSQL never allows dirty reads, so it treats Read Uncommitted exactly like Read Committed. (Some other databases do allow dirty reads at this level.)

**Read Committed.** B read the row (1), then A committed a change to 7, then B read the row again in the **same** transaction: it got **1, then 7**. That is a non-repeatable read.

**Repeatable Read.** The same steps, but B started with `REPEATABLE READ`: it got **1, then 1**. B keeps seeing its snapshot until it finishes.

Every database is a little different here. MySQL’s InnoDB, for example, uses Repeatable Read as its default. Always check the documentation of the database you use.

## A Real Race Condition: The Last Phone in Stock

This is where isolation matters in real apps. A shop has **one** phone left. Aisha and Rahul press “Buy” at the same moment. We simulated this in Node.js with the `pg` library, running both purchases at once with `Promise.all`.

```php
CREATE TABLE products (
  id INT PRIMARY KEY,
  name TEXT,
  stock INT NOT NULL CHECK (stock >= 0)
);
INSERT INTO products VALUES (1, 'Phone', 1);Code language: PHP (php)
```

### The buggy version: read, then write

```javascript
async function buy(buyer) {
  const client = await pool.connect();
  try {
    await client.query("BEGIN");
    const { rows } = await client.query("SELECT stock FROM products WHERE id = 1");
    // ... some app logic takes a few milliseconds here ...
    if (rows[0].stock < 1) {
      await client.query("ROLLBACK");
      return `${buyer}: sold out`;
    }
    await client.query("UPDATE products SET stock = $1 WHERE id = 1", [rows[0].stock - 1]);
    await client.query("COMMIT");
    return `${buyer}: bought it`;
  } finally {
    client.release();
  }
}

console.log(await Promise.all([buy("Aisha"), buy("Rahul")]));Code language: JavaScript (javascript)
```

Result:

```css
[ 'Aisha: bought it', 'Rahul: bought it' ]   stock: 0Code language: CSS (css)
```

**Both** customers were told they bought the phone, but only one phone existed. Using a transaction did not help. Both transactions read `stock = 1` before either one wrote, and both wrote `stock = 0`. This is a **lost update**, and the `CHECK` constraint could not catch it because 0 is a valid value.

Here are three ways to fix it.

### Fix 1: Lock the row with SELECT … FOR UPDATE

```javascript
const { rows } = await client.query(
  "SELECT stock FROM products WHERE id = 1 FOR UPDATE"
);
// ...
await client.query("UPDATE products SET stock = stock - 1 WHERE id = 1");Code language: JavaScript (javascript)
```

`FOR UPDATE` locks the row. The second transaction must **wait** at this line until the first one commits, and then it reads the new value:

```css
[ 'Aisha: bought it', 'Rahul: sold out' ]   stock: 0Code language: CSS (css)
```

### Fix 2: Do the check inside one atomic UPDATE

Often you don’t need to read first at all. Put the condition in the `WHERE` clause and check how many rows changed:

```javascript
async function buy(buyer) {
  const { rowCount } = await pool.query(
    "UPDATE products SET stock = stock - 1 WHERE id = 1 AND stock >= 1"
  );
  return rowCount === 1 ? `${buyer}: bought it` : `${buyer}: sold out`;
}Code language: JavaScript (javascript)
```

```css
[ 'Aisha: bought it', 'Rahul: sold out' ]   stock: 0Code language: CSS (css)
```

A single statement is atomic, and the database handles the locking for you. This is the simplest and fastest fix, and it is the one to reach for first.

### Fix 3: Use the SERIALIZABLE isolation level

Keep the original read-then-write code, but start with `BEGIN ISOLATION LEVEL SERIALIZABLE`:

```javascript
[ 'Aisha: bought it',
  'Rahul: error 40001 could not serialize access due to concurrent update' ]   stock: 0Code language: JavaScript (javascript)
```

PostgreSQL noticed that the two transactions could not both succeed as if they ran one after another, and it **aborted** one of them with error code `40001`. Your app must catch this error and **retry** the whole transaction. On the retry, Rahul would see stock 0 and get “sold out”. Serializable is the safest level, but every transaction needs retry logic.

## Using Transactions Correctly in Node.js:

Two rules matter when you use a connection pool:

- **Use one client for the whole transaction.** `pool.query()` may send each statement to a **different** connection, so `BEGIN` and `COMMIT` would end up in different sessions. Always `pool.connect()` first, and run every statement on that client.

- **Always roll back on error and release the client**, or the connection stays stuck inside a broken transaction.

A small helper takes care of both:

```javascript
async function withTransaction(pool, work) {
  const client = await pool.connect();
  try {
    await client.query("BEGIN");
    const result = await work(client);
    await client.query("COMMIT");
    return result;
  } catch (err) {
    await client.query("ROLLBACK");
    throw err;
  } finally {
    client.release();
  }
}

// usage
await withTransaction(pool, async (tx) => {
  await tx.query("UPDATE accounts SET balance = balance - $1 WHERE id = $2", [200, 1]);
  await tx.query("UPDATE accounts SET balance = balance + $1 WHERE id = $2", [200, 2]);
});Code language: JavaScript (javascript)
```

Most ORMs (Prisma, Sequelize, TypeORM, Drizzle) have a built-in version of this, such as `prisma.$transaction(...)`.

## Common Mistakes to Avoid:

### 1. Believing a transaction prevents all race conditions:

As the phone example showed, the default isolation level still allows lost updates. Use atomic updates, `FOR UPDATE`, or Serializable.

### 2. Long transactions:

A transaction that holds locks while it calls an external API or waits for user input blocks everyone else. Do slow work **before** `BEGIN`, and keep transactions short.

### 3. Forgetting to retry:

With Serializable (and sometimes with deadlocks), the database may abort a transaction on purpose. Catch errors `40001` and `40P01` and retry a few times.

### 4. Locking rows in different orders:

If transaction 1 locks account A then B, and transaction 2 locks B then A, they can wait for each other forever: a **deadlock**. PostgreSQL detects it and aborts one of them. Always lock rows in the same order, for example by ID.

### 5. Missing constraints:

Constraints like `CHECK (balance >= 0)` and `UNIQUE` are your last line of defense. Even if app code has a bug, the database refuses bad data and the transaction rolls back.

## Conclusion:

A transaction groups statements into one all-or-nothing unit with `BEGIN`, `COMMIT` and `ROLLBACK`. ACID describes its promises: **Atomicity** (all or nothing), **Consistency** (rules always hold), **Isolation** (concurrent transactions don’t interfere, up to the chosen level) and **Durability** (committed data survives crashes).

The default Read Committed level is enough for most work, but it does not stop lost updates. For “check then change” logic, prefer a single atomic `UPDATE ... WHERE`, use `SELECT ... FOR UPDATE` when you must read first, or use Serializable with retries.

In the next database lesson, we will learn **Database Normalization (1NF, 2NF, 3NF)** and how to design tables that avoid duplicate and inconsistent data in the first place.

### Related posts:

[SQL Joins Explained with Examples](https://blog.khanwaseem.com/sql-joins-explained/)
[SQL Server](https://blog.khanwaseem.com/sql-server/)
[JavaScript – Promises and async/await](https://blog.khanwaseem.com/javascript-promises-and-async-await/)
[MongoDB: Unveiling the Power of NoSQL Database](https://blog.khanwaseem.com/mongodb-unveiling-the-power-of-nosql-database/)

Powered by [YARPP](https://yarpp.com).
