--- name: backend-patterns description: Design or review backend services, APIs, jobs, and persistence when boundaries, reliability, consistency, or observability matter. --- # Backend Patterns Fit the repository's architecture and operational model. Make failure behavior and trust boundaries explicit. ## Interfaces and validation Validate untrusted input at the boundary and keep domain invariants in the domain layer. Use typed, versioned contracts where the stack supports them. Return errors that are useful to callers without exposing internals or sensitive data. Preserve backward compatibility or provide an explicit migration path. Authorization must be enforced server-side at the resource or action boundary, not inferred from UI state. Keep authentication, authorization, validation, and business rules distinct enough to audit. ## Data and consistency Choose transaction boundaries around invariants. Make retryable operations idempotent and use unique constraints or idempotency keys where duplicate effects matter. Avoid holding database transactions across network calls. Treat migrations as forward-operable changes with rollback or roll-forward considerations. For caching, define the source of truth, key ownership, TTL, invalidation, and stale-data behavior. For queues and jobs, define delivery semantics, retries, poison-message handling, concurrency, and observability. ## Reliability and operations Set bounded timeouts for network calls. Retry only transient failures with limits and jitter, and avoid retry multiplication across layers. Use structured logs and metrics with correlation identifiers while excluding credentials, tokens, private payloads, and unnecessary personal data. ## Verification Test contracts and important failure paths at the narrowest layer that can prove them. Add integration tests for persistence, serialization, authorization, or external boundaries that mocks would conceal. For concurrency or performance claims, use a controlled test or benchmark. Do not add distributed infrastructure, background processing, caching, or a new persistence technology without evidence that the simpler design fails the requirement.