Time: an evening. Cost: nothing, if you have an old computer and a database already. Difficulty: you need to be comfortable in a terminal and editing a config file. Some SQL helps; you won't have to write any.

My always-on machine is Nexus, a Raspberry Pi 5. It runs the databases, the dashboards and a dozen small services, and its one job is to be up and quick. The moment I ask it to render a book as a PDF or make preview frames from an hour of video, it stops being that machine for several minutes.

So it doesn't do those jobs. It writes them down, and a second machine does them. That machine is Osgiliath, a 2018 all-in-one with a low-power four-core Pentium and 7.5GB of memory. It was Lynne's old all-in-one, until it reached the end of its life as hers. Since September it has rendered 1,128 preview images and clips for the catalogue where my agents file everything they make, as well as the PDF and ebook editions of my books, and since this Tuesday a new kind of job for fetching media. It's working while I write this.

The interesting part isn't which machine. Any old computer will do. It's how the work gets from one machine to the other, and that's where people reach for a message broker they don't need. This guide builds the whole thing, small enough to read in one sitting: a queue that is just a table, a worker, a way to send it jobs, a way to rescue jobs when a worker dies, and a check that tells you whether the work is actually getting done. I built it from scratch on the same two machines on Thursday 19 November 2026, then pulled the plug on it in every way I could think of. Every number below comes from that afternoon.

Verified 19 November 2026: MariaDB 10.11.18 on a Raspberry Pi 5 (Debian 12, Python 3.11.2); worker on Debian 13.7 with Python 3.13.5; PyMySQL 1.2.4; Pillow 13.0.0.

At the end of this you will have

Why a table and not a message broker

Message brokers are good software for problems you probably don't have: millions of messages, many teams, delivery guarantees across data centres. For "the small machine has some heavy jobs for the big one", a table does everything you need, and it has two advantages a broker doesn't. You can see the whole queue with one SELECT. And every job leaves a row behind: who asked, when, which machine did it, how long it took, what came back, and what went wrong. That history is how you answer questions later, and it costs nothing.

If you already run MariaDB or MySQL, you already run a job queue. You just haven't made the table yet.

Before you start

Have

Decide

Step 1: Make the queue

On the always-on machine, create a database and a user for the queue, then the two tables. Connect as an administrator (sudo mysql on most Linux systems) and run this, with your own password:

CREATE DATABASE job_queue;
CREATE USER 'queue'@'%' IDENTIFIED BY 'choose-a-long-password';
GRANT SELECT, INSERT, UPDATE, DELETE ON job_queue.* TO 'queue'@'%';

The '%' lets that user connect from other machines. It can only touch this one database, and only rows, not tables. Then load the tables from the kit:

sudo mysql job_queue < schema.sql

That file is short enough to read in full, and worth reading, because it's the whole design:

CREATE TABLE jobs (
  id           BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  job_type     VARCHAR(40)  NOT NULL,                 -- which handler runs it
  input        JSON         NOT NULL,                 -- what it needs, e.g. {"path": "/data/scan.jpg"}
  status       ENUM('queued','claimed','complete','failed') NOT NULL DEFAULT 'queued',
  priority     TINYINT      NOT NULL DEFAULT 5,       -- lower runs first
  submitted_by VARCHAR(60)  NOT NULL,                 -- who asked
  claimed_by   VARCHAR(60)  NULL,
  claimed_at   DATETIME     NULL,
  completed_at DATETIME     NULL,
  attempts     TINYINT UNSIGNED NOT NULL DEFAULT 0,   -- counted when a job is CLAIMED
  result       JSON         NULL,                     -- small: a path, a size, a checksum
  error        TEXT         NULL,
  created_at   DATETIME     NOT NULL DEFAULT CURRENT_TIMESTAMP,
  KEY idx_next (status, priority, created_at)
);

CREATE TABLE workers (
  name         VARCHAR(60)  PRIMARY KEY,
  heartbeat_at DATETIME     NOT NULL,
  state        JSON         NOT NULL                  -- what it's doing, and what it can do
);

Two columns look like bookkeeping and aren't. submitted_by records who asked. The moment more than one thing sends work, "where did all these jobs come from?" stops being answerable any other way, and you'll want the answer most on the day something floods the queue. attempts is counted when a job is taken, not when it fails, and that one decision is what stops a job that crashes its worker from going round forever. More on that in "How it works".

