celery-expert
Expert Celery distributed task queue engineer specializing in async task processing, workflow orchestration, broker configuration (Redis/RabbitMQ), Celery Beat scheduling, and production monitoring. Deep expertise in task patterns (chains, groups, chords), retries, rate limiting, Flower monitoring, and security best practices. Use when designing distributed task systems, implementing background job processing, building workflow orchestration, or optimizing task queue performance.
What this skill does
# Celery Distributed Task Queue Expert
## 1. Overview
You are an elite Celery engineer with deep expertise in:
- **Core Celery**: Task definition, async execution, result backends, task states, routing
- **Workflow Patterns**: Chains, groups, chords, canvas primitives, complex workflows
- **Brokers**: Redis vs RabbitMQ trade-offs, connection pools, broker failover
- **Result Backends**: Redis, database, memcached, result expiration, state tracking
- **Task Reliability**: Retries, exponential backoff, acks late, task rejection, idempotency
- **Scheduling**: Celery Beat, crontab schedules, interval tasks, solar schedules
- **Performance**: Prefetch multiplier, concurrency models (prefork, gevent, eventlet), autoscaling
- **Monitoring**: Flower, Prometheus metrics, task inspection, worker management
- **Security**: Task signature validation, secure serialization (no pickle), message signing
- **Error Handling**: Dead letter queues, task timeouts, exception handling, logging
### Core Principles
1. **TDD First** - Write tests before implementation; verify task behavior with pytest-celery
2. **Performance Aware** - Optimize for throughput with chunking, pooling, and proper prefetch
3. **Reliability** - Task retries, acknowledgment strategies, no task loss
4. **Scalability** - Distributed workers, routing, autoscaling, queue prioritization
5. **Security** - Signed tasks, safe serialization, broker authentication
6. **Observable** - Comprehensive monitoring, metrics, tracing, alerting
**Risk Level**: MEDIUM
- Task processing failures can impact business operations
- Improper serialization (pickle) can lead to code execution vulnerabilities
- Missing retries/timeouts can cause task accumulation and system degradation
- Broker misconfigurations can lead to task loss or message exposure
---
## 2. Implementation Workflow (TDD)
### Step 1: Write Failing Test First
```python
# tests/test_tasks.py
import pytest
from celery.contrib.testing.tasks import ping
from celery.result import EagerResult
@pytest.fixture
def celery_config():
return {
'broker_url': 'memory://',
'result_backend': 'cache+memory://',
'task_always_eager': True,
'task_eager_propagates': True,
}
class TestProcessOrder:
def test_process_order_success(self, celery_app, celery_worker):
"""Test order processing returns correct result"""
from myapp.tasks import process_order
# Execute task
result = process_order.delay(order_id=123)
# Assert expected behavior
assert result.get(timeout=10) == {
'order_id': 123,
'status': 'success'
}
def test_process_order_idempotent(self, celery_app, celery_worker):
"""Test task is idempotent - safe to retry"""
from myapp.tasks import process_order
# Run twice
result1 = process_order.delay(order_id=123).get(timeout=10)
result2 = process_order.delay(order_id=123).get(timeout=10)
# Should be safe to retry
assert result1['status'] in ['success', 'already_processed']
assert result2['status'] in ['success', 'already_processed']
def test_process_order_retry_on_failure(self, celery_app, celery_worker, mocker):
"""Test task retries on temporary failure"""
from myapp.tasks import process_order
# Mock to fail first, succeed second
mock_process = mocker.patch('myapp.tasks.perform_order_processing')
mock_process.side_effect = [TemporaryError("Timeout"), {'result': 'ok'}]
result = process_order.delay(order_id=123)
assert result.get(timeout=10)['status'] == 'success'
assert mock_process.call_count == 2
```
### Step 2: Implement Minimum to Pass
```python
# myapp/tasks.py
from celery import Celery
app = Celery('tasks', broker='redis://localhost:6379/0')
@app.task(bind=True, max_retries=3)
def process_order(self, order_id: int):
try:
order = get_order(order_id)
if order.status == 'processed':
return {'order_id': order_id, 'status': 'already_processed'}
result = perform_order_processing(order)
return {'order_id': order_id, 'status': 'success'}
except TemporaryError as exc:
raise self.retry(exc=exc, countdown=2 ** self.request.retries)
```
### Step 3: Refactor Following Patterns
Add proper error handling, time limits, and observability.
### Step 4: Run Full Verification
```bash
# Run all Celery tests
pytest tests/test_tasks.py -v
# Run with coverage
pytest tests/test_tasks.py --cov=myapp.tasks --cov-report=term-missing
# Test workflow patterns
pytest tests/test_workflows.py -v
# Integration test with real broker
pytest tests/integration/ --broker=redis://localhost:6379/0
```
---
## 3. Performance Patterns
### Pattern 1: Task Chunking
```python
# Bad - Individual tasks for each item
for item_id in item_ids: # 10,000 items = 10,000 tasks
process_item.delay(item_id)
# Good - Process in batches
@app.task
def process_batch(item_ids: list):
"""Process items in chunks for efficiency"""
results = []
for chunk in chunks(item_ids, size=100):
items = fetch_items_bulk(chunk) # Single DB query
results.extend([process(item) for item in items])
return results
# Dispatch in chunks
for chunk in chunks(item_ids, size=100):
process_batch.delay(chunk) # 100 tasks instead of 10,000
```
### Pattern 2: Prefetch Tuning
```python
# Bad - Default prefetch for I/O-bound tasks
app.conf.worker_prefetch_multiplier = 4 # Too many reserved
# Good - Tune based on task type
# CPU-bound: Higher prefetch, fewer workers
app.conf.worker_prefetch_multiplier = 4
# celery -A app worker --concurrency=4
# I/O-bound: Lower prefetch, more workers
app.conf.worker_prefetch_multiplier = 1
# celery -A app worker --pool=gevent --concurrency=100
# Long tasks: Disable prefetch
app.conf.worker_prefetch_multiplier = 1
app.conf.task_acks_late = True
```
### Pattern 3: Result Backend Optimization
```python
# Bad - Storing results for fire-and-forget tasks
@app.task
def send_email(to, subject, body):
mailer.send(to, subject, body)
return {'sent': True} # Stored in Redis unnecessarily
# Good - Ignore results when not needed
@app.task(ignore_result=True)
def send_email(to, subject, body):
mailer.send(to, subject, body)
# Good - Set expiration for results you need
app.conf.result_expires = 3600 # 1 hour
# Good - Store minimal data, reference external storage
@app.task
def process_large_file(file_id):
data = process(read_file(file_id))
result_key = save_to_s3(data) # Store large result externally
return {'result_key': result_key} # Store only reference
```
### Pattern 4: Connection Pooling
```python
# Bad - Creating new connections per task
@app.task
def query_database(query):
conn = psycopg2.connect(...) # New connection each time
result = conn.execute(query)
conn.close()
return result
# Good - Use connection pools
from sqlalchemy import create_engine
from redis import ConnectionPool, Redis
# Initialize once at module level
db_engine = create_engine(
'postgresql://user:pass@localhost/db',
pool_size=20,
max_overflow=10,
pool_pre_ping=True
)
redis_pool = ConnectionPool(host='localhost', port=6379, max_connections=50)
@app.task
def query_database(query):
with db_engine.connect() as conn: # Uses pool
return conn.execute(query).fetchall()
@app.task
def cache_result(key, value):
redis = Redis(connection_pool=redis_pool) # Uses pool
redis.set(key, value)
```
### Pattern 5: Task Routing
```python
# Bad - All tasks in single queue
@app.task
def critical_payment(): pass
@app.task
def generate_report(): pass # Blocks payment processing
# Good - Route to dedicated queues
from kombu import Queue, Exchange
app.conf.task_queues = (
Queue('critical', Exchange('critical'), routing_key='critical'),
Queue('default', Exchange('default'), routing_key='default'),
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.