research/expiring-old-rows-in-sqlite
Expiring Old Rows in SQLite Without Blocking Writers: One DELETE, Batches and Batches With a Pause
Engineering Note · November 25, 2026 · 8 minute read · SQLite · Python · Databases · Testing
To expire old rows in SQLite without stalling the rest of your app, delete in small batches and pause between them. We deleted 800,000 rows older than 60 days from a one-million-row table while another connection inserted a row every 5 ms. One DELETE statement finished in about 1.4 seconds and made an insert wait just as long. Batches of 5,000, run back to back, made it slightly worse: about 2 seconds. Adding a 50 ms pause after each batch brought the worst insert wait down to about 35 ms, in both rollback-journal and WAL mode. The cleanup took about 10 seconds instead, which nobody waits on.
Everything below was run on Linux with Python 3.11.18 and its bundled SQLite 3.45.1. The outputs are the real ones from these runs.
Why does a cleanup block anything?
SQLite allows one writer at a time for the whole database file. A DELETE takes the write lock and holds it until it commits. Every other connection that wants to write, such as the contact form saving a new submission, has to wait.
How it waits depends on the journal mode:
- Rollback journal (
delete, the default): while the delete is committing, readers can be blocked too. - WAL (write-ahead log): readers keep reading the last committed state. Writers still queue behind the one writer.
And on the busy timeout: a connection with a busy timeout retries for that long before giving up; one with no timeout fails at once with database is locked.
A scheduled cleanup, such as “delete form submissions older than 60 days,” is exactly the kind of large write that runs while the site is live. So we measured what it does to a steady stream of inserts.
What did we run?
A table of form submissions with an index on created_at, one million rows of which 800,000 are older than the cutoff. A writer thread inserts a row every 5 ms on its own connection with a 10-second busy timeout, and records how long each insert takes. The cleanup runs on a second connection, three ways, in each journal mode:
one_statement:DELETE FROM submissions WHERE created_at < ?, then commit.batches: delete up to 5,000 rows by primary key, commit, repeat at once until a batch comes back short.batches_with_pause: the same, withtime.sleep(0.05)after each commit.
# expire.py: delete old rows by created_at in one statement vs in batches,
# while a second connection keeps inserting. Measures how long the inserts wait.
import sqlite3, threading, time, os, sys, statistics
DB = "expire.db"
ROWS = 1_000_000 # rows in the table before the cleanup
OLD = 800_000 # of which this many are older than the cutoff
DAY = 86_400
def setup(journal):
for f in (DB, DB + "-wal", DB + "-shm", DB + "-journal"):
if os.path.exists(f): os.remove(f)
c = sqlite3.connect(DB)
c.execute(f"PRAGMA journal_mode={journal}")
c.execute("CREATE TABLE submissions (id INTEGER PRIMARY KEY, created_at INTEGER NOT NULL, body TEXT NOT NULL)")
c.execute("CREATE INDEX submissions_created_at ON submissions(created_at)")
now = int(time.time())
# Old rows are 100 to 60 days old, recent rows are under 30 days old.
c.executemany("INSERT INTO submissions (created_at, body) VALUES (?, ?)",
((now - 100*DAY + i*(40*DAY)//OLD if i < OLD else now - 30*DAY + (i-OLD)*(30*DAY)//(ROWS-OLD), "x"*200) for i in range(ROWS)))
c.commit(); c.close()
return now - 90*DAY + 30*DAY # cutoff: 60 days ago
def writer(stop, waits, errors):
c = sqlite3.connect(DB, timeout=10, isolation_level=None) # busy timeout 10 s
while not stop.is_set():
t = time.perf_counter()
try:
c.execute("INSERT INTO submissions (created_at, body) VALUES (?, ?)", (int(time.time()), "new"))
waits.append(time.perf_counter() - t)
except sqlite3.OperationalError as e:
errors.append(str(e))
time.sleep(0.005)
c.close()
def one_statement(c, cutoff):
c.execute("DELETE FROM submissions WHERE created_at < ?", (cutoff,))
c.commit()
def batches(c, cutoff, size=5_000):
while True:
cur = c.execute("DELETE FROM submissions WHERE id IN "
"(SELECT id FROM submissions WHERE created_at < ? LIMIT ?)", (cutoff, size))
c.commit()
if cur.rowcount < size: break
def batches_with_pause(c, cutoff, size=5_000):
while True:
cur = c.execute("DELETE FROM submissions WHERE id IN "
"(SELECT id FROM submissions WHERE created_at < ? LIMIT ?)", (cutoff, size))
c.commit()
if cur.rowcount < size: break
time.sleep(0.05) # let waiting writers in
def run(journal, method):
cutoff = setup(journal)
stop, waits, errors = threading.Event(), [], []
w = threading.Thread(target=writer, args=(stop, waits, errors)); w.start()
time.sleep(0.3)
c = sqlite3.connect(DB, timeout=10)
t = time.perf_counter(); method(c, cutoff); took = time.perf_counter() - t
time.sleep(0.3); stop.set(); w.join()
left = c.execute("SELECT count(*) FROM submissions WHERE created_at < ?", (cutoff,)).fetchone()[0]
c.close()
w_ms = sorted(x*1000 for x in waits)
print(f"{journal:6} {method.__name__:18} cleanup {took:5.2f} s | inserts {len(w_ms):4} "
f"median {statistics.median(w_ms):6.2f} ms max {w_ms[-1]:7.1f} ms | errors {len(errors)} | old rows left {left}")
if __name__ == "__main__":
print("SQLite", sqlite3.sqlite_version, "| Python", sys.version.split()[0])
for journal in ("delete", "wal"):
for method in (one_statement, batches, batches_with_pause):
run(journal, method)
The batch query deletes by id IN (SELECT … LIMIT ?) because DELETE … LIMIT only works when SQLite is compiled with SQLITE_ENABLE_UPDATE_DELETE_LIMIT. The build we used accepted DELETE … LIMIT 5, but you can’t count on every build having it, so the subquery is the portable form. EXPLAIN QUERY PLAN confirmed both forms use the index:
DELETE FROM submissions WHERE created_at < ?
SEARCH submissions USING INDEX submissions_created_at (created_at<?)
DELETE FROM submissions WHERE id IN (SELECT id FROM submissions WHERE created_at < ? LIMIT ?)
SEARCH submissions USING INTEGER PRIMARY KEY (rowid=?)
LIST SUBQUERY 1
SEARCH submissions USING COVERING INDEX submissions_created_at (created_at<?)
What happened?
SQLite 3.45.1 | Python 3.11.18
delete one_statement cleanup 1.44 s | inserts 93 median 1.28 ms max 1433.3 ms | errors 0 | old rows left 0
delete batches cleanup 1.96 s | inserts 77 median 1.53 ms max 2034.2 ms | errors 0 | old rows left 0
delete batches_with_pause cleanup 10.29 s | inserts 1213 median 1.60 ms max 35.5 ms | errors 0 | old rows left 0
wal one_statement cleanup 1.20 s | inserts 80 median 0.87 ms max 1132.8 ms | errors 0 | old rows left 0
wal batches cleanup 1.62 s | inserts 124 median 0.71 ms max 234.8 ms | errors 0 | old rows left 0
wal batches_with_pause cleanup 9.68 s | inserts 1464 median 0.67 ms max 34.5 ms | errors 0 | old rows left 0
We ran the script three times. The pattern held each time; the numbers moved a little. Across the three runs, the worst insert wait was 1.43 to 1.63 s for one statement in rollback mode, 2.03 to 2.34 s for back-to-back batches in rollback mode, 0.83 to 1.13 s for one statement in WAL mode, 0.23 to 0.63 s for back-to-back batches in WAL mode, and 23 to 56 ms for batches with a pause in either mode.
Why didn’t batches help on their own?
In rollback mode, back-to-back batches were worse than one statement. The cleanup committed a batch and started the next one immediately. Meanwhile, the waiting insert was asleep in its busy handler, which retries on a timer rather than being woken when the lock is free. By the time it retried, the next batch held the lock again. So the insert waited for nearly the whole cleanup, which now took longer than the single statement.
WAL mode gave inserts a few more chances to slip in, so back-to-back batches did help there, but the worst wait was still hundreds of milliseconds and varied a lot between runs.
The 50 ms pause is what changed the result. It leaves the lock free long enough for the waiting insert’s next retry to find it, so inserts get in between batches instead of after the whole cleanup. The worst insert wait became roughly the time of one batch, a few tens of milliseconds.
What does a missing busy timeout do?
We ran the one-statement delete again with the inserting connection set to timeout=0:
delete: busy timeout 0, one-statement delete -> 271 failed inserts; first error: 'database is locked'
wal: busy timeout 0, one-statement delete -> 142 failed inserts; first error: 'database is locked'
With the 10-second timeout, every run above had zero errors. A form handler without a busy timeout would turn the nightly cleanup into failed submissions. Python’s sqlite3 defaults to a 5-second timeout. Check what your driver does, and set PRAGMA busy_timeout explicitly if you are not sure.
What we would ship
- An index on the timestamp column.
PRAGMA journal_mode=WALand a busy timeout on every connection.- A cleanup that deletes 5,000 rows by primary key per transaction, commits, sleeps 50 ms, and stops when a batch comes back short.
- A schedule outside busy hours, plus a heartbeat check so you hear about it when the cleanup stops running.
For a form like the one in today’s article, Your Contact Form Is a Sales Channel, keep submissions at least long enough to cover your monthly count of what the site recorded against what arrived, before the cleanup deletes them.
Limitations
- One machine, one disk, Linux, Python’s
sqlite3module and SQLite 3.45.1. Absolute times depend on the disk and the row size; the 200-byte rows here are smaller than many real submissions. - One writer thread, inserting about every 5 ms. We did not test many concurrent writers, readers holding long transactions, or other processes.
- We did not tune the batch size or the pause; 5,000 rows and 50 ms were our first choice and were good enough here.
- Deleting rows does not shrink the database file. We did not measure
VACUUMorincremental_vacuum, which have their own locking costs. - The busy handler’s retry timing comes from SQLite’s default handler as used by Python. Other drivers may install their own and behave differently.
Related reading
- Heartbeat Checks for Scheduled Jobs: Alerting When a Job Did Not Run
- SQLite UPSERT with RETURNING: Building an Atomic Counter You Can Trust
- Idempotency Keys for a Booking Form: Stopping Double Clicks and Retries From Creating Two Bookings
Frequently asked questions
How do I delete old rows from SQLite on a schedule?
Index the timestamp column, then delete in batches by primary key: DELETE FROM t WHERE id IN (SELECT id FROM t WHERE created_at < ? LIMIT 5000), committed after each batch, with a short pause before the next. Repeat until a batch deletes fewer rows than the limit. In our test this kept other writers' waits to about 35 ms.
Why does a large DELETE block inserts in SQLite?
SQLite allows one writer at a time for the whole database. A DELETE holds the write lock until it commits, so any insert from another connection waits, or fails with "database is locked" if it has no busy timeout. In WAL mode readers are not blocked, but writers still are.
Why didn't deleting in batches help on its own?
Because the cleanup started its next batch immediately after each commit, before the waiting insert got the lock. The waiting connection retries on a timer, and the gap between batches was shorter than that timer. Adding a 50 ms pause between batches let inserts through, and the worst wait dropped from about 2 seconds to about 35 ms.
What busy timeout should a SQLite connection use?
Long enough to outlast your longest write. With a busy timeout of 0, our insert loop got 271 "database is locked" errors in rollback mode and 142 in WAL mode during a one-statement cleanup. With a 10-second timeout it got none. Python's sqlite3 module defaults to 5 seconds; other drivers may default to 0.
Does WAL mode fix lock contention during deletes?
Partly. In our runs WAL mode roughly halved typical insert times and let readers continue, but a one-statement DELETE still made inserts wait 0.8 to 1.1 seconds, because SQLite still allows only one writer. Batching with a pause is what kept writer waits short in both modes.