Database Transactions and ACID · Lesson 46 of 112

Database Locks and Deadlocks

What you will learn

  • What a lock is and why it makes others wait
  • What a deadlock is
  • How SQLite reports lock conflicts
  • How to keep waits short

1. Locks

A lock is a note on some data that says "I am using this; wait your turn". Locks are how most databases keep transactions from damaging each other. A reader and a writer, or two writers, may have to wait. The finer the lock (a row rather than a whole database), the less waiting.

SQLite locks the whole database file: many readers at once, but only one writer. The examples use two connections, a and b, to a file with a stock table, and a short timeout so waiting ends quickly:

import sqlite3, os, tempfile

path = os.path.join(tempfile.mkdtemp(), "shop.db")
a = sqlite3.connect(path, isolation_level=None)
b = sqlite3.connect(path, timeout=0.3, isolation_level=None)
a.execute("CREATE TABLE stock (item TEXT PRIMARY KEY, qty INTEGER NOT NULL)")
a.execute("INSERT INTO stock VALUES ('pen', 10)")

2. One writer at a time

BEGIN IMMEDIATE tells SQLite "I will write; take the write lock now". A changes a row and keeps the transaction open. B tries to write too:

a.execute("BEGIN IMMEDIATE")
a.execute("UPDATE stock SET qty = qty - 1")
try:
    b.execute("UPDATE stock SET qty = qty - 1")
except sqlite3.OperationalError as e:
    print("B:", e)
print("B can still read:", b.execute("SELECT qty FROM stock").fetchone())
a.execute("COMMIT")
b.execute("UPDATE stock SET qty = qty - 1")
print("B wrote after A committed:", b.execute("SELECT qty FROM stock").fetchone())
B: database is locked
B can still read: (10,)
B wrote after A committed: (8,)

B waited up to its 0.3 second timeout, then got database is locked. B could still read (and saw the committed 10, not A's unfinished 9). After A committed, B's write succeeded, and both purchases counted (10 - 1 - 1 = 8).

timeout is how long a connection will keep trying before giving up. Python's default is 5 seconds.

Taking the write lock yourself, in SQL. This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). A SQL cell has one connection, so it cannot show a second user waiting, but it shows the commands. BEGIN IMMEDIATE takes the write lock at the start; the relative updates then read and write in one step each, and COMMIT lets the next writer in. The stock table is a small one of its own; Reset data starts again.

CREATE TABLE stock (item TEXT PRIMARY KEY, qty INTEGER NOT NULL);
INSERT INTO stock VALUES ('pen', 10), ('ink', 5);
BEGIN IMMEDIATE;
UPDATE stock SET qty = qty - 1 WHERE item = 'pen';
UPDATE stock SET qty = qty - 1 WHERE item = 'ink';
COMMIT;
SELECT * FROM stock ORDER BY item;
item  qty
----  ---
ink     4
pen     9
(2 rows)
CREATE TABLE stock (item TEXT PRIMARY KEY, qty INTEGER NOT NULL);
INSERT INTO stock VALUES ('pen', 10), ('ink', 5);
BEGIN IMMEDIATE;
UPDATE stock SET qty = qty - 1 WHERE item = 'pen';
UPDATE stock SET qty = qty - 1 WHERE item = 'ink';
COMMIT;
SELECT * FROM stock ORDER BY item;
item  qty
----  ---
ink     4
pen     9
(2 rows)
CREATE TABLE stock (item TEXT PRIMARY KEY, qty INTEGER NOT NULL);
INSERT INTO stock VALUES ('pen', 10), ('ink', 5);
BEGIN IMMEDIATE;
UPDATE stock SET qty = qty - 1 WHERE item = 'pen';
UPDATE stock SET qty = qty - 1 WHERE item = 'ink';
COMMIT;
SELECT * FROM stock ORDER BY item;
item  qty
----  ---
ink     4
pen     9
(2 rows)

Both items were changed together, in the same order pen then ink that every program should use.

3. Deadlock

