← Back to Python, page 4

python-0075 · Hard senior

Design a background job worker in Python that processes tasks from a queue reliably.

Workers pull jobs from a durable queue (Redis, RabbitMQ, SQS or a database table), process them, and acknowledge only after success, so crashes cause redelivery. Make handlers idempotent, retry with backoff and a dead-letter queue after N failures, handle SIGTERM by finishing the current job, and bound concurrency. Monitor queue depth, failures and job duration.

Full answer
python
from collections import deque
queue = deque([("send_email", 0), ("flaky_report", 0), ("broken_job", 0)])
failures = {"flaky_report": 2}
dead_letter, done, shutting_down = [], [], False

def handle(name):
    if name == "broken_job":
        raise RuntimeError("always fails")
    if failures.get(name, 0) > 0:
        failures[name] -= 1
        raise RuntimeError("transient")
    return f"{name} ok"

while queue and not shutting_down:
    name, attempts = queue.popleft()
    try:
        done.append(handle(name))
    except RuntimeError as e:
        if attempts + 1 >= 3:
            dead_letter.append((name, str(e)))
        else:
            queue.append((name, attempts + 1))
    if len(done) == 2 and not queue:
        shutting_down = True
print(done)
print(dead_letter)
print("stopped cleanly:", shutting_down or not queue)

Output:

text
['send_email ok', 'flaky_report ok']
[('broken_job', 'always fails')]
stopped cleanly: True

The run uses an in-memory queue to show the control flow: a job that fails twice is retried and then succeeds, a job that always fails lands in the dead-letter list after three attempts, and a shutdown flag stops the loop cleanly between jobs.

Production concerns:

  • Delivery is at least once, so handlers must tolerate duplicates (idempotency keys, upserts).
  • Acknowledge after the work commits; with a database queue, mark done in the same transaction as the business change.
  • Visibility timeouts: if a worker dies mid-job, the job becomes visible again after a timeout.
  • Graceful shutdown: on SIGTERM, stop taking new jobs and finish or requeue the current one.
  • Concurrency: processes for CPU-heavy jobs, threads or asyncio for I/O-heavy ones.
  • Scheduling and priorities: separate queues per priority rather than one mixed queue.

Celery, RQ, Dramatiq and arq implement these patterns; knowing them helps evaluate which to use.

python
from collections import deque
queue = deque([("send_email", 0), ("flaky_report", 0), ("broken_job", 0)])
failures = {"flaky_report": 2}
dead_letter, done, shutting_down = [], [], False

def handle(name):
    if name == "broken_job":
        raise RuntimeError("always fails")
    if failures.get(name, 0) > 0:
        failures[name] -= 1
        raise RuntimeError("transient")
    return f"{name} ok"

while queue and not shutting_down:
    name, attempts = queue.popleft()
    try:
        done.append(handle(name))
    except RuntimeError as e:
        if attempts + 1 >= 3:
            dead_letter.append((name, str(e)))
        else:
            queue.append((name, attempts + 1))
    if len(done) == 2 and not queue:
        shutting_down = True
print(done)
print(dead_letter)
print("stopped cleanly:", shutting_down or not queue)

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Acknowledge after success
  • Idempotent handlers for at-least-once delivery
  • Retries with backoff and dead-letter queues
  • Graceful shutdown on SIGTERM
  • Monitor depth, failures and duration

Common mistakes

  • Acknowledging before processing
  • Non-idempotent handlers with automatic retries

Follow-ups

  • How would you schedule a job for later?
  • How do visibility timeouts work in SQS?

Tips

  • State the delivery guarantee