Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Concept · 20 min · revision 3

Designing Jobs for At-Least-Once Delivery

Make job handlers safe to run more than once, and give every job bounded retries with backoff and jitter, time limits that fit inside the visibility timeout, and a dead-letter table you can replay from.

Contentsand lesson path

What you will learn

  • Make jobs safe under at-least-once delivery with idempotent handlers, bounded retries with backoff, time limits and a dead-letter path.

01. Why it matters

A worker finishes a job and sends an acknowledgement (an ack); the broker then deletes the message. If the ack is lost, or the worker dies before sending it, the broker cannot tell this from a job that never ran, so it delivers the job again. Consumers that ack after processing (on RabbitMQ, SQS, Kafka) therefore deliver at least once, with duplicates. Celery does this only with acks_late=True; by default it acks just before the task runs, so a worker crash loses the task.

Narrower exactly-once features exist (Kafka transactions, SQS FIFO deduplication within five minutes), but none can make a card charge or an email in another system happen exactly once.

Jobs also fail and hang. A job that retries forever, or hangs without failing, can block a queue for days. This lesson covers both halves: handlers that tolerate duplicates, and the retry, time-limit and dead-letter rules around them.

02. At-most-once and at-least-once

With at-most-once delivery the message is removed as soon as a worker receives it (ack on receive). If the worker crashes mid-job, the job is gone. That suits only data nobody misses, such as a live cursor position.

With at-least-once delivery the broker keeps the message in flight and deletes it only when the worker acks after finishing (ack on finish, called late ack in Celery). If the worker crashes or its time runs out, the message becomes visible again and another worker gets it. This prevents loss from worker crashes, at the price of duplicates, but not every loss: a broker that loses its own data (Redis without persistence, an unreplicated disk), a message that expires under the queue's retention limit before anyone processes it, or a job dropped after too many attempts with no dead-letter queue are still lost.

What vendors call "exactly-once processing" is at-least-once delivery plus an idempotent handler: the job may run twice, but the second run changes nothing.

03. Making a handler idempotent

An operation is idempotent when running it twice leaves the same state as running it once. Three patterns cover most handlers:

  • Absolute state changes. Instead of balance = balance - 50, write UPDATE orders SET status = 'paid' WHERE id = :id AND status = 'pending'. A second run matches zero rows and changes nothing.
  • A unique idempotency key. Derive one key per business operation, such as payment_{order_id} or the event id the producer put in the message. Never use anything that changes between deliveries, such as an attempt counter or a timestamp. Insert the key into a table with a UNIQUE constraint; when the insert fails, the work was already done.
  • Pass the key to the other system. Payment providers such as Stripe accept an idempotency key and return the first result when they see it again.

The handler below uses all three.

Python · excerpt: idempotent task handler (app modules not shown)
import asyncio
import logging

from sqlalchemy import update

from app.db import AsyncSessionLocal
from app.models import Order
from app.payment_gateway import charge_card

logger = logging.getLogger("worker.tasks")


async def process_order_payment(order_id: str, idempotency_key: str):
    """One charge per key, however often the task is delivered."""
    # 1. Short transaction: claim the order. 'charging' is claimable again,
    #    so a delivery that crashed mid-charge can be finished by a retry.
    async with AsyncSessionLocal() as session, session.begin():
        order = (await session.execute(
            update(Order)
            .where(Order.id == order_id,
                   Order.status.in_(("pending", "charging")))
            .values(status="charging")
            .returning(Order.total_cents)
        )).one_or_none()
    if order is None:
        logger.info("Order %s missing or already paid; skipping", order_id)
        return

    # 2. No transaction and no row lock are held during the network call.
    #    The same key on every delivery makes the gateway return one charge.
    charge = await asyncio.wait_for(
        charge_card(amount_cents=order.total_cents,
                    idempotency_key=idempotency_key),
        timeout=10,
    )

    # 3. Second short transaction: record the result.
    async with AsyncSessionLocal() as session, session.begin():
        await session.execute(
            update(Order)
            .where(Order.id == order_id, Order.status == "charging")
            .values(status="paid", transaction_ref=charge.transaction_id)
        )
    logger.info("Successfully charged order %s", order_id)

Follow three deliveries of the same task, each with the key payment_order_123:

  • First delivery: the conditional UPDATE moves the order from pending to charging and commits. The worker charges the card with the key and records paid in a second short transaction.
  • Later deliveries: the claim matches no row (the order is paid), so the worker returns.
  • A crash between charge and record: the order stays in charging, which a retry may claim again. The retry sends the same key, and the gateway returns the existing charge instead of making a second one.