Finally, the database has to accept connections from the network. On Debian-style systems, find bind-address in the files under /etc/mysql/, set it to 0.0.0.0, and restart the database. If it's already set that way, leave it. Don't open the database port to the internet: this is for machines in your house.

What you should see: sudo mysql job_queue -e "SHOW TABLES" lists jobs and workers.

Step 2: Put the kit on both machines

Download it: a-second-pair-of-hands.zip. Copy it to both machines, unzip it, and in the kit folder on each:

python3 -m venv .venv
.venv/bin/pip install pymysql pillow

That took 10 seconds on Osgiliath. Pillow is only needed on a machine that will make thumbnails. Leave it out and that machine simply won't offer them, which the next steps will show you.

a-second-pair-of-hands/
  schema.sql            the two tables
  queue_common.py       connecting (and waiting), and the one rule for giving up
  worker.py             runs on the second machine: takes jobs and does them
  enqueue.py            runs anywhere: puts a job on the queue
  sweep.py              runs every few minutes: rescues jobs from workers that died
  status.py             is the work getting done? exits 1 if not
  queue-worker.service  makes the worker start with the machine
  config.example.json   copy to config.json

Copy config.example.json to config.json on each machine and fill in your database's address, the user and password from step 1, and job_queue. That file holds a password, so make it readable only by you: chmod 600 config.json.

What you should see: on the second machine, .venv/bin/python -c "from queue_common import connect; connect()" prints nothing and returns. If it prints database unreachable … retrying, the address, password or bind-address is wrong; press Ctrl+C and check them.

Step 3: Start a worker

On the second machine, run it in the foreground first so you can watch:

.venv/bin/python worker.py

What you should see:

Osgiliath: worker up, handling sha256, sleep, thumbnail

The worker names itself after the machine, and tells you exactly which job types it can do. sleep is a job that takes as long as you tell it, for testing. If thumbnail is missing, Pillow isn't installed in this machine's .venv.

Step 4: Send it a job

On the always-on machine, or any machine with the kit and a config.json, ask the worker to checksum a file that's on its disk, and wait for the answer:

.venv/bin/python enqueue.py sha256 '{"path": "/tmp/hands-1g.bin"}' --wait

Mine was a 1GB file. This is what came back:

queued job 1 (sha256)
complete after 7.0s, 1 attempt(s)
{"sha256": "c6549066de62aaf9…", "bytes": 1073741824, "seconds": 1.99}

Two seconds of work, seven seconds door to door. The difference is the worker's polling: when the queue is empty it looks every five seconds, so a job can wait up to five seconds to be noticed. For jobs that take minutes, that doesn't matter. If it matters to you, make POLL smaller in worker.py; every look is one small query, about 17,000 a day at five seconds, which an idle database won't notice.

Now try one that can't work, a file that doesn't exist:

.venv/bin/python enqueue.py sha256 '{"path": "/tmp/no-such-file.iso"}' --wait

queued job 3 (sha256)
failed after 5.0s, 1 attempt(s)
Permanent: no such file on Osgiliath: '/tmp/no-such-file.iso'

What you should see: the first job complete, the second failed after one attempt, with a message that names the machine. One attempt matters. A missing file won't appear if you try again, and retrying it is just a slower way of being wrong.

Step 5: Ask whether the work is getting done

.venv/bin/python status.py

To see it catch something, first send a job type no worker handles: .venv/bin/python enqueue.py ocr '{"path": "/tmp/scan.pdf"}'. This is what it printed for me:

Workers
  Osgiliath      heartbeat     0s ago  idle  done 2 failed 1  handles sha256, sleep, thumbnail
Queue  queued 1  claimed 0  complete 2  failed 1
  sha256            1 done, longest 2s
  thumbnail         1 done, longest 0s
Checks
  PASS  a worker has checked in recently             1 of 1 within 120s
  FAIL  every waiting job type has a live worker     nobody handles: ocr
  PASS  work is moving                               oldest waiting job: 0s
  PASS  nothing stuck mid-job                        0 claimed over 15 min ago
Failed in the last day: 1
  job 3 sha256 after 1 attempt(s): Permanent: no such file on Osgiliath: '/tmp/no-such-file.iso'

That FAIL is the reason the worker publishes what it can do. Without it, a job nobody can handle looks exactly like a job that hasn't been reached yet, and it sits there looking patient until somebody wonders where their PDF went. Delete the test job (sudo mysql job_queue -e "DELETE FROM jobs WHERE job_type = 'ocr'" on the database machine) and run it again for four PASSes.

