Retries and Backoff for Reliable Tasks: Retry What Heals, Wait Longer, Add Jitter, Set Limits
A background task that fetches a file from S3 and transcribes it, made reliable: retry only connection and timeout errors, back off 2, 4, 8 seconds, spread ten jobs with jitter, and stop hung tasks with soft and hard limits. Real timings from a run.
What you will learn
- Retry only the errors that can heal, with Celery's autoretry_for
- Read exponential backoff: waits of 2, 4 and 8 seconds and where they come from
- Explain what retry_jitter really does, and why a bigger backoff gives it room
- Stop a task that hangs with a soft and a hard time limit, and leave a note when it fails
Before you start
- The Training Pipeline as a DAG
- Python exceptions (try and except)
Some failures heal if you wait, and some never do. A storage service that's down for a minute will be back. A corrupt file will be corrupt forever. A reliable task knows the difference: it retries the right errors, waits longer each time, and puts a limit on everything.
The example here is a background task that fetches an audio file from S3 and transcribes it, run by a Celery worker. Whisper and S3 are replaced by small stand-ins, so there's no GPU or AWS account involved, and every timing below comes from a real run. The same rules apply to any step in a training pipeline.
A delivery driver
A delivery driver knocks and nobody's home, so he comes back in an hour. Still nobody, so he waits two hours this time. After three visits he stops and leaves a note on the door. But if the house doesn't exist, one visit is enough.
A visit is a try. The growing wait is backoff. "Nobody home" can heal; a missing house never will. Our task needs to know the difference.
One outage, FAILED for good
Start with a task that has no retries:
@celery_app.task(name="transcribe_plain", bind=True)
def transcribe_plain(self, project_id, blips=0, corrupt=0):
store.log(project_id, "try")
try:
audio = stand_in.fetch_audio(project_id, blips)
stand_in.decode(audio, corrupt)
store.set_status(project_id, "COMPLETED")
except Exception as exc:
store.set_status(project_id, "FAILED", repr(exc))
raise
When this shape of task was pointed at an S3 that closes every connection, boto3 (the AWS library) retried on its own: six connections over about 10.3 seconds, then it gave up. The project was marked FAILED, the task ran once, and nobody tried again. So a short blip is fine, boto3 absorbs it. A longer outage ends the whole job.
Can it heal?
The fix starts with one question: can this error heal? Here's the retrying task:
@celery_app.task(
name="transcribe",
base=NoteOnFailure,
autoretry_for=(ConnectionError, TimeoutError),
retry_backoff=2,
retry_backoff_max=60,
retry_jitter=True,
max_retries=3,
)
def transcribe(project_id, blips=0, corrupt=0):
store.log(project_id, "try")
audio = stand_in.fetch_audio(project_id, blips)
stand_in.decode(audio, corrupt)
store.set_status(project_id, "COMPLETED")
autoretry_for is the list of errors worth another try: connection and timeout. If S3 is down, we get a ConnectionError, it's on the list, and the job goes back on the queue. A corrupt file raises a ValueError. It's not on the list, so it fails right away:
project p-206: FAILED, tries 1
try 1 at 0.0 s
note: ValueError('corrupt audio file')
This decorator is plain Celery, so it works the same in Flask and Django apps. Only where the Celery app gets created differs.
Wait, then wait longer
To see exact waits, a second version, transcribe_steady, has the same settings with retry_jitter=False. This job fails twice, then works:
project p-202: COMPLETED, tries 3
try 1 at 0.0 s
try 2 at 2.0 s
try 3 at 6.1 s
The worker log says the same thing:
Task transcribe_steady retry: Retry in 2s: ConnectionError('s3 not reachable')
Task transcribe_steady retry: Retry in 4s: ConnectionError('s3 not reachable')
retry_backoff=2 makes the first wait 2 seconds, then the wait doubles to 4. Celery's formula is countdown = min(maximum, factor * (2 ** retries)), so the waits go 2, 4, 8, capped by retry_backoff_max. That's exponential backoff.
One thing to remember: every retry runs the task from the top, so the work starts again.
Don't retry what can't heal
Here's a common trap. It feels safe to retry everything:
# the trap: this list also catches errors that never heal
@celery_app.task(
name="transcribe_greedy",
base=NoteOnFailure,
autoretry_for=(Exception,),
retry_backoff=2,
retry_jitter=False,
max_retries=3,
)
The same corrupt file now gets four tries over fourteen seconds, with the same error every time:
project p-207: FAILED, tries 4
try 1 at 0.0 s
try 2 at 2.0 s
try 3 at 6.0 s
try 4 at 14.1 s
note: ValueError('corrupt audio file')
You've made a broken file fail slowly, and it holds a worker slot on every try.
Stop, and leave a note
Now keep S3 down for good. With max_retries=3 we get four tries: one first try plus three retries.
After the last try, on_failure runs. It's a small base class shared by all the retrying tasks:
class NoteOnFailure(Task):
def on_failure(self, exc, task_id, args, kwargs, einfo):
store.set_status(args[0], "FAILED", repr(exc))
project p-208: FAILED, tries 4
try 1 at 0.0 s
try 2 at 2.0 s
try 3 at 6.0 s
try 4 at 14.1 s
note: ConnectionError('s3 not reachable')
That's the note on the door. During the waits, the status never showed FAILED; it stayed QUEUED, because on_failure only runs once the retries are used up.
Ten jobs fail together
Now the interesting part. S3 goes down and ten jobs fail together. Each one fails twice, then works, so 30 tries in all. Here are the tries per second:
| Second | Jitter off (backoff 2) | Jitter on (backoff 2) |
|---|---|---|
| 0 | 10 | 16 |
| 1 | 0 | 3 |
| 2 | 10 | 5 |
| 3 | 0 | 2 |
| 4 | 0 | 3 |
| 5 | 0 | 1 |
| 6 | 10 | 0 |
| Peak | 10 | 16 |
With jitter off, there are three spikes: ten tries at 0, ten at 2 seconds, ten at 6. Every retry hits S3 in the very same second. With retry_jitter=True, the later seconds drop to five at most. But the first second got worse: sixteen. Why?
The number is a ceiling
The answer is one line in the Celery source:
countdown = random.randrange(countdown + 1)
With jitter on, the backoff number is a ceiling, not the wait. With a wait of 2, it picks 0, 1 or 2 at random. In a sample, 0 came up about a third of the time (33.4%), and the average wait was half the ceiling. So many first retries happened at once, in second 0. One project, p-204, even had all three tries at 0.0 seconds: no backoff at all.
The fix is to give jitter room. Here's the same ten-job storm with retry_backoff=10:
@celery_app.task(
name="transcribe_wide",
base=NoteOnFailure,
autoretry_for=(ConnectionError, TimeoutError),
retry_backoff=10,
retry_backoff_max=60,
retry_jitter=True,
max_retries=3,
)
Only one retry lands in the first second (the other ten tries at second 0 are the first tries), and then never more than four in any second, spread over 24 seconds. All ten projects still completed in 3 tries. A wait of 0 gets rare, and on average jitter waits half the number.
Soft asks, hard kills
Last case: a task that doesn't fail, it just hangs.
@celery_app.task(
name="transcribe_hung",
base=NoteOnFailure,
soft_time_limit=5,
time_limit=8,
)
def transcribe_hung(project_id, seconds=60):
store.log(project_id, "try")
store.set_status(project_id, "TRANSCRIBING")
try:
time.sleep(seconds) # stuck, like a hung Whisper
except SoftTimeLimitExceeded:
store.log(project_id, "soft limit")
# a good place to delete temp files
raise
The soft limit fires right at 5 seconds. It's an exception inside the task, so you can catch it and clean up, and the project ends as failed:
project p-301: FAILED, tries 1
try 1 at 0.0 s
soft limit at 5.0 s
note: SoftTimeLimitExceeded()
Now a task whose cleanup hangs too. At 8 seconds the hard limit kills the process (Hard time limit (8s) exceeded for transcribe_stuck). No except, no on_failure, so the status stays where it was:
project p-302: TRANSCRIBING, tries 1
try 1 at 0.0 s
soft limit at 5.0 s
Something else has to find that project later. The worker itself survived and completed the next job (p-303). A real app sets these too; the one in this example uses a soft limit of one hour and a hard limit one minute later.
Recap
| Rule | Setting | What we saw |
|---|---|---|
| Retry only what can heal | autoretry_for=(ConnectionError, TimeoutError) | Corrupt file: 1 try. With Exception: 4 tries, 14 s, same error |
| Wait longer each time | retry_backoff=2 | Tries at 0, 2, 6.1 s |
| Spread retries, give jitter room | retry_jitter=True, retry_backoff=10 | Peak after second 0: at most 4 |
| Stop and leave a note | max_retries=3, on_failure | 4 tries, then FAILED with the error |
| End whatever hangs | soft_time_limit, time_limit | Soft at 5 s (caught), hard at 8 s (killed) |
Try it yourself: change retry_backoff to 30 in tasks_wide.py, send the ten jobs, and read the tries per second. A blip should be a short wait, not a failed project.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Orchestrating ML Pipelines with Airflow: Schedule, Retries and Backfill
Next →CI with GitHub Actions: Run the Tests and Build the Docker Image on Every Push
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
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.