SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
  • Common Database Types
  • SQL vs NoSQL
  • ACID Transactions
  • B-Trees and B+ Trees
  • LSM Trees
  • Transaction Isolation Levels
  • Locking and MVCC
  • Normalization
  • OLTP vs OLAP
  • BASE and PACELC
  • Write-Ahead Log (WAL)
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Data and Storage/Database Basics

ACID Transactions

All-or-nothing changes that keep your data correct, even when things crash.

⏱ 15 min readIntermediateMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

A transaction is a group of database steps that must be treated as one single action. ACID is the list of four promises that make a transaction safe.

  • Atomicity: all of it happens, or none of it.
  • Consistency: your rules (like “total money stays the same”) still hold afterwards.
  • Isolation: two users at the same time do not trip over each other.
  • Durability: once it says “done”, the data survives a crash.

02Concept: What is it?

Moving 100 rupees from account A to account B takes two steps: take 100 from A, add 100 to B. If the server crashes between them, the money has vanished. A transaction wraps both steps so that the database treats them as one unit.

A transfer as one transaction
BEGIN;
  UPDATE accounts SET balance = balance - 100 WHERE id = 'A';
  UPDATE accounts SET balance = balance + 100 WHERE id = 'B';
COMMIT;   -- both changes become real at this moment
-- ROLLBACK;  -- or undo everything since BEGIN
The four promises
⚛️Atomicityall or nothing
📏Consistencyrules stay true
🚧Isolationno interference
💾Durabilitysurvives a crash
Think of ACID as four different kinds of safety.
🧠Honest note about the C
Atomicity, isolation and durability are things the database provides. Consistency is shared: the database enforces the rules you declare (keys, uniqueness, checks), but you decide what the rules are. Some people call the C “glue to make the acronym work”.

03Real-Life Example

🍵Buying a Train Ticket
You pay at the counter. The clerk must do two things: take your money and give you the ticket. It would be terrible if the lights went out after taking your money but before printing the ticket. So the clerk writes the whole deal in a notebook first. If the power fails, the notebook tells them whether to finish the sale or cancel it. And two clerks must never sell the same last seat to two people.
Ticket counter
ACID
Take money and give ticket, or do neither
Atomicity
Seats sold never exceed seats that exist
Consistency
Two clerks do not sell the same seat
Isolation
The notebook that survives a power cut
Durability (the write-ahead log)
Cancelling a half-finished sale
Rollback
Stamping the sale as final
Commit
Happy path and failure path
All steps work
BEGIN
→↓
Step 1
→↓
Step 2
→↓
✅COMMIT
A step fails
BEGIN
→↓
Step 1
→↓
💥Step 2 fails
→↓
↩️ROLLBACK

04Why Do We Need It?

💰Money must add up
Without transactions, a crash in the middle can lose or double money.
📦Stock and bookings
Two buyers must not get the last seat or the last item.
🧹Simple code
You do not need to write clean-up code for every possible failure point.
🔁Safe retries
After a failure you can simply try the whole transaction again.
👥Many users at once
Isolation lets thousands of users work together without corrupting data.
🗣️Interview staple
ACID, isolation levels and when to give them up come up constantly.
Transactions let you think about one clean step at a time, instead of every possible failure in between.

05Where Do We Use It?

🏦Banking
Transfers, fees and interest.
🛒Orders
Create order, reserve stock and take payment together.
✈️Bookings
Seats, rooms and slots that must not be double sold.
🏷️Inventory
Counts that must stay exact.
📒Ledgers and accounting
Every debit has a matching credit.
🗄️Most relational databases
PostgreSQL, MySQL (InnoDB) and SQL Server all offer ACID transactions.

06Types / Parts / How It Works

The four properties in detail

PropertyPromiseHow it is usually done
AtomicityAll steps happen, or none doAn undo log: old values are kept so a half-finished transaction can be rolled back
ConsistencyData moves from one valid state to anotherConstraints (primary key, unique, foreign key, check) plus your application logic
IsolationConcurrent transactions behave as if they ran one by one (to some chosen degree)Locks, or MVCC (keeping several versions of a row so readers do not block writers)
DurabilityCommitted data survives power loss and crashesA write-ahead log (WAL): the change is written to a log file on disk and flushed before COMMIT is confirmed