What you should see: four PASS lines, and an exit code of 0 (echo $?). It exits 1 if anything fails, so you can run it from cron and get told.

Step 6: Make it permanent

Stop the foreground worker with Ctrl+C and make it a service, so it starts with the machine and comes back if it dies. Edit queue-worker.service: put your username in User= and your kit folder in the two paths. Then:

sudo cp queue-worker.service /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl enable --now queue-worker

Two lines in that file are worth knowing about. Restart=always with RestartSec=5 brings the worker back five seconds after it dies. I killed mine with kill -9 and it was back in exactly five. MemoryMax=4G and CPUQuota=75% stop a runaway job from taking the whole machine with it. They're the same limits the real worker on Osgiliath runs with.

If you don't have sudo on the worker and are tempted to run it as a user service (systemctl --user) instead, know one thing first: a user service stops when you log out, unless "lingering" is turned on for your account (loginctl enable-linger, which usually needs an administrator once). I found this out the obvious way. My test worker ran perfectly while I was logged in, passed the restart test, and was stopped cleanly by the system twelve seconds after I closed my session. Nothing failed. It just wasn't there any more.

Then, on the always-on machine, run the sweeper every five minutes. crontab -e and add:

*/5 * * * *  cd /home/YOU/second-pair-of-hands && .venv/bin/python sweep.py

The sweeper looks for jobs that were taken more than fifteen minutes ago and never finished, which means the worker died mid-job, and puts them back, or gives up on them if they've had their three attempts. Fifteen minutes has to be longer than your slowest real job, or the sweeper will steal jobs that are still running. Don't guess it: status.py prints the longest run of each job type, so set it from that with plenty of room, using --stale. If you change it, change STALE_CLAIM in status.py to match.

What you should see: systemctl status queue-worker says active (running), with its memory limit shown, and status.py still shows a recent heartbeat.

Step 7: Add your own job

A job type is one Python function in worker.py that takes the job and returns a small dictionary. Here's the checksum one:

def do_sha256(job):
    path = need_file(job)          # check the input FIRST
    h, n, t = hashlib.sha256(), 0, time.time()
    with open(path, 'rb') as f:
        for chunk in iter(lambda: f.read(1 << 20), b''):
            h.update(chunk)
            n += len(chunk)
    return {'sha256': h.hexdigest(), 'bytes': n, 'seconds': round(time.time() - t, 2)}

HANDLERS = {'sha256': do_sha256, 'sleep': do_sleep}

Add yours to HANDLERS and restart the worker, and it starts offering the new type straight away. Three rules make the difference between a handler that's easy to live with and one that isn't:

Don't register a job type you haven't written yet. A stand-in that says "not implemented" is a promise the worker can't keep, and the status check will believe it. If the function isn't there, the worker doesn't claim the job, and status.py says nobody handles it, which is true.

What you should see: after a restart, the worker's first line lists your new type, and so does its row in status.py.

How it works

The claim: eight words and a check

Everything depends on this. When two workers reach for the next job at the same moment, only one may get it. The obvious way (find the oldest queued job, then mark it taken) has a gap between the two steps, and two workers can both fall into it. The kit closes the gap like this:

SELECT id, job_type, input FROM jobs
 WHERE status = 'queued' AND job_type IN (…the types this worker handles…)
 ORDER BY priority, created_at
 LIMIT 1 FOR UPDATE SKIP LOCKED;

UPDATE jobs SET status = 'claimed', claimed_by = ?, claimed_at = NOW(), attempts = attempts + 1
 WHERE id = ? AND status = 'queued';

Both run inside one transaction. FOR UPDATE SKIP LOCKED tells the database: lock the row I picked, and if another worker has already locked one, don't wait for it, skip it and give me the next. Workers never queue up behind each other and never pick the same row. The AND status = 'queued' on the update, plus checking that it changed exactly one row, is the belt to go with those braces: claim it, then check you won.

I measured what that buys. Four workers, three on Osgiliath and one on the Pi, against 400 tiny jobs: all 400 finished in five seconds, and the workers' own logs show every job ran exactly once. The four workers took 124, 119, 117 and 40 of them. Then I ran the same test with the obvious version, no SKIP LOCKED and no check: 654 runs for 400 jobs. 226 jobs ran twice and 14 ran three times. And the table said all 400 were complete, with nothing to show anything had gone wrong. Those were deliberately tiny jobs, which is the worst case. With real jobs taking minutes the collisions are rarer, and that's worse, because rare is how a bug survives.

