Tutorial 16: Celery + Redis for ML Task Queues
Table of Contents
Introduction
Machine learning inference can range from milliseconds for a simple scikit-learn model to minutes for a complex deep learning pipeline involving image processing, feature extraction, and ensemble predictions. When inference takes more than a few hundred milliseconds, handling it synchronously within a web request creates poor user experience and risks request timeouts.
Task queues solve this by offloading long-running work to background workers. The client submits a task, receives an ID immediately, and polls for results later. This pattern enables your API to remain responsive, supports horizontal scaling of compute-intensive workloads, and provides built-in retry logic for failed tasks.
Celery is the most widely used distributed task queue for Python, and Redis is its most popular message broker. Together, they form a battle-tested foundation for asynchronous ML inference, batch processing, model training jobs, and data pipeline orchestration.
This tutorial walks you through building a complete async ML inference system with Celery, Redis, and FastAPI — from basic setup to production-ready deployment.
Prerequisites
- Python 3.9 or higher
- Redis server (local or Docker)
- Basic understanding of REST APIs and async programming
- Install required packages:
pip install celery[redis] redis fastapi uvicorn scikit-learn joblib numpy pandas flower pydantic
Start Redis with Docker:
docker run -d --name redis -p 6379:6379 redis:7-alpine
Understanding Task Queues for ML
Architecture Overview
The Celery architecture consists of three main components:
Producer (Client): Your web application (e.g., FastAPI) that submits tasks. It sends task messages to the broker and returns immediately, giving the caller a task ID for later retrieval. Broker (Redis): The message queue that holds tasks until workers pick them up. Redis acts as both the broker (task queue) and the result backend (where completed task results are stored). Worker: A separate process (or set of processes) that consumes tasks from the broker, executes them, and stores the results. For ML, each worker loads the model into memory and processes inference requests.Client (FastAPI) --> Redis Broker --> Worker 1 (ML Model)
--> Worker 2 (ML Model)
--> Worker 3 (ML Model)
|
Redis Result Backend
|
Client polls for result
When to Use Task Queues for ML
| Use Case | Sync API | Task Queue |
|----------|----------|------------|
| Simple model, < 100ms inference | Preferred | Overkill |
| Complex pipeline, 1-30s inference | Risky (timeouts) | Preferred |
| Batch predictions (1000+ items) | Not feasible | Required |
| GPU inference with queuing | Impractical | Ideal |
| Model training triggers | Not possible | Required |
Setting Up Celery with Redis
Project Structure
ml-celery-project/
celeryapp.py # Celery application configuration
tasks.py # Task definitions
api.py # FastAPI application
ml/
model.py # Model loading and inference
preprocessing.py # Feature preprocessing
models/
fraudmodel.pkl # Trained model file
config.py # Configuration settings
requirements.txt
docker-compose.yml
Celery Application Configuration
# celeryapp.py
from celery import Celery
Create the Celery application
app = Celery('ml
tasks')
Configure Celery
app.conf.update(
# Broker settings (Redis)
brokerurl='redis://localhost:6379/0',
resultbackend='redis://localhost:6379/1',
# Serialization
taskserializer='json',
resultserializer='json',
acceptcontent=['json'],
# Time limits
tasksofttimelimit=120, # Soft limit: 2 minutes (raises SoftTimeLimitExceeded)
tasktimelimit=180, # Hard limit: 3 minutes (kills the task)
resultexpires=3600, # Results expire after 1 hour
# Worker settings
workerprefetchmultiplier=1, # Fetch one task at a time (important for long ML tasks)
workermaxtasksperchild=100, # Restart worker after 100 tasks (prevents memory leaks)
workermaxmemoryperchild=2000000, # 2GB memory limit per worker
# Task behavior
taskackslate=True, # Acknowledge task after completion (not on receipt)
taskrejectonworkerlost=True, # Requeue task if worker dies
# Task routes (optional: route tasks to specific queues)
taskroutes={
'tasks.predictsingle': {'queue': 'inference'},
'tasks.predictbatch': {'queue': 'batch'},
'tasks.trainmodel': {'queue': 'training'},
},
# Retry settings
taskdefaultretrydelay=30, # Wait 30 seconds before retrying
taskmaxretries=3,
)
Auto-discover tasks from modules
app.autodiscovertasks(['tasks'])
Configuration Module
# config.py
import os
class Config:
REDISURL = os.getenv('REDISURL', 'redis://localhost:6379/0')
RESULTBACKEND = os.getenv('RESULTBACKEND', 'redis://localhost:6379/1')
MODELPATH = os.getenv('MODELPATH', 'models/fraudmodel.pkl')
BATCHSIZE = int(os.getenv('BATCHSIZE', '64'))
LOGLEVEL = os.getenv('LOGLEVEL', 'INFO')
Creating Async ML Inference Tasks
Model Module
# ml/model.py
import joblib
import numpy as np
import logging
from functools import lrucache
from config import Config
logger = logging.getLogger(name)
@lrucache(maxsize=1)
def loadmodel(modelpath=None):
"""Load and cache the ML model. Called once per worker process."""
path = modelpath or Config.MODELPATH
logger.info(f"Loading model from {path}")
model = joblib.load(path)
logger.info("Model loaded successfully")
return model
def runinference(features: dict) -> dict:
"""Run model inference on a single feature dictionary."""
model = loadmodel()
featurenames = [
'amount', 'amountzscore', 'useravgamount', 'userstdamount',
'usertxncount', 'hourofday', 'isweekend', 'categoryencoded',
]
featurevector = np.array(
[features.get(name, 0.0) for name in featurenames]
).reshape(1, -1)
prediction = int(model.predict(featurevector)[0])
probabilities = model.predictproba(featurevector)[0].tolist()
return {
'prediction': prediction,
'probabilities': probabilities,
'confidence': float(max(probabilities)),
'modelversion': getattr(model, 'version', 'unknown'),
}
def runbatchinference(featurelist: list) -> list:
"""Run model inference on a batch of feature dictionaries."""
model = loadmodel()
featurenames = [
'amount', 'amountzscore', 'useravgamount', 'userstdamount',
'usertxncount', 'hourofday', 'isweekend', 'categoryencoded',
]
featurematrix = np.array([
[f.get(name, 0.0) for name in featurenames]
for f in featurelist
])
predictions = model.predict(featurematrix).tolist()
probabilities = model.predictproba(featurematrix).tolist()
results = []
for i, (pred, probs) in enumerate(zip(predictions, probabilities)):
results.append({
'index': i,
'prediction': int(pred),
'probabilities': probs,
'confidence': float(max(probs)),
})
return results
Task Definitions
# tasks.py
import time
import logging
from celery import sharedtask, group, chain, chord
from celery.exceptions import SoftTimeLimitExceeded
from ml.model import runinference, runbatchinference
logger = logging.getLogger(name)
@sharedtask(
bind=True,
name='tasks.predictsingle',
queue='inference',
maxretries=3,
defaultretrydelay=10,
ackslate=True,
)
def predictsingle(self, features: dict, requestid: str = None):
"""Run inference on a single input asynchronously."""
starttime = time.time()
try:
logger.info(f"Processing prediction request: {requestid}")
result = runinference(features)
result['requestid'] = requestid
result['processingtimems'] = round((time.time() - starttime) 1000, 2)
logger.info(f"Prediction completed in {result['processingtimems']}ms")
return result
except SoftTimeLimitExceeded:
logger.error(f"Task {self.request.id} exceeded time limit")
raise
except Exception as exc:
logger.error(f"Prediction failed: {exc}", excinfo=True)
raise self.retry(exc=exc)
@sharedtask(
bind=True,
name='tasks.predictbatch',
queue='batch',
maxretries=2,
softtimelimit=300,
timelimit=360,
)
def predictbatch(self, featurelist: list, batchid: str = None):
"""Run inference on a batch of inputs."""
starttime = time.time()
try:
logger.info(f"Processing batch {batchid} with {len(featurelist)} items")
results = runbatchinference(featurelist)
return {
'batchid': batchid,
'totalitems': len(featurelist),
'results': results,
'processingtimems': round((time.time() - starttime) 1000, 2),
}
except SoftTimeLimitExceeded:
logger.error(f"Batch task {self.request.id} exceeded time limit")
raise
except Exception as exc:
logger.error(f"Batch prediction failed: {exc}", excinfo=True)
raise self.retry(exc=exc)
@sharedtask(name='tasks.preprocessandpredict')
def preprocessandpredict(rawdata: dict):
"""Preprocess raw data, then run prediction."""
# Simulate preprocessing
features = {
'amount': rawdata.get('amount', 0),
'amountzscore': (rawdata.get('amount', 0) - 500) / 200,
'useravgamount': rawdata.get('historicalavg', 0),
'userstdamount': rawdata.get('historicalstd', 0),
'usertxncount': rawdata.get('txncount', 0),
'hourofday': rawdata.get('hour', 12),
'isweekend': rawdata.get('isweekend', 0),
'categoryencoded': rawdata.get('categorycode', 0),
}
return runinference(features)
@sharedtask(name='tasks.aggregateresults')
def aggregateresults(results: list):
"""Aggregate results from multiple predictions."""
fraudcount = sum(1 for r in results if r.get('prediction') == 1)
return {
'totalpredictions': len(results),
'frauddetected': fraudcount,
'fraudrate': fraudcount / len(results) if results else 0,
'avgconfidence': sum(r.get('confidence', 0) for r in results) / len(results) if results else 0,
}
Task Chains, Groups, and Chords
Celery provides powerful primitives for composing complex workflows from simple tasks.
Task Chains (Sequential Execution)
from celery import chain
Chain: preprocess -> predict -> postprocess (each result feeds into the next)
workflow = chain(
preprocessandpredict.s({'amount': 1500, 'hour': 23, 'txncount': 5}),
)
result = workflow.applyasync()
print(result.get(timeout=60))
Task Groups (Parallel Execution)
from celery import group
Group: run multiple predictions in parallel
dataitems = [
{'amount': 100, 'hour': 10, 'txncount': 50},
{'amount': 5000, 'hour': 3, 'txncount': 2},
{'amount': 250, 'hour': 14, 'txncount': 100},
{'amount': 8000, 'hour': 1, 'txncount': 1},
]
job = group(
preprocessandpredict.s(item) for item in dataitems
)
result = job.applyasync()
Get all results (blocks until all complete)
predictions = result.get(timeout=120)
for pred in predictions:
print(f"Prediction: {pred['prediction']}, Confidence: {pred['confidence']:.4f}")
Task Chords (Parallel + Callback)
from celery import chord
Chord: run predictions in parallel, then aggregate the results
dataitems = [
{'amount': 100, 'hour': 10, 'txncount': 50},
{'amount': 5000, 'hour': 3, 'txncount': 2},
{'amount': 250, 'hour': 14, 'txncount': 100},
]
All predictions run in parallel, then aggregateresults is called with all results
workflow = chord(
[preprocessandpredict.s(item) for item in dataitems],
aggregateresults.s()
)
result = workflow.applyasync()
summary = result.get(timeout=120)
print(f"Summary: {summary}")
Integration with FastAPI
FastAPI Application
# api.py
import uuid
from fastapi import FastAPI, HTTPException, BackgroundTasks
from pydantic import BaseModel, Field
from typing import List, Optional
from celery.result import AsyncResult
from tasks import predictsingle, predictbatch, preprocessandpredict
from celery import group, chord
from tasks import aggregateresults
app = FastAPI(title="ML Inference API", version="1.0.0")
--- Request/Response Models ---
class PredictionRequest(BaseModel):
amount: float = Field(..., description="Transaction amount")
hourofday: int = Field(ge=0, le=23)
useravgamount: float = 0.0
userstdamount: float = 0.0
usertxncount: int = 0
isweekend: int = Field(ge=0, le=1, default=0)
categoryencoded: int = 0
class BatchPredictionRequest(BaseModel):
items: List[PredictionRequest]
class TaskResponse(BaseModel):
taskid: str
status: str
message: str
class TaskStatusResponse(BaseModel):
taskid: str
status: str
result: Optional[dict] = None
error: Optional[str] = None
--- Endpoints ---
@app.get("/health")
async def healthcheck():
return {"status": "healthy"}
@app.post("/predict/async", responsemodel=TaskResponse)
async def submitprediction(request: PredictionRequest):
"""Submit a single prediction task asynchronously."""
requestid = str(uuid.uuid4())
features = request.modeldump()
task = predictsingle.applyasync(
kwargs={'features': features, 'requestid': requestid},
taskid=requestid,
)
return TaskResponse(
taskid=task.id,
status="submitted",
message="Prediction task submitted. Poll /tasks/{taskid} for results.",
)
@app.post("/predict/batch", responsemodel=TaskResponse)
async def submitbatchprediction(request: BatchPredictionRequest):
"""Submit a batch prediction task."""
batchid = str(uuid.uuid4())
featurelist = [item.modeldump() for item in request.items]
task = predictbatch.applyasync(
kwargs={'featurelist': featurelist, 'batchid': batchid},
taskid=batchid,
)
return TaskResponse(
taskid=task.id,
status="submitted",
message=f"Batch of {len(featurelist)} items submitted.",
)
@app.post("/predict/parallel", responsemodel=TaskResponse)
async def submitparallelpredictions(request: BatchPredictionRequest):
"""Submit predictions in parallel using Celery chord with aggregation."""
jobid = str(uuid.uuid4())
items = [item.modeldump() for item in request.items]
workflow = chord(
[preprocessandpredict.s(item) for item in items],
aggregateresults.s()
)
result = workflow.applyasync(taskid=jobid)
return TaskResponse(
taskid=result.id,
status="submitted",
message=f"Parallel job with {len(items)} tasks submitted.",
)
@app.get("/tasks/{taskid}", responsemodel=TaskStatusResponse)
async def gettaskstatus(taskid: str):
"""Check the status of a submitted task."""
result = AsyncResult(taskid)
if result.state == 'PENDING':
return TaskStatusResponse(taskid=taskid, status="pending")
elif result.state == 'STARTED':
return TaskStatusResponse(taskid=taskid, status="processing")
elif result.state == 'SUCCESS':
return TaskStatusResponse(
taskid=taskid,
status="completed",
result=result.result,
)
elif result.state == 'FAILURE':
return TaskStatusResponse(
taskid=taskid,
status="failed",
error=str(result.info),
)
elif result.state == 'RETRY':
return TaskStatusResponse(taskid=taskid, status="retrying")
else:
return TaskStatusResponse(taskid=taskid, status=result.state.lower())
@app.delete("/tasks/{taskid}")
async def revoketask(taskid: str):
"""Cancel a pending or running task."""
result = AsyncResult(taskid)
result.revoke(terminate=True, signal='SIGTERM')
return {"taskid": taskid, "status": "revoked"}
Running the Stack
# Terminal 1: Start Redis
docker run -d --name redis -p 6379:6379 redis:7-alpine
Terminal 2: Start Celery worker for inference queue
celery -A celeryapp worker --queues=inference --concurrency=4 --loglevel=info -n inference@%h
Terminal 3: Start Celery worker for batch queue
celery -A celeryapp worker --queues=batch --concurrency=2 --loglevel=info -n batch@%h
Terminal 4: Start FastAPI
uvicorn api:app --host 0.0.0.0 --port 8000 --reload
Terminal 5: Test the API
curl -X POST http://localhost:8000/predict/async \
-H "Content-Type: application/json" \
-d '{"amount": 5000, "hourofday": 3, "usertxncount": 2}'
Monitoring with Flower
Flower is a real-time web-based monitoring tool for Celery.
# Install and run Flower
pip install flower
Start Flower on port 5555
celery -A celeryapp flower --port=5555 --broker=redis://localhost:6379/0
Access the dashboard at http://localhost:5555
Flower Capabilities
- Dashboard: Overview of all workers, active tasks, and throughput
- Workers: CPU, memory, and task count per worker
- Tasks: View task states (PENDING, STARTED, SUCCESS, FAILURE, RETRY)
- Broker: Queue sizes and message rates
- API: Programmatic access to monitoring data
Custom Monitoring with Celery Signals
# monitoring.py
from celery.signals import taskprerun, taskpostrun, taskfailure, taskretry
import time
import logging
logger = logging.getLogger(name)
taskstarttimes = {}
@taskprerun.connect
def taskstarted(sender=None, taskid=None, kwargs):
"""Record task start time."""
taskstarttimes[taskid] = time.time()
logger.info(f"Task {sender.name} [{taskid}] started")
@taskpostrun.connect
def taskcompleted(sender=None, taskid=None, state=None, kwargs):
"""Log task completion and duration."""
starttime = taskstarttimes.pop(taskid, None)
duration = (time.time() - starttime) 1000 if starttime else 0
logger.info(f"Task {sender.name} [{taskid}] completed in {duration:.0f}ms, state: {state}")
@taskfailure.connect
def taskfailed(sender=None, taskid=None, exception=None, kwargs):
"""Log task failures for alerting."""
logger.error(f"Task {sender.name} [{taskid}] FAILED: {exception}")
@taskretry.connect
def taskretrying(sender=None, request=None, reason=None, kwargs):
"""Log task retries."""
logger.warning(f"Task {sender.name} retrying: {reason}")
Error Handling and Retries
Configuring Retry Behavior
@sharedtask(
bind=True,
maxretries=5,
defaultretrydelay=10,
retrybackoff=True, # Exponential backoff: 10s, 20s, 40s, 80s, 160s
retrybackoffmax=300, # Cap at 5 minutes
retryjitter=True, # Add random jitter to prevent thundering herd
autoretryfor=(ConnectionError, TimeoutError), # Auto-retry for these exceptions
)
def predictwithretry(self, features: dict):
"""Task with comprehensive retry configuration."""
try:
result = runinference(features)
return result
except MemoryError:
# Do not retry on memory errors - worker needs restart
logger.critical("Worker out of memory!")
raise
except ValueError as exc:
# Retry with custom delay for input errors
raise self.retry(exc=exc, countdown=5, maxretries=2)
except Exception as exc:
# Default retry behavior
logger.error(f"Unexpected error: {exc}")
raise self.retry(exc=exc)
Dead Letter Queue Pattern
@sharedtask(name='tasks.handledeadletter')
def handle
deadletter(failedtaskinfo: dict):
"""Process tasks that have exhausted all retries."""
logger.error(f"Dead letter: {failed
taskinfo}")
# Store in database, send alert, etc.
@shared
task(bind=True, maxretries=3)
def predict
withdlq(self, features: dict):
"""Task that routes to DLQ after max retries."""
try:
return run
inference(features)
except Exception as exc:
if self.request.retries >= self.maxretries:
handledeadletter.delay({
'taskid': self.request.id,
'features': features,
'error': str(exc),
'retries': self.request.retries,
})
raise
raise self.retry(exc=exc)
Scaling Workers
Horizontal Scaling Strategies
# Scale by queue type - dedicate workers to specific workloads
Inference workers (fast tasks, high concurrency)
celery -A celeryapp worker \
--queues=inference \
--concurrency=8 \
--pool=prefork \
--loglevel=info \
-n inference1@%h
Batch workers (long tasks, lower concurrency)
celery -A celeryapp worker \
--queues=batch \
--concurrency=2 \
--pool=prefork \
--loglevel=info \
-n batch1@%h
Training workers (GPU tasks, single concurrency)
celery -A celeryapp worker \
--queues=training \
--concurrency=1 \
--pool=solo \
--loglevel=info \
-n training1@%h
Auto-scaling
# Auto-scale between 2 and 10 worker processes based on load
celery -A celeryapp worker \
--autoscale=10,2 \
--queues=inference \
--loglevel=info
Priority Queues
# Define priority queues in configuration
app.conf.taskqueues = [
Queue('highpriority', routingkey='high'),
Queue('default', routingkey='default'),
Queue('lowpriority', routingkey='low'),
]
Submit tasks with different priorities
predictsingle.applyasync(
kwargs={'features': vipfeatures},
queue='highpriority',
priority=9, # Higher number = higher priority (0-9)
)
Production Deployment
Docker Compose for Production
version: '3.8'
services:
redis:
image: redis:7-alpine
ports:
- "6379:6379"
volumes:
- redis-data:/data
command: >
redis-server
--maxmemory 4gb
--maxmemory-policy allkeys-lru
--save 60 1000
--appendonly yes
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 10s
timeout: 5s
retries: 3
api:
build: .
ports:
- "8000:8000"
environment:
- REDISURL=redis://redis:6379/0
- RESULTBACKEND=redis://redis:6379/1
dependson:
redis:
condition: servicehealthy
command: uvicorn api:app --host 0.0.0.0 --port 8000 --workers 4
inference-worker:
build: .
environment:
- REDISURL=redis://redis:6379/0
- RESULTBACKEND=redis://redis:6379/1
- MODELPATH=/app/models/fraudmodel.pkl
volumes:
- ./models:/app/models
dependson:
redis:
condition: servicehealthy
command: >
celery -A celeryapp worker
--queues=inference
--concurrency=4
--pool=prefork
--max-tasks-per-child=200
--loglevel=info
-n inference@%h
deploy:
replicas: 2
resources:
limits:
cpus: '2.0'
memory: 4G
batch-worker:
build: .
environment:
- REDISURL=redis://redis:6379/0
- RESULTBACKEND=redis://redis:6379/1
- MODELPATH=/app/models/fraudmodel.pkl
volumes:
- ./models:/app/models
dependson:
redis:
condition: service
healthy
command: >
celery -A celeryapp worker
--queues=batch
--concurrency=2
--pool=prefork
--max-tasks-per-child=50
--loglevel=info
-n batch@%h
flower:
build: .
ports:
- "5555:5555"
environment:
- REDISURL=redis://redis:6379/0
dependson:
redis:
condition: service
healthy
command: >
celery -A celeryapp flower
--port=5555
--broker=redis://redis:6379/0
--basicauth=admin:flowerpassword
celery-beat:
build: .
environment:
- REDISURL=redis://redis:6379/0
- RESULTBACKEND=redis://redis:6379/1
dependson:
redis:
condition: servicehealthy
command: celery -A celeryapp beat --loglevel=info
volumes:
redis-data:
Periodic Tasks with Celery Beat
# celeryapp.py - Add beat schedule
from celery.schedules import crontab
app.conf.beat
schedule = {
'health-check-every-minute': {
'task': 'tasks.workerhealthcheck',
'schedule': 60.0, # Every 60 seconds
},
'model-reload-daily': {
'task': 'tasks.reloadmodel',
'schedule': crontab(hour=2, minute=0), # Every day at 2:00 AM
},
'cleanup-old-results': {
'task': 'tasks.cleanupresults',
'schedule': crontab(hour='/6'), # Every 6 hours
},
}
Best Practices
1. Keep Tasks Small and Focused
Each task should do one thing well. Use chains and groups to compose complex workflows from simple building blocks.
2. Always Set Time Limits
Without time limits, a hung task can block a worker indefinitely. Set both soft and hard time limits.
3. Use ackslate for Critical Tasks
Setting ackslate=True ensures that if a worker crashes mid-task, the message returns to the queue and is picked up by another worker.
4. Handle Model Loading Efficiently
Load the model once per worker process, not per task. Use lrucache or worker initialization signals:
from celery.signals import workerprocessinit
@worker
processinit.connect
def init
worker(**kwargs):
"""Initialize model when worker process starts."""
loadmodel()
5. Monitor Queue Depths
Alert when queue depth exceeds a threshold — this indicates workers cannot keep up with incoming tasks:
import redis
def checkqueuedepth(queuename='inference', threshold=100):
r = redis.Redis(host='localhost', port=6379, db=0)
depth = r.llen(queuename)
if depth > threshold:
logger.warning(f"Queue '{queuename}' depth is {depth}, exceeds threshold {threshold}")
return depth
6. Use Task IDs Wisely
Use deterministic task IDs to prevent duplicate submissions:
taskid = f"predict-{userid}-{transactionid}"
predict
single.applyasync(kwargs=kwargs, taskid=taskid)
7. Set workerprefetch_multiplier=1 for ML
ML tasks are typically long-running. The default prefetch multiplier (4) causes workers to hoard tasks, leading to uneven load distribution.
Conclusion
Celery with Redis provides a robust, battle-tested foundation for asynchronous ML workloads. In this tutorial, you learned how to:
- Set up Celery with Redis as both broker and result backend
- Create async ML inference tasks with proper error handling and retries
- Compose complex workflows using chains, groups, and chords
- Build a FastAPI application that submits and tracks async tasks
- Monitor workers and tasks with Flower
- Handle errors gracefully with exponential backoff and dead letter queues
- Scale workers horizontally with queue-based routing
- Deploy the complete stack with Docker Compose
This architecture handles everything from single real-time predictions to batch processing of thousands of items, with full visibility into task states and automatic recovery from failures. Start with a simple setup, measure your throughput requirements, and scale workers as needed.