Isolation levels

Perfect isolation is slow, so databases let you choose a level. Higher levels stop more strange effects but cost speed. The names below come from the SQL standard. Real products differ in details, so read your database's docs.

LevelStopsCan still show
Read uncommittedAlmost nothingDirty reads: you see data another user has not committed (and may roll back)
Read committedDirty readsNon-repeatable reads: the same row read twice gives two answers
Repeatable readDirty and non-repeatable reads (often by using a snapshot)Phantoms (new rows appear) in some databases, and write skew in snapshot-based ones
SerializableAll of the aboveNothing, but it is the slowest, and transactions may wait or be told to retry
ACID
Safety first
  • Strong guarantees on every commit
  • Simple to reason about
  • Common in relational databases
  • Harder to spread over many machines
BASE
Availability first
  • Basically Available, Soft state, Eventually consistent
  • Copies may disagree briefly
  • Common in large scale-out stores
  • You handle conflicts in your app
How the write-ahead log gives atomicity and durability
📝Change request
→↓1
📜Write to logflush to disk
→↓2
✅Tell user: committed
⇢⇣3 later
🗄️Update data pages
The key step: the log is safe on disk first
The log is written first and flushed. The real data pages can be written later. After a crash, the database reads the log and fixes things.
VisualizerCrash a bank transfer, then run two users at onceIn the first tab, drag the crash slider and turn the transaction off. In the second tab, change the isolation level and see which strange effect appears.
What do you want to explore?
Wrapped in a transaction?
Log flushed to disk at COMMIT?
Transfer 100 from account A to account B
1. BEGIN
2. A = A - 100 💥
3. B = B + 100
4. COMMIT
Account A
500
was 500
Account B
500
was 500
Total money
1000
still 1,000
State after restart
rolled back
The database restarted, saw an unfinished transaction in its log, and rolled it back. Atomicity: all or nothing.

A simplified model with a fixed timeline and no random numbers. Real databases differ in details (for example, PostgreSQL treats read uncommitted like read committed, and some engines make serializable transactions wait or retry). Consistency, the C in ACID, means your own rules (like total money stays 1,000) hold after each transaction.

07How to Use It / Steps / Implementation

Using transactions well

  1. 1
    Group steps that must succeed together
    Debit and credit, create order and reduce stock. If one failing would leave a mess, they belong in one transaction.
  2. 2
    Keep transactions short
    A long transaction holds locks or old row versions for a long time and slows everyone else. Never wait for a user or a slow network call inside one.
  3. 3
    Pick the isolation level you need
    Many databases default to read committed (PostgreSQL) or repeatable read (MySQL InnoDB). Use serializable only for the few operations that need it.
  4. 4
    Handle failures and retries
    A transaction can fail because of a deadlock or a serialization error. Retry the whole transaction, and make it safe to repeat.
  5. 5
    Avoid lost updates
    Use atomic updates (SET stock = stock - 1), row locks (SELECT ... FOR UPDATE) or version numbers (optimistic locking).
  6. 6
    Keep a consistent lock order
    If every transaction touches accounts in the same order, deadlocks become rare.
  7. 7
    Across several services, use a different tool
    A single database transaction cannot cover many services. See saga or two-phase commit ideas instead.
⚠️Lost update
Two users read stock = 5 and both write 4. One sale is lost. The fix is to let the database do the maths atomically (stock = stock - 1), or to lock the row, or to check a version number.

08Key Terms to Know

TermMeaning in easy words
TransactionA group of operations treated as one unit
CommitMake all the changes in the transaction permanent
RollbackUndo all the changes since BEGIN
Write-ahead log (WAL)A log written and flushed before data pages, used for recovery
LockA flag that stops others from touching a row while you use it
MVCCMulti-version concurrency control: keep several versions of a row so readers and writers do not block each other
Dirty readReading data another transaction has not committed
Phantom readA repeated query finds new rows that another transaction added
DeadlockTwo transactions each wait for the other, so neither can move. The database kills one
Two-phase commit (2PC)A protocol to commit one transaction across several databases

