Design and implement a FastAPI microservice with async SQLAlchemy, Pydantic v2 schemas, dependency injection, and production-ready observability.
## CONTEXT FastAPI has grown to become the second most popular Python web framework on GitHub with over 75K stars, largely due to its native async support and automatic OpenAPI documentation generation. Benchmarks consistently show FastAPI handling 3-5x more concurrent requests than synchronous Django or Flask applications for I/O-bound workloads. However, many developers fail to fully leverage async patterns, accidentally blocking the event loop with synchronous database calls or CPU-bound operations. According to the 2024 Python Developers Survey, 34% of Python web developers now use FastAPI in production, up from 18% just two years ago. ## ROLE Act as a senior Python microservice architect with 11 years of experience building distributed systems. You have designed and deployed FastAPI services at scale for real-time bidding platforms, payment processing systems, and IoT data ingestion pipelines processing 500K+ events per second. You are a contributor to the FastAPI ecosystem, have deep expertise in SQLAlchemy 2.0 async patterns, and have published articles on structuring FastAPI projects for long-term maintainability. You have migrated multiple Flask and Django services to FastAPI with zero-downtime deployments. ## RESPONSE GUIDELINES - Provide a complete project structure using the repository pattern to separate business logic from framework-specific code - Use Pydantic v2 models with field validators, computed fields, and model_config for all request and response schemas - Implement dependency injection using FastAPI Depends for database sessions, authentication, and shared services - Include async SQLAlchemy 2.0 with connection pooling, relationship loading strategies, and transaction management - Do NOT use synchronous database calls or blocking I/O operations inside async endpoint handlers - Do NOT hardcode configuration values when environment variables with Pydantic Settings provide a cleaner approach ## TASK CRITERIA 1. **Project Structure** -- Organize code into routers, services, repositories, schemas, and models directories following clean architecture principles with clear dependency direction from outer layers to inner layers 2. **Async Endpoints** -- Define routes with proper HTTP method decorators, status codes, response models, and dependency injection for authentication and database session management 3. **Database Layer** -- Set up async SQLAlchemy engine and session factory with connection pooling, define models with mapped_column syntax, and create repository classes encapsulating all query logic 4. **Schema Validation** -- Build Pydantic v2 request and response schemas with field constraints, custom validators, discriminated unions for polymorphic data, and separate Create, Update, and Response models 5. **Error Handling** -- Implement custom exception handlers for domain errors, database constraint violations, and upstream service failures with RFC 7807 problem detail response format 6. **Health and Observability** -- Add liveness and readiness probe endpoints, Prometheus metrics middleware for request duration and error rates, structured JSON logging with request correlation IDs, and startup/shutdown lifecycle hooks 7. **Testing** -- Write async test cases using pytest-asyncio and httpx AsyncClient with database fixtures, mock external services, and parameterized test data 8. **Containerization** -- Provide a multi-stage Dockerfile, docker-compose.yml for local development with database and cache services, and environment configuration management ## INFORMATION ABOUT ME - My service purpose: [INSERT YOUR MICROSERVICE DOMAIN, e.g., user authentication, order processing, notification dispatch] - My database choice: [INSERT YOUR DATABASE, e.g., PostgreSQL, MongoDB, Redis] - My message broker: [INSERT YOUR BROKER IF ANY, e.g., RabbitMQ, Kafka, Redis Streams, None] - My deployment target: [INSERT YOUR PLATFORM, e.g., Kubernetes, AWS ECS, Docker Compose] - My upstream dependencies: [INSERT EXTERNAL SERVICES YOUR SERVICE CALLS, e.g., payment gateway API, email service, user service] - My SLA requirements: [INSERT YOUR TARGETS, e.g., p99 latency under 200ms, 99.9% uptime] ## RESPONSE FORMAT - Start with a directory tree showing the complete project layout with file descriptions - Present each module as a complete Python file with type annotations, docstrings, and inline comments - Include a requirements.txt or pyproject.toml with pinned dependency versions - Provide docker-compose.yml and Dockerfile for immediate local development setup - End with example API calls using httpx or curl showing request and response payloads
Or press ⌘C to copy