knaxuslearn · build · ship

Projects / Task queue / Phase 3

Phase 3 of 4 · about 2.5 hours

Workers that die

You end with a worker you can kill -9 mid-job, with the job picked up by someone else.

Step 3.1: Break it first (about 35 minutes)

A process can vanish without raising anything: the machine reboots, the kernel kills it for using too much memory, someone runs kill -9. That signal cannot be caught, so no cleanup code runs. Our job stays running forever. Let's see it. Create try_stuck.py (in the Phase 2 folder, with the Phase 2 code):

import os
import signal
import subprocess
import sys
import time

import taskq

path = "stuck.db"
for suffix in ("", "-wal", "-shm"):
    if os.path.exists(path + suffix):
        os.remove(path + suffix)
db = taskq.connect(path)
taskq.enqueue(db, "slow", seconds=5)

first = subprocess.Popen([sys.executable, "worker.py", path])
time.sleep(0.5)
first.send_signal(signal.SIGKILL)  # the machine loses power, the process is OOM-killed, ...
first.wait()

try:
    subprocess.run([sys.executable, "worker.py", path], timeout=3)
except subprocess.TimeoutExpired:
    print("worker 2 gave up after 3s")
print("job state:", db.execute("SELECT state, attempts FROM jobs").fetchone())
worker 2 gave up after 3s
job state: ('running', 1)

The second worker waited, saw a job marked running, and never touched it, because nothing says the first worker is dead. The job is stuck. A queue that loses jobs when a process dies has not done the one thing a queue is for.

Step 3.2: Leases (about 55 minutes)

We cannot tell "slow" from "dead", but we can use time. When a worker claims a job, it gets a lease: "this job is yours until time T". If T passes and the job is still running, we assume the worker is gone and let someone else claim it. Add a column lease_until, a LEASE setting at the top, and change claim, finish and fail:

LEASE = float(os.environ.get("TASKQ_LEASE", "30"))  # seconds a worker may hold a job
def claim(db):
    now = time.time()
    # A job whose lease ran out and has no attempts left is finished for good.
    db.execute(
        """
        UPDATE jobs SET state = 'dead', error = 'lease expired on the last attempt'
        WHERE state = 'running' AND lease_until < ? AND attempts >= max_attempts
        """,
        (now,),
    )
    row = db.execute(
        """
        UPDATE jobs SET state = 'running', attempts = attempts + 1, lease_until = ?
        WHERE id = (
          SELECT id FROM jobs
          WHERE (state = 'queued' AND run_at <= ?)
             OR (state = 'running' AND lease_until < ?)
          ORDER BY run_at, id LIMIT 1
        )
        RETURNING id, name, payload, attempts, max_attempts
        """,
        (now + LEASE, now, now),
    ).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):
    cur = db.execute(
        "UPDATE jobs SET state = 'done', error = NULL WHERE id = ? AND state = 'running' AND attempts = ?",
        (job["id"], job["attempts"]),
    )
    return cur.rowcount == 1


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

Read claim slowly:

  • The first statement marks a lease-expired job dead if it has no attempts left. Without that, a job that crashes its worker every time would be claimed forever.
  • The WHERE clause now accepts two kinds of job: queued ones that are due, and running ones whose lease expired.
  • Every claim sets a new lease_until and adds an attempt.
  • finish and fail only act if the job is still running and the attempt number matches the one the worker was given. This is a fencing check. A slow worker that comes back after its lease expired holds an old attempt number, so its late answer is ignored. They return False or "lost the job" so the worker can say what happened.

Update worker.py to use the return value of finish:

        else:
            if taskq.finish(db, job):
                done += 1
            else:
                log(f"job {job['id']} finished too late, another worker owns it now")


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

That block replaces the else: branch at the end of the loop from Phase 2.

Step 3.3: Kill it (about 30 minutes)

Now the test that mattered. try_crash.py starts a worker with a 1 second lease on a job that takes 5 seconds, kills it with kill -9, waits for the lease to run out and starts a second worker:

import os
import signal
import subprocess
import sys
import time

import taskq

path = "crash.db"
for suffix in ("", "-wal", "-shm"):
    if os.path.exists(path + suffix):
        os.remove(path + suffix)
db = taskq.connect(path)
taskq.enqueue(db, "slow", seconds=5)

env = dict(os.environ, TASKQ_LEASE="1")
first = subprocess.Popen([sys.executable, "worker.py", path], env=env)
time.sleep(0.5)
print("state while worker 1 runs:", db.execute("SELECT state, attempts FROM jobs").fetchone())
first.send_signal(signal.SIGKILL)
first.wait()
print("worker 1 killed with kill -9")
print("state right after:", db.execute("SELECT state, attempts FROM jobs").fetchone())

time.sleep(1.2)
second = subprocess.run([sys.executable, "worker.py", path], env=env, capture_output=True, text=True)
print("worker 2 says:", second.stdout.strip())
print("final state:", db.execute("SELECT state, attempts FROM jobs").fetchone())
state while worker 1 runs: ('running', 1)
worker 1 killed with kill -9
state right after: ('running', 1)
worker 2 says: jobs done: 1
final state: ('done', 2)

After the kill the job still says running, because nobody told the database. Once the lease expired, the second worker claimed it, and the final state is done with 2 attempts. No job was lost.

Step 3.4: When the lease is too short (about 30 minutes)

Leases have a cost: you must choose the length. Too short, and healthy workers lose their jobs. try_late.py uses a 0.5 second lease on a job that takes 1.5 seconds:

import os
import subprocess
import sys
import time

import taskq

path = "late.db"
for suffix in ("", "-wal", "-shm"):
    if os.path.exists(path + suffix):
        os.remove(path + suffix)
db = taskq.connect(path)
taskq.enqueue(db, "slow", seconds=1.5)  # takes longer than the lease below

env = dict(os.environ, TASKQ_LEASE="0.5")
run = lambda name: subprocess.Popen(
    [sys.executable, "-u", "worker.py", path], env=env,
    stdout=subprocess.PIPE, text=True,
)
a = run("A")
time.sleep(0.8)  # A's lease has run out by now
b = run("B")
print("worker A:", a.communicate()[0].strip().replace("\n", " | "))
print("worker B:", b.communicate()[0].strip().replace("\n", " | "))
print("final:", db.execute("SELECT state, attempts FROM jobs").fetchone())
worker A: job 1 finished too late, another worker owns it now | job 1 finished too late, another worker owns it now | jobs done: 0
worker B: job 1 finished too late, another worker owns it now | jobs done: 0
final: ('dead', 3)

Every worker kept finishing "too late", because the job always outlived its lease, so it bounced between workers until the attempts ran out and it went dead. The fencing check protected us from two workers both marking it done, but it could not make the job fit. The fixes are to set the lease longer than your slowest job, or to let a running job renew its lease with a heartbeat. We leave the heartbeat for "Keep going".

Phase 3 done

A worker can die at any moment and the job comes back. The price is that a job might run twice: a worker that finishes the work and dies just before finish will have its job redone. A queue like this is at least once: every job runs one or more times, never zero. That means handlers should be safe to repeat, for example by checking "was this email already sent?".