Scheduled Jobs and Running Workers Day to Day
Run recurring jobs from one scheduler without double runs, make them safe when they do run twice, and operate workers day to day: graceful shutdown, process recycling and queue metrics.
Contentsand lesson path
On this page
- Why it matters
- Single-scheduler dispatch and competing worker pools
- Worker lifecycles: graceful shutdown and memory recycling
- Queue observability and production telemetry
- Check your understanding
- Apply it
- Review prompt
Lessons of Background Jobs & Task Queues
- What Belongs Outside the Request, and Which Broker Fits Concept · 20 min
- Lab: A Worker, a Broker and a Status Endpoint Lab · 30 min
- Designing Jobs for At-Least-Once Delivery Concept · 20 min
- Enqueue After Commit with an Outbox Table Worked example · 25 min
- Scheduled Jobs and Running Workers Day to Day Concept · 15 min
- Check: What Happens When the Worker Dies? Knowledge check · 8 questions
What you will learn
- Enqueue jobs consistently with database writes (transactional outbox or enqueue-after-commit) and run periodic jobs on a schedule.
- Make jobs safe under at-least-once delivery with idempotent handlers, bounded retries with backoff, time limits and a dead-letter path.
01. Why it matters
Most background jobs are triggered by a request or an event, such as generating an invoice when a payment succeeds. Production systems also depend on recurring scheduled jobs: a daily reconciliation at midnight, a weekly newsletter, purging expired sessions, archiving old partitions.
A naive approach is embedding in-process schedulers—such as Python APScheduler or timer loops (asyncio.sleep)—directly into the main web application process. However, as soon as your backend scales horizontally across multiple container replicas or auto-scaling groups, every web replica runs its own independent timer. A scheduled midnight billing job will execute as many times as you have web servers, causing duplicate charges, database lock contention, and notification spam.
Running workers day to day also brings problems that web APIs meet less often: long-running processes whose memory keeps growing, termination signals during every deployment, workers that reserve more tasks than they can run, and tasks that hang without failing. This lesson covers the scheduler first, then those worker problems.
02. Single-scheduler dispatch and competing worker pools
The basic rule is a separation of responsibilities:
- Schedulers dispatch, workers execute: The scheduler should not run heavy work itself. Its job is to wake up on the schedule tick (e.g.
0 0 * * *), build a small task message and publish it to the broker. A scheduler that only publishes finishes each tick in milliseconds, so one slow job cannot delay the next tick. - Competing worker pool: The pool of worker processes consumes scheduled messages from the queue like any other task, spreading the load across CPU cores and machines.
- One scheduler at a time (leader election): Scheduled tasks should fire once per time window, so only one scheduler should dispatch at a time. This is done either by a container orchestrator (such as a Kubernetes
CronJobresource that spawns a short-lived container to push the job to Redis/RabbitMQ) or by distributed leader election. Neither guarantees exactly once: Kubernetes documents that a CronJob creates a Job "approximately once" per scheduled time, so it can occasionally create two, or none if the controller missed the time by more thanstartingDeadlineSeconds.
In multi-instance deployments where a dedicated scheduler daemon runs on several nodes for high availability, the instances elect a leader through a lock: a PostgreSQL advisory lock (pg_try_advisory_lock) or a Redis lock with a TTL lease. Celery Beat has no leader election of its own; you add it with a lock-based scheduler such as RedBeat, or with your own lock code. Only the leader publishes scheduled messages, while standby replicas wait for the lease to expire. A lease can still briefly produce two leaders — a leader that pauses (a long GC, a frozen VM) past its lease resumes and dispatches while a new leader already does — so the lock reduces duplicates without ruling them out.
Design every scheduled task to be safe when it runs twice, or not at all, for a window:
- Idempotent per window: start the run by inserting a row with
UNIQUE (job_name, window_start)and stop if it already exists; if the lock protects writes elsewhere, pass a fencing token (a number that grows with every new lease) that the protected store checks. - Overlap: decide what happens when the previous run is still going at the next tick — skip or wait, never run both. For a CronJob set
concurrencyPolicy: Forbid; in Celery, take a lock for the job, or rely on the per-window row. - Missed runs: when the scheduler was down at midnight, decide per job whether to catch up (run once for the missed window, which the per-window row makes safe) or skip it.
startingDeadlineSecondson a CronJob sets how late a run may still start; for other schedulers, check what they do on restart before you rely on it.
# celery_app.py - Celery and Celery Beat settings for scheduled tasks
from celery import Celery
from celery.schedules import crontab
app = Celery("ops_worker", broker="redis://localhost:6379/0")
app.conf.update(
# 1. Scheduled task schedule definitions (Celery Beat)
beat_schedule={
"daily-reconciliation": {
"task": "tasks.reconcile_daily_ledger",
"schedule": crontab(hour=0, minute=0), # Midnight UTC
},
"purge-stale-outbox": {
"task": "tasks.purge_expired_outbox_rows",
"schedule": crontab(minute="*/30"), # Every 30 minutes
},
},
# 2. Worker concurrency and prefetch controls
worker_prefetch_multiplier=1, # Reserve 1 task per pool process
task_acks_late=True, # Ack after the task returns or fails
# With Redis, an unacked task is redelivered after visibility_timeout
# (default 1 hour): keep it above the longest task_time_limit and any
# ETA/countdown, or long tasks run twice.
broker_transport_options={"visibility_timeout": 2 * 3600},
task_reject_on_worker_lost=True, # Requeue if the child dies (can loop)
# 3. Memory leak mitigation via process recycling
worker_max_tasks_per_child=1000, # Recycle worker process every 1k tasks
worker_max_memory_per_child=250000, # KiB: recycle a child above ~250 MB
# 4. Hard execution limits against hung tasks
task_soft_time_limit=300, # Raise SoftTimeLimitExceeded after 5 mins
task_time_limit=360, # Kill and replace the child after 6 mins
)03. Worker lifecycles: graceful shutdown and memory recycling
Workers are restarted on every deployment, so they must follow the Unix process lifecycle:
- Graceful draining on SIGTERM: When Kubernetes, Docker or systemd stops a worker during a rolling deployment, it first sends
SIGTERM. The worker should stop taking new tasks from the broker at once and start draining. During this period, the worker allows active in-flight tasks a grace period (e.g. 30 to 60 seconds) to finish their current unit of work, commit database transactions, and send task acknowledgements. Only if tasks are still running when the grace period expires does the orchestrator sendSIGKILL, which cannot be caught; with late acknowledgement those tasks are then redelivered, so they must be idempotent. Losing one pool child is different from losing the whole worker: when only a child dies (the OOM killer, a crash in a C extension), the parent is still alive and, even withtask_acks_late, acknowledges the task and records it as failed withWorkerLostError. Settask_reject_on_worker_lost=Trueto have it re-queued instead, as the configuration above does, and accept the risk that a task which itself kills the child is re-queued again and again. Celery 5.7 addstask_retry_on_worker_lost=True, which instead sends the task again asTask.retry()would, afterdefault_retry_delay, somax_retriesbounds that loop and the task then ends as failed (Celery configuration docs). - Fair prefetching (
prefetch_multiplier = 1): By default, Celery reserves several messages per worker process (the multiplier is 4) to save network round trips. If long tasks, such as 10-minute video encodings, sit reserved behind a busy process, they wait while other workers are idle. A multiplier of 1 with late acknowledgement spreads long tasks more evenly; for very short tasks a higher prefetch can be faster, so measure. - Process recycling against memory leaks: The memory of long-running Python workers often grows over time: C extensions and caches leak, and a fragmented heap is rarely handed back to the operating system. Recycling each child process after a bounded number of tasks (
worker_max_tasks_per_child = 1000) or above a memory limit returns its memory when the child exits. The parent starts a replacement, so the pool keeps serving; the leak itself is still worth finding.
04. Queue observability and production telemetry
A worker fleet is hard to run blind. Four metrics belong on its dashboard and in its alerts:
- Queue backlog (depth): The total count of pending, unconsumed messages currently sitting inside the queue. While occasional brief spikes are normal during traffic surges, a queue depth that keeps increasing means tasks arrive faster than the workers finish them: add workers, or find out why tasks got slower.
- Queue wait time (lag): The elapsed duration between when a task is enqueued by the API and when a worker actually begins executing it. For customer-facing work such as password reset emails, set a target of a few seconds and alert when the wait exceeds it.
- Dead-letter queue (DLQ) rate: The arrival rate of tasks sent to the dead-letter queue after exhausting all retry attempts. Any sustained increase in DLQ arrivals points to an upstream schema mismatch, an expired third-party API token, or an unhandled software bug that someone should look at soon.
- Worker liveness and heartbeats: Tracking periodic heartbeat pings from worker nodes. If a worker pod crashes due to an out-of-memory (OOM) event without sending a graceful exit message, heartbeat timeouts alert the supervisor to requeue orphaned tasks.
05. Check your understanding
06. Apply it
Check your own worker configuration and deployment manifests against these practices:
- Process recycling: Enable
worker_max_tasks_per_child(e.g. 500–1000 tasks) or memory-based recycling in your worker startup flags. - Task timeouts: Give every task both a soft time limit (allowing handlers to catch
SoftTimeLimitExceededand save checkpoint state) and a hard limit, so a task stuck on a network read cannot hold a worker for ever. - Graceful shutdown: Inspect your Kubernetes pod specification or Docker Compose files. Check that
terminationGracePeriodSeconds(default 30 s; raise it for long jobs) gives workers enough time to drain in-flight jobs cleanly beforeSIGKILLis sent. - Queue depth alerts: Export broker queue length metrics to Prometheus or Datadog, and configure alert thresholds to notify on-call engineers when queue lag crosses acceptable SLA boundaries.
07. Review prompt
Summarise the separation between recurring schedulers and worker pools, and how a per-window row makes a duplicate run harmless. Explain why SIGTERM handling matters during rolling deployments and what still happens to a task that outlives the grace period, how process recycling mitigates memory leaks in long-running workers, and why queue depth and queue wait time are the first metrics to watch for a worker fleet.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.