No transaction or row lock is held during the network call, so a slow gateway cannot pin a database connection (see the blockers and deadlocks lab). The price is a visible charging state.

A distributed lock (for example Redis SET key token NX PX 30000) is not idempotency: a worker that pauses longer than the lease loses the lock while it keeps running. Treat locks as an optimisation and keep the truth in conditional updates and unique constraints.

04. Retries, time limits and a dead-letter path

Idempotency makes retries safe. Four rules make them useful.

  1. Retry only transient errors. A timeout, a refused connection, a 429 or a 5xx may succeed later. A validation error, a missing record or another 4xx will fail the same way every time, so send it straight to the dead-letter path.
  2. Bound the attempts. Set a maximum, for example 4 attempts in total as in the demo below. Unbounded retries make one bad job permanent load.
  3. Back off exponentially, with jitter. Wait roughly 1, 2, 4, 8 seconds between attempts, up to a cap, so a struggling service has time to recover. Jitter (a random part of the delay) stops a thousand jobs that failed together from retrying in the same second.
  4. Turn hangs into failures. A job stuck on a network read never fails, so retries and dead-lettering never see it while it holds a worker. Give every network call its own timeout, and give each task a hard time limit after which the worker kills it.

Time limits interact with the visibility timeout (the lease in the code below): how long the broker hides a claimed message before handing it to another worker. It must be longer than the task's hard time limit. If a job takes 90 seconds and the visibility timeout is 60, a second worker starts the same job while the first is still running. SQS defaults to 30 seconds; a long job can extend it while it works (ChangeMessageVisibility, up to 12 hours in total). Keep the order: call timeouts < task time limit < visibility timeout.

When a job runs out of attempts or fails permanently, move it to a dead-letter queue (DLQ) or table with its last error, and alert when anything arrives there. A DLQ is a holding area, not a bin: after fixing the cause, replay the job with a fresh attempt budget. Idempotent handlers make replay safe.

The runnable queue below implements the retry, lease and dead-letter rules on PostgreSQL; the Celery excerpt after it adds time limits. You need Python 3.12 or later with psycopg[binary] (tested with Python 3.13 and psycopg 3.3.9) and PostgreSQL (tested on 17.12), for example docker run -d --name jobs-pg -e POSTGRES_USER=jobs -e POSTGRES_PASSWORD=jobs -p 5432:5432 postgres:17-alpine. Set DATABASE_URL if yours differs.

Python · jobqueue.py (part 1: tables and backoff)
import os
import random
from datetime import timedelta

import psycopg
from psycopg.types.json import Jsonb

DSN = os.environ.get("DATABASE_URL", "postgresql://jobs:[email protected]:5432/jobs")
LEASE = timedelta(seconds=30)  # visibility timeout: longer than any run
BASE, CAP = 1.0, 60.0          # backoff: 1 s doubling, never above 60 s
rng = random.Random(7)         # seeded so the demo prints the same delays

SCHEMA = """
DROP TABLE IF EXISTS jobs, dead_jobs;
CREATE TABLE jobs (
  id           bigserial PRIMARY KEY,
  kind         text NOT NULL,
  payload      jsonb NOT NULL,
  attempts     int NOT NULL DEFAULT 0,
  max_attempts int NOT NULL DEFAULT 4,
  visible_at   timestamptz NOT NULL,
  last_error   text
);
CREATE TABLE dead_jobs (
  id bigint PRIMARY KEY, kind text NOT NULL, payload jsonb NOT NULL,
  attempts int NOT NULL, last_error text, died_at timestamptz NOT NULL
);
"""


class Permanent(Exception):
    """Retrying cannot help: bad input, missing record, 4xx from a partner."""


def enqueue(conn, kind, payload, now):
    sql = "INSERT INTO jobs (kind, payload, visible_at) VALUES (%s, %s, %s)"
    conn.execute(sql, (kind, Jsonb(payload), now))


def backoff(attempt):
    """Exponential backoff with full jitter: random in [0, min(cap, base*2^n)]."""
    return rng.uniform(0, min(CAP, BASE * 2 ** (attempt - 1)))
Python · jobqueue.py (part 2: claim, succeed, fail, replay)
def claim(conn, now):
    """Take one visible job and hide it for LEASE. Counts as an attempt."""
    return conn.execute(
        """UPDATE jobs SET attempts = attempts + 1, visible_at = %(now)s + %(lease)s
           WHERE id = (SELECT id FROM jobs WHERE visible_at <= %(now)s
                       ORDER BY visible_at, id LIMIT 1 FOR UPDATE SKIP LOCKED)
           RETURNING id, kind, payload, attempts, max_attempts""",
        {"now": now, "lease": LEASE},
    ).fetchone()