09Pros, Cons and Trade-offs

✅ Pros
  • Data stays correct even with crashes
  • Simpler application code
  • Safe concurrent users
  • Clear model that is well understood
⚠️ Cons
  • Slower than doing no safety work
  • Locks and waiting can reduce throughput
  • Hard to keep across many machines or services
  • Long transactions cause trouble
  • Higher isolation levels can force retries

Trade-offs

ChoiceWe gainWe lose
Higher isolationFewer odd effectsMore waiting and retries
Lower isolationSpeed and concurrencyRisk of anomalies you must handle
Flush log on every commitNo lost commitsEach commit waits for the disk
Group commits or async flushHigher throughputA crash may lose the last few commits
Distributed transactionAtomic over many nodesSlower, blocked if the coordinator fails

10Common Problems and Mistakes

Common mistakes

  1. No transaction around a multi-step change. A crash leaves half the work done.
  2. Assuming the default isolation is serializable. It rarely is, so races such as lost updates and write skew can still happen.
  3. Long transactions. Waiting on an API call inside a transaction holds locks and blocks others.
  4. Read, think, write. Reading a value, computing in the app, then writing it back is a classic lost update. Use an atomic update or a lock.
  5. Ignoring deadlocks. They will happen under load. Catch them and retry.
  6. Expecting ACID across services. Calling two services and two databases is not one transaction.

Things to watch

🔒Deadlocks
Order your updates the same way everywhere, and retry when one occurs.
🧟Write skew
Two transactions read the same data, then write different rows, and together break a rule (for example two doctors both go off call).
🐢Lock waits
A hot row can make every writer queue up.
💽Fsync cost
Durability needs a disk flush. Disk speed limits commit rate.

11Real-World Examples

🐘PostgreSQL
ACID with MVCC. Default isolation is read committed, and serializable is available.
🐬MySQL InnoDB
ACID with a redo log and an undo log. Default isolation is repeatable read.
🍃MongoDB
Has supported multi-document ACID transactions since version 4.0 (general idea).
⚡DynamoDB
Offers transactional reads and writes across a limited number of items.
🌍Spanner and CockroachDB
ACID transactions across machines and regions, at the price of extra latency.
🏦Payment systems
Core ledgers rely on ACID so every debit has a credit.
📝Note
Defaults and features differ by product and version. Always confirm in the official docs.
Mini case: transfer between two services
💳Debit servicelocal tx
→↓event
🏦Credit servicelocal tx
←if it fails: refund
↩️Compensate
One database transaction cannot cover two services. Teams use a saga: a chain of local transactions, with a compensating step if one fails.

12Related Topics to Read Next

SQL vs NoSQL→

Where ACID is strong, and where it is relaxed.

Relational Databases→

The home of ACID transactions.

CAP Theorem→

Why distributed transactions are hard.

Idempotency→

Make retried transactions safe.

Replication→

How committed data reaches other copies.

Delivery Semantics→

Exactly-once and at-least-once for messages.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔Transaction: a group of steps treated as one. BEGIN, then COMMIT or ROLLBACK.
  • ✔Atomicity: all or nothing. Done by an undo log.
  • ✔Consistency: your rules still hold. Constraints plus your logic.
  • ✔Isolation: no interference. Locks or MVCC. Choose a level.
  • ✔Durability: committed means kept. Write-ahead log, flushed to disk.
  • ✔Levels: read uncommitted, read committed, repeatable read, serializable.
  • ✔Watch for: lost updates, write skew, deadlocks, long transactions.
  • ✔One line: “Wrap steps that must succeed together in one transaction, keep it short, and choose the lowest isolation that is still safe.”
← Previous
SQL vs NoSQL
Next →
B-Trees and B+ Trees