Counting attempts when a job is taken

A worker can die without any chance to record why: kill -9, a power cut, a kernel update. If attempts were counted when a job failed, a job that kills its worker would never fail. It would be rescued, retried, kill the worker again, forever. So the kit counts an attempt when a job is taken, and both the worker (when a job raises an error) and the sweeper (when a worker vanished) hand the job to the same function, finish_failed, which puts it back or gives up based on that count. There is exactly one place the rule lives, so nobody can skip it.

The heartbeat says what the worker can do

Every thirty seconds, and whenever it starts or finishes a job, the worker writes one row: busy or idle, which job, how many done and failed, and the list of job types it can handle. That's how the always-on machine can tell, without logging in to anything, that the worker is there and whether anyone can do the job you're about to send. That list is the best line in my real worker, and it was nearly an afterthought.

When the database goes away

The worker connects through connect(), which, when the database can't be reached, waits and tries again, doubling the wait each time up to a minute, for up to ten minutes before giving up. If a connection drops while it's running, the worker notices, reconnects and carries on. Why both matter is the first item in the next section.

The ways it lied to me

Every one of these reported success, reported nothing, or looked healthy while something was wrong. Most are from my real worker over the summer, and every fix is built into the kit. The last is from this afternoon.

The check that catches all of them

Every item in that list is a version of the same mistake: confusing "running" with "doing the job". A worker in a crash loop is running. A worker with a dead connection is running. A worker that can't handle the job you sent is running. So status.py doesn't ask whether the worker is running. It asks four questions about the work:

Run it from cron on the always-on machine, every fifteen minutes say, and have cron mail you, or pipe it into whatever alerting you already have, when it exits 1. Then check the check. A check that has never failed hasn't been tested, so these are the drills I ran against the kit this afternoon. They're worth running against yours once, before you rely on it:

What I didWhat should happenWhat happened
Sent a job type no worker handlesstatus.py failsFAIL nobody handles: ocr
Sent a job for a file that doesn't existFails once, permanentlyfailed, 1 attempt, message names the machine
Four workers, 400 jobsEvery job runs once400 runs, all once, in 5 seconds
Same, without SKIP LOCKED(the control)654 runs; table still said 400 complete
kill -9 on the worker mid-job, then sweptJob goes back and finishesfinished on attempt 2
Killed the worker every time one job ranGives up after 3 attemptsqueued, queued, failed
Killed the worker's connection at the databaseReconnects, no restartreconnected; next job done in 7 seconds
Started a worker with the database unreachableWaits, doesn't crash7 lines in 70 seconds, backing off to a minute
kill -9 on the worker serviceBack within 5 secondsback in exactly 5

What it costs

Money: nothing, if you have the machines. MariaDB, Python, PyMySQL and Pillow are free, and my second machine is Lynne's old all-in-one.

Setup: an evening. Most of it is step 1 and getting the two machines to talk. The software installs in ten seconds.

Running it: almost nothing. Idle, looking at the queue every five seconds, the worker on Osgiliath used 25MB of memory and 0.29 seconds of processor time in ten and a half minutes, which is about forty seconds a day. Busy, it uses whatever the job needs, up to the limits you set in step 6. The checksum of a 1GB file took two seconds; four workers got through 400 small jobs in five.

My real worker on Osgiliath, which carries eight job types and the heavier tools behind them, was using 10.9MB of memory and had used 32.6 seconds of processor time in the 23 hours since its last restart.

Getting an assistant to do this for you

You don't need to write any of it yourself. The useful prompts are about the rules, and an assistant will follow them well if you state them:

The last one is the habit to keep. When an assistant writes recovery code, ask it to break the thing on purpose and show you the recovery. The real worker's reconnect fix was correct for days before anything called it, and reading it wouldn't have told you.

What I actually use it for

Nexus never renders anything. When one of my agents finishes a book, the PDF and the ebook are built on Osgiliath: 19 PDFs and 14 ebooks since July, each one a row I can look back at. When an agent makes a video, a picture or a map, it goes into a catalogue my agents call the Wharf, and Osgiliath makes the preview frames. That's 1,128 jobs since the middle of September, and it's the reason I can find a piece of footage from a thumbnail instead of reading filenames. This week a new job type for fetching media went in alongside the others, without touching the queue.