def succeed(conn, job_id):
    conn.execute("DELETE FROM jobs WHERE id = %s", (job_id,))


def fail(conn, job, err, now):
    """Retry later with backoff, or move the job to dead_jobs."""
    job_id, _, _, attempts, max_attempts = job
    if isinstance(err, Permanent) or attempts >= max_attempts:
        conn.execute(
            """WITH gone AS (DELETE FROM jobs WHERE id = %s
                             RETURNING id, kind, payload, attempts)
               INSERT INTO dead_jobs SELECT *, %s, %s FROM gone""",
            (job_id, repr(err), now))
        return None
    delay = backoff(attempts)
    conn.execute(
        "UPDATE jobs SET visible_at = %s, last_error = %s WHERE id = %s",
        (now + timedelta(seconds=delay), repr(err), job_id))
    return delay


def replay(conn, job_id, now):
    """Put a dead job back in the queue with a fresh attempt budget."""
    conn.execute(
        """WITH back AS (DELETE FROM dead_jobs WHERE id = %s
                         RETURNING id, kind, payload)
           INSERT INTO jobs (id, kind, payload, visible_at)
           SELECT id, kind, payload, %s FROM back""",
        (job_id, now))

One column, visible_at, serves as both the visibility timeout and the retry delay. Claiming a job pushes it one lease into the future, so if the worker dies, the job reappears when the lease ends; a failure sets it to the backoff time. claim counts the attempt before the job runs, so a job that crashes the worker every time still uses up its attempts. SKIP LOCKED lets several workers claim different rows at once.

The demo drives one worker with a fake clock (t, in seconds), so it finishes at once instead of waiting out real delays. Its four jobs cover four cases: an email that times out twice, an export with a bad payload, a webhook to a partner that is down, and a report whose worker is killed mid-job.

Python · demo.py (part 1: fake handlers)
from datetime import datetime, timezone

import psycopg

from jobqueue import (DSN, SCHEMA, Permanent, claim, enqueue, fail, replay,
                      succeed)

START = datetime(2026, 11, 17, 9, 0, tzinfo=timezone.utc)  # fake clock
partner_up = False


def handle(kind, payload, attempt):
    if kind == "email" and attempt < 3:
        raise TimeoutError("SMTP read timed out")  # transient
    if kind == "export" and "user_id" not in payload:
        raise Permanent("payload has no user_id")  # retrying cannot help
    if kind == "webhook" and not partner_up:
        raise ConnectionError("partner returned 503")  # transient


def t(now):
    return (now - START).total_seconds()  # fake-clock seconds since START


def log(now, job, text):
    print(f"t={t(now):5.2f} job {job[0]} {job[1]:<7} try {job[3]}: {text}")
Python · demo.py (part 2: the worker loop and the run)
def work(conn, now):
    """One worker, driven by the fake clock, until the queue is empty."""
    while True:
        with conn.transaction():
            job = claim(conn, now)
        if job is None:
            nxt = conn.execute("SELECT min(visible_at) FROM jobs").fetchone()[0]
            if nxt is None:
                return now
            now = nxt  # jump ahead instead of sleeping
            continue
        if job[1] == "report" and job[3] == 1:
            log(now, job, "worker killed mid-job, no ack")
            continue  # the lease runs out and the job becomes visible again
        try:
            if job[3] > job[4]:
                raise Permanent("lease expired on every attempt")
            handle(job[1], job[2], job[3])
        except Exception as err:
            with conn.transaction():
                delay = fail(conn, job, err, now)
            where = "dead_jobs" if delay is None else f"retry at t={t(now) + delay:.2f}"
            log(now, job, f"{type(err).__name__} -> {where}")
        else:
            with conn.transaction():
                succeed(conn, job[0])
            log(now, job, "done")


with psycopg.connect(DSN, autocommit=True) as conn:
    conn.execute(SCHEMA)
    enqueue(conn, "email", {"to": "[email protected]"}, START)
    enqueue(conn, "export", {"format": "csv"}, START)
    enqueue(conn, "webhook", {"order": 42}, START)
    enqueue(conn, "report", {"month": "2026-10"}, START)
    now = work(conn, START)
    for row in conn.execute("SELECT id, kind, attempts, last_error FROM dead_jobs"):
        print("dead:", *row)
    partner_up = True  # someone fixed the cause, then replays job 3
    with conn.transaction():
        replay(conn, 3, now)
    work(conn, now)
