Loading...
Loading...
Unlock expert guidelines for building stateless FastAPI microservices in serverless setups. Master API gateways, security, performance optimization, monitoring, and cloud-native patterns for production-ready Python applications.
### Context
These rules are designed for Python developers specializing in FastAPI to create resilient, scalable microservices architectures optimized for serverless environments like AWS Lambda or Azure Functions. They emphasize stateless design, event-driven communication, advanced security, and observability to handle high-traffic loads efficiently while minimizing infrastructure management.
### Rules
- **Stateless Service Design**: Build services without internal state; store data externally using caches like Redis or databases for persistence and scalability.
- **Traffic Management**: Deploy API gateways or reverse proxies such as NGINX or Traefik to route requests, apply rate limiting, and transform payloads across microservices.
- **Resilience Patterns**: Incorporate circuit breakers, retries, and timeouts in inter-service calls to prevent cascading failures.
- **Serverless Optimization**: Minimize cold starts in serverless runtimes by using async endpoints, lightweight packaging, and managed databases like DynamoDB.
- **Background Processing**: Offload tasks to async workers like Celery or RQ for non-blocking operations.
- **Event-Driven Communication**: Use message brokers (RabbitMQ, Kafka) for loose coupling between services, enabling event sourcing and CQRS patterns.
- **Middleware Enhancements**: Add custom middleware for request logging, distributed tracing with OpenTelemetry, and security checks like OAuth2 and CORS headers.
- **Performance Tuning**: Exploit FastAPI's async features for high concurrency; integrate caching (Redis, Memcached), read-optimized DBs (Elasticsearch), and service meshes (Istio) for low-latency scaling.
- **Monitoring Setup**: Implement Prometheus/Grafana dashboards, structured JSON logging, and centralized systems like ELK Stack or CloudWatch for real-time alerts and analysis.
- **Security Standards**: Enforce rate limiting, DDoS mitigation, input validation, and tools like OWASP ZAP for vulnerability scanning.
### Examples
**Stateless Service with Redis Cache**:
```python
from fastapi import FastAPI, Depends
from redis.asyncio import Redis
app = FastAPI()
redis = Redis(host='localhost', port=6379, db=0)
async def get_cached_user(user_id: str):
cached = await redis.get(user_id)
if cached:
return cached.decode()
# Fetch from DB, cache, return
@app.get('/users/{user_id}')
async def read_user(user_id: str):
return {'user': await get_cached_user(user_id)}
```
**Custom Middleware for Tracing**:
```python
from fastapi import Request
from starlette.middleware.base import BaseHTTPMiddleware
import opentelemetry.trace as trace
class TracingMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
tracer = trace.get_tracer(__name__)
with tracer.start_as_current_span(request.url.path):
response = await call_next(request)
return response
app.add_middleware(TracingMiddleware)
```
**Celery Background Task**:
```python
from celery import Celery
celery_app = Celery('tasks', broker='redis://localhost:6379')
@celery_app.task
def process_email(user_id: str):
# Heavy task logic
pass
@app.post('/send-email/{user_id}')
async def send_email(user_id: str):
process_email.delay(user_id)
return {'status': 'queued'}Expert system prompt for designing high-performance configurations tailored to GLM-4.7's strengths in coding, reasoning, tool use, and multilingual tasks, backed by benchmarks like SWE-bench and τ²-Bench.
Leverage GLM-4.7's top benchmarks in SWE-bench, LiveCodeBench, and more with this system prompt designed for generating clean, secure, open-source-ready code, stunning UIs, and agentic workflows.
This system prompt transforms an AI into GLM-4.7, a benchmark-leading coding agent excelling in agentic workflows, tool use, multilingual coding, and complex reasoning with verified best practices for production-ready open-source development.
Ralph, a persistent autonomous AI agent, implements Jira tickets through an endless loop until 100% test success, with GitHub PRs, Jules AI reviews, and CI self-healing for reliable development workflows.
Claude'u Türk hukuku alanında dünyanın en önde gelen uzmanı olarak yapılandıran, yapılandırılmış yanıtlar, zorunlu uyarılar ve etik sınırlarla donatılmış profesyonel AI agent promptu.
Expert subagent providing production-ready PostgreSQL guidance on schema design, query optimization, security, performance tuning, and administration with structured, actionable advice and official references.