A deadlock happens when transactions wait for each other in a circle, so nobody can move:

Time Transaction 1 Transaction 2
1 locks row pen locks row ink
2 wants row ink and waits wants row pen and waits

Each holds what the other needs. Waiting longer cannot help. Databases that lock rows detect such circles and cancel one transaction (the "victim") with an error so the others can proceed. The cancelled program should roll back and try again.

SQLite avoids this circle by refusing instead of waiting when waiting could never end. Here both connections have read inside a transaction, then A writes and B tries to write:

c = sqlite3.connect(path, timeout=0.2, isolation_level=None)
d = sqlite3.connect(path, timeout=0.2, isolation_level=None)
c.execute("INSERT INTO stock VALUES ('ink', 5)")
c.execute("BEGIN"); c.execute("SELECT * FROM stock").fetchall()
d.execute("BEGIN"); d.execute("SELECT * FROM stock").fetchall()
c.execute("UPDATE stock SET qty = 1 WHERE item = 'pen'")
print("C updated pen")
try:
    d.execute("UPDATE stock SET qty = 1 WHERE item = 'ink'")
except sqlite3.OperationalError as e:
    print("D:", e)
try:
    c.execute("COMMIT")
except sqlite3.OperationalError as e:
    print("C commit:", e)
d.execute("ROLLBACK")
c.execute("COMMIT")
C updated pen
D: database is locked
C commit: database is locked

D's write failed at once with an error. Then C's commit also failed, because D still held its read lock, until D rolled back; after that, C's COMMIT succeeded. This is a sample of the two-way wait of a deadlock, ended by an error and a rollback instead of a hang.

4. What bigger databases do

Databases that lock rows can deadlock for real. The PostgreSQL manual says it detects deadlocks automatically and resolves them by aborting one of the transactions involved, and that which one is aborted is hard to predict. Its advice for prevention is to acquire locks on multiple objects in a consistent order in every application, and to keep transactions short. A program that is chosen as the victim gets an error and should retry the whole transaction.

5. Keeping locks short

  • Keep transactions small and quick: do slow work (network calls, waiting for a person) outside a transaction.
  • Touch rows in the same order in every program (always pen before ink), so circles cannot form.
  • Use BEGIN IMMEDIATE in SQLite when you know you will write, so the conflict shows up at the start, not halfway.
  • Be ready to retry on lock errors and deadlocks (lesson 6.8).

Worked example: why does the order matter?

Two programs each need to update both pen and ink.

Order Program 1 Program 2 Risk
Different pen, then ink ink, then pen can deadlock
Same pen, then ink pen, then ink the second just waits for the first

With the same order, the second program waits at its first lock, holding nothing the first needs, so no circle can form. The programs and items are made up.

Common mistakes

  • Holding a transaction open while waiting for a user or a web call.
  • Locking more than you need (a whole table when one row would do).
  • Treating "database is locked" as a bug to hide. It is a normal signal to wait or retry.
  • Updating tables in different orders in different parts of the program.

Key takeaways

  • Locks make transactions wait for each other to keep data correct.
  • A deadlock is a circle of waits; the database cancels one transaction and the program retries.
  • SQLite allows many readers but one writer, and reports database is locked when waiting fails.
  • Short transactions, the same order of updates, and retries keep locking problems small.

Practice

1. What does a lock do?

Show answer

It marks data as in use, so other transactions that need it must wait.

2. What is a deadlock?

Show answer

Two or more transactions wait for each other in a circle, so none can continue.

3. What should a program do when it is chosen as the deadlock victim?

Show answer

Roll back and run the transaction again.

4. In the SQLite test, why could B still read while A held the write lock?

Show answer

SQLite allows reading while a writer has not yet committed; B saw the last committed value.

5. Why does updating rows in the same order in every program help?

Show answer

Programs queue up at the first lock instead of each holding something the other needs, so no circular wait can form.

6. Why should slow work be kept outside a transaction?

Show answer

A transaction holds its locks until it ends, so slow work inside it makes others wait longer.