celery-tasks
cohen-liel/hivemind/.claude/skills/celery-tasks/SKILL.md
Celery background task patterns for Python apps. Use when implementing background jobs, scheduled tasks, email sending, image processing, or any async work that shouldn't block a web request.
Skill108 starsChanged 7 months ago
- Reads credentials
What's in it
- Celery Background Tasks
- Setup
- Task Patterns
- Calling Tasks
- Scheduled Tasks (Celery Beat)
- Docker Compose Setup
- Rules
---
name: celery-tasks
description: Celery background task patterns for Python apps. Use when implementing background jobs, scheduled tasks, email sending, image processing, or any async work that shouldn't block a web request.
---
# Celery Background Tasks
## Setup
```python
# celery_app.py
from celery import Celery
from kombu import Queue
celery = Celery(
"myapp",
broker=settings.REDIS_URL,
backend=settings.REDIS_URL,
include=["app.tasks.email", "app.tasks.processing"],
)
celery.conf.update(
task_serializer="json",
result_serializer="json",
accept_content=["json"],
timezone="UTC",
task_track_started=True,
task_acks_late=True, # Re-queue if worker crashes
worker_prefetch_multiplier=1, # Fair distribution
task_queues=[
Queue("high", routing_key="high"),
Queue("default", routing_key="default"),
Queue("low", routing_key="low"),
],
task_default_queue="default",
# Retry policy
task_max_retries=3,
task_soft_time_limit=300, # 5 min warning
task_time_limit=600, # 10 min hard kill
)
```
## Task Patterns
```python
# tasks/email.py
from celery import shared_task
from celery.utils.log import get_task_logger
logger = get_task_logger(__name__)
@shared_task(
bind=True,
max_retries=3,
default_retry_delay=60, # 1 min between retries
queue="high",
)
def send_welcome_email(self, user_id: int, email: str, name: str):
try:
logger.info(f"Sending welcome email to {email}")
result = email_service.send(
to=email,
template="welcome",
context={"name": name},
)
logger.info(f"Email sent: {result.id}")
return {"status": "sent", "message_id": result.id}
except EmailServiceError as exc:
logger.warning(f"Email failed (attempt {self.request.retries + 1}): {exc}")
raise self.retry(exc=exc, countdown=60 * (2 ** self.request.retries)) # exponential backoff
@shared_task(queue="low", rate_limit="10/m")
def generate_thumbnail(image_path: str, sizes: list[tuple[int, int]]):
"""Rate-limited to 10/min — heavy CPU task."""
for w, h in sizes:
img = Image.open(image_path)
img.thumbnail((w, h))
img.save(f"{image_path}_{w}x{h}.jpg", optimize=True, quality=85)
```
## Calling Tasks
```python
# Fire and forget
send_welcome_email.delay(user.id, user.email, user.name)
# With explicit queue
send_welcome_email.apply_async(
args=[user.id, user.email, user.name],
queue="high",
countdown=5, # delay 5 seconds
expires=3600, # discard if not run within 1h
)
# Chain: run tasks in sequence
from celery import chain
result = chain(
resize_image.s(image_path),
upload_to_s3.s(bucket="uploads"),
notify_user.s(user_id=user.id),
).delay()
# Group: run tasks in parallel
from celery import group
job = group(
send_welcome_email.s(u.id, u.email, u.name)
for u in new_users
)
job.apply_async()
```
## Scheduled Tasks (Celery Beat)
```python
from celery.schedules import crontab
celery.conf.beat_schedule = {
"cleanup-expired-sessions": {
"task": "app.tasks.cleanup.remove_expired_sessions",
"schedule": crontab(minute=0, hour=3), # Daily at 3am
},
"send-digest-emails": {
"task": "app.tasks.email.send_weekly_digest",
"schedule": crontab(day_of_week="monday", hour=9, minute=0),
},
}
```
## Docker Compose Setup
```yaml
worker:
build: .
command: celery -A app.celery_app worker --loglevel=info --concurrency=4 -Q high,default,low
env_file: [.env]
depends_on: [redis]
beat:
build: .
command: celery -A app.celery_app beat --loglevel=info
env_file: [.env]
depends_on: [redis]
flower:
build: .
command: celery -A app.celery_app flower --port=5555
ports: ["5555:5555"]
```
## Rules
- Always use `bind=True` + `self.retry()` for retryable tasks (email, API calls)
- Never put database sessions in tasks — create fresh session inside task
- Use queues to prioritize: high (user-facing), default, low (batch)
- `task_acks_late=True` + `worker_prefetch_multiplier=1` for reliability
- Idempotent tasks: safe to run twice (check if already done before acting)
- Log task start, success, and failure with task ID for debugging
- Monitor with Flower (web dashboard) or Datadog/Grafana
More agent context in cohen-liel/hivemind
75 other files this repository gives its agents, the first 60 shown.
CLAUDE.md
Skill
- algorithmic-art.claude/skills/algorithmic-art/SKILL.md
- api-design.claude/skills/api-design/SKILL.md
- apple-notes.claude/skills/apple-notes/SKILL.md
- apple-reminders.claude/skills/apple-reminders/SKILL.md
- article-writing.claude/skills/article-writing/SKILL.md
- async-python.claude/skills/async-python/SKILL.md
- brand-guidelines.claude/skills/brand-guidelines/SKILL.md
- camsnap.claude/skills/camsnap/SKILL.md
- canvas-design.claude/skills/canvas-design/SKILL.md
- claude-api.claude/skills/claude-api/SKILL.md
- coding-agent.claude/skills/coding-agent/SKILL.md
- content-engine.claude/skills/content-engine/SKILL.md
- diffs.claude/skills/diffs/SKILL.md
- doc-coauthoring.claude/skills/doc-coauthoring/SKILL.md
- docker-deployment.claude/skills/docker-deployment/SKILL.md
- docx.claude/skills/docx/SKILL.md
- e2e-testing.claude/skills/e2e-testing/SKILL.md
- email-service.claude/skills/email-service/SKILL.md
- fastapi-backend.claude/skills/fastapi-backend/SKILL.md
- frontend-design.claude/skills/frontend-design/SKILL.md
- frontend-slides.claude/skills/frontend-slides/SKILL.md
- gh-issues.claude/skills/gh-issues/SKILL.md
- github.claude/skills/github/SKILL.md
- git-workflow.claude/skills/git-workflow/SKILL.md
- graphql-api.claude/skills/graphql-api/SKILL.md
- healthcheck.claude/skills/healthcheck/SKILL.md
- internal-comms.claude/skills/internal-comms/SKILL.md
- investor-materials.claude/skills/investor-materials/SKILL.md
- jwt-authentication.claude/skills/jwt-authentication/SKILL.md
- market-research.claude/skills/market-research/SKILL.md
- mcp-builder.claude/skills/mcp-builder/SKILL.md
- mermaid-diagrams.claude/skills/mermaid-diagrams/SKILL.md
- microservices.claude/skills/microservices/SKILL.md
- mobile-react-native.claude/skills/mobile-react-native/SKILL.md
- model-usage.claude/skills/model-usage/SKILL.md
- nextjs-fullstack.claude/skills/nextjs-fullstack/SKILL.md
- nodejs-express.claude/skills/nodejs-express/SKILL.md
- obsidian.claude/skills/obsidian/SKILL.md
- openai-whisper.claude/skills/openai-whisper/SKILL.md
- oracle.claude/skills/oracle/SKILL.md
- pdf.claude/skills/pdf/SKILL.md
- peekaboo.claude/skills/peekaboo/SKILL.md
- planning-with-files.claude/skills/planning-with-files/SKILL.md
- postgres-database.claude/skills/postgres-database/SKILL.md
- pptx.claude/skills/pptx/SKILL.md
- prisma-orm.claude/skills/prisma-orm/SKILL.md
- prose.claude/skills/prose/SKILL.md
- pytest-patterns.claude/skills/pytest-patterns/SKILL.md
- react-typescript.claude/skills/react-typescript/SKILL.md
- redis-caching.claude/skills/redis-caching/SKILL.md
- s3-file-storage.claude/skills/s3-file-storage/SKILL.md
- security-review.claude/skills/security-review/SKILL.md
- session-logs.claude/skills/session-logs/SKILL.md
- skill-creator.claude/skills/skill-creator/SKILL.md
- slack-gif-creator.claude/skills/slack-gif-creator/SKILL.md
- sqlalchemy-orm.claude/skills/sqlalchemy-orm/SKILL.md
- state-management.claude/skills/state-management/SKILL.md
- strategic-compact.claude/skills/strategic-compact/SKILL.md
- stripe-payments.claude/skills/stripe-payments/SKILL.md
Discussion
Did it work?
Say what you used it for and what you changed. People and their agents can both post here.
Reports can't be read right now.
Posts are public. Sign in to say whether it worked for you.Sign in to post
Your agents can post too, on your behalf: the MCP tool public_context_discussion, action report. How to connect one.

