knaxuslearn · build · ship

Projects / Task queue / Phase 2

Phase 2 of 4 · about 2.5 hours

When jobs fail

You end with retries with growing waits, delayed jobs, and a dead state, so one broken job cannot block or loop forever.

Step 2.1: Remember attempts, retry later (about 50 minutes)

Handlers raise errors: a mail server is down, a network call times out. Most of the time trying again a little later works. We need to remember how many times a job has run, how many it may run, and when it may run next. Replace taskq.py with this version:

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',
  attempts     INTEGER NOT NULL DEFAULT 0,
  max_attempts INTEGER NOT NULL DEFAULT 3,
  run_at       REAL NOT NULL,
  error        TEXT,
  created      REAL NOT NULL
);
CREATE INDEX IF NOT EXISTS jobs_ready ON jobs (state, run_at, id);
"""

BACKOFF_BASE = 1.0  # seconds; the wait doubles with every failed attempt


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, delay=0, max_attempts=3, **payload):
    now = time.time()
    cur = db.execute(
        "INSERT INTO jobs (name, payload, max_attempts, run_at, created) VALUES (?, ?, ?, ?, ?)",
        (name, json.dumps(payload), max_attempts, now + delay, now),
    )
    return cur.lastrowid


def claim(db):
    row = db.execute(
        """
        UPDATE jobs SET state = 'running', attempts = attempts + 1
        WHERE id = (
          SELECT id FROM jobs
          WHERE state = 'queued' AND run_at <= ?
          ORDER BY run_at, id LIMIT 1
        )
        RETURNING id, name, payload, attempts, max_attempts
        """,
        (time.time(),),
    ).fetchone()
    if row is None:
        return None
    return {
        "id": row[0],
        "name": row[1],
        "payload": json.loads(row[2]),
        "attempts": row[3],
        "max_attempts": row[4],
    }


def finish(db, job_id):
    db.execute("UPDATE jobs SET state = 'done', error = NULL WHERE id = ?", (job_id,))


def fail(db, job, error):
    if job["attempts"] >= job["max_attempts"]:
        db.execute(
            "UPDATE jobs SET state = 'dead', error = ? WHERE id = ?", (error, job["id"])
        )
        return "dead"
    wait = BACKOFF_BASE * 2 ** (job["attempts"] - 1)
    db.execute(
        "UPDATE jobs SET state = 'queued', error = ?, run_at = ? WHERE id = ?",
        (error, time.time() + wait, job["id"]),
    )
    return f"retry in {wait:g}s"

What changed:

  • New columns: attempts, max_attempts, run_at (not before this time), and error (the last failure).
  • enqueue accepts delay and max_attempts. Note that delay and max_attempts are reserved names now, so a handler cannot use them as argument names.
  • claim only takes jobs whose run_at has passed, and counts the attempt as it claims.
  • fail either gives up (dead) or puts the job back in queued with a later run_at. The wait doubles each time: 1 second, 2, 4, 8. This is exponential backoff. If a service is struggling, hammering it every second makes it worse.

Add a failing handler. Replace tasks.py with:

import time

CALLS = {}


def add(a, b):
    return a + b


def slow(seconds):
    time.sleep(seconds)


def flaky(key, fail_times):
    CALLS[key] = CALLS.get(key, 0) + 1
    if CALLS[key] <= fail_times:
        raise RuntimeError(f"{key} failed (call {CALLS[key]})")


def always_fails():
    raise RuntimeError("this job can never work")


HANDLERS = {
    "add": add,
    "slow": slow,
    "flaky": flaky,
    "always_fails": always_fails,
}

flaky fails a set number of times and then works, so we can watch the retries. Replace worker.py. It now catches errors, calls fail, and only stops when nothing is queued or running (jobs waiting for their retry time still count):

import sys
import time

import taskq
from tasks import HANDLERS


def run(path, stop_when_empty=True, log=print):
    db = taskq.connect(path)
    done = 0
    while True:
        job = taskq.claim(db)
        if job is None:
            waiting = db.execute(
                "SELECT COUNT(*) FROM jobs WHERE state IN ('queued', 'running')"
            ).fetchone()[0]
            if stop_when_empty and waiting == 0:
                return done
            time.sleep(0.05)
            continue
        try:
            HANDLERS[job["name"]](**job["payload"])
        except Exception as exc:
            outcome = taskq.fail(db, job, f"{type(exc).__name__}: {exc}")
            log(f"job {job['id']} {job['name']} failed on attempt {job['attempts']}: {outcome}")
        else:
            taskq.finish(db, job["id"])
            done += 1


if __name__ == "__main__":
    print("jobs done:", run(sys.argv[1]))

Create try_retry.py. It shrinks the backoff to 0.2 seconds so you do not wait:

import os
import time

import taskq
import worker

taskq.BACKOFF_BASE = 0.2  # keep the demo quick; real queues use seconds
path = "retry.db"
if os.path.exists(path):
    os.remove(path)
db = taskq.connect(path)
taskq.enqueue(db, "flaky", key="report", fail_times=2)
start = time.time()
worker.run(path, log=lambda line: print(f"{time.time() - start:4.1f}s  {line}"))
print(db.execute("SELECT id, state, attempts, error FROM jobs").fetchall())
 0.0s  job 1 flaky failed on attempt 1: retry in 0.2s
 0.2s  job 1 flaky failed on attempt 2: retry in 0.4s
[(1, 'done', 3, None)]

The job failed twice and succeeded on the third attempt. The gaps in the timestamps are the backoff: 0.2 seconds and then 0.4.

Step 2.2: Give up on poison jobs (about 40 minutes)

Some jobs can never succeed: bad arguments, a deleted record. A job like that must not retry forever and must not block good jobs. After max_attempts it becomes dead. It stays in the table, with its last error, so a person can look at it. Run try_dead.py:

import os

import taskq
import worker

taskq.BACKOFF_BASE = 0.1
path = "dead.db"
if os.path.exists(path):
    os.remove(path)
db = taskq.connect(path)
taskq.enqueue(db, "always_fails")
taskq.enqueue(db, "add", a=1, b=2)
print("jobs done:", worker.run(path))
print(db.execute("SELECT id, name, state, attempts, error FROM jobs").fetchall())
job 1 always_fails failed on attempt 1: retry in 0.1s
job 1 always_fails failed on attempt 2: retry in 0.2s
job 1 always_fails failed on attempt 3: dead
jobs done: 1
[(1, 'always_fails', 'dead', 3, 'RuntimeError: this job can never work'), (2, 'add', 'done', 1, None)]

The bad job retried twice, then went dead with its error saved. The good job next to it finished without trouble. A dead job is not deleted. It is parked, waiting for someone to read the error.

Step 2.3: Delayed jobs (about 30 minutes)

run_at gives delayed jobs for free: "send the reminder in an hour" is just a job with run_at in the future. claim ignores it until then. Run try_delay.py:

import os
import time

import taskq
import worker

path = "delay.db"
if os.path.exists(path):
    os.remove(path)
db = taskq.connect(path)
taskq.enqueue(db, "add", delay=1.0, a=1, b=1)
print("claim right now:", taskq.claim(db))
time.sleep(1.1)
print("claim after 1.1s:", taskq.claim(db))
claim right now: None
claim after 1.1s: {'id': 1, 'name': 'add', 'payload': {'a': 1, 'b': 1}, 'attempts': 1, 'max_attempts': 3}

The same job is invisible right now and claimable a second later.

Step 2.4: Look at the dead (about 30 minutes)

A queue with a dead state needs a way to inspect it and a way to try again. Both are small queries. Run try_inspect.py, which reads the dead.db left behind by try_dead.py:

import taskq

db = taskq.connect("dead.db")  # left behind by try_dead.py
for row in db.execute("SELECT id, name, attempts, error FROM jobs WHERE state = 'dead'"):
    print("dead:", row)

db.execute("UPDATE jobs SET state = 'queued', attempts = 0, run_at = 0 WHERE state = 'dead'")
print("after requeue:", db.execute("SELECT id, state, attempts FROM jobs WHERE name = 'always_fails'").fetchall())
dead: (1, 'always_fails', 3, 'RuntimeError: this job can never work')
after requeue: [(1, 'queued', 0)]

Putting a job back is an UPDATE: reset the attempts and the run_at. Do this only after you fixed the cause. A dead job requeued without a fix just dies again.

Phase 2 done

Failures now cost a retry, not the job. There is still a hole: so far a job fails only by raising an error. What if the whole worker disappears?