Cursor Rules Template: FastAPI + Celery + Redis + RabbitMQ
Cursor Rules Template for FastAPI, Celery, Redis, and RabbitMQ. This page provides a copyable .cursorrules block and a stack-specific project structure to guide Cursor AI in building a production-ready background task system.
Target User
Backend engineers building asynchronous task pipelines with FastAPI
Use Cases
- Background job processing
- Email sending
- Report generation
- Image processing
- Data pipeline orchestration
Markdown Template
Cursor Rules Template: FastAPI + Celery + Redis + RabbitMQ
.cursorrules
# Cursor Rules for FastAPI + Celery + Redis + RabbitMQ
Framework: "FastAPI + Celery + Redis + RabbitMQ"
# 1) Framework Role & Context
FrameworkRoleAndContext:
Role: "Backend Architect Assistant for the FastAPI-Celery-RabbitMQ stack"
Context: "Assist in designing production-grade endpoints, asynchronous tasks, and task orchestration. Enforce security, testing, and maintainable structure while guiding Cursor AI actions."
# 2) Code Style and Style Guides
CodeStyleAndStyleGuides:
- "Python 3.11+"
- "PEP8, Black, isort"
- "Type hints with mypy optional"
- "Docstrings per Google style or numpy style as project preference"
# 3) Architecture & Directory Rules
ArchitectureAndDirectoryRules:
- "Separate FastAPI app from Celery config: app/ and worker/ layout"
- "Use app.api for routers, app.core for config, app.models for ORM, and app.tasks for Celery tasks"
- "Celery app in celery_app.py with explicit imports and app.config_from_object()"
- "Use a central config module to read env vars (SECRET_KEY, BROKER_URL, RESULT_BACKEND)"
# 4) Authentication & Security Rules
AuthenticationAndSecurityRules:
- "OAuth2 with JWT for API endpoints; Blacklist/refresh flow disabled in tests"
- "Do not hardcode credentials; use env vars and a secret manager"
- "Limit Celery task visibility; do not expose task IDs publicly without validation"
- "Enable TLS in deployment; lock down broker connections via firewall rules"
# 5) Database and ORM patterns
DatabaseAndORMPatterns:
- "SQLAlchemy or Tortoise ORM for relational data"
- "Use async session for FastAPI endpoints when possible; wrap sync DB calls in run_in_executor if needed"
- "Migrations managed with Alembic (or equivalent)"
# 6) Testing & Linting Workflows
TestingAndLintingWorkflows:
- "Unit tests for endpoints with fastapi.testclient and pytest-asyncio for async endpoints"
- "Test Celery tasks with in-memory broker or a dedicated test broker; assert result_backend state"
- "Pre-commit hooks for linting and formatting; CI runs pytest and mypy"
# 7) Prohibited Actions and Anti-patterns for the AI
ProhibitedActionsAndAntiPatternsForAI:
- "Do not generate real credentials or secrets in code blocks or config"
- "Do not hardcode broker URLs with default credentials in production"
- "Avoid using synchronous, blocking I/O in FastAPI requests when invoking Celery tasks"
- "Do not bypass authentication or expose internal task queues to the public internet"Overview
Direct answer: This Cursor Rules Template provides a complete, copy-pasteable .cursorrules block for FastAPI + Celery + Redis + RabbitMQ, plus a stack-specific project structure and guardrails to keep AI-assisted development safe and productive.
The Cursor rules configuration is designed for a Python-based backend that exposes FastAPI endpoints while offloading heavy tasks to Celery workers. Redis serves as the broker and RabbitMQ is configured as the messaging backbone for reliable task routing. Use this template to guide Cursor AI in implementing architecture, security, testing, and deployment considerations for this stack.
When to Use These Cursor Rules
- Starting a new FastAPI project that requires robust background task processing with Celery.
- Defining a safe, auditable task flow across Redis-based broker and RabbitMQ-based messaging with guaranteed delivery.
- Enforcing code style, testing, and security constraints from the initial project setup.
- Providing Cursor AI with strict anti-patterns to avoid architectural drift and insecure patterns.
Copyable .cursorrules Configuration
.cursorrules
# Cursor Rules for FastAPI + Celery + Redis + RabbitMQ
Framework: "FastAPI + Celery + Redis + RabbitMQ"
# 1) Framework Role & Context
FrameworkRoleAndContext:
Role: "Backend Architect Assistant for the FastAPI-Celery-RabbitMQ stack"
Context: "Assist in designing production-grade endpoints, asynchronous tasks, and task orchestration. Enforce security, testing, and maintainable structure while guiding Cursor AI actions."
# 2) Code Style and Style Guides
CodeStyleAndStyleGuides:
- "Python 3.11+"
- "PEP8, Black, isort"
- "Type hints with mypy optional"
- "Docstrings per Google style or numpy style as project preference"
# 3) Architecture & Directory Rules
ArchitectureAndDirectoryRules:
- "Separate FastAPI app from Celery config: app/ and worker/ layout"
- "Use app.api for routers, app.core for config, app.models for ORM, and app.tasks for Celery tasks"
- "Celery app in celery_app.py with explicit imports and app.config_from_object()"
- "Use a central config module to read env vars (SECRET_KEY, BROKER_URL, RESULT_BACKEND)"
# 4) Authentication & Security Rules
AuthenticationAndSecurityRules:
- "OAuth2 with JWT for API endpoints; Blacklist/refresh flow disabled in tests"
- "Do not hardcode credentials; use env vars and a secret manager"
- "Limit Celery task visibility; do not expose task IDs publicly without validation"
- "Enable TLS in deployment; lock down broker connections via firewall rules"
# 5) Database and ORM patterns
DatabaseAndORMPatterns:
- "SQLAlchemy or Tortoise ORM for relational data"
- "Use async session for FastAPI endpoints when possible; wrap sync DB calls in run_in_executor if needed"
- "Migrations managed with Alembic (or equivalent)"
# 6) Testing & Linting Workflows
TestingAndLintingWorkflows:
- "Unit tests for endpoints with fastapi.testclient and pytest-asyncio for async endpoints"
- "Test Celery tasks with in-memory broker or a dedicated test broker; assert result_backend state"
- "Pre-commit hooks for linting and formatting; CI runs pytest and mypy"
# 7) Prohibited Actions and Anti-patterns for the AI
ProhibitedActionsAndAntiPatternsForAI:
- "Do not generate real credentials or secrets in code blocks or config"
- "Do not hardcode broker URLs with default credentials in production"
- "Avoid using synchronous, blocking I/O in FastAPI requests when invoking Celery tasks"
- "Do not bypass authentication or expose internal task queues to the public internet"
Recommended Project Structure
myproject/
├── app/
│ ├── __init__.py
│ ├── main.py
│ ├── api/
│ │ └── v1/
│ │ └── endpoints.py
│ ├── core/
│ │ └── config.py
│ ├── models/
│ │ └── models.py
│ └── tasks/
│ └── tasks.py
├── celery_app.py
├── requirements.txt
└── tests/
├── test_api.py
└── test_tasks.py
Core Engineering Principles
- Idempotent endpoints and idempotent Celery task design to avoid duplicates
- Clear separation of concerns between API, task processing, and data access
- Strong type hints, thorough validation, and explicit error handling
- Config-driven behavior with environment-specific overrides
- Deterministic tests and automation for deployments
Code Construction Rules
- End-to-end typing for inputs/outputs; define Pydantic models for request/response payloads
- Celery tasks defined in app.tasks with a well-named task function and retry policy
- Broker (RabbitMQ) and backend (Redis) URLs sourced from environment variables
- Endpoints trigger Celery tasks asynchronously; return task_id with proper status endpoints
- Use FastAPI dependencies for authentication, rate limiting, and CORS where appropriate
- Avoid blocking calls in FastAPI; use async DB sessions or run_in_executor for sync DB calls
- Document API and task schemas; include example payloads and expected responses
Security and Production Rules
- Use TLS termination and rotate secrets; store keys in a secret manager
- Do not expose Celery Flower or internal queues; restrict access by IP or VPN
- Validate and sanitize all inputs; enforce strict schema validation
- Limit task payload size and avoid sending secrets in task args
- Implement proper logging with redaction for sensitive fields
Testing Checklist
- Unit tests for validators, models, and utility functions
- Integration tests for API endpoints and Celery task submission
- End-to-end tests for a sample task from API call to task completion
- Linting and static type checks in CI; run Black, isort, and mypy
- Security checks: verify token validation, secret handling, and TLS in dev/staging
Common Mistakes to Avoid
- Reusing local RabbitMQ/Redis defaults in production; always configure via env
- Blocking the event loop inside endpoint handlers
- Overloading task payloads with secrets or large binary data
- Skipping proper task result checks or not handling retries robustly
FAQ
What is the Cursor Rules Template for FastAPI + Celery + Redis + RabbitMQ?
The Cursor Rules Template provides a ready-to-paste .cursorrules block and stack-specific guidance to configure Cursor AI for building a production-grade FastAPI service with Celery workers, Redis as broker, and RabbitMQ-based messaging. It defines roles, security, testing, and structure to reduce architectural drift.
How do I tailor the .cursorrules for my environment?
Adjust environment-specific values (BROKER_URL, RESULT_BACKEND, SECRET_KEY) in your deployment environment. Replace default hostnames with your actual Redis and RabbitMQ endpoints and enable TLS. Ensure your code style and testing workflows align with your CI pipeline.
How can I test Celery tasks locally?
Use a local Redis and a local RabbitMQ instance for development. Run the Celery worker against the same broker and backend URLs defined in the config. Write unit tests for tasks and integration tests that simulate API triggers and verify task results or state transitions.
What security practices are essential for this stack?
Use OAuth2/JWT for API endpoints, do not expose broker credentials, store secrets in a vault, enable TLS, and validate inputs. Ensure Celery tasks do not receive sensitive data as plaintext and implement proper auth checks before task submissions.
How do I run this template in CI/CD?
Include tests for API endpoints and Celery tasks, linting with Black/isort, and type checks. Provide a docker-compose file for Redis and RabbitMQ, and ensure environment variables are injected securely in the pipeline. Run migrations, then deploy to staging before production.
Where can I extend this template?
Extend by adding new routers under app/api/v1, Celery task modules under app/tasks, and additional models under app/models. Update .cursorrules to reflect new architecture and tests for the new components.