← All mindmapsMAIN TOPIC · 13 / 14AI Backend Engineering
API contracts, model serving, security and resilience
Explore full topic ↗ Readable revision notes (18 concepts)
The same content as the visual sheet, optimized for mobile and assistive technology.
01 · API design
- REST resources; GET reads; POST creates/processes
- Use status codes: 400, 401, 403, 429, 5xx
- Version contracts; paginate large collections
02 · FastAPI & validation
- Pydantic validates request/response schemas
- async endpoints suit nonblocking I/O
- CPU/GPU work needs workers or external service
03 · Auth & authorization
- Authenticate identity; authorize each object/action
- Verify token signature, expiry and claims
- Keep API keys server-only; scope credentials
04 · Inference serving
- Load model once per worker where feasible
- Batch compatible requests; set memory limits
- Stream tokens via SSE; cancel on disconnect
05 · Persistence
- SQL transactions for durable state; vector store for retrieval
- Parameterized queries; indexes and migrations
- Use idempotency keys for retryable writes
06 · Performance
- Cache safe responses using model/version/context key
- Connection pools, bounded concurrency, timeouts
- Queue slow jobs; expose status and cancellation
07 · Security
- Validate uploads, size, MIME and paths
- Prevent injection, SSRF, XSS and CSRF as applicable
- Rate limit; restrict CORS; use TLS and redacted logs
08 · Observability
- Request IDs; structured logs, traces and metrics
- Health/readiness endpoints; monitor p95 and errors
- Do not log prompts containing secrets or personal data
09 · Deployment
- Container + environment config; never commit secrets
- Graceful shutdown; retry transient errors with jitter
- Test contracts, load, auth isolation and failure paths
10 · HTTP & REST semantics
- GET safe/read-only; PUT typically idempotent replacement; PATCH partial; POST task/create.
- 201 created, 202 accepted, 204 no content; 400/422 validation; 401 auth, 403 denied.
- Use consistent error schema; correlation IDs; version contracts.
11 · FastAPI & Pydantic
- Declare input/output models; validate types, bounds and unknown fields appropriately.
- Dependency injection for auth, DB session, service layer.
- Async for nonblocking I/O; do not call blocking CPU/GPU workload in event loop.
12 · Auth, JWT & authorization
- Verify signature, issuer, audience, expiry; do not trust decoded claims alone.
- Authorization per resource/tenant; RBAC/ABAC where suitable.
- Cookies may require CSRF defenses; CORS not authorization; rotate secrets.
13 · Database & ORM
- Use parameterized SQL, pool connections; avoid N+1 and unbounded queries.
- Atomic transactions for related writes; use indexes and migrations.
- Store durable job state; vector store for search; choose consistency needs.
14 · Model serving & streaming
- Load model once per worker where practical; bounded concurrency and GPU memory.
- SSE streams server events; WebSocket bidirectional; cancel on disconnect.
- Separate prefill/decode timeouts; batch compatible inference requests.
15 · Background jobs
- Return 202/job ID for long tasks; queue worker executes and persists status.
- Retries with backoff/jitter; idempotency keys; dead-letter failures.
- Visibility timeout/lease; handle duplicate deliveries; cancel where safe.
16 · Caching & rate limits
- Cache key includes model, prompt, data version and authorization scope.
- TTL + invalidation; avoid cache stampede with single-flight.
- Token bucket/sliding window; quotas per user; return 429 and retry guidance.
17 · Security & abuse prevention
- Size/type limits, SSRF protection for fetched URLs, output escaping.
- Prompt injection: untrusted content cannot grant tool permissions.
- Least privilege, TLS, secret rotation, redacted logs; verify upload paths.
18 · Testing & deploy
- Test schema contracts, auth isolation, duplicate writes, DB failure and timeouts.
- Containerize, health/readiness checks, graceful shutdown and metrics.
- Load test realistic token lengths, concurrency and p95; canary rollback.
References & further study
Original schematics illustrate concepts, not measured data. Review these references for full derivations and implementation details.