Difficulty: Intermediate
What are the ACID properties of a database transaction, and how does a database actually guarantee each one?
ACID is the set of guarantees a database gives for a transaction: Atomicity (all of its changes happen or none do), Consistency (it moves the database from one valid state to another, respecting every constraint), Isolation (concurrent transactions do not see each other's half-done work), and Durability (once committed, the change survives a crash). Together they let you write a money transfer as a few SQL statements and trust that it behaves like a single indivisible step.
Moving ₹500 from Asha's Paytm wallet to Ravi's is two updates: debit Asha, credit Ravi. Without ACID, a crash between them destroys ₹500, two concurrent transfers can both read the old balance and overspend, and a "successful" transfer could vanish after a power cut. Each letter closes one of these holes.
ROLLBACK or after a crash, uncommitted changes are undone. Postgres does this with MVCC row versions (an aborted transaction's rows are simply invisible), InnoDB with undo logs.PRIMARY KEY, FOREIGN KEY, UNIQUE, CHECK (balance >= 0), NOT NULL. If any statement would break one, the transaction fails. Note that "C" is partly the application's job: the database cannot know that money must be conserved unless you encode it.fsync before the commit is acknowledged. Data pages can be written later; after a crash the database replays the WAL. Settings like Postgres synchronous_commit = off or MySQL innodb_flush_log_at_trx_commit = 2 trade a small durability window for speed.fsync can break it. Durability across machines needs synchronous replication.All major relational databases (PostgreSQL, MySQL InnoDB, SQL Server, Oracle) are ACID. MongoDB has supported multi-document ACID transactions since 4.0 (replica sets) and 4.2 (sharded clusters), and distributed SQL systems like CockroachDB, YugabyteDB, Spanner and TiDB provide ACID across nodes. Payment systems at companies like Razorpay rely on these guarantees for ledgers, often combined with idempotency keys so retries do not double-charge.
CREATE TABLE wallets (
user_id BIGINT PRIMARY KEY,
balance_paise BIGINT NOT NULL CHECK (balance_paise >= 0) -- Consistency
);
BEGIN; -- Atomicity starts here
UPDATE wallets SET balance_paise = balance_paise - 50000
WHERE user_id = 1; -- fails CHECK if balance too low
UPDATE wallets SET balance_paise = balance_paise + 50000
WHERE user_id = 2;
COMMIT; -- Durability: WAL flushed before OK
-- If either UPDATE fails, the whole transaction is rolled back
-- and neither wallet changes.
Both updates commit together or not at all. The CHECK constraint makes the database reject an overdraft, and the row locks taken by UPDATE isolate concurrent transfers on the same wallet.
Atomicity, Consistency, Isolation, Durability, Write-Ahead Log, Transactions