Expected output (python demo.py)
t= 0.00 job 1 email   try 1: TimeoutError -> retry at t=0.32
t= 0.00 job 2 export  try 1: Permanent -> dead_jobs
t= 0.00 job 3 webhook try 1: ConnectionError -> retry at t=0.15
t= 0.00 job 4 report  try 1: worker killed mid-job, no ack
t= 0.15 job 3 webhook try 2: ConnectionError -> retry at t=1.45
t= 0.32 job 1 email   try 2: TimeoutError -> retry at t=0.47
t= 0.47 job 1 email   try 3: done
t= 1.45 job 3 webhook try 3: ConnectionError -> retry at t=3.60
t= 3.60 job 3 webhook try 4: ConnectionError -> dead_jobs
t=30.00 job 4 report  try 2: done
dead: 2 export 1 Permanent('payload has no user_id')
dead: 3 webhook 4 ConnectionError('partner returned 503')
t=30.00 job 3 webhook try 1: done

The email succeeds on its third try. The export is dead-lettered after one try, because retrying a bad payload cannot help. The webhook's delay ceiling doubles each time (1, 2, 4 seconds), jitter picks a random point below it, and after the fourth attempt the job is dead-lettered with its last error. The report's worker died without acking, so the job waited until the 30-second lease ran out, then ran again. Once the partner is back, replaying job 3 succeeds on a fresh first try. The delays repeat on every run only because the random generator is seeded.

Python · tasks.py, configuration excerpt for Celery 5.7 (not run against a broker)
import httpx
from celery import Celery

app = Celery("exports", broker="redis://localhost:6379/0")
# Redis redelivers an unacknowledged task after this many seconds: keep it
# above time_limit and above the longest retry delay, or tasks run twice.
app.conf.broker_transport_options = {"visibility_timeout": 3600}


class PartnerUnavailable(Exception):
    """429 or 5xx from the partner: worth trying again later."""


@app.task(
    autoretry_for=(httpx.TransportError, PartnerUnavailable),  # transient only
    retry_backoff=2,        # about 2, 4, 8, 16 ... seconds before each retry
    retry_backoff_max=600,  # but never more than 10 minutes
    retry_jitter=True,      # pick a random delay between 0 and that value
    max_retries=5,          # after 5 retries the task fails for good
    acks_late=True,         # acknowledge after the run, so a crash redelivers
    soft_time_limit=120,    # raises SoftTimeLimitExceeded inside the task
    time_limit=150,         # then the worker kills the child process
)
def push_export(export_id: int) -> None:
    with httpx.Client(timeout=10.0) as client:  # every call has a timeout
        r = client.post(f"https://partner.example/exports/{export_id}")
    if r.status_code == 429 or r.status_code >= 500:
        raise PartnerUnavailable(f"partner returned {r.status_code}")
    r.raise_for_status()  # other 4xx: a bug or bad data, retrying cannot help

In Celery these rules are task options, and autoretry_for lists the transient exceptions. Two details matter. First, Celery has no dead-letter queue of its own: when the retries run out, the task ends in the FAILURE state and, by default, its message is acknowledged and gone, so record failures yourself (for example in an on_failure handler) or, on RabbitMQ, raise Reject(requeue=False) into a dead-letter exchange. Second, even with acks_late, Celery acknowledges a task whose worker process was killed. task_reject_on_worker_lost requeues it instead, with a documented risk of message loops; Celery 5.7 adds task_retry_on_worker_lost, which resends it like a retry, bounded by max_retries.

05. Check your understanding

Practice check · 3 questions

Delivery, idempotency and leases

Three questions on acknowledgements, conditional updates and visibility timeouts.

Q1. Why do production message brokers like RabbitMQ or SQS deliver at least once rather than exactly once?
Q2. Workers claim jobs with a 60-second visibility timeout. A new report job takes about 90 seconds and always succeeds. What happens in production?
Q3. How does conditional updating (`WHERE status = 'pending'`) protect an order worker against duplicate delivery?
Practice only: not graded, not saved, not evidence.

06. Apply it

For the "export my data" project, write down the retry policy of the export job before you code it: which exceptions are transient, the maximum attempts, the backoff base and cap, the timeout of each storage or database call, the task's hard time limit, and a visibility timeout above that limit. Then add a dead_jobs table (or a DLQ) and a replay command, and test them by making the storage call fail permanently once.

Test duplicates too: run the handler twice with the same payload, then five copies at once with asyncio.gather(), and check that only one CSV exists. The next lesson handles a crash between the database commit and the enqueue.

07. Review prompt

Without looking back: explain why a lost ack forces at-least-once delivery, and name two ways a message can still be lost. Describe two idempotency patterns. State the rules of a retry policy (which errors, how many attempts, what delay, why jitter), order call timeouts, task time limit and visibility timeout, and say what happens after the last attempt.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check