Watching Celery Workers: What Flower Sees, Queue Depth and the Oldest Job's Age from Redis, a Request ID and One Trace
A background job fails quietly. Flower lists what workers reported, so 12 waiting jobs had zero rows. Redis gives the real depth, and a stamped enqueued_at gives the oldest job's age (79 s, past a 60 s promise). A request ID in the headers tells one job's story, a trace shows 3.8 s spent in the queue, and the alert goes on age, not CPU.
What you will learn
- Read what Flower shows and what it can't see
- Measure queue depth and the age of the oldest job straight from Redis
- Carry a request ID from the sender to every log line, including child tasks
- Trace one job across the queue with OpenTelemetry, and choose what deserves an alert
Before you start
- Celery and Redis for background tasks
- Basic Python logging
A background job fails quietly, and nobody is looking at it. So this is about seeing what the workers are doing: Flower first, then Redis, then following one job.
Think of a head chef glancing at the ticket rail. How many tickets are waiting? That's the queue depth. How old is the oldest ticket? Fresh tickets are fine; one ticket waiting forever is not. That's the age of the oldest job. Which station is stuck? That's what Flower is for. One look, and the chef knows if the kitchen is falling behind.
What Flower reads
Flower is already in the subtitle app's Compose file. Workers send events, like task started and task succeeded, and Flower keeps a list. Its API showed six tasks succeeded and one failed; the failure kept its error, "audio stream ended early", and the slowest run took 2.1 seconds. Flower itself asks the workers to send these events. No event, no row.
What Flower can't see
Keep the worker busy and send twelve jobs. The task list has zero rows for them, because events come from workers and these jobs haven't met one. The waiting count says twelve. Turn on task_send_sent_event and the sender sends an event too, so six more jobs show up as pending. Restart Flower and the list is empty, because it's kept in memory; the count says eighteen, because it asks Redis directly. The count is right, but it's only a number. It can't tell you how old a job is.
Depth and age, straight from Redis
r = redis.Redis.from_url(BROKER)
MAX_AGE = 60 # seconds: what we promised the user
def look(queue="celery"):
depth = r.llen(queue)
oldest = r.lindex(queue, -1) # the next job out
if oldest is None:
return depth, 0.0
headers = json.loads(oldest)["headers"]
return depth, time.time() - headers["enqueued_at"]
A new job arrived every two seconds, and the worker needed six seconds for each. r.llen gives the depth; r.lindex(queue, -1) gives the next job out, because new jobs go in at one end of the Redis list. Depth reached 40 and the oldest job had waited 79 seconds; it crossed the 60-second limit by 100 seconds, so it alerted. Sixty jobs were sent and Flower listed 22. The other 38 were waiting, with no error anywhere.
Where the age comes from
Open a message and there's an id, a task name, retries, but no time it was sent. So add it:
@before_task_publish.connect
def stamp(headers, **_):
headers["enqueued_at"] = time.time()
if current_task and "request_id" not in headers:
rid = current_task.request.get("request_id")
headers["request_id"] = rid
before_task_publish fires for every message, and this stamps enqueued_at. Age is now minus that. A signal only runs in a process that imported it, so the sender has to import this file too.
One ID, three places
The send script plays the API: it makes a short request ID, logs it, and apply_async carries it in the task headers. Celery's own correlation_id already holds the task ID, so this one is called request_id. A filter on the log handler reads it from the running task:
class AddRequestId(logging.Filter):
def filter(self, record):
record.request_id = "-"
if current_task:
req = current_task.request
record.request_id = req.get("request_id", "-")
return True
@after_setup_task_logger.connect
def add_filter(logger, **_):
for handler in logger.handlers:
handler.addFilter(AddRequestId())
The job retried once, and both tries carried the same ID, so a retry keeps its headers. But it also sent a second task, notify, and without help its log line showed a dash. That's why stamp copies the ID from the running task into whatever it sends.
One trace across the queue
def start_tracing():
if os.environ.get("TRACING") != "1":
return
exporter = ConsoleSpanExporter(
out=sys.__stdout__, formatter=one_line
)
provider = TracerProvider()
processor = SimpleSpanProcessor(exporter)
provider.add_span_processor(processor)
trace.set_tracer_provider(provider)
CeleryInstrumentor().instrument()
@worker_process_init.connect(weak=False)
def in_each_worker_process(**_):
start_tracing()
The Celery instrumentor gives you this in one call. The sender makes a span called apply_async; its trace ID goes into the task headers as traceparent, so it sits in Redis with the job. The worker makes a second span, run, with the same trace ID and the send span as its parent. The gap between them: 3.8 seconds in the queue. Both sides need the instrumentor; where the sender had none, the worker started a separate trace. Tracing in general is in LLM observability and tracing.
What deserves an alert?
| Case | Depth | Oldest | Alert? |
|---|---|---|---|
| One worker behind (CPU nearly zero) | 40 | 79 s | Yes |
| A burst of quick jobs | 48 | a fraction of a second | No |
| Every worker dead; Flower's list doesn't change | 3 | 70 s | Yes |
CPU told you nothing: time.sleep keeps it flat here, and real Whisper would keep it busy on a good day too. Alert on age past what you promised, and on depth that keeps growing.
Common mistakes
- Reading a quiet Flower page as a healthy queue.
- Alerting on depth alone, which fires on harmless bursts.
- Stamping in a signal the sender never imports.
- Losing the request ID on tasks sent from inside tasks.
Quick recap
- Flower shows what workers reported.
- Depth and age come straight from Redis, with an
enqueued_atstamp. - A request ID puts one job's story in your logs; a trace shows where the time went.
Try it yourself
Write a small alert script that calls look every ten seconds and logs when the age passes the limit.
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.
