Single logo
  • Courses
  • Blog
  • About
Join for freeJoin free
Machine Learning
  • First Look at a Dataset: 6 Checks Before You Plot or Model
  • Plotting Distributions with seaborn: Histograms, KDE, Counts and log1p
  • Scatter Plots and Pair Plots: See How Two Columns Relate
  • Finding Outliers: Box Plots, Violin Plots and the IQR Rule
  • Correlation and Heatmaps: Covariance, df.corr() and What They Miss
  • Train-Test Split and Data Leakage: Split First, Learn After
  • Handling Missing Data: Count the Blanks, Then Fill Them with SimpleImputer
  • Encoding Categorical Data: OrdinalEncoder, OneHotEncoder and LabelEncoder
  • Feature Scaling: StandardScaler, MinMaxScaler and Which Models Care
  • Pipelines and ColumnTransformer: All Preprocessing and the Model in One Object
  • Feature Selection and the Curse of Dimensionality: Keep the Columns That Matter
  • Project: Preprocess Rain in Australia from Raw CSV to Model-Ready Data
    Regression
    • Linear Regression and the Cost Function: Draw a Line, Score It
    • Gradient Descent Explained: Feel the Slope, Step Downhill
    • Linear Regression in scikit-learn: Fit, Predict and Read the Price Tags
    • Regression Metrics: MAE, RMSE, R-squared and the Baseline to Beat
    • Polynomial Regression, Overfitting and Underfitting: Bend the Line, Watch the Test Score
    • Regularisation with Ridge and Lasso: Put a Price on Big Weights
    Classification and Evaluation
    • Logistic Regression and the Sigmoid: Score, Squash, Decide
    • Logistic Regression in scikit-learn: predict, predict_proba and Softmax
    • Why Accuracy Lies: The Confusion Matrix, Baselines and Type I/II Errors
    • Precision, Recall and F1 Score: Two Questions and One Balance
    • ROC Curve, AUC and Choosing a Classification Threshold
    • Handling Imbalanced Data: class_weight, SMOTE and the Resampling Leak
    • Cross-Validation: KFold, StratifiedKFold, cross_val_score and cross_validate
    Classic Algorithms
    • K-Nearest Neighbours (KNN): Distance, k and Why Scaling Is a Must
    • Naive Bayes: Prior Times Likelihood, a Spam Filter by Hand and GaussianNB
    • Support Vector Machines (SVM): The Widest Road, C, Kernels and gamma
    • Decision Trees: Gini, max_depth and Feature Importances on Rain in Australia
    • Bagging and Random Forest: Many Shaky Trees, One Steady Answer
    • Boosting: Residuals by Hand, AdaBoost, Gradient Boosting and XGBoost
    • Voting and Stacking: Does a Team of Models Beat the Best One?
    Model Selection and Tuning
    • Hyperparameter Tuning with GridSearchCV and RandomizedSearchCV
    • Which Features Matter? Feature Importances, Permutation Importance and SHAP
    • Project: The Classification Master Template, from Raw CSV to a Saved Model
    • K-Means Clustering: Find Groups in Data With No Labels
    • Choosing k for K-Means: the Elbow Method and the Silhouette Score
    • Hierarchical Clustering and DBSCAN: Dendrograms, Linkage, eps and Noise
    • Dimensionality Reduction with PCA: 13 Columns Down to 2
    • Association Rules and Market Basket Analysis: Support, Confidence, Lift and Apriori
    • Recommender Systems: Item-Based Collaborative Filtering with Cosine Similarity
    • Bag of Words with CountVectorizer: Turn Text into Word Counts
    • TF-IDF with TfidfVectorizer: Common Words Fade, Rare Words Speak
    • Build a Text Classifier with TF-IDF and a Pipeline: Naive Bayes vs LinearSVC
    • Why Neural Networks: Pixels, One Neuron and Layers
    • The Forward Pass and Activation Functions: ReLU, Sigmoid, Tanh and Softmax
    • Loss and Backpropagation: How Wrong, and Who Is to Blame
    • The Training Loop: Epochs, Mini-Batches, Learning Rate and Optimisers
    • Your First Neural Network with Keras: MNIST Digits at 97.7%
    • The Same Network in PyTorch: DataLoader, nn.Module and the Five-Line Training Loop
    • Convolutional Neural Networks (CNN) Basics: Filters, Feature Maps and Pooling
    • Embeddings: Words as Vectors, Cosine Similarity and nn.Embedding
    • Similarity Search: Finding the Closest Vectors with NumPy and NearestNeighbors
    • Dropout, Early Stopping and Batch Norm: Judge Each One by the Validation Curve
    • Transfer Learning on Images: A Frozen ResNet-18, a Small Head and an Honest Baseline
    • Attention Explained Without the Maths: Query, Key, Value and the Word "it"
    • Transformer Building Blocks in PyTorch: Follow the Shapes Through Attention and a Block
    • Pretrained Models from Hugging Face: A Sentiment Pipeline and Sentence Embeddings on a CPU
    • Loading a Language Model and Running Inference: Download, Load, Tokenize, Generate
    • Model Size and Memory: Parameters x Bytes, Quantization, and Where to Run a Model
    • Training on a GPU: Mixed Precision, Gradient Accumulation and Checkpoints That Really Resume
    • When NOT to Fine-Tune: A Decision Tree of Prompt, RAG, Tools, Then Fine-Tuning
    • Full Fine-Tuning vs LoRA vs QLoRA: What Each One Changes and What It Costs
    • LoRA Fine-Tune of a Tiny Model: Teach SmolLM2-135M Your House Style on a CPU
    • Knowledge Distillation: Teach a Model 100 Times Smaller From a Teacher's Soft Labels
    • Serving Open Models: Continuous Batching, vLLM and Cold Starts
      Engineering Basics
      • Python Virtual Environments: One Project, One Toolbox
      • Git and GitHub Fundamentals: Commits, Branches, Push and Pull
      • Testing a FastAPI App with pytest: Three Small Tests
      • Config and Logging Instead of Hard-Coded Values in ML Training
      • SQL Essentials for Python: SELECT, WHERE, JOIN and GROUP BY
      Data and Features in Production
      • Time Splits and Group Splits: Make the Split Match How the Model Is Used
      • Time Series Basics: Lags, Rolling Windows and Walk-Forward Backtesting
      • Feature Engineering Patterns, Each One Tested: Date Parts, Differences, Windows and Target Encoding
      • Point-in-Time Correctness: Join Features as of Each Event with merge_asof
      • Data Validation and Schema Checks: Stop Bad Input Before It Reaches the Model
      • Training-Serving Skew: Same Model, Different Inputs, and How to Detect It
      • Feature Stores: Offline and Online Stores, and When You Actually Need One
      • Data Versioning with DVC: Tie Every Model to the Exact Data That Trained It
      Experiments and Model Quality
      • MLOps in One Picture: Code, Data, Model and the Lifecycle Loop
      • Experiment Tracking with MLflow: Log Params, Metrics and the Model, Then Compare Runs
      • MLflow Model Registry Aliases: Serve the Champion, Ship a New Version and Roll Back in One Line
      • The Cost of Being Wrong: Baselines, a Price per Mistake and the Cheapest Threshold
      • Probability Calibration: Can You Trust the 0.8? Reliability Curves, Platt and Isotonic
      • Slice Evaluation and Fairness Checks: Score the Model Group by Group
      Serving Models
      • Saving and Loading Models with joblib: One Pipeline, One File
      • FastAPI Hello World: Routes, uvicorn and the Free Swagger Page
      • Deploy a Machine Learning Model with FastAPI: POST /predict for a Saved Model
      • Docker Essentials for ML: Images, Containers and Volumes with a Model API
      • Containerising a Model API: A Dockerfile for FastAPI and scikit-learn, Line by Line
      • Online, Batch or Streaming? Picking the Serving Pattern for an ML Model
      • A Production FastAPI for an ML Model: Input Limits, /health, /ready and a Model Version
      • Batch Scoring a Million Rows: Chunks, a Run ID and a Safe Rerun
      • Latency Math: p50, p95, p99 and Why the Tail Reaches Your Users
      • Measuring Latency of an ML API: Timing Inside with OpenTelemetry, Outside with a Load Test and Locust
      • Making ML Inference Fast: ONNX, Micro-Batching and Quantisation, Measured
      • Sizing and Autoscaling an Inference Service: From One Replica to a Replica Count
      Pipelines, CI/CD and Cloud
      • The Training Pipeline as a DAG: Steps, Files, Retries and a Safe Rerun
      • Orchestrating ML Pipelines with Airflow: Schedule, Retries and Backfill
      • Retries and Backoff for Reliable Tasks: Retry What Heals, Wait Longer, Add Jitter, Set Limits
      • CI with GitHub Actions: Run the Tests and Build the Docker Image on Every Push
      • CI/CD for ML: A Quality Gate That Blocks a Weaker Model, Even When Every Test Passes
      • Which Cloud for What: AWS, Azure, Google Cloud, GPU Clouds, Edge and Platforms
      • IaaS, PaaS, Containers or Serverless? Choosing Where a Model API Runs
      • Kubernetes at a High Level: Pods, a Deployment and a Service for a Model API
      • Managed ML Platforms: What SageMaker, Vertex AI and Azure ML Give You, and Tie You To
      • Deploying a Model API to AWS: ECR, Secrets Manager, CloudWatch and Fargate, Then Teardown
      • Cloud Cost Thinking for ML: Size x Count x Hours x Rate, and Three Decisions Worth Ten Times
      Monitoring and Release
      • Monitoring Drift and Retraining: When a Model Gets Worse With No Code Change
      • Drift Detection in Code: PSI Bin by Bin, the KS Test, Evidently and a Measured Threshold
      • Shadow, Canary and Rollback: Releasing a New Model Without Betting Everything on It
      • A/B Tests for Models: Did the New Model Make Things Better for People?
      • When Labels Arrive Weeks Late: What to Watch Before You Can Grade the Model
      • Retraining Triggers: Schedule, Drift and Performance, Wired to One Retrain Pipeline
      • The User Feedback Loop: Why Thumbs Up Isn't the Truth, and What a Small Random Review Adds
      • Debugging a Model in Production: A Four-Step Runbook, Cheap Checks First
      • Project: Car Price Predictor End to End, from CSV to a FastAPI Price API
      • Fraud Scoring, Part 1: The Problem, the Metric and the Baseline
      • Fraud Scoring, Part 2: Training With Time Splits, Leak-Free Features and a Cost-Picked Threshold
      • Fraud Scoring, Part 3: Serving It With FastAPI, Docker and a 50 ms Budget
      • Fraud Scoring, Part 4: Release and Monitoring With Shadow, Drift and Late Labels
      • Demand Forecasting, Part 1: The Business Problem, a Price per Mistake and the Line to Beat
      • Recommendations, Part 1: Two Stages, Candidates Then Ranking
      • Demand Forecasting, Part 2: Walk-Forward Backtesting, Ridge vs Boosting and the Slices an Average Hides
      • Recommendations, Part 2: Candidate Generation With Embeddings
      • Demand Forecasting, Part 3: The Nightly Batch Pipeline That Survives a Crash
      • Recommendations, Part 3: The Ranker and Offline Metrics (Recall@k and nDCG)
      • Demand Forecasting, Part 4: Serving the Forecasts, the Outcome Join and a Retrain Rule
      • Recommendations, Part 4: Serving With FastAPI, a Cache and a Popular Fallback
      • Ticket Routing, Part 1: A Safe Split, Keyword Rules and a TF-IDF Baseline
      • Ticket Routing, Part 2: Fine-Tuning a Small Encoder on a CPU, With a Run Log and Honest Ranges
      • Ticket Routing, Part 3: Quantise to int8, Host Behind FastAPI and Measure the Server
      • Ticket Routing, Part 4: Canary, Automatic Rollback and "Does Your Small Model Reason?"
      1. Blog
      2. /
      3. Machine Learning
      4. /
      5. MLOps and Production ML

      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.

      Chaand Sheikh

      ·27 November 2026Pipelines, CI/CD and Cloud

      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.

      Four tries with exponential backoff, then a note 0 s 2 s 6 s 14.1 s try 1 try 2 try 3 try 4 wait 2 wait 4 wait 8 on_failure: FAILED + error
      p-208: S3 never comes back. Four tries, waits doubling, then the note on the door.

      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:

      SecondJitter off (backoff 2)Jitter on (backoff 2)
      01016
      103
      2105
      302
      403
      501
      6100
      Peak1016

      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,
      )
      Tries per second, retry_backoff=10 with jitter 11 4 0 5 10 15 20 24 second
      retry_backoff=10, jitter on: 30 tries over 24 seconds. Second 0 holds the ten first tries plus one retry; after that, never more than 4.

      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

      RuleSettingWhat we saw
      Retry only what can healautoretry_for=(ConnectionError, TimeoutError)Corrupt file: 1 try. With Exception: 4 tries, 14 s, same error
      Wait longer each timeretry_backoff=2Tries at 0, 2, 6.1 s
      Spread retries, give jitter roomretry_jitter=True, retry_backoff=10Peak after second 0: at most 4
      Stop and leave a notemax_retries=3, on_failure4 tries, then FAILED with the error
      End whatever hangssoft_time_limit, time_limitSoft 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 →
      ← Previous
      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
      Single logo

      StudyEasy AI Community

      Hosted onSkool

      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

      Join free on Skool
      Go deeper with a course

      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.

      On this page
      • A delivery driver
      • One outage, FAILED for good
      • Can it heal?
      • Wait, then wait longer
      • Don't retry what can't heal
      • Stop, and leave a note
      • Ten jobs fail together
      • The number is a ceiling
      • Soft asks, hard kills
      • Recap
      Single logo

      StudyEasy AI Community

      Hosted onSkool

      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

      Join free on Skool
      Go deeper with a course

      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)

      Single logo

      Empowering Education, One Course at a Time

      About
      About usContact usFAQs
      Legal
      Terms of ServicePrivacy Policy

      © 2026 StudyEasy Organization. All rights reserved.