AI Hints
Home›System Design Tutorial›Correct and Copied
System Design · Lesson 40 of 120

Transactions and ACID

All or nothing.

⏱ 2 min read▶ Video at 46:54🎓 Free
Watch this lesson in the System Design courseWatch on YouTube ↗Full System Design course

When a customer orders a mug, two things must happen. Stock goes down by one, and an order is created. If only one of them happens, the data is wrong. A transaction makes them happen together, or not at all.

Transactions and ACID
From the video: Transactions and ACID
  • Stock down, order created
  • Both or neither
  • A transaction

ACID

Good transactions have four properties, called ACID. Atomic means all or nothing. Consistent means the rules always hold, like stock never going below zero. Isolated means transactions running at the same time don't see each other's half finished work. And durable means once it's saved, it survives a crash.

LetterMeaning
Atomicall or nothing
Consistentrules always hold
Isolatedno half-finished views
Durablesurvives a crash

A transaction rolls back

Python comes with SQ Lite, a small relational database. We start with one mug in stock. The transaction lowers the stock, then tries to create an order, but the order fails. Run it. Because both steps were in one transaction, the stock change is undone too. Stock is still one.

txn.pypython
import sqlite3

db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE stock (item TEXT, qty INT)")
db.execute("CREATE TABLE orders (item TEXT NOT NULL)")
db.execute("INSERT INTO stock VALUES ('mug', 1)")
db.commit()

try:
    with db:  # one transaction
        db.execute("UPDATE stock SET qty = qty - 1 WHERE item = 'mug'")
        db.execute("INSERT INTO orders VALUES (NULL)")  # fails
except sqlite3.IntegrityError as e:
    print("failed:", e)

print("stock:", db.execute("SELECT qty FROM stock").fetchone()[0])
Output
failed: NOT NULL constraint failed: orders.item
stock: 1

Summary

Transactions make several changes happen together or not at all, with the ACID guarantees. Next, keeping copies of your data on other machines. Replication.

Key takeaways
  • Atomic
  • Consistent, Isolated
  • Durable
Next up: Replication — copies of your data