Safe to Run Twice: Why a Celery Job Comes Back, and a Status Check, a Leased Lock and a Failed-Jobs Table That Keep It Calm
With acks_late, Redis keeps a copy of every taken job and hands it out again after the visibility timeout. A killed worker gave runs 2; a 200-second job with a 10-second timeout gave runs 3 with both workers alive. A status check, a Redis lock with a 10-second lease renewed after each chunk, and a failed_jobs table bring it back to one run.
What you will learn
- Explain how acks_late and Redis's visibility timeout bring a job back
- Show two ways one job runs twice: a killed worker and a job slower than the timeout
- Set the visibility timeout longer than the longest job, and know its price
- Guard a task with a status check, a Redis lock with a renewed lease, and a failed-jobs table
Before you start
- Celery and Redis for background tasks
- Retries and backoff for reliable tasks
Here's something that surprises a lot of developers: a queue can hand out the same job more than once. So your job has to be safe to run twice. This bug is very easy to miss, because everything looks fine in the logs.
Think of a cheque, number 1042. You hand it to the bank, and the ledger now says that number is paid. Hand in the same cheque again, and the bank looks at the number, sees it's already paid, and nothing moves. In the app, the cheque number is the project ID and the ledger is the status in the database. That's idempotent: doing it twice leaves the same result as doing it once.
The examples use a Celery task with time.sleep standing in for Whisper, on Redis, with two workers, A and B.
acks_late keeps a copy
celery_app.conf.update(
task_acks_late=True,
worker_prefetch_multiplier=1,
task_soft_time_limit=60 * 60,
task_time_limit=60 * 60 + 60,
broker_transport_options={
"visibility_timeout": VISIBILITY,
},
)
With task_acks_late=True, the worker takes the ticket but a copy stays with Redis on a shelf: taken, not finished. When the job finishes, the worker sends an ack and the copy is removed. But if no ack arrives within the visibility timeout, Redis puts the job back on the queue. That copy saves you when a worker dies, and it's also where every duplicate comes from.
Two ways to run twice
The unprotected task has no guard at all:
@celery_app.task(name="transcribe_unsafe")
def transcribe_unsafe(project_id, seconds=30):
store.log_run(project_id, socket.gethostname())
store.set_status(project_id, "TRANSCRIBING")
time.sleep(seconds) # the stand-in for Whisper
store.set_status(project_id, "COMPLETED")
return "transcribed"
The worker dies mid-job
Worker A starts project p-101 and store.log_run records it: runs 1. Seven seconds in, the worker is killed with kill -9, no goodbye. A little later the job comes back and worker B picks it up. The report: status completed, runs 2, and the second run started 97 seconds after the first. The job wasn't lost, which is good. But the second run started from the very beginning.
Just a slow job
This time nothing crashes. The job takes 200 seconds and the visibility timeout is 10. Run 1 starts on worker B. At 79 seconds run 2 starts on worker A, and at 197 seconds run 3. Three runs of one job, both workers alive the whole time. Redis only sees a job past its timeout, and it looks about every hundred seconds, so a short job can slip through with one run just because it finished before Redis looked. That's why a quick test can show nothing.
Timeout longer than the job
The limits here match the subtitle app: soft limit 3,600 seconds (one hour), hard limit one minute more. And the default visibility timeout is also 3,600 seconds. That's a tie with no margin. The soft limit usually stops the job right around then, so it's a narrow window, but it's a window. Set the timeout longer than your longest job, say two hours. The price: after a real crash, the job can wait up to two hours to come back. A longer timeout makes duplicates rarer. It doesn't make them impossible, so the task still needs its own guard.
The guard: a status check and a lock
r = redis.Redis.from_url(BROKER)
LEASE = 10 # seconds the lock lasts if nobody renews it
@celery_app.task(
name="transcribe_safe", bind=True, max_retries=None
)
def transcribe_safe(self, project_id, seconds=30):
if store.get_status(project_id) == "COMPLETED":
return "already done"
lock = r.lock(f"lock:{project_id}", timeout=LEASE)
if not lock.acquire(blocking=False):
# busy: another worker has it, so look again later
raise self.retry(countdown=LEASE)
try:
store.log_run(project_id, socket.gethostname())
store.set_status(project_id, "TRANSCRIBING")
for _ in range(seconds): # one chunk at a time
time.sleep(1)
lock.reacquire() # still alive: renew the lease
store.set_status(project_id, "COMPLETED")
return "transcribed"
finally:
lock.release()
Is it already done?
The very first line reads the status from the database, exactly like the bank checking its ledger. Project p-105 was sent again with status completed, so the task returned "already done". The report shows runs 1, and the check took less than a millisecond.
One runner at a time
That handles a finished job. A copy arriving while the first is still running needs a lock. Worker B takes a Redis lock named after the project; whoever holds it is the only one allowed to run this job. The lock has a 10-second lease, and after every chunk of work lock.reacquire() renews it: I'm still alive, keep it for me. The copy arrives on worker A, can't get the lock, and raise self.retry says look again later. In the test it looked twelve times. Then the job finished, and the last look said already done. Twelve looks, one run, and the report confirms runs 1.
The copy doesn't simply vanish, and that matters. Kill the worker holding the lock, and reacquire never runs again. Nobody renews the lease, so after 10 seconds the lock frees itself. The job comes back, worker B gets the lock and runs it. The report says runs 2, 96 seconds apart, and that's fine, because the first one never finished. Two runs, but never at the same time. Keep each chunk shorter than the lease, and write the output under the project ID so a rerun simply overwrites it.
A job that can never work
class ParkOnFailure(Task):
def on_failure(self, exc, task_id, args, kwargs, einfo):
tries = self.request.retries + 1
store.park(task_id, args[0], repr(exc), tries)
store.set_status(args[0], "FAILED")
@celery_app.task(
name="transcribe_poison",
base=ParkOnFailure,
autoretry_for=(OSError,),
max_retries=2,
default_retry_delay=2,
)
def transcribe_poison(project_id):
store.log_run(project_id, socket.gethostname())
# this file never decodes, so every try fails
raise OSError("audio stream ended early")
Some jobs never work: a poison message, like a corrupt audio file. This task retries twice, three tries in all, at 0, 2 and 4 seconds, and all three fail. Then what? Only a line in a log, because Celery on Redis has no dead-letter queue. So on_failure builds a small one: it writes the job into a failed_jobs table, and the report shows it parked after three tries. Like the post office's undeliverable desk, the letter is parked where someone can find it, fix it and send it again.
The same ideas without Celery, in a simulated document queue with leases and a dead-letter queue, are in a message queue for document ingestion.
Common mistakes
- Trusting a short test. A job that finishes before Redis looks shows no duplicate.
- Leaving the visibility timeout equal to the hard limit.
- A lock with no lease. If the holder dies, the job is stuck forever.
- A lease shorter than one chunk of work, so the lock expires mid-chunk.
- Dropping the copy when the lock is busy. Retry it, so it can take over after a crash.
Quick recap
| Case | Without a guard | With the guard |
|---|---|---|
| Worker killed mid-job | runs 2, from scratch | runs 2, never at the same time |
| Job slower than the timeout | runs 3, both workers alive | 12 looks, runs 1 |
| Sent again after it finished | runs again | "already done", runs 1 |
| Poison file | a log line only | parked in failed_jobs after 3 tries |
Try it yourself
Write a small replay script that reads the failed_jobs table and sends each parked project again.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Python Virtual Environments: One Project, One Toolbox
Why every Python project gets its own virtual environment: two projects that need different versions of requests, python -m venv .venv, activation, pip install and the PyCharm setting that activates it for you.
Git and GitHub Fundamentals: Commits, Branches, Push and Pull
The Git you use every day, on a tiny hello-ml project: commits as save points, the staging area, a branch merged with a fast-forward, then push, clone, pull and pull requests with a teammate.
Testing a FastAPI App with pytest: Three Small Tests
A tiny FastAPI app with a Hello World route and a name route that refuses numbers, three pytest tests that check it, and what happens when the validation is deleted by mistake.
Config and Logging Instead of Hard-Coded Values in ML Training
Take the hard-coded values out of a car price training script: one config.toml read with tomllib, logging with levels and a run id on every line, and secrets read from the environment. Same RMSE, 2195, before and after.
