Databases · Intermediate · 22 min
Use SQLite safely in a Python app: WAL mode, foreign keys and busy timeouts
By Padding · Updated 18 Nov 2026
Python 3.15.2 · sqlite3 standard library module · python:3.15-slim (Debian)
You will build a small room-booking store on SQLite with Python 3.15, reproduce the "database is locked" error with two writer processes, and end with a connection helper that turns on foreign keys, WAL mode, a busy timeout and BEGIN IMMEDIATE writes, plus a tested online backup.
On this page
SQLite is a full SQL database in a single file, and Python ships with a driver for it in the standard library. It is a good choice for a small web app on one server: there is no database server to run, back up separately or secure on the network. It also has defaults that surprise people in production. Foreign keys are not enforced, two processes that write at the same time can fail with database is locked, and copying the file while the app runs can give you a broken backup.
In this tutorial you build a tiny booking store for two meeting rooms and run into each of those problems on purpose. You run two writer processes side by side to see the lock, then fix it with WAL mode, a busy timeout, short write transactions and BEGIN IMMEDIATE. By the end you have a db.py helper you can reuse, an online backup script, and a rough measure of how many writes per second your machine can take.
Everything uses the sqlite3 module that comes with Python 3.15, so there is nothing to install.
Step 1 · Create a project and check your SQLite version
Make a throwaway folder for the demo and print the Python and SQLite versions. Python's sqlite3 module uses whatever SQLite library it was built against, and that version decides which features you can use.
mkdir -p ~/sqlite-demo
cd ~/sqlite-demo
python3 -c "import sys, sqlite3; print('Python', sys.version.split()[0]); print('SQLite', sqlite3.sqlite_version)"Check it worked
The first line starts with Python 3.15. The second shows an SQLite version of 3.37.0 or later, which you need for STRICT tables in the next step. If yours is older, use a newer Python build (the official python:3.15 images and current Linux distributions are all well past 3.37).
Step 2 · Write a STRICT schema
Create the schema. There are two rooms and a bookings table. UNIQUE (room_id, starts_at) means a room can only be booked once per time slot, whatever the application code does. STRICT at the end of each table makes SQLite check column types. Without it, SQLite stores almost any value in any column, so a bug that writes 'one' into an integer column goes unnoticed until a report breaks.
cat > schema.sql <<'SQL'
CREATE TABLE IF NOT EXISTS rooms (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL UNIQUE
) STRICT;
CREATE TABLE IF NOT EXISTS bookings (
id INTEGER PRIMARY KEY,
room_id INTEGER NOT NULL REFERENCES rooms (id),
guest TEXT NOT NULL,
starts_at TEXT NOT NULL,
UNIQUE (room_id, starts_at)
) STRICT;
INSERT OR IGNORE INTO rooms (id, name) VALUES (1, 'Baobab'), (2, 'Volta');
SQL
cat > create_db.py <<'PY'
import sqlite3
from pathlib import Path
conn = sqlite3.connect("bookings.db", autocommit=True)
conn.executescript(Path("schema.sql").read_text())
tables = conn.execute(
"SELECT name FROM sqlite_schema WHERE type = 'table' ORDER BY name"
).fetchall()
print([name for (name,) in tables])
conn.close()
PY
python3 create_db.pyautocommit=True tells Python not to open transactions for you. You will see why that matters in the next steps.
Now try to store text in the integer room_id column:
cat > strict_check.py <<'PY'
import sqlite3
conn = sqlite3.connect("bookings.db", autocommit=True)
try:
conn.execute(
"INSERT INTO bookings (room_id, guest, starts_at) VALUES ('one', 'Typo', '2026-12-01T08:00')"
)
except sqlite3.IntegrityError as err:
print("rejected:", err)
conn.close()
PY
python3 strict_check.pySTRICT still accepts text that converts to an integer without loss, such as '1', so form values that arrive as strings keep working.
SQLite stores TEXT as UTF-8, so names such as Adébáyọ̀ or Nomvula are kept exactly. Its built-in lower(), upper() and case-insensitive LIKE only fold ASCII letters, though. If you search names in several languages, normalise case in Python (str.casefold()) before you store or compare them.
Check it worked
create_db.py prints ['bookings', 'rooms']. strict_check.py prints a line starting with rejected: and an error such as cannot store TEXT value in INTEGER column bookings.room_id.
Step 3 · See that foreign keys are off by default
The schema says room_id REFERENCES rooms (id), but SQLite only enforces that when each connection asks for it. Insert a booking for room 99, which does not exist, then turn enforcement on and try again:
cat > fk_check.py <<'PY'
import sqlite3
conn = sqlite3.connect("bookings.db", autocommit=True)
print("foreign_keys =", conn.execute("PRAGMA foreign_keys").fetchone()[0])
conn.execute(
"INSERT INTO bookings (room_id, guest, starts_at) VALUES (99, 'Ghost', '2026-12-01T08:00')"
)
orphans = conn.execute("PRAGMA foreign_key_check(bookings)").fetchall()
print("orphan rows:", len(orphans))
conn.execute("DELETE FROM bookings WHERE room_id = 99")
conn.execute("PRAGMA foreign_keys = ON")
try:
conn.execute(
"INSERT INTO bookings (room_id, guest, starts_at) VALUES (99, 'Ghost', '2026-12-01T08:00')"
)
except sqlite3.IntegrityError as err:
print("rejected:", err)
conn.close()
PY
python3 fk_check.pyPRAGMA foreign_key_check lists rows that break a foreign key, which is useful on an existing database that ran without enforcement for a while.
PRAGMA foreign_keys = ON has no effect inside an open transaction. Python's default mode (the autocommit attribute is LEGACY_TRANSACTION_CONTROL) and autocommit=False both open transactions behind your back, so a pragma sent at the wrong moment can be silently ignored. With autocommit=True, nothing is open until you write BEGIN, so pragmas sent right after connecting always apply. The trade-off is that conn.commit() and conn.rollback() do nothing in this mode: you write BEGIN and COMMIT yourself, which step 6 wraps in a helper.
Check it worked
The output is foreign_keys = 0, orphan rows: 1 and rejected: FOREIGN KEY constraint failed.
Step 4 · Hit "database is locked" with two writers
A web app with several worker processes has several connections writing to the same file. SQLite allows only one writer at a time. Write a booking script that holds its write transaction open for a few seconds, the way a request handler does when it calls a slow service between BEGIN and COMMIT:
cat > naive_book.py <<'PY'
import sqlite3
import sys
import time
guest, starts_at, hold = sys.argv[1], sys.argv[2], float(sys.argv[3])
# A one-second timeout so the failure shows quickly. Python's default is five.
conn = sqlite3.connect("bookings.db", timeout=1, autocommit=True)
try:
conn.execute("BEGIN")
conn.execute(
"INSERT INTO bookings (room_id, guest, starts_at) VALUES (1, ?, ?)",
(guest, starts_at),
)
time.sleep(hold) # slow work inside the transaction
conn.execute("COMMIT")
print(guest, "booked", starts_at)
except sqlite3.OperationalError as err:
print(guest, "failed:", err)
finally:
conn.close()
PYStart Amina's booking in the background, holding its transaction for three seconds. Half a second later, start Bayo's booking for a different slot:
python3 naive_book.py Amina 2026-12-01T09:00 3 &
sleep 0.5
python3 naive_book.py Bayo 2026-12-01T10:00 0
waitBayo's process waits for the lock for one second, gives up and raises OperationalError. With the default five-second timeout the same thing happens to any writer stuck behind a transaction that takes longer than five seconds, and under load those waits add up.
Check it worked
You see Bayo failed: database is locked about one second after starting, then Amina booked 2026-12-01T09:00 when her three seconds are up. Only Amina's booking is in the database.
Step 5 · Turn on WAL mode and a longer busy timeout
Put the safe settings in one place. Every part of your app opens connections through this helper, so no connection forgets a setting:
cat > db.py <<'PY'
import sqlite3
DB_PATH = "bookings.db"
def connect(path=DB_PATH):
conn = sqlite3.connect(path, timeout=10, autocommit=True)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA foreign_keys = ON")
conn.execute("PRAGMA journal_mode = WAL")
return conn
PY
python3 -c "
from db import connect
conn = connect()
for pragma in ('journal_mode', 'busy_timeout', 'foreign_keys'):
print(pragma, conn.execute(f'PRAGMA {pragma}').fetchone()[0])
print('autocommit', conn.autocommit)
conn.close()
"What each line does:
timeout=10sets SQLite's busy timeout. A connection that finds the database locked retries for up to ten seconds before it raises an error.PRAGMA busy_timeoutreports it in milliseconds.PRAGMA journal_mode = WALswitches from the default rollback journal to write-ahead logging. Writes go to abookings.db-walfile first (with abookings.db-shmindex beside it), so readers keep reading the last committed data while a write is in progress, and a writer never waits for readers. WAL mode is stored in the database file, so it stays on, but setting it on every connection costs nothing and protects you if someone recreates the file. Keep a WAL database on a local disk, not a network share. The-waland-shmfiles exist only while a connection is open: when the last connection closes cleanly, SQLite copies the log back intobookings.dband removes them, so anlsafter your scripts finish shows justbookings.db.conn.row_factory = sqlite3.Rowmakes rows behave like read-only dictionaries, so code saysrow["guest"]instead ofrow[2].
Now repeat the two-writer test with the helper, and read the bookings while the first write is still open:
cat > book.py <<'PY'
import sqlite3
import sys
import time
from db import connect
guest, starts_at, hold = sys.argv[1], sys.argv[2], float(sys.argv[3])
conn = connect()
try:
conn.execute("BEGIN")
conn.execute(
"INSERT INTO bookings (room_id, guest, starts_at) VALUES (1, ?, ?)",
(guest, starts_at),
)
time.sleep(hold)
conn.execute("COMMIT")
print(guest, "booked", starts_at)
except sqlite3.OperationalError as err:
print(guest, "failed:", err)
finally:
conn.close()
PY
cat > list_bookings.py <<'PY'
from db import connect
conn = connect()
rows = conn.execute(
"SELECT r.name AS room, b.guest, b.starts_at"
" FROM bookings b JOIN rooms r ON r.id = b.room_id"
" ORDER BY b.room_id, b.starts_at"
).fetchall()
for row in rows:
print(f"{row['room']:<8} {row['starts_at']} {row['guest']}")
print(len(rows), "bookings")
conn.close()
PY
python3 book.py Kofi 2026-12-01T11:00 3 &
sleep 0.5
python3 book.py Lindiwe 2026-12-01T12:00 0 &
sleep 0.5
python3 list_bookings.py
wait
python3 list_bookings.pyCheck it worked
The settings check prints journal_mode wal, busy_timeout 10000, foreign_keys 1 and autocommit True. While any connection is open, bookings.db-wal and bookings.db-shm sit next to bookings.db; once every script has finished they are gone again, which is normal. In the run, the first listing appears at once and shows only Amina's booking (1 bookings): Kofi's write is not committed yet, and the reader did not have to wait for it. Then Kofi booked and Lindiwe booked appear, because Lindiwe's process waited for the lock this time. The final listing shows 3 bookings.
Step 6 · Use BEGIN IMMEDIATE for read-then-write transactions
A busy timeout does not fix every lock. Booking code usually reads first ("is this slot free?") and writes second. A plain BEGIN is deferred: the transaction only reads at first, and asks for the write lock when it reaches the INSERT. If another connection committed a write in between, the data this transaction read is out of date, and SQLite refuses the write straight away with database is locked (the extended code is SQLITE_BUSY_SNAPSHOT). Waiting would not help, so the busy timeout is skipped.
Write a script that checks the slot, pauses to stand in for work, then books. The last argument picks the kind of transaction:
cat > check_and_book.py <<'PY'
import sqlite3
import sys
import time
from db import connect
guest, starts_at, think, mode = sys.argv[1], sys.argv[2], float(sys.argv[3]), sys.argv[4]
conn = connect()
try:
conn.execute("BEGIN IMMEDIATE" if mode == "immediate" else "BEGIN")
taken = conn.execute(
"SELECT guest FROM bookings WHERE room_id = 2 AND starts_at = ?",
(starts_at,),
).fetchone()
time.sleep(think)
if taken:
conn.execute("ROLLBACK")
print(f"{guest}: slot taken by {taken['guest']}")
else:
conn.execute(
"INSERT INTO bookings (room_id, guest, starts_at) VALUES (2, ?, ?)",
(guest, starts_at),
)
conn.execute("COMMIT")
print(f"{guest}: booked")
except sqlite3.OperationalError as err:
print(f"{guest}: failed: {err}")
finally:
conn.close()
PYRun Chidi and Dami for the same Volta slot with a deferred BEGIN, then again for another slot with BEGIN IMMEDIATE:
python3 check_and_book.py Chidi 2026-12-01T09:00 1 deferred &
sleep 0.3
python3 check_and_book.py Dami 2026-12-01T09:00 2 deferred
wait
python3 check_and_book.py Chidi 2026-12-01T11:00 1 immediate &
sleep 0.3
python3 check_and_book.py Dami 2026-12-01T11:00 2 immediate
waitIn the deferred run, both read the slot as free. Chidi writes first and commits. Dami's read is now stale, so her INSERT fails at once, even though the busy timeout is ten seconds. In the immediate run, BEGIN IMMEDIATE takes the write lock before reading. Dami's BEGIN IMMEDIATE waits (the busy timeout applies here) until Chidi commits, then reads fresh data and sees the slot is gone. Even if your code got this wrong, the UNIQUE (room_id, starts_at) constraint would stop a double booking.
Make the safe version the only one your app uses. Replace db.py with a version that adds a write_transaction helper:
cat > db.py <<'PY'
import sqlite3
from contextlib import contextmanager
DB_PATH = "bookings.db"
def connect(path=DB_PATH):
conn = sqlite3.connect(path, timeout=10, autocommit=True)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA foreign_keys = ON")
conn.execute("PRAGMA journal_mode = WAL")
return conn
@contextmanager
def write_transaction(conn):
"""Hold the write lock for the whole block; commit on success, roll back on error."""
conn.execute("BEGIN IMMEDIATE")
try:
yield conn
except BaseException:
conn.execute("ROLLBACK")
raise
else:
conn.execute("COMMIT")
PY
cat > tx_check.py <<'PY'
import sqlite3
from db import connect, write_transaction
conn = connect()
with write_transaction(conn):
conn.execute(
"INSERT INTO bookings (room_id, guest, starts_at) VALUES (2, 'Ngozi', '2026-12-01T14:00')"
)
try:
with write_transaction(conn):
conn.execute(
"INSERT INTO bookings (room_id, guest, starts_at) VALUES (2, 'Ola', '2026-12-01T15:00')"
)
conn.execute(
"INSERT INTO bookings (room_id, guest, starts_at) VALUES (99, 'Ola', '2026-12-01T16:00')"
)
except sqlite3.IntegrityError as err:
print("rolled back:", err)
names = [row["guest"] for row in conn.execute("SELECT guest FROM bookings WHERE room_id = 2 ORDER BY id")]
print(names)
conn.close()
PY
python3 tx_check.pyKeep the block short. Do slow work, such as calling a payment provider or sending an email, before write_transaction or after it, never inside, because every other writer waits for as long as the block runs.
Check it worked
The deferred run prints Chidi: booked and Dami: failed: database is locked. The immediate run prints Chidi: booked and Dami: slot taken by Chidi. tx_check.py prints rolled back: FOREIGN KEY constraint failed and ['Chidi', 'Chidi', 'Ngozi']: Ola's first insert was undone along with the failing one.
Step 7 · Back up the database while the app is running
Copying bookings.db with cp while the app writes can capture a half-finished change, and it misses anything still in bookings.db-wal. The backup API copies a consistent snapshot through SQLite itself, while other connections keep working:
cat > backup.py <<'PY'
import sqlite3
from db import connect
source = connect()
target = sqlite3.connect("bookings-backup.db", autocommit=True)
source.backup(target)
target.close()
source.close()
check = sqlite3.connect("bookings-backup.db", autocommit=True)
print("integrity:", check.execute("PRAGMA integrity_check").fetchone()[0])
print("bookings in backup:", check.execute("SELECT count(*) FROM bookings").fetchone()[0])
check.close()
PY
python3 book.py Efe 2026-12-02T09:00 2 &
sleep 0.5
python3 backup.py
wait
python3 list_bookings.py | tail -n 1Efe's booking is still open when the copy is taken, so it is not in the backup, and the backup is still complete and consistent. Copy the backup off the server afterwards; a backup on the same disk does not survive the disk. If you pay for bandwidth by the megabyte, as on many prepaid or metered plans, compress it first with gzip -k bookings-backup.db. SQLite files compress well.
The sqlite3 command-line tool can do the same with .backup, and SQL's VACUUM INTO 'file.db' writes a compacted copy.
Check it worked
backup.py prints integrity: ok and bookings in backup: 6. After wait, Efe's booking has committed and the last line of the listing is 7 bookings.
Step 8 · Measure your write rate and decide if SQLite is enough
Every committed write transaction waits for the disk to confirm the data is saved, and writes happen one at a time. That makes the write rate the number that decides whether SQLite fits. Measure it on your server with a thousand small transactions in a separate file:
cat > bench.py <<'PY'
import time
from db import connect, write_transaction
conn = connect("bench.db")
conn.execute("CREATE TABLE IF NOT EXISTS hits (id INTEGER PRIMARY KEY, at REAL NOT NULL) STRICT")
count = 1000
started = time.perf_counter()
for _ in range(count):
with write_transaction(conn):
conn.execute("INSERT INTO hits (at) VALUES (?)", (time.time(),))
elapsed = time.perf_counter() - started
print(f"{count} write transactions in {elapsed:.2f} s, about {count / elapsed:.0f} per second")
conn.close()
PY
python3 bench.pyThe figure depends on the disk: a cheap VPS on network storage is far slower than a laptop SSD. In WAL mode, PRAGMA synchronous = NORMAL raises the rate a lot. The database stays consistent, but the last few commits can be lost if the machine loses power, so only use it where that is acceptable.
SQLite is usually enough when:
- The app runs on one server, with all processes on the same machine and the database on a local disk.
- Your peak writes per second sit well below the number you just measured, and each write transaction is short.
- You can live with a short outage to restore from a backup.
Move to a client-server database such as PostgreSQL when several servers need to write to the same data, when you need users and permissions inside the database, when writes are heavy and sustained, or when you need replicas for failover.
Check it worked
You see one line such as 1000 write transactions in 0.84 s, about 1190 per second. Your numbers will differ. Compare the rate with your app's busiest minute: if your busiest minute needs no more than about a tenth of the rate you measured, you have room to grow on one server.
Step 9 · Clean up
Remove the demo folder, which holds the databases, the backup and the scripts, plus any -wal and -shm files left behind if a script was killed before it closed its connection. Make sure no script is still running first:
cd ~
rm -rf ~/sqlite-demoCheck it worked
ls ~/sqlite-demo reports that the folder does not exist. Python stays installed, and db.py is worth keeping in your own project as the one place connections are opened.
Next steps
- Use SQLite through an ORM in a web app: store data in a Flask app with SQLAlchemy.
- See the same SQLite rules from TypeScript: store library books in SQLite with Drizzle.
- When you outgrow one server, move to PostgreSQL: connect to PostgreSQL from Python with psycopg.
- Learn how a client-server database handles concurrent transactions: understand PostgreSQL transactions and isolation levels.
Related tutorials
- Throttle login attempts with a sliding window in RedisYou will protect a Python login function from password guessing with a sliding-window log in Redis sorted sets, checked atomically in a Lua script, with per-address lockouts that double each time, an account-wide rule that asks for an extra check instead of locking the owner out, and tests that replay 50 guesses.
- Run background jobs with Redis Streams and consumer groupsYou will build a small receipt-sending job queue on Redis 8 Streams with two Python workers that share the work, recover jobs from a crashed worker, park repeated failures in a dead-letter stream and never send the same receipt twice.
- Recover the clinic database to a point in time with WAL archivingYou will archive the clinic database's WAL, take a base backup, undo a destructive DELETE by replaying the archive to the second before it ran, and rehearse that restore on a scratch copy.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials