Backend Skill — Production Backend Engineering (2025–2026)
This skill covers framework-agnostic backend engineering principles: API design, database patterns, caching, security, observability, architecture decisions, and deployment. Combine with framework-specific skills (FastAPI, Express, Django, Spring, etc.) for implementation details.
1. API Design Fundamentals
REST URL conventions
Resources are nouns (plural). HTTP methods are the verbs.
GET /api/v1/users # List users
POST /api/v1/users # Create a user
GET /api/v1/users/123 # Get user 123
PATCH /api/v1/users/123 # Partial update
PUT /api/v1/users/123 # Full replace
DELETE /api/v1/users/123 # Delete user 123
GET /api/v1/users/123/orders # User's orders (shallow nesting)
GET /api/v1/users/123/orders/456 # Specific order
# ❌ Anti-patterns
GET /api/v1/getAllUsers
POST /api/v1/createUser
POST /api/v1/deleteUser
GET /api/v1/user?id=123
URL design rules
- Use plural nouns:
/users, /orders, /products.
- Use lowercase with hyphens:
/order-items, not /orderItems or /order_items.
- Keep nesting shallow (max 2 levels):
/users/123/orders is fine; /users/123/orders/456/items/789/reviews is too deep — flatten to /reviews?item_id=789.
- Use query parameters for filtering, sorting, pagination:
/users?role=admin&sort=-created_at&page=2.
- Avoid exposing internal IDs when possible — use UUIDs or slugs for public-facing resources.
HTTP methods and semantics
| Method |
Idempotent |
Safe |
Use for |
| GET |
Yes |
Yes |
Read resources |
| POST |
No |
No |
Create resources, trigger actions |
| PUT |
Yes |
No |
Full replace of a resource |
| PATCH |
Yes* |
No |
Partial update |
| DELETE |
Yes |
No |
Remove a resource |
| HEAD |
Yes |
Yes |
Like GET but headers only |
| OPTIONS |
Yes |
Yes |
CORS preflight, capabilities |
*PATCH is idempotent when using merge-patch semantics (the common case).
HTTP status codes
Use them correctly — they are part of your API contract.
2xx — Success
200 OK — Standard success response
201 Created — Resource created (include Location header)
204 No Content — Success with no response body (DELETE, PUT)
3xx — Redirection
301 Moved Permanently — Resource URL changed permanently
304 Not Modified — Cached version is still valid
4xx — Client Errors
400 Bad Request — Malformed syntax or invalid input
401 Unauthorized — Missing or invalid authentication
403 Forbidden — Authenticated but insufficient permissions
404 Not Found — Resource doesn't exist
409 Conflict — State conflict (e.g., duplicate email)
422 Unprocessable Entity — Valid syntax but semantic errors
429 Too Many Requests — Rate limit exceeded (include Retry-After header)
5xx — Server Errors
500 Internal Server Error — Unhandled server error
502 Bad Gateway — Upstream service failure
503 Service Unavailable — Temporary overload or maintenance
504 Gateway Timeout — Upstream service timeout
Consistent error response format
Follow RFC 9457 (Problem Details for HTTP APIs):
{
"type": "https://api.example.com/errors/validation",
"title": "Validation Error",
"status": 422,
"detail": "The email field is required and must be a valid email address.",
"instance": "/api/v1/users",
"errors": [
{
"field": "email",
"message": "This field is required.",
"code": "required"
}
]
}
Rules for error responses:
- Always return a consistent structure across all endpoints.
- Include machine-readable error codes alongside human-readable messages.
- Include field-level validation errors so clients can fix all issues in one round-trip.
- Never leak internal details (stack traces, SQL queries, file paths) in production errors.
- Log the full error server-side; return a sanitized version to the client.
2. API Versioning
Strategies
| Strategy |
Example |
Pros |
Cons |
| URL path |
/api/v1/users |
Explicit, easy to route |
URL pollution |
| Header |
Accept: application/vnd.api+json;version=2 |
Clean URLs |
Hidden, harder to test |
| Query param |
/api/users?version=2 |
Simple |
Inconsistent |
Recommendation: Use URL path versioning (/api/v1/). It's the most explicit, easiest to route, cache, and document. When introducing a breaking change, create a new version (/api/v2/) and run both in parallel with a deprecation timeline.
Deprecation protocol
- Announce deprecation with a
Deprecation header and Sunset header on old endpoints.
- Provide a migration guide.
- Give clients at least 6–12 months before removal.
- Monitor usage of deprecated endpoints before turning them off.
3. Pagination
Cursor-based pagination (recommended)
Best for real-time data, large datasets, and infinite scroll. Immune to offset drift when data changes.
GET /api/v1/orders?limit=20&after=eyJpZCI6MTIzfQ
Response:
{
"data": [...],
"pagination": {
"has_next": true,
"next_cursor": "eyJpZCI6MTQzfQ",
"has_previous": true,
"previous_cursor": "eyJpZCI6MTI0fQ"
}
}
Offset-based pagination (simpler)
Fine for admin dashboards, small datasets, or when users need to jump to specific pages.
GET /api/v1/users?page=3&per_page=25
Response:
{
"data": [...],
"pagination": {
"page": 3,
"per_page": 25,
"total": 482,
"total_pages": 20
}
}
Pagination rules
- Always set a maximum page size (e.g.,
per_page capped at 100).
- Default to a reasonable page size (20–50).
- Include pagination metadata in every list response.
- For very large datasets (millions of rows), cursor-based is the only performant option.
4. Filtering, Sorting, and Field Selection
# Filtering
GET /api/v1/products?category=electronics&price_min=100&price_max=500&in_stock=true
# Sorting (prefix with - for descending)
GET /api/v1/products?sort=-price,name
# Field selection (reduce payload size)
GET /api/v1/users?fields=id,name,email
# Full-text search
GET /api/v1/products?q=wireless+headphones
Be consistent across all endpoints. Document every supported filter, sort field, and selection parameter.
5. Authentication & Authorization
Authentication methods by use case
| Use case |
Method |
| User-facing apps |
OAuth 2.0 / OIDC |
| Server-to-server |
API keys + HMAC signing |
| Microservice-to-microservice |
Mutual TLS (mTLS) or JWT |
| Simple internal tools |
API keys in headers |
JWT best practices
Authorization: Bearer eyJhbGciOiJSUzI1NiIs...
- Use short-lived access tokens (5–15 minutes) with long-lived refresh tokens (days/weeks).
- Store JWTs in httpOnly, Secure, SameSite=Strict cookies for browser clients — never in localStorage.
- Use asymmetric signing (RS256/ES256) for distributed systems so services can verify without the private key.
- Include minimal claims:
sub (user ID), exp, iat, iss, roles/scopes.
- Validate
exp, iss, and aud on every request.
- Implement token revocation via a short blocklist or by keeping access tokens very short-lived.
OAuth 2.0 / OIDC
- Use Authorization Code flow with PKCE for all client types (web, mobile, SPA).
- Never use the Implicit flow — it's deprecated.
- Use established providers (Auth0, Clerk, Keycloak, Supabase Auth) rather than rolling your own.
- Always validate the
state parameter to prevent CSRF.
- Store client secrets server-side only.
Authorization patterns
- RBAC (Role-Based Access Control): Assign roles (admin, editor, viewer) with predefined permissions. Works for most applications.
- ABAC (Attribute-Based Access Control): Policies based on user attributes, resource attributes, and context. More flexible but more complex.
- Check authorization at every layer: Middleware for route-level checks, service layer for business-logic checks. Never rely on a single layer.
6. Database Design
Schema design principles
- Normalize first, denormalize intentionally. Start with 3NF; denormalize specific tables for read performance when you have evidence (not speculation) of a bottleneck.
- Use appropriate data types: Don't store dates as strings, don't use TEXT for short fixed-length fields, use DECIMAL/NUMERIC for money (never FLOAT).
- Always have a primary key: Prefer auto-incrementing integers for internal IDs; use UUIDs (v7 for sortability) for public-facing IDs.
- Add created_at and updated_at to every table (with timezone).
- Use foreign keys for referential integrity in OLTP databases.
- Index strategically: Index columns used in WHERE, JOIN, ORDER BY. Composite indexes follow the leftmost prefix rule. Don't over-index — each index slows writes.
Query optimization
-- ✅ Use EXPLAIN ANALYZE to understand query plans
EXPLAIN ANALYZE
SELECT u.id, u.name, COUNT(o.id) as order_count
FROM users u
LEFT JOIN orders o ON o.user_id = u.id
WHERE u.created_at > '2026-01-01'
GROUP BY u.id, u.name
ORDER BY order_count DESC
LIMIT 20;
-- ✅ Avoid SELECT * — fetch only needed columns
SELECT id, name, email FROM users WHERE active = true;
-- ❌ N+1 queries — the most common performance killer
-- Fetching users, then looping to fetch each user's orders separately
-- ✅ Fix: JOIN or batch fetch in a single query
Common query pitfalls
| Pitfall |
Fix |
| N+1 queries |
Use JOINs, eager loading, or batch fetching |
| Missing indexes on foreign keys |
Always index FK columns |
| Full table scans on large tables |
Add appropriate indexes; use LIMIT |
| Using OFFSET for deep pagination |
Switch to cursor/keyset pagination |
| Locking issues on hot tables |
Use row-level locking; consider read replicas |
| Not using connection pooling |
Use PgBouncer, HikariCP, or framework-level pools |
SQL vs NoSQL decision
| Choose SQL (PostgreSQL, MySQL) when |
Choose NoSQL when |
| Complex relationships and JOINs |
Document-shaped data (MongoDB) |
| ACID transactions required |
High write throughput at scale (Cassandra) |
| Structured, well-known schema |
Key-value lookups / caching (Redis) |
| Reporting and aggregation |
Graph relationships (Neo4j) |
| Most CRUD applications |
Time-series data (InfluxDB, TimescaleDB) |
Default to PostgreSQL for most applications. It handles JSON (jsonb), full-text search, geospatial data, and scales to millions of rows before you need anything exotic.
7. Caching
Caching layers
Client ──→ CDN ──→ API Gateway ──→ Application Cache ──→ Database
↑ ↑ ↑
Static Response Redis/Memcached
assets caching or in-memory
Caching strategies
| Strategy |
How it works |
Best for |
| Cache-aside (Lazy loading) |
App checks cache → miss → query DB → write to cache |
General-purpose; most common |
| Write-through |
App writes to cache AND DB simultaneously |
Strong consistency requirements |
| Write-behind (Write-back) |
App writes to cache; cache async writes to DB |
High write throughput |
| Read-through |
Cache itself fetches from DB on miss |
Simpler app code |
Cache invalidation
Cache invalidation is one of the two hard problems in CS. Strategies:
- TTL (Time-to-Live): Set expiration. Simple but can serve stale data.
- Event-driven invalidation: Invalidate cache when the underlying data changes (e.g., after a write).
- Tag-based invalidation: Tag cache entries; invalidate all entries with a given tag.
- Versioned keys: Include a version number in the cache key; bump it on changes.
Redis patterns
# Cache-aside pattern (pseudocode)
def get_user(user_id):
cached = redis.get(f"user:{user_id}")
if cached:
return deserialize(cached)
user = db.query("SELECT * FROM users WHERE id = %s", user_id)
redis.setex(f"user:{user_id}", 300, serialize(user)) # TTL: 5 min
return user
# Distributed locking (prevent thundering herd)
lock = redis.set(f"lock:user:{user_id}", "1", nx=True, ex=10)
if lock:
# Only one process rebuilds the cache
...
What to cache
- Cache: Expensive query results, computed aggregations, API responses from third parties, session data, frequently-read and rarely-changed data.
- Don't cache: User-specific sensitive data without proper scoping, rapidly-changing data where staleness is unacceptable, one-time reads.
8. Rate Limiting
Protect your API from abuse, ensure fair usage, and prevent cascading failures.
Algorithms
| Algorithm |
Behavior |
Best for |
| Token bucket |
Tokens refill at a steady rate; requests consume tokens |
Smooth rate limiting with burst allowance |
| Sliding window |
Counts requests in a rolling time window |
Precise rate limiting |
| Fixed window |
Counts requests per fixed time window |
Simplest to implement |
Implementation
# Response headers for rate limiting
X-RateLimit-Limit: 1000 # Max requests per window
X-RateLimit-Remaining: 847 # Requests remaining
X-RateLimit-Reset: 1712800000 # Unix timestamp when window resets
Retry-After: 30 # Seconds to wait (on 429 response)
- Apply rate limits per API key/user, not just per IP (IPs are shared behind NATs/VPNs).
- Use different limits for different tiers (free: 100/hr, pro: 10,000/hr).
- Return
429 Too Many Requests with a Retry-After header.
- Implement at the API gateway or reverse proxy level for efficiency.
- Use Redis or a distributed counter for multi-instance deployments.
9. Background Jobs & Async Processing
When to use background jobs
- Email/notification sending
- PDF/report generation
- Image/video processing
- Data import/export
- Webhook delivery and retries
- Scheduled tasks (cron-like)
- Any operation that takes > 1–2 seconds
Architecture
API Server ──→ Message Queue ──→ Workers
│ (Redis, RabbitMQ, │
│ Kafka, SQS) │
│ ↓
└── Returns 202 Accepted Process job
with job status URL Update status
Notify on completion
Job design principles
- Idempotent: Jobs should be safe to retry. If a job runs twice, the result should be the same.
- Small and focused: Each job does one thing. Chain jobs for complex workflows.
- Observable: Log job start/end/failure. Track duration, success rate, and queue depth.
- Retry with backoff: Use exponential backoff with jitter (e.g., 1s, 2s, 4s, 8s + random jitter).
- Dead letter queue: Failed jobs after max retries go to a DLQ for manual inspection.
- Timeout: Set maximum execution time to prevent zombie jobs.
Tools
| Language/Ecosystem |
Tool |
| Python |
Celery + Redis/RabbitMQ, ARQ, Dramatiq |
| Node.js |
BullMQ + Redis, Temporal |
| Java/Kotlin |
Spring Batch, Quartz |
| Language-agnostic |
Kafka, RabbitMQ, AWS SQS, Temporal |
10. Security
OWASP Top 10 awareness (2025–2026)
The most critical backend security risks. Every backend engineer should know these:
- Broken Access Control — Enforce authorization at every endpoint and data access layer.
- Cryptographic Failures — Use TLS everywhere. Hash passwords with bcrypt/argon2. Encrypt sensitive data at rest.
- Injection — Use parameterized queries / ORMs. Never concatenate user input into SQL/commands.
- Insecure Design — Threat model during design, not after deployment.
- Security Misconfiguration — Disable debug endpoints in production. Remove default credentials. Set security headers.
- Vulnerable Components — Keep dependencies updated. Audit with
npm audit, pip-audit, Snyk, or Dependabot.
- Authentication Failures — Implement account lockout, rate limiting on login, MFA.
- Data Integrity Failures — Verify software updates and CI/CD pipelines. Use SRI for CDN assets.
- Logging & Monitoring Failures — Log security events. Set up alerts for anomalies.
- SSRF — Validate and sanitize URLs the server fetches. Allowlist permitted domains.
Security headers
Strict-Transport-Security: max-age=63072000; includeSubDomains; preload
Content-Security-Policy: default-src 'self'; script-src 'self'
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
Referrer-Policy: strict-origin-when-cross-origin
Permissions-Policy: camera=(), microphone=(), geolocation=()
Input validation
- Validate all input: request body, query params, path params, headers.
- Validate on the server — client validation is for UX, not security.
- Use schema validation libraries (Pydantic, Zod, Joi, JSON Schema).
- Reject unexpected fields (strict mode).
- Sanitize output when rendering user content to prevent XSS.
Password storage
- Never store passwords in plain text or with reversible encryption.
- Use bcrypt (cost factor ≥ 12) or argon2id (preferred for new systems).
- Salt is built into bcrypt/argon2 — don't roll your own salting scheme.
11. Observability
Observability = Logs + Metrics + Traces. Design it alongside your application, not as an afterthought.
The three pillars
Logs — Structured event records.
{
"timestamp": "2026-04-10T14:32:01Z",
"level": "error",
"service": "order-service",
"request_id": "req_abc123",
"user_id": "usr_456",
"message": "Payment processing failed",
"error": "stripe_timeout",
"duration_ms": 30042
}
- Use structured logging (JSON) — not unstructured text.
- Include request IDs / correlation IDs that propagate across services.
- Log at appropriate levels: DEBUG (development only), INFO (significant events), WARN (recoverable issues), ERROR (failures requiring attention).
- Never log passwords, tokens, PII, or credit card numbers.
Metrics — Aggregated numerical measurements.
Key metrics to track (the RED method):
- Rate: Requests per second
- Errors: Error rate (4xx, 5xx)
- Duration: Response time (p50, p95, p99)
Additional: CPU/memory usage, queue depth, active connections, cache hit ratio, DB query time.
Traces — Request flow across services.
- Use OpenTelemetry (the industry standard) for instrumentation.
- Propagate trace context (
traceparent header) across service boundaries.
- Trace critical paths: API → service → database → external API.
Alerting rules
- Alert on symptoms (high error rate, slow response times), not causes.
- Set thresholds based on SLOs (Service Level Objectives), e.g., "99.9% of requests complete in < 500ms."
- Use severity levels: critical (paging), warning (next business day), info (dashboard only).
- Avoid alert fatigue — every alert should be actionable.
Tools
| Category |
Tools |
| Logging |
ELK Stack, Loki + Grafana, Datadog |
| Metrics |
Prometheus + Grafana, Datadog, CloudWatch |
| Tracing |
Jaeger, Tempo, Datadog APM, Honeycomb |
| All-in-one |
Datadog, New Relic, Grafana Cloud |
| Instrumentation |
OpenTelemetry (universal standard) |
12. Architecture Patterns
Monolith vs Microservices
|
Modular Monolith |
Microservices |
| Start with |
✅ Always start here |
Migrate to when needed |
| Deploy |
Single artifact |
Independent per service |
| Complexity |
Lower operational overhead |
Higher (networking, observability, consistency) |
| Team size |
< 20–30 engineers |
Large orgs with team boundaries |
| Data |
Single database |
Database per service |
Start with a well-structured monolith. Extract services only when you have clear domain boundaries and team/scaling needs that justify the operational complexity.
Layered architecture (for any backend)
┌─────────────────────────────────┐
│ Presentation (Routes/Handlers) │ ← HTTP layer, input validation
├─────────────────────────────────┤
│ Service / Business Logic │ ← Domain rules, orchestration
├─────────────────────────────────┤
│ Repository / Data Access │ ← Database queries, external APIs
├─────────────────────────────────┤
│ Infrastructure │ ← DB connections, caches, queues
└─────────────────────────────────┘
Rules:
- Each layer only calls the layer directly below it.
- Routes should be thin — delegate to services.
- Services contain business logic — no HTTP concepts (no request/response objects).
- Repositories abstract data access — services don't write SQL directly.
Communication patterns
| Pattern |
Protocol |
Use when |
| Synchronous request/response |
HTTP/REST, gRPC |
Direct queries, CRUD |
| Async messaging |
RabbitMQ, Kafka, SQS |
Decoupled processing, event-driven workflows |
| Streaming |
gRPC streams, WebSockets, SSE |
Real-time updates, live feeds |
| Webhooks |
HTTP callbacks |
Notifying external systems of events |
Resilience patterns
- Circuit breaker: Stop calling a failing service; fail fast and recover gracefully.
- Retry with exponential backoff + jitter: Retry transient failures without thundering herd.
- Timeout: Set timeouts on all external calls. A missing timeout is a bug.
- Bulkhead: Isolate failures — don't let one slow dependency bring down the entire system.
- Health checks: Expose
/health (liveness) and /ready (readiness) endpoints.
13. Webhooks
Sending webhooks
- Sign payloads with HMAC-SHA256 so receivers can verify authenticity.
- Use exponential backoff for retries (e.g., 5 attempts: 1m, 5m, 30m, 2h, 24h).
- Consider successful delivery as 2xx response within a timeout (e.g., 30s).
- Log all delivery attempts for debugging.
- Provide a webhook event log / dashboard in your API.
- Send a minimal payload with an event type and resource ID; let receivers fetch details via API.
Receiving webhooks
- Verify the signature before processing.
- Respond with
200 OK quickly; process asynchronously.
- Handle duplicate deliveries gracefully (idempotent processing).
- Use a queue for processing to avoid blocking the webhook endpoint.
14. Testing Backend Systems
Testing pyramid
╱ E2E Tests ╲ ← Few: Full user flows
╱ Integration ╲ ← Some: API endpoints with real DB
╱ Unit Tests ╲ ← Many: Business logic, utilities
╱────────────────────╲
What to test at each level
Unit tests (fast, isolated):
- Business logic functions
- Validation rules
- Data transformations
- Edge cases and error paths
Integration tests (with real dependencies):
- API endpoints end-to-end (HTTP → handler → service → DB → response)
- Database queries against a test database
- Cache behavior
- Authentication/authorization flows
Contract tests (for API consumers):
- Verify your API responses match the documented schema.
- Use tools like Pact or Schemathesis.
Load tests (before production):
- Use k6, Locust, or Gatling.
- Test at 2–3× expected peak traffic.
- Identify bottlenecks: slow queries, memory leaks, connection exhaustion.
Testing rules
- Test behavior, not implementation.
- Use factories (Factory Boy, Faker) to generate test data — not fixtures.
- Isolate tests — each test should set up and tear down its own data.
- Test error paths as thoroughly as happy paths.
- Run tests in CI on every pull request.
15. Deployment & Infrastructure
Container best practices (Docker)
# Multi-stage build for smaller images
FROM python:3.12-slim AS builder
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
FROM python:3.12-slim
WORKDIR /app
COPY --from=builder /usr/local/lib/python3.12/site-packages /usr/local/lib/python3.12/site-packages
COPY . .
# Run as non-root user
RUN adduser --disabled-password appuser
USER appuser
EXPOSE 8000
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
- Use multi-stage builds for smaller images.
- Run as a non-root user.
- Pin exact versions for base images and dependencies.
- Use
.dockerignore to exclude unnecessary files.
- Scan images for vulnerabilities (Trivy, Snyk).
CI/CD pipeline
Push → Lint → Unit Tests → Build Image → Integration Tests → Security Scan → Deploy to Staging → E2E Tests → Deploy to Production
- Every commit triggers lint + unit tests.
- Every PR merge triggers full pipeline including integration tests.
- Use blue-green or canary deployments for zero-downtime releases.
- Rollback must be a single command / automated on error spike.
Health checks
// GET /health (liveness — is the process alive?)
{ "status": "ok" }
// GET /ready (readiness — can the service handle traffic?)
{
"status": "ok",
"checks": {
"database": "connected",
"redis": "connected",
"queue": "connected"
}
}
16. API Documentation
- Use OpenAPI 3.1 (Swagger) for REST APIs.
- Generate docs from code (not maintained separately) — most frameworks support this.
- Include: authentication instructions, endpoint references, request/response examples, error format, rate limits, pagination details.
- Provide runnable examples (curl, HTTPie, or language-specific snippets).
- Keep docs in sync — stale docs are worse than no docs.
- Consider publishing an
llms.txt for AI agent consumption.
17. Common Pitfalls
| Pitfall |
Fix |
| No input validation |
Validate everything server-side with schema libraries |
| Leaking internal errors to clients |
Return generic errors; log details server-side |
| N+1 database queries |
Use JOINs, eager loading, or DataLoader patterns |
| No rate limiting |
Implement at API gateway level; return 429 with Retry-After |
| OFFSET-based pagination on large datasets |
Switch to cursor/keyset pagination |
| Rolling your own auth |
Use established providers or battle-tested libraries |
| No timeouts on external calls |
Set timeouts on every HTTP client, DB connection, and queue consumer |
| Monolithic error handling |
Use structured error types with consistent response format |
| No request/correlation IDs |
Generate and propagate IDs for cross-service tracing |
| Testing only happy paths |
Test error cases, edge cases, and auth failures |
| Skipping database migrations |
Use Alembic, Flyway, or Prisma Migrate — never ALTER in production manually |
| No health check endpoints |
Expose /health and /ready for orchestrator probes |
| Storing secrets in code/env files in git |
Use secret managers (Vault, AWS Secrets Manager, etc.) |
| Ignoring CORS until frontend integration |
Configure CORS from day one with explicit origins |
18. Production Readiness Checklist
Before shipping to production, verify:
API Design:
Security:
Database:
Observability:
Infrastructure:
1---
2name: backend
3description: >
4 Use this skill whenever building, designing, reviewing, or debugging backend systems,
5 APIs, services, or server-side architecture. Triggers include any mention of REST API
6 design, GraphQL, gRPC, database design, SQL optimization, caching (Redis, Memcached),
7 authentication/authorization (JWT, OAuth), message queues (Kafka, RabbitMQ), microservices,
8 monolith architecture, observability (logging, metrics, tracing), rate limiting, pagination,
9 error handling patterns, API versioning, background jobs, webhooks, CI/CD, Docker, or
10 deployment. Also use when the user asks to "design an API", "structure a backend",
11 "optimize queries", "add caching", "set up auth", "handle errors", or any server-side
12 architecture question. This skill is framework-agnostic — for framework-specific guidance
13 (FastAPI, Express, Django, etc.), combine this with the relevant framework skill.
14 Covers production patterns for 2025–2026: API design, database architecture, caching,
15 security, observability, scalability, and deployment.
16metadata:
17 source: https://skillmd.com/skills/aibot88/backend
18---
19
20# Backend Skill — Production Backend Engineering (2025–2026)
21
22This skill covers framework-agnostic backend engineering principles: API design, database patterns, caching, security, observability, architecture decisions, and deployment. Combine with framework-specific skills (FastAPI, Express, Django, Spring, etc.) for implementation details.
23
24---
25
26## 1. API Design Fundamentals
27
28### REST URL conventions
29
30Resources are **nouns** (plural). HTTP methods are the **verbs**.
31
32```
33GET /api/v1/users # List users
34POST /api/v1/users # Create a user
35GET /api/v1/users/123 # Get user 123
36PATCH /api/v1/users/123 # Partial update
37PUT /api/v1/users/123 # Full replace
38DELETE /api/v1/users/123 # Delete user 123
39
40GET /api/v1/users/123/orders # User's orders (shallow nesting)
41GET /api/v1/users/123/orders/456 # Specific order
42
43# ❌ Anti-patterns
44GET /api/v1/getAllUsers
45POST /api/v1/createUser
46POST /api/v1/deleteUser
47GET /api/v1/user?id=123
48```
49
50### URL design rules
51
52- Use **plural nouns**: `/users`, `/orders`, `/products`.
53- Use **lowercase with hyphens**: `/order-items`, not `/orderItems` or `/order_items`.
54- Keep nesting **shallow** (max 2 levels): `/users/123/orders` is fine; `/users/123/orders/456/items/789/reviews` is too deep — flatten to `/reviews?item_id=789`.
55- Use **query parameters** for filtering, sorting, pagination: `/users?role=admin&sort=-created_at&page=2`.
56- Avoid exposing internal IDs when possible — use UUIDs or slugs for public-facing resources.
57
58### HTTP methods and semantics
59
60| Method | Idempotent | Safe | Use for |
61|:--------|:-----------|:-----|:---------------------------------|
62| GET | Yes | Yes | Read resources |
63| POST | No | No | Create resources, trigger actions |
64| PUT | Yes | No | Full replace of a resource |
65| PATCH | Yes* | No | Partial update |
66| DELETE | Yes | No | Remove a resource |
67| HEAD | Yes | Yes | Like GET but headers only |
68| OPTIONS | Yes | Yes | CORS preflight, capabilities |
69
70*PATCH is idempotent when using merge-patch semantics (the common case).
71
72### HTTP status codes
73
74Use them correctly — they are part of your API contract.
75
76```
772xx — Success
78 200 OK — Standard success response
79 201 Created — Resource created (include Location header)
80 204 No Content — Success with no response body (DELETE, PUT)
81
823xx — Redirection
83 301 Moved Permanently — Resource URL changed permanently
84 304 Not Modified — Cached version is still valid
85
864xx — Client Errors
87 400 Bad Request — Malformed syntax or invalid input
88 401 Unauthorized — Missing or invalid authentication
89 403 Forbidden — Authenticated but insufficient permissions
90 404 Not Found — Resource doesn't exist
91 409 Conflict — State conflict (e.g., duplicate email)
92 422 Unprocessable Entity — Valid syntax but semantic errors
93 429 Too Many Requests — Rate limit exceeded (include Retry-After header)
94
955xx — Server Errors
96 500 Internal Server Error — Unhandled server error
97 502 Bad Gateway — Upstream service failure
98 503 Service Unavailable — Temporary overload or maintenance
99 504 Gateway Timeout — Upstream service timeout
100```
101
102### Consistent error response format
103
104Follow RFC 9457 (Problem Details for HTTP APIs):
105
106```json
107{
108 "type": "https://api.example.com/errors/validation",
109 "title": "Validation Error",
110 "status": 422,
111 "detail": "The email field is required and must be a valid email address.",
112 "instance": "/api/v1/users",
113 "errors": [
114 {
115 "field": "email",
116 "message": "This field is required.",
117 "code": "required"
118 }
119 ]
120}
121```
122
123Rules for error responses:
124- Always return a consistent structure across all endpoints.
125- Include machine-readable error codes alongside human-readable messages.
126- Include field-level validation errors so clients can fix all issues in one round-trip.
127- **Never leak internal details** (stack traces, SQL queries, file paths) in production errors.
128- Log the full error server-side; return a sanitized version to the client.
129
130---
131
132## 2. API Versioning
133
134### Strategies
135
136| Strategy | Example | Pros | Cons |
137|:--------------|:--------------------------------|:------------------------|:-------------------------|
138| URL path | `/api/v1/users` | Explicit, easy to route | URL pollution |
139| Header | `Accept: application/vnd.api+json;version=2` | Clean URLs | Hidden, harder to test |
140| Query param | `/api/users?version=2` | Simple | Inconsistent |
141
142**Recommendation**: Use **URL path versioning** (`/api/v1/`). It's the most explicit, easiest to route, cache, and document. When introducing a breaking change, create a new version (`/api/v2/`) and run both in parallel with a deprecation timeline.
143
144### Deprecation protocol
145
1461. Announce deprecation with a `Deprecation` header and `Sunset` header on old endpoints.
1472. Provide a migration guide.
1483. Give clients at least 6–12 months before removal.
1494. Monitor usage of deprecated endpoints before turning them off.
150
151---
152
153## 3. Pagination
154
155### Cursor-based pagination (recommended)
156
157Best for real-time data, large datasets, and infinite scroll. Immune to offset drift when data changes.
158
159```
160GET /api/v1/orders?limit=20&after=eyJpZCI6MTIzfQ
161
162Response:
163{
164 "data": [...],
165 "pagination": {
166 "has_next": true,
167 "next_cursor": "eyJpZCI6MTQzfQ",
168 "has_previous": true,
169 "previous_cursor": "eyJpZCI6MTI0fQ"
170 }
171}
172```
173
174### Offset-based pagination (simpler)
175
176Fine for admin dashboards, small datasets, or when users need to jump to specific pages.
177
178```
179GET /api/v1/users?page=3&per_page=25
180
181Response:
182{
183 "data": [...],
184 "pagination": {
185 "page": 3,
186 "per_page": 25,
187 "total": 482,
188 "total_pages": 20
189 }
190}
191```
192
193### Pagination rules
194
195- Always set a **maximum page size** (e.g., `per_page` capped at 100).
196- Default to a reasonable page size (20–50).
197- Include pagination metadata in every list response.
198- For very large datasets (millions of rows), cursor-based is the only performant option.
199
200---
201
202## 4. Filtering, Sorting, and Field Selection
203
204```
205# Filtering
206GET /api/v1/products?category=electronics&price_min=100&price_max=500&in_stock=true
207
208# Sorting (prefix with - for descending)
209GET /api/v1/products?sort=-price,name
210
211# Field selection (reduce payload size)
212GET /api/v1/users?fields=id,name,email
213
214# Full-text search
215GET /api/v1/products?q=wireless+headphones
216```
217
218Be consistent across all endpoints. Document every supported filter, sort field, and selection parameter.
219
220---
221
222## 5. Authentication & Authorization
223
224### Authentication methods by use case
225
226| Use case | Method |
227|:-----------------------|:------------------------|
228| User-facing apps | OAuth 2.0 / OIDC |
229| Server-to-server | API keys + HMAC signing |
230| Microservice-to-microservice | Mutual TLS (mTLS) or JWT |
231| Simple internal tools | API keys in headers |
232
233### JWT best practices
234
235```
236Authorization: Bearer eyJhbGciOiJSUzI1NiIs...
237```
238
239- Use **short-lived access tokens** (5–15 minutes) with **long-lived refresh tokens** (days/weeks).
240- Store JWTs in **httpOnly, Secure, SameSite=Strict cookies** for browser clients — never in localStorage.
241- Use **asymmetric signing** (RS256/ES256) for distributed systems so services can verify without the private key.
242- Include minimal claims: `sub` (user ID), `exp`, `iat`, `iss`, `roles/scopes`.
243- Validate `exp`, `iss`, and `aud` on every request.
244- Implement **token revocation** via a short blocklist or by keeping access tokens very short-lived.
245
246### OAuth 2.0 / OIDC
247
248- Use **Authorization Code flow with PKCE** for all client types (web, mobile, SPA).
249- Never use the Implicit flow — it's deprecated.
250- Use established providers (Auth0, Clerk, Keycloak, Supabase Auth) rather than rolling your own.
251- Always validate the `state` parameter to prevent CSRF.
252- Store client secrets server-side only.
253
254### Authorization patterns
255
256- **RBAC (Role-Based Access Control)**: Assign roles (admin, editor, viewer) with predefined permissions. Works for most applications.
257- **ABAC (Attribute-Based Access Control)**: Policies based on user attributes, resource attributes, and context. More flexible but more complex.
258- **Check authorization at every layer**: Middleware for route-level checks, service layer for business-logic checks. Never rely on a single layer.
259
260---
261
262## 6. Database Design
263
264### Schema design principles
265
266- **Normalize first, denormalize intentionally.** Start with 3NF; denormalize specific tables for read performance when you have evidence (not speculation) of a bottleneck.
267- **Use appropriate data types**: Don't store dates as strings, don't use TEXT for short fixed-length fields, use DECIMAL/NUMERIC for money (never FLOAT).
268- **Always have a primary key**: Prefer auto-incrementing integers for internal IDs; use UUIDs (v7 for sortability) for public-facing IDs.
269- **Add created_at and updated_at** to every table (with timezone).
270- **Use foreign keys** for referential integrity in OLTP databases.
271- **Index strategically**: Index columns used in WHERE, JOIN, ORDER BY. Composite indexes follow the leftmost prefix rule. Don't over-index — each index slows writes.
272
273### Query optimization
274
275```sql
276-- ✅ Use EXPLAIN ANALYZE to understand query plans
277EXPLAIN ANALYZE
278SELECT u.id, u.name, COUNT(o.id) as order_count
279FROM users u
280LEFT JOIN orders o ON o.user_id = u.id
281WHERE u.created_at > '2026-01-01'
282GROUP BY u.id, u.name
283ORDER BY order_count DESC
284LIMIT 20;
285
286-- ✅ Avoid SELECT * — fetch only needed columns
287SELECT id, name, email FROM users WHERE active = true;
288
289-- ❌ N+1 queries — the most common performance killer
290-- Fetching users, then looping to fetch each user's orders separately
291-- ✅ Fix: JOIN or batch fetch in a single query
292```
293
294### Common query pitfalls
295
296| Pitfall | Fix |
297|:--------|:----|
298| N+1 queries | Use JOINs, eager loading, or batch fetching |
299| Missing indexes on foreign keys | Always index FK columns |
300| Full table scans on large tables | Add appropriate indexes; use LIMIT |
301| Using OFFSET for deep pagination | Switch to cursor/keyset pagination |
302| Locking issues on hot tables | Use row-level locking; consider read replicas |
303| Not using connection pooling | Use PgBouncer, HikariCP, or framework-level pools |
304
305### SQL vs NoSQL decision
306
307| Choose SQL (PostgreSQL, MySQL) when | Choose NoSQL when |
308|:------------------------------------|:------------------|
309| Complex relationships and JOINs | Document-shaped data (MongoDB) |
310| ACID transactions required | High write throughput at scale (Cassandra) |
311| Structured, well-known schema | Key-value lookups / caching (Redis) |
312| Reporting and aggregation | Graph relationships (Neo4j) |
313| Most CRUD applications | Time-series data (InfluxDB, TimescaleDB) |
314
315**Default to PostgreSQL** for most applications. It handles JSON (jsonb), full-text search, geospatial data, and scales to millions of rows before you need anything exotic.
316
317---
318
319## 7. Caching
320
321### Caching layers
322
323```
324Client ──→ CDN ──→ API Gateway ──→ Application Cache ──→ Database
325 ↑ ↑ ↑
326 Static Response Redis/Memcached
327 assets caching or in-memory
328```
329
330### Caching strategies
331
332| Strategy | How it works | Best for |
333|:---------|:-------------|:---------|
334| **Cache-aside** (Lazy loading) | App checks cache → miss → query DB → write to cache | General-purpose; most common |
335| **Write-through** | App writes to cache AND DB simultaneously | Strong consistency requirements |
336| **Write-behind** (Write-back) | App writes to cache; cache async writes to DB | High write throughput |
337| **Read-through** | Cache itself fetches from DB on miss | Simpler app code |
338
339### Cache invalidation
340
341Cache invalidation is one of the two hard problems in CS. Strategies:
342
343- **TTL (Time-to-Live)**: Set expiration. Simple but can serve stale data.
344- **Event-driven invalidation**: Invalidate cache when the underlying data changes (e.g., after a write).
345- **Tag-based invalidation**: Tag cache entries; invalidate all entries with a given tag.
346- **Versioned keys**: Include a version number in the cache key; bump it on changes.
347
348### Redis patterns
349
350```
351# Cache-aside pattern (pseudocode)
352def get_user(user_id):
353 cached = redis.get(f"user:{user_id}")
354 if cached:
355 return deserialize(cached)
356
357 user = db.query("SELECT * FROM users WHERE id = %s", user_id)
358 redis.setex(f"user:{user_id}", 300, serialize(user)) # TTL: 5 min
359 return user
360
361# Distributed locking (prevent thundering herd)
362lock = redis.set(f"lock:user:{user_id}", "1", nx=True, ex=10)
363if lock:
364 # Only one process rebuilds the cache
365 ...
366```
367
368### What to cache
369
370- **Cache**: Expensive query results, computed aggregations, API responses from third parties, session data, frequently-read and rarely-changed data.
371- **Don't cache**: User-specific sensitive data without proper scoping, rapidly-changing data where staleness is unacceptable, one-time reads.
372
373---
374
375## 8. Rate Limiting
376
377Protect your API from abuse, ensure fair usage, and prevent cascading failures.
378
379### Algorithms
380
381| Algorithm | Behavior | Best for |
382|:----------|:---------|:---------|
383| **Token bucket** | Tokens refill at a steady rate; requests consume tokens | Smooth rate limiting with burst allowance |
384| **Sliding window** | Counts requests in a rolling time window | Precise rate limiting |
385| **Fixed window** | Counts requests per fixed time window | Simplest to implement |
386
387### Implementation
388
389```
390# Response headers for rate limiting
391X-RateLimit-Limit: 1000 # Max requests per window
392X-RateLimit-Remaining: 847 # Requests remaining
393X-RateLimit-Reset: 1712800000 # Unix timestamp when window resets
394Retry-After: 30 # Seconds to wait (on 429 response)
395```
396
397- Apply rate limits **per API key/user**, not just per IP (IPs are shared behind NATs/VPNs).
398- Use different limits for different tiers (free: 100/hr, pro: 10,000/hr).
399- Return `429 Too Many Requests` with a `Retry-After` header.
400- Implement at the **API gateway or reverse proxy** level for efficiency.
401- Use Redis or a distributed counter for multi-instance deployments.
402
403---
404
405## 9. Background Jobs & Async Processing
406
407### When to use background jobs
408
409- Email/notification sending
410- PDF/report generation
411- Image/video processing
412- Data import/export
413- Webhook delivery and retries
414- Scheduled tasks (cron-like)
415- Any operation that takes > 1–2 seconds
416
417### Architecture
418
419```
420API Server ──→ Message Queue ──→ Workers
421 │ (Redis, RabbitMQ, │
422 │ Kafka, SQS) │
423 │ ↓
424 └── Returns 202 Accepted Process job
425 with job status URL Update status
426 Notify on completion
427```
428
429### Job design principles
430
431- **Idempotent**: Jobs should be safe to retry. If a job runs twice, the result should be the same.
432- **Small and focused**: Each job does one thing. Chain jobs for complex workflows.
433- **Observable**: Log job start/end/failure. Track duration, success rate, and queue depth.
434- **Retry with backoff**: Use exponential backoff with jitter (e.g., 1s, 2s, 4s, 8s + random jitter).
435- **Dead letter queue**: Failed jobs after max retries go to a DLQ for manual inspection.
436- **Timeout**: Set maximum execution time to prevent zombie jobs.
437
438### Tools
439
440| Language/Ecosystem | Tool |
441|:-------------------|:-----|
442| Python | Celery + Redis/RabbitMQ, ARQ, Dramatiq |
443| Node.js | BullMQ + Redis, Temporal |
444| Java/Kotlin | Spring Batch, Quartz |
445| Language-agnostic | Kafka, RabbitMQ, AWS SQS, Temporal |
446
447---
448
449## 10. Security
450
451### OWASP Top 10 awareness (2025–2026)
452
453The most critical backend security risks. Every backend engineer should know these:
454
4551. **Broken Access Control** — Enforce authorization at every endpoint and data access layer.
4562. **Cryptographic Failures** — Use TLS everywhere. Hash passwords with bcrypt/argon2. Encrypt sensitive data at rest.
4573. **Injection** — Use parameterized queries / ORMs. Never concatenate user input into SQL/commands.
4584. **Insecure Design** — Threat model during design, not after deployment.
4595. **Security Misconfiguration** — Disable debug endpoints in production. Remove default credentials. Set security headers.
4606. **Vulnerable Components** — Keep dependencies updated. Audit with `npm audit`, `pip-audit`, Snyk, or Dependabot.
4617. **Authentication Failures** — Implement account lockout, rate limiting on login, MFA.
4628. **Data Integrity Failures** — Verify software updates and CI/CD pipelines. Use SRI for CDN assets.
4639. **Logging & Monitoring Failures** — Log security events. Set up alerts for anomalies.
46410. **SSRF** — Validate and sanitize URLs the server fetches. Allowlist permitted domains.
465
466### Security headers
467
468```
469Strict-Transport-Security: max-age=63072000; includeSubDomains; preload
470Content-Security-Policy: default-src 'self'; script-src 'self'
471X-Content-Type-Options: nosniff
472X-Frame-Options: DENY
473Referrer-Policy: strict-origin-when-cross-origin
474Permissions-Policy: camera=(), microphone=(), geolocation=()
475```
476
477### Input validation
478
479- Validate **all** input: request body, query params, path params, headers.
480- Validate on the server — client validation is for UX, not security.
481- Use schema validation libraries (Pydantic, Zod, Joi, JSON Schema).
482- Reject unexpected fields (strict mode).
483- Sanitize output when rendering user content to prevent XSS.
484
485### Password storage
486
487- **Never** store passwords in plain text or with reversible encryption.
488- Use **bcrypt** (cost factor ≥ 12) or **argon2id** (preferred for new systems).
489- Salt is built into bcrypt/argon2 — don't roll your own salting scheme.
490
491---
492
493## 11. Observability
494
495Observability = Logs + Metrics + Traces. Design it alongside your application, not as an afterthought.
496
497### The three pillars
498
499**Logs** — Structured event records.
500```json
501{
502 "timestamp": "2026-04-10T14:32:01Z",
503 "level": "error",
504 "service": "order-service",
505 "request_id": "req_abc123",
506 "user_id": "usr_456",
507 "message": "Payment processing failed",
508 "error": "stripe_timeout",
509 "duration_ms": 30042
510}
511```
512
513- Use **structured logging** (JSON) — not unstructured text.
514- Include **request IDs / correlation IDs** that propagate across services.
515- Log at appropriate levels: DEBUG (development only), INFO (significant events), WARN (recoverable issues), ERROR (failures requiring attention).
516- **Never log** passwords, tokens, PII, or credit card numbers.
517
518**Metrics** — Aggregated numerical measurements.
519
520Key metrics to track (the RED method):
521- **Rate**: Requests per second
522- **Errors**: Error rate (4xx, 5xx)
523- **Duration**: Response time (p50, p95, p99)
524
525Additional: CPU/memory usage, queue depth, active connections, cache hit ratio, DB query time.
526
527**Traces** — Request flow across services.
528
529- Use **OpenTelemetry** (the industry standard) for instrumentation.
530- Propagate trace context (`traceparent` header) across service boundaries.
531- Trace critical paths: API → service → database → external API.
532
533### Alerting rules
534
535- Alert on **symptoms** (high error rate, slow response times), not causes.
536- Set thresholds based on **SLOs** (Service Level Objectives), e.g., "99.9% of requests complete in < 500ms."
537- Use severity levels: critical (paging), warning (next business day), info (dashboard only).
538- Avoid alert fatigue — every alert should be actionable.
539
540### Tools
541
542| Category | Tools |
543|:---------|:------|
544| Logging | ELK Stack, Loki + Grafana, Datadog |
545| Metrics | Prometheus + Grafana, Datadog, CloudWatch |
546| Tracing | Jaeger, Tempo, Datadog APM, Honeycomb |
547| All-in-one | Datadog, New Relic, Grafana Cloud |
548| Instrumentation | OpenTelemetry (universal standard) |
549
550---
551
552## 12. Architecture Patterns
553
554### Monolith vs Microservices
555
556| | Modular Monolith | Microservices |
557|:--|:-----------------|:--------------|
558| **Start with** | ✅ Always start here | Migrate to when needed |
559| **Deploy** | Single artifact | Independent per service |
560| **Complexity** | Lower operational overhead | Higher (networking, observability, consistency) |
561| **Team size** | < 20–30 engineers | Large orgs with team boundaries |
562| **Data** | Single database | Database per service |
563
564**Start with a well-structured monolith.** Extract services only when you have clear domain boundaries and team/scaling needs that justify the operational complexity.
565
566### Layered architecture (for any backend)
567
568```
569┌─────────────────────────────────┐
570│ Presentation (Routes/Handlers) │ ← HTTP layer, input validation
571├─────────────────────────────────┤
572│ Service / Business Logic │ ← Domain rules, orchestration
573├─────────────────────────────────┤
574│ Repository / Data Access │ ← Database queries, external APIs
575├─────────────────────────────────┤
576│ Infrastructure │ ← DB connections, caches, queues
577└─────────────────────────────────┘
578```
579
580Rules:
581- Each layer only calls the layer directly below it.
582- Routes should be thin — delegate to services.
583- Services contain business logic — no HTTP concepts (no request/response objects).
584- Repositories abstract data access — services don't write SQL directly.
585
586### Communication patterns
587
588| Pattern | Protocol | Use when |
589|:--------|:---------|:---------|
590| Synchronous request/response | HTTP/REST, gRPC | Direct queries, CRUD |
591| Async messaging | RabbitMQ, Kafka, SQS | Decoupled processing, event-driven workflows |
592| Streaming | gRPC streams, WebSockets, SSE | Real-time updates, live feeds |
593| Webhooks | HTTP callbacks | Notifying external systems of events |
594
595### Resilience patterns
596
597- **Circuit breaker**: Stop calling a failing service; fail fast and recover gracefully.
598- **Retry with exponential backoff + jitter**: Retry transient failures without thundering herd.
599- **Timeout**: Set timeouts on all external calls. A missing timeout is a bug.
600- **Bulkhead**: Isolate failures — don't let one slow dependency bring down the entire system.
601- **Health checks**: Expose `/health` (liveness) and `/ready` (readiness) endpoints.
602
603---
604
605## 13. Webhooks
606
607### Sending webhooks
608
609- Sign payloads with HMAC-SHA256 so receivers can verify authenticity.
610- Use exponential backoff for retries (e.g., 5 attempts: 1m, 5m, 30m, 2h, 24h).
611- Consider successful delivery as 2xx response within a timeout (e.g., 30s).
612- Log all delivery attempts for debugging.
613- Provide a webhook event log / dashboard in your API.
614- Send a minimal payload with an event type and resource ID; let receivers fetch details via API.
615
616### Receiving webhooks
617
618- Verify the signature before processing.
619- Respond with `200 OK` quickly; process asynchronously.
620- Handle duplicate deliveries gracefully (idempotent processing).
621- Use a queue for processing to avoid blocking the webhook endpoint.
622
623---
624
625## 14. Testing Backend Systems
626
627### Testing pyramid
628
629```
630 ╱ E2E Tests ╲ ← Few: Full user flows
631 ╱ Integration ╲ ← Some: API endpoints with real DB
632 ╱ Unit Tests ╲ ← Many: Business logic, utilities
633 ╱────────────────────╲
634```
635
636### What to test at each level
637
638**Unit tests** (fast, isolated):
639- Business logic functions
640- Validation rules
641- Data transformations
642- Edge cases and error paths
643
644**Integration tests** (with real dependencies):
645- API endpoints end-to-end (HTTP → handler → service → DB → response)
646- Database queries against a test database
647- Cache behavior
648- Authentication/authorization flows
649
650**Contract tests** (for API consumers):
651- Verify your API responses match the documented schema.
652- Use tools like Pact or Schemathesis.
653
654**Load tests** (before production):
655- Use k6, Locust, or Gatling.
656- Test at 2–3× expected peak traffic.
657- Identify bottlenecks: slow queries, memory leaks, connection exhaustion.
658
659### Testing rules
660
661- Test **behavior**, not implementation.
662- Use **factories** (Factory Boy, Faker) to generate test data — not fixtures.
663- Isolate tests — each test should set up and tear down its own data.
664- Test **error paths** as thoroughly as happy paths.
665- Run tests in CI on every pull request.
666
667---
668
669## 15. Deployment & Infrastructure
670
671### Container best practices (Docker)
672
673```dockerfile
674# Multi-stage build for smaller images
675FROM python:3.12-slim AS builder
676WORKDIR /app
677COPY requirements.txt .
678RUN pip install --no-cache-dir -r requirements.txt
679
680FROM python:3.12-slim
681WORKDIR /app
682COPY --from=builder /usr/local/lib/python3.12/site-packages /usr/local/lib/python3.12/site-packages
683COPY . .
684# Run as non-root user
685RUN adduser --disabled-password appuser
686USER appuser
687EXPOSE 8000
688CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
689```
690
691- Use **multi-stage builds** for smaller images.
692- Run as a **non-root user**.
693- Pin **exact versions** for base images and dependencies.
694- Use `.dockerignore` to exclude unnecessary files.
695- Scan images for vulnerabilities (Trivy, Snyk).
696
697### CI/CD pipeline
698
699```
700Push → Lint → Unit Tests → Build Image → Integration Tests → Security Scan → Deploy to Staging → E2E Tests → Deploy to Production
701```
702
703- **Every commit** triggers lint + unit tests.
704- **Every PR merge** triggers full pipeline including integration tests.
705- Use **blue-green** or **canary deployments** for zero-downtime releases.
706- **Rollback** must be a single command / automated on error spike.
707
708### Health checks
709
710```json
711// GET /health (liveness — is the process alive?)
712{ "status": "ok" }
713
714// GET /ready (readiness — can the service handle traffic?)
715{
716 "status": "ok",
717 "checks": {
718 "database": "connected",
719 "redis": "connected",
720 "queue": "connected"
721 }
722}
723```
724
725---
726
727## 16. API Documentation
728
729- Use **OpenAPI 3.1** (Swagger) for REST APIs.
730- Generate docs **from code** (not maintained separately) — most frameworks support this.
731- Include: authentication instructions, endpoint references, request/response examples, error format, rate limits, pagination details.
732- Provide **runnable examples** (curl, HTTPie, or language-specific snippets).
733- Keep docs in sync — stale docs are worse than no docs.
734- Consider publishing an `llms.txt` for AI agent consumption.
735
736---
737
738## 17. Common Pitfalls
739
740| Pitfall | Fix |
741|:--------|:----|
742| No input validation | Validate everything server-side with schema libraries |
743| Leaking internal errors to clients | Return generic errors; log details server-side |
744| N+1 database queries | Use JOINs, eager loading, or DataLoader patterns |
745| No rate limiting | Implement at API gateway level; return 429 with Retry-After |
746| OFFSET-based pagination on large datasets | Switch to cursor/keyset pagination |
747| Rolling your own auth | Use established providers or battle-tested libraries |
748| No timeouts on external calls | Set timeouts on every HTTP client, DB connection, and queue consumer |
749| Monolithic error handling | Use structured error types with consistent response format |
750| No request/correlation IDs | Generate and propagate IDs for cross-service tracing |
751| Testing only happy paths | Test error cases, edge cases, and auth failures |
752| Skipping database migrations | Use Alembic, Flyway, or Prisma Migrate — never ALTER in production manually |
753| No health check endpoints | Expose `/health` and `/ready` for orchestrator probes |
754| Storing secrets in code/env files in git | Use secret managers (Vault, AWS Secrets Manager, etc.) |
755| Ignoring CORS until frontend integration | Configure CORS from day one with explicit origins |
756
757---
758
759## 18. Production Readiness Checklist
760
761Before shipping to production, verify:
762
763**API Design:**
764- [ ] Consistent URL structure and naming
765- [ ] Proper HTTP status codes on all endpoints
766- [ ] Structured error responses (RFC 9457)
767- [ ] API versioning in place
768- [ ] Pagination on all list endpoints
769- [ ] Rate limiting configured
770
771**Security:**
772- [ ] HTTPS only (TLS 1.2+ minimum)
773- [ ] Authentication on all non-public endpoints
774- [ ] Authorization checks at route AND service layer
775- [ ] Input validation on all endpoints
776- [ ] Security headers set (HSTS, CSP, etc.)
777- [ ] Secrets in secret manager (not in code)
778- [ ] Dependencies scanned for vulnerabilities
779
780**Database:**
781- [ ] Connection pooling configured
782- [ ] Indexes on frequently-queried columns and foreign keys
783- [ ] Migrations managed with a migration tool
784- [ ] Backups automated and tested
785
786**Observability:**
787- [ ] Structured logging with correlation IDs
788- [ ] Key metrics exported (request rate, error rate, latency)
789- [ ] Alerting configured on SLO thresholds
790- [ ] Health check endpoints (`/health`, `/ready`)
791
792**Infrastructure:**
793- [ ] Containerized with non-root user
794- [ ] CI/CD pipeline with automated tests
795- [ ] Rollback procedure documented and tested
796- [ ] Load tested at 2–3× expected peak