The Complete Production SOP: How to Deploy and Run Celery Distributed Task Queue & Worker Tuning in Autonomous AI Agents
Step-by-step SOP to install and run Celery Distributed Task Queue & Worker Tuning in Codex, Claude Code, and Cursor. Includes verified prompts and fixes.
Technical Overview & Architectural Context
Autonomous coding agents frequently make critical configuration blunders when setting up distributed task queues with Python Celery. Without strict procedural boundaries, LLMs routinely default to naive configurations: setting `broker_url` without idempotency safeguards, neglecting acknowledgment mechanics like `task_acks_late`, leaving `worker_prefetch_multiplier` at default values (which starves concurrent workers on heterogeneous task durations), and mixing CPU-bound jobs with I/O-bound tasks in a single unmanaged worker pool.
Prerequisites & Environment Requirements
Verified Search Intents & Long-Tail Queries Solved
This operational tutorial is engineered to provide deterministic solutions for these developer search queries:
Step-by-Step Execution Playbook
Local Environment Setup & SKILL.md Mounting
Create the local skill manifest directory and inject verified procedural rules into your agent runtime.
Agent runtimes such as Claude Code, Cursor, Windsurf, and Codex locate contextual capabilities through standard skill directories. By placing `SKILL.md` under `~/.agents/skills/celery-distributed-task-worker-pool/` or `.cursor/skills/`, the agent automatically indexes frontmatter triggers like 'tune celery worker concurrency' and 'configure celery task routing' without expanding system prompts unnecessarily.
mkdir -p ~/.agents/skills/celery-distributed-task-worker-pool && curl -fsSL https://askills.dev/api/skills/celery-distributed-task-worker-pool/raw -o ~/.agents/skills/celery-distributed-task-worker-pool/SKILL.md---
name: "celery-distributed-task-worker-pool"
description: "Run distributed asynchronous background tasks and scheduled crons with Python Celery."
metadata:
author: "Celery"
version: "1.0.0"
runtime_compatibility:
- "codex"
- "claude-code"
- "cursor"
- "windsurf"
triggers:
- "tune celery worker concurrency"
- "configure celery task routing"
- "enable celery task_acks_late"
permissions:
fs_read: true
fs_write: "workspace"
shell_exec: false
net_access: false
---
# Celery Distributed Task Queue & Worker Tuning
Configures Celery with Redis/RabbitMQ brokers: configuring prefork vs gevent/eventlet pools, worker concurrency, task routing, late acknowledgments (task_acks_late), and flower monitoring dashboards.
## When to Invoke
Invoke this skill whenever you need to:
- tune celery worker concurrency
- configure celery task routing
- enable celery task_acks_late
## Execution SOP & Rules
1. Initialize Celery app: app = Celery('tasks', broker='redis://localhost:6379/0').
2. Configure app.conf.task_routes = {'tasks.heavy_*': {'queue': 'heavy'}, 'tasks.email_*': {'queue': 'email'}}.
3. Set task_acks_late = True and worker_prefetch_multiplier = 1 for long-running reliable tasks.
4. Run workers specifying queue and pool: celery -A tasks worker -l info -Q heavy -c 4.
## Verification Checklist
- Run local linting, syntax validation, and type-checks before reporting completion.
- Ensure all created or modified files adhere to workspace boundaries and avoid uncommitted secrets.
- Verify tests or build commands exit cleanly with return code 0.Place the SKILL.md inside `.claude/skills/` or `.cursor/skills/` at repo root to make Celery worker boundaries deterministic across your entire engineering team without consuming baseline context tokens.
Ensure `shell_exec: false` remains respected in unmanaged environments; autonomous agents must generate tested Python configs and systemd/supervisord manifests rather than directly launching unmonitored background daemons.
Celery Configuration & Broker Isolation
Inject dedicated broker settings, late acknowledgment flags, and queue routes without leaking secrets.
Instruct your agent to declare explicit task queues and set `task_acks_late=True` alongside `worker_prefetch_multiplier=1`. This prevents workers from prefetching and hogging long-running batches if an unexpected crash or OOM event occurs during execution.
uv pip install celery[redis] pytest-celery flowerimport os
from celery import Celery
from kombu import Queue, Exchange
broker_url = os.getenv('CELERY_BROKER_URL', 'redis://localhost:6379/0')
result_backend = os.getenv('CELERY_RESULT_BACKEND', 'redis://localhost:6379/1')
app = Celery('prod_worker', broker=broker_url, backend=result_backend)
app.conf.update(
task_default_queue='default',
task_queues=(
Queue('default', Exchange('default'), routing_key='default'),
Queue('heavy', Exchange('heavy'), routing_key='heavy'),
Queue('email', Exchange('email'), routing_key='email'),
),
task_routes={
'tasks.heavy_*': {'queue': 'heavy'},
'tasks.email_*': {'queue': 'email'},
},
task_acks_late=True,
task_reject_on_worker_lost=True,
worker_prefetch_multiplier=1,
worker_max_tasks_per_child=50,
timezone='UTC',
enable_utc=True,
)Always configure `worker_max_tasks_per_child` (e.g., 50 to 100) when running prefork workers doing data processing to prevent runaway Python memory leaks.
Never configure `task_acks_late=True` without verifying that every task in the queue is idempotent. If a task fails mid-execution and restarts, non-idempotent operations may produce duplicate writes.
Intent Matching & Worker Tuning Trigger Invocation
Prompt the agent using frontmatter triggers to configure multi-pool worker topologies.
Provide high-intent user requests matching the triggers `tune celery worker concurrency` or `configure celery task routing`. The agent will construct optimal worker launch processes segregating heavy CPU prefork workers from gevent or thread-based I/O workers.
Target specific worker pools directly in the prompt by distinguishing between CPU-bound prefork queues and high-concurrency gevent I/O queues.
Avoid running gevent or eventlet worker pools alongside C-extensions that do not yield the GIL unless monkey-patching is invoked before any other imports.
Verification, Linting & Output Quality Gate
Execute automated self-healing checks and Celery configuration validation before finishing.
The agent must run linting tools (such as ruff or flake8) and verify configuration integrity using Celery's inspect and check utilities within the local environment before submitting changes.
python -m celery -A celery_config.app report && uv run ruff check celery_config.pyAdd a dry-run task routing test using `app.control.inspect()` in your integration suite to catch misrouted tasks before production deployment.
Running `celery -A ... inspect ping` inside a sandbox without an active Redis or RabbitMQ service will hang unless a connection timeout is strictly passed.
Real-World Scenario: Architecting Scalable Asynchronous Report Generation and Email Queuing
“We are suffering from worker starvation in our data service. Please configure celery task routing, enable celery task_acks_late, and tune celery worker concurrency to segregate heavy PDF reports from immediate email dispatch.”
Runtime Troubleshooting & Failure Modes
Root Cause: The Celery worker ran out of memory (OOM) due to unbounded task execution or memory leaks within prefork child processes on large data tasks.
app.conf.update(worker_max_tasks_per_child=20, worker_prefetch_multiplier=1)
# Run worker with limited concurrency:
celery -A celery_config.app worker -Q heavy -c 2 -l info --max-memory-per-child=500000Root Cause: Celery worker daemon started before broker container was ready, or broker URL environment variable fallback is pointing to an invalid localhost port.
export CELERY_BROKER_URL="redis://127.0.0.1:6379/0"
python -c "import redis; r = redis.Redis.from_url('${CELERY_BROKER_URL}'); print(r.ping())"Frequently Asked Questions (Celery Distributed Task Queue & Worker Tuning SOP)
Q:Can I use Celery Distributed Task Queue & Worker Tuning across Codex, Claude Code, and Cursor simultaneously?
Yes. This skill adheres to standard SKILL.md conventions. Placing the file in your project repository under `.cursor/skills/`, `.claude/skills/`, or globally under `~/.agents/skills/` ensures all supported runtimes ingest identical procedural constraints.
Q:How does Celery Distributed Task Queue & Worker Tuning prevent context window overflow during long agent sessions?
It provides concise declarative routing and tuning rules instead of forcing the agent to reason through extensive Celery documentation. The agent relies on deterministic parameter templates (`worker_prefetch_multiplier = 1`, `task_acks_late = True`) without conversational back-and-forth.
Q:Does this skill require escalated root or container permissions?
No. The skill enforces `fs_write: workspace` and `shell_exec: false`. The agent is directed to generate valid Python modules and supervisor/systemd templates safely inside your working directory without needing sudo or raw shell execution.
Ready to equip your autonomous agent with Celery Distributed Task Queue & Worker Tuning?
Copy the complete audited SKILL.md specification or download the 1-click zip bundle directly from our verified registry.