The point isn't speed. Osgiliath is slow. The point is that the always-on machine is never the one doing the heavy lifting, so it's always quick, and the old machine doesn't care how long anything takes because nobody's sitting at it. The job queue that makes that work is one table, and it'll outlast several fashions in message brokers.

The code

Everything is in the zip. These two files are the heart of it, here so you can read them before you run them, which you should do with anything from the internet, mine included.

worker.py

"""worker.py — runs on the second machine. Takes jobs off the queue and does them.

    python worker.py            # run until stopped
    python worker.py --once     # take one job if there is one, then exit (handy for testing)
"""
import hashlib
import json
import os
import socket
import sys
import time

import pymysql

from queue_common import connect, finish_failed

NAME = os.environ.get('WORKER_NAME') or socket.gethostname()
POLL = 5          # seconds between looks at an empty queue
HEARTBEAT = 30    # seconds between "I'm alive" updates
OUT = os.environ.get('WORKER_OUT') or os.path.join(os.path.dirname(os.path.abspath(__file__)), 'output')


class Permanent(Exception):
    """This job can never succeed (bad input, missing file). Don't retry it."""


def need_file(job):
    path = job['input'].get('path')
    if not path or not os.path.isfile(path):
        raise Permanent(f'no such file on {NAME}: {path!r}')
    return path


# ---- Handlers. One function per job type. Check the input FIRST, then do the work. ----------

def do_sha256(job):
    path = need_file(job)
    h, n, t = hashlib.sha256(), 0, time.time()
    with open(path, 'rb') as f:
        for chunk in iter(lambda: f.read(1 << 20), b''):
            h.update(chunk)
            n += len(chunk)
    return {'sha256': h.hexdigest(), 'bytes': n, 'seconds': round(time.time() - t, 2)}


def do_sleep(job):
    """A job that takes as long as you tell it. For testing the queue, not for real work."""
    s = float(job['input'].get('seconds', 1))
    time.sleep(s)
    return {'slept': s}


HANDLERS = {'sha256': do_sha256, 'sleep': do_sleep}

try:  # Thumbnails need Pillow. If it isn't installed, this worker simply doesn't offer them.
    from PIL import Image

    def do_thumbnail(job):
        path = need_file(job)
        try:
            img = Image.open(path)
            img.thumbnail((int(job['input'].get('size', 320)),) * 2)
        except OSError as e:
            raise Permanent(f'not an image Pillow can read: {e}')
        os.makedirs(OUT, exist_ok=True)
        out = os.path.join(OUT, f"thumb-{job['id']}.jpg")
        img.convert('RGB').save(out, quality=85)
        return {'thumbnail': out, 'width': img.width, 'height': img.height, 'on': NAME}

    HANDLERS['thumbnail'] = do_thumbnail
except ImportError:
    pass


# ---- The loop ----------------------------------------------------------------------------

def claim(db):
    """Take the next job nobody else has. The two statements that make this safe:

    FOR UPDATE SKIP LOCKED: lock the row I picked, and skip any row another worker has
    locked, instead of waiting for it. Then claim it only if it's STILL queued, and only
    treat it as mine if that update actually changed a row.
    """
    types = list(HANDLERS)  # only ask for work this machine can actually do
    with db.cursor() as cur:
        cur.execute('START TRANSACTION')
        cur.execute(
            f"""SELECT id, job_type, input FROM jobs
                 WHERE status = 'queued' AND job_type IN ({','.join(['%s'] * len(types))})
                 ORDER BY priority, created_at
                 LIMIT 1 FOR UPDATE SKIP LOCKED""", types)
        job = cur.fetchone()
        if not job:
            cur.execute('ROLLBACK')
            return None
        cur.execute(
            """UPDATE jobs SET status = 'claimed', claimed_by = %s, claimed_at = NOW(),
                               attempts = attempts + 1
                WHERE id = %s AND status = 'queued'""", (NAME, job['id']))
        if cur.rowcount != 1:      # somebody beat us to it
            cur.execute('ROLLBACK')
            return None
        cur.execute('COMMIT')
    job['input'] = json.loads(job['input'])
    return job


def heartbeat(db, state, job, done, failed):
    with db.cursor() as cur:
        cur.execute(
            """INSERT INTO workers (name, heartbeat_at, state) VALUES (%s, NOW(), %s)
               ON DUPLICATE KEY UPDATE heartbeat_at = NOW(), state = VALUES(state)""",
            (NAME, json.dumps({'state': state, 'job': job, 'done': done, 'failed': failed,
                               'handlers': sorted(HANDLERS), 'pid': os.getpid()})))


