/celery:task-patternsfrom celery
Provides production-ready Celery task templates with error handling, retries, rate limiting, time limits, and custom task classes. Useful for building robust asynchronous task processing.
Ships in celery. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them; scripts run unread.
Production-ready Celery task templates with comprehensive error handling, retry mechanisms, rate limiting, and custom behavior patterns.
This skill provides battle-tested templates and patterns for building robust Celery tasks. Each template demonstrates production-ready code with proper error handling, logging, retry logic, and security best practices.
Template: templates/basic-task.py
Simple task with standard error handling and logging.
Use when:
Features:
Template: templates/retry-task.py
Tasks with automatic retry mechanisms and exponential backoff.
Use when:
Features:
autoretry_forExample: See examples/task-with-retries.md for complete implementation guide
Template: templates/rate-limited-task.py
Tasks with rate limiting to control execution speed.
Use when:
Features:
Example: See examples/rate-limiting.md for complete guide
Template: templates/time-limited-task.py
Tasks with soft and hard time limits to prevent runaway execution.
Use when:
Features:
Template: templates/custom-task-class.py
Custom task base classes with specialized behavior.
Use when:
Features:
Example: See examples/custom-task-classes.md for comprehensive guide
Template: templates/pydantic-validation.py
Type-safe tasks with Pydantic model validation.
Use when:
Features:
Template: templates/database-task.py
Best practices for database operations in tasks.
Use when:
Features:
Template: templates/api-task.py
Best practices for external API calls in tasks.
Use when:
Features:
Usage: ./scripts/generate-task.sh <template_name> <output_file> [task_name]
Generate new Celery task from template with customizations.
Available templates:
Example:
./scripts/generate-task.sh retry-task tasks/my_api_call.py fetch_data
Usage: ./scripts/test-task.sh <task_file.py> [task_name]
Test Celery task by:
Example:
./scripts/test-task.sh templates/retry-task.py fetch_api_data
Usage: ./scripts/validate-task.sh <task_file.py>
Comprehensive validation including:
Example:
./scripts/validate-task.sh templates/api-task.py
# Use retry-task.py template
from templates.retry_task import fetch_api_data
# Queue task
result = fetch_api_data.delay('https://api.example.com/data')
# Get result
data = result.get(timeout=60)
print(data)
# Use rate-limited-task.py template
from templates.rate_limited_task import api_call_rate_limited
# Process 100 items at 10/minute rate
for i in range(100):
api_call_rate_limited.delay(f'/endpoint/{i}')
# Celery automatically enforces rate limit
# Use database-task.py template
from templates.database_task import insert_record, bulk_insert
# Single insert
result1 = insert_record.delay('users', {
'name': 'John Doe',
'email': '[email protected]'
})
# Bulk insert
records = [
{'name': 'Jane', 'email': '[email protected]'},
{'name': 'Bob', 'email': '[email protected]'},
]
result2 = bulk_insert.delay('users', records)
# Use custom-task-class.py template
from templates.custom_task_class import monitored_task
# Automatic metrics tracking
result = monitored_task.delay(123)
# Metrics logged automatically:
# - Start time
# - Duration
# - Success/failure
# - Arguments
# Use pydantic-validation.py template
from templates.pydantic_validation import process_user
# Valid data
user_data = {
'user_id': 123,
'email': '[email protected]',
'username': 'john_doe',
'age': 30,
'tags': ['premium']
}
result = process_user.delay(user_data)
# Invalid data returns structured error
invalid_data = {
'user_id': -1, # Invalid
'email': 'not-email', # Invalid
}
result = process_user.delay(invalid_data)
# Returns: {'status': 'error', 'errors': [...]}
# ✅ CORRECT
api_key = os.getenv('API_KEY', 'your_api_key_here')
# ❌ WRONG
api_key = 'sk-abc123xyz456'
# ✅ CORRECT
response = requests.get(url, timeout=30)
# ❌ WRONG
response = requests.get(url) # Can hang forever
# ✅ CORRECT
db.execute("SELECT * FROM users WHERE id = %s", (user_id,))
# ❌ WRONG
db.execute(f"SELECT * FROM users WHERE id = {user_id}")
@app.task(
bind=True,
autoretry_for=(RequestException,),
retry_backoff=True,
rate_limit='10/m'
)
def robust_api_call(self, url: str):
"""Retries on failure, respects rate limits."""
pass
@app.task(bind=True)
def well_logged_task(self, item_id: int):
logger.info(f"Starting task for item {item_id}")
try:
result = process(item_id)
logger.info(f"Successfully processed {item_id}")
return result
except Exception as exc:
logger.error(f"Failed to process {item_id}: {exc}")
raise
This skill follows strict security rules:
Choose basic-task.py when:
Choose retry-task.py when:
Choose rate-limited-task.py when:
Choose time-limited-task.py when:
Choose custom-task-class.py when:
Choose pydantic-validation.py when:
Choose database-task.py when:
Choose api-task.py when:
# Validate task structure
./scripts/validate-task.sh templates/retry-task.py
# Test task execution
./scripts/test-task.sh templates/retry-task.py fetch_api_data
# Start worker
celery -A tasks worker --loglevel=info
# Execute tasks
python3 templates/retry-task.py
@app.task(
bind=True,
autoretry_for=(RequestException,),
retry_backoff=True,
retry_jitter=True,
max_retries=5
)
@app.task(
rate_limit='10/m',
soft_time_limit=60,
time_limit=120
)
@app.task(
bind=True,
autoretry_for=(ValidationError, RequestException),
retry_backoff=True,
max_retries=3
)
def validated_api_task(self, request: dict):
# Validate with Pydantic
req = ApiRequest(**request)
# Make API call with retry
return make_call(req.url)
@app.task(
bind=True, # Access self (required for retry)
base=CustomTask, # Custom task class
autoretry_for=(Exception,), # Exceptions to retry
retry_backoff=True, # Exponential backoff
retry_backoff_max=600, # Max backoff seconds
retry_jitter=True, # Add randomness
max_retries=5, # Max attempts
default_retry_delay=10, # Default delay
rate_limit='10/m', # Rate limit
soft_time_limit=60, # Soft timeout (catchable)
time_limit=120, # Hard timeout (kills task)
ignore_result=False, # Store result
priority=5 # Task priority (0-9)
)
# Automatic
autoretry_for=(RequestException, Timeout)
# Manual
raise self.retry(exc=exc, countdown=60)
rate_limit='10/s' # 10 per second
rate_limit='100/m' # 100 per minute
rate_limit='1000/h' # 1000 per hour
examples/task-with-retries.md - Complete retry guideexamples/rate-limiting.md - Complete rate limiting guideexamples/custom-task-classes.md - Custom class guideAlways run validation before committing:
./scripts/validate-task.sh your-task.py
Validation checks:
examples/custom-task-classes.md (opens in a new tab)examples/rate-limiting.md (opens in a new tab)examples/task-with-retries.md (opens in a new tab)scripts/generate-task.sh (opens in a new tab)scripts/test-task.sh (opens in a new tab)scripts/validate-task.sh (opens in a new tab)templates/api-task.py (opens in a new tab)templates/basic-task.py (opens in a new tab)templates/custom-task-class.py (opens in a new tab)templates/database-task.py (opens in a new tab)templates/pydantic-validation.py (opens in a new tab)templates/rate-limited-task.py (opens in a new tab)templates/retry-task.py (opens in a new tab)templates/time-limited-task.py (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
celery-tasks, task-patterns, retry-logic, rate-limiting, error-handling
npx claudepluginhub vanman2024/ai-dev-marketplace --plugin celery10 skills in this plugin
/beat-schedulingPeriodic task scheduling patterns with Celery Beat (crontab, interval, solar). Use when configuring periodic tasks, setting up task schedules, implementing recurring jobs, configuring django-celery-beat, or creating dynamic schedules./broker-configurationsMessage broker setup patterns (Redis, RabbitMQ, SQS) for Celery including connection strings, SSL configuration, high availability, and production best practices. Use when configuring message brokers, setting up Redis/RabbitMQ/SQS, troubleshooting broker connections, implementing HA/failover, securing broker communications with SSL, or when user mentions broker setup, connection issues, sentinel, quorum queues, or AWS SQS integration./celery-config-patternsCelery configuration templates for all frameworks (Django, Flask, FastAPI, standalone). Use when configuring Celery, setting up task queues, creating Celery apps, integrating with frameworks, or when user mentions Celery configuration, task queue setup, broker configuration, or framework integration./deployment-configsProduction deployment configurations for Celery workers and beat schedulers across Docker, Kubernetes, and systemd environments. Use when deploying Celery to production, containerizing workers, orchestrating with Kubernetes, setting up systemd services, configuring health checks, implementing graceful shutdowns, or when user mentions deployment, Docker, Kubernetes, systemd, production setup, or worker containerization./framework-integrationsDjango, Flask, FastAPI integration patterns for Celery. Use when integrating Celery with Django, Flask, or FastAPI, setting up framework-specific configurations, handling application contexts, managing database transactions with tasks, configuring async workers, or when user mentions Django Celery, Flask Celery, FastAPI background tasks, framework integration, or web framework task queues./monitoring-flowerFlower monitoring setup and configuration for Celery including real-time monitoring, authentication, custom dashboards, and Prometheus metrics integration. Use when setting up Celery monitoring, configuring Flower web UI, implementing authentication, creating custom dashboards, integrating with Prometheus, or when user mentions Flower, Celery monitoring, task monitoring, worker monitoring, or real-time metrics.Other plugins' skills for the same job