Projects / Task queue / Phase 1
Phase 1 of 4 · about 2.5 hours
Jobs in a table
You end with a queue file, a worker that drains it, and proof that two workers can share it without running a job twice.
A job is a row: a name, some arguments and a state. A worker is a loop: take a queued job, run it, mark it done. The only hard part is the word "take" when several workers loop at once. We build the easy parts first and then break the obvious way to do "take".
Step 1.1: The jobs table (about 30 minutes)
Create taskq.py. Why SQLite and not a plain list in memory? A file survives a crash, and SQLite lets many processes share it safely.
import json
import sqlite3
import time
SCHEMA = """
CREATE TABLE IF NOT EXISTS jobs (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
payload TEXT NOT NULL,
state TEXT NOT NULL DEFAULT 'queued',
created REAL NOT NULL
);
CREATE INDEX IF NOT EXISTS jobs_state ON jobs (state, id);
"""
def connect(path):
db = sqlite3.connect(path, timeout=30, isolation_level=None)
db.execute("PRAGMA journal_mode = WAL")
db.executescript(SCHEMA)
return db
def enqueue(db, name, **payload):
cur = db.execute(
"INSERT INTO jobs (name, payload, created) VALUES (?, ?, ?)",
(name, json.dumps(payload), time.time()),
)
return cur.lastrowid
def claim(db):
row = db.execute(
"""
UPDATE jobs SET state = 'running'
WHERE id = (SELECT id FROM jobs WHERE state = 'queued' ORDER BY id LIMIT 1)
RETURNING id, name, payload
"""
).fetchone()
if row is None:
return None
return {"id": row[0], "name": row[1], "payload": json.loads(row[2])}
def finish(db, job_id):
db.execute("UPDATE jobs SET state = 'done' WHERE id = ?", (job_id,))
Walk through the pieces:
stateis one ofqueued,runningordone. The index on(state, id)lets a worker find the next queued job quickly.PRAGMA journal_mode = WALturns on write-ahead logging, so readers do not block the writer.isolation_level=Nonemakes every statement its own transaction. We want that: each step below is one statement, and a statement is atomic.timeout=30tells SQLite to wait up to 30 seconds when another process holds the write lock, instead of failing at once.claimis oneUPDATE ... RETURNINGstatement. It picks the oldest queued job, marks it running and hands the row back, all in one step. Step 1.4 explains why that matters.
Try it. Create try_basic.py:
import os
import sqlite3
import taskq
print("SQLite version:", sqlite3.sqlite_version)
path = "basic.db"
if os.path.exists(path):
os.remove(path)
db = taskq.connect(path)
for n in range(3):
taskq.enqueue(db, "add", a=n, b=10)
job = taskq.claim(db)
print("claimed:", job)
print("states:", db.execute("SELECT id, state FROM jobs ORDER BY id").fetchall())
taskq.finish(db, job["id"])
print("states:", db.execute("SELECT id, state FROM jobs ORDER BY id").fetchall())
SQLite version: 3.53.1
claimed: {'id': 1, 'name': 'add', 'payload': {'a': 0, 'b': 10}}
states: [(1, 'running'), (2, 'queued'), (3, 'queued')]
states: [(1, 'done'), (2, 'queued'), (3, 'queued')]
The first line is your SQLite version. A claimed job moves to running and the others wait, and finish marks it done.
Step 1.2: A worker (about 40 minutes)
Handlers are plain functions. Create tasks.py:
import time
def add(a, b):
return a + b
def slow(seconds):
time.sleep(seconds)
HANDLERS = {"add": add, "slow": slow}
Then worker.py, a loop that claims, runs and finishes:
import sys
import taskq
from tasks import HANDLERS
def run(path, stop_when_empty=True):
db = taskq.connect(path)
done = 0
while True:
job = taskq.claim(db)
if job is None:
if stop_when_empty:
return done
continue
HANDLERS[job["name"]](**job["payload"])
taskq.finish(db, job["id"])
done += 1
if __name__ == "__main__":
print("jobs done:", run(sys.argv[1]))
HANDLERS[job["name"]](**job["payload"]) looks up the function by name and calls it with the stored arguments. That is why the payload is JSON: it has to survive being written to a file and read by another process. Run it with try_worker.py:
import os
import taskq
import worker
path = "worker.db"
if os.path.exists(path):
os.remove(path)
db = taskq.connect(path)
for n in range(5):
taskq.enqueue(db, "add", a=n, b=n)
print("jobs done:", worker.run(path))
print(db.execute("SELECT state, COUNT(*) FROM jobs GROUP BY state").fetchall())
jobs done: 5
[('done', 5)]
Five jobs went in and five came out done. With one worker there is nothing to go wrong. Now add more workers.
Step 1.3: The obvious way breaks (about 40 minutes)
Many people write "take a job" as two steps: read the oldest queued job, then mark it running. It looks fine. Let's race it against the one-statement version. Four processes each loop until the queue is empty, and write down every job they claim in a log table. Create try_race.py:
import multiprocessing as mp
import os
import sqlite3
import sys
import time
import taskq
JOBS, WORKERS = 1000, 4
def naive_claim(db):
row = db.execute("SELECT id FROM jobs WHERE state = 'queued' ORDER BY id LIMIT 1").fetchone()
if row is None:
return None
db.execute("UPDATE jobs SET state = 'running' WHERE id = ?", (row[0],))
return row[0]
def atomic_claim(db):
job = taskq.claim(db)
return None if job is None else job["id"]
def work(path, mode):
db = taskq.connect(path)
claim = naive_claim if mode == "naive" else atomic_claim
mine = []
while (job_id := claim(db)) is not None:
mine.append((job_id, os.getpid()))
db.executemany("INSERT INTO log VALUES (?, ?)", mine)
def trial(mode):
path = f"race_{mode}.db"
if os.path.exists(path):
os.remove(path)
db = taskq.connect(path)
db.execute("CREATE TABLE log (job_id INTEGER, pid INTEGER)")
db.execute("BEGIN")
for n in range(JOBS):
taskq.enqueue(db, "add", a=n, b=1)
db.execute("COMMIT")
start = time.perf_counter()
procs = [mp.Process(target=work, args=(path, mode)) for _ in range(WORKERS)]
for p in procs:
p.start()
for p in procs:
p.join()
took = time.perf_counter() - start
total = db.execute("SELECT COUNT(*) FROM log").fetchone()[0]
dupes = db.execute(
"SELECT COUNT(*) FROM (SELECT job_id FROM log GROUP BY job_id HAVING COUNT(*) > 1)"
).fetchone()[0]
print(f"{mode:6} claims: {total} jobs claimed twice: {dupes} ({took:.2f}s)")
if __name__ == "__main__":
trial("naive")
trial("atomic")
naive claims: 1003 jobs claimed twice: 2 (0.44s)
atomic claims: 1000 jobs claimed twice: 0 (0.54s)
naive_claim handed out 1,000 jobs plus a few more: some jobs were claimed by two workers. Your exact numbers will differ from run to run (races are random), but the naive line should show claims above 1,000 and a number above zero in "claimed twice". The atomic line is exactly 1,000 claims and 0 twice.
Here is the story of one duplicate. Worker A reads "job 7 is next". Before A runs its update, worker B also reads "job 7 is next". Both then mark it running, and both run it. Each step was fine on its own. The gap between them is the bug.
In a real queue that gap means two welcome emails, or two charges on one card.
Step 1.4: Why one statement is safe (about 40 minutes)
The fix is not a lock you write yourself. It is to do the "find" and the "mark" in one statement, so nothing can happen between them.
In claim, the subquery finds the oldest queued id and the outer UPDATE marks that row, inside one statement. SQLite allows one writer at a time per database file, so while one process runs its UPDATE, the others wait their turn (up to the timeout we set). When a waiting process gets in, the first job is already running, so its subquery picks the next one. RETURNING gives back the claimed row in the same step, so we never need a second query to ask "which job did I get?".
Three things to remember:
- Pitfall:
RETURNINGneeds SQLite 3.35 (March 2021) or newer. On an older version the statement fails with a syntax error, which is why we checked the version at the start. - One writer at a time is the price of this design. Step 4.4 measures what it costs.
- SQLite has to be on a local disk. Its write-ahead log does not work over a network file system.
Phase 1 done
You have a queue in a file and workers that share it safely. Next we deal with jobs that fail.