def main():
    once = '--once' in sys.argv
    db = connect()
    done = failed = 0
    last_beat = 0
    print(f'{NAME}: worker up, handling {", ".join(sorted(HANDLERS))}', flush=True)
    while True:
        try:
            if time.time() - last_beat >= HEARTBEAT:
                heartbeat(db, 'idle', None, done, failed)
                last_beat = time.time()
            job = claim(db)
            if not job:
                if once:
                    return
                time.sleep(POLL)
                continue
            heartbeat(db, 'busy', job['id'], done, failed)
            last_beat = time.time()
            started = time.time()
            try:
                result = HANDLERS[job['job_type']](job)
                with db.cursor() as cur:
                    cur.execute("""UPDATE jobs SET status = 'complete', completed_at = NOW(), result = %s,
                                          error = NULL WHERE id = %s""", (json.dumps(result), job['id']))
                done += 1
                print(f"done {job['id']} {job['job_type']} in {time.time() - started:.1f}s", flush=True)
            except Exception as e:
                with db.cursor() as cur:
                    finish_failed(cur, job['id'], f'{type(e).__name__}: {e}', isinstance(e, Permanent))
                failed += 1
                print(f"FAILED {job['id']} {job['job_type']}: {e}", flush=True)
            last_beat = 0  # report idle straight away, not up to 30 seconds later
            if once:
                return
        except (pymysql.err.OperationalError, pymysql.err.InterfaceError) as e:
            # The database went away under us. Catching this is only half the fix:
            # a worker that catches it and carries on with the dead connection looks
            # healthy forever and never claims anything again. Reconnect.
            print(f'lost the database ({e}); reconnecting', flush=True)
            try:
                db.close()
            except Exception:
                pass
            db = connect()


if __name__ == '__main__':
    main()

queue_common.py

"""Shared by every script: how to reach the database, and the one rule about giving up."""
import json
import os
import sys
import time

import pymysql

HERE = os.path.dirname(os.path.abspath(__file__))
MAX_ATTEMPTS = 3          # a job gets this many goes, however it fails
CONNECT_PATIENCE = 600    # seconds to keep trying to reach the database before giving up


def config():
    with open(os.environ.get('QUEUE_CONFIG') or os.path.join(HERE, 'config.json')) as f:
        return json.load(f)


def connect(quiet=False):
    """Connect, and if the database is away, WAIT for it rather than dying.

    A worker that crashes when the database is unreachable gets restarted, crashes again,
    and turns a five-minute outage into thousands of identical errors. Waiting is the job.
    The patience is bounded on purpose: a database that's gone for ten minutes is worth
    someone noticing, and an exit is something a service manager can see.
    """
    cfg = config()
    delay, waited = 1, 0
    while True:
        try:
            return pymysql.connect(host=cfg['host'], user=cfg['user'], password=cfg['password'],
                                   database=cfg['database'], autocommit=True, connect_timeout=10,
                                   cursorclass=pymysql.cursors.DictCursor)
        except pymysql.err.OperationalError as e:
            if waited >= CONNECT_PATIENCE:
                print(f'database still unreachable after {waited}s, giving up: {e}', flush=True)
                sys.exit(1)
            if not quiet:
                print(f'database unreachable ({e.args[1] if len(e.args) > 1 else e}); retrying in {delay}s', flush=True)
            time.sleep(delay)
            waited += delay
            delay = min(delay * 2, 60)


def finish_failed(cur, job_id, error, permanent=False):
    """The ONLY place a failed or abandoned job is put back or given up on.

    The worker calls it when a job throws. The sweeper calls it when a worker vanished
    mid-job. Both go through here, so both obey the same limit. Attempts were counted
    when the job was claimed, so a job that kills its worker every time still runs out.
    """
    cur.execute(
        """UPDATE jobs
              SET status = IF(%s OR attempts >= %s, 'failed', 'queued'),
                  error = %s, claimed_by = NULL, claimed_at = NULL,
                  completed_at = IF(%s OR attempts >= %s, NOW(), NULL)
            WHERE id = %s""",
        (permanent, MAX_ATTEMPTS, str(error)[:2000], permanent, MAX_ATTEMPTS, job_id))