Architecture¶
The project follows a Layered Modular Architecture: each layer depends only on the layers below it.
🏗️ Layered Structure¶
graph TD
MW[Middleware: request context, CORS, GZip, activity log] --> API
API[API Layer - app/api] --> Services[Service Layer - app/services]
API --> CRUD
Services --> CRUD[CRUD Layer - app/crud]
CRUD --> DB[(PostgreSQL 18)]
API -. queue_email: BackgroundTasks or SQS .-> Email[app/core/email → SMTP / Mailpit]
subgraph Core[Core Layer - app/core]
Config[config]
Security[security]
Exceptions[exceptions]
Logger[logger]
Telemetry[telemetry]
Limiter[limiter]
end
API -.-> Core
Services -.-> Core
CRUD -.-> Core
| Layer | Responsibility | Rules |
|---|---|---|
API (app/api) |
Routing, request validation, auth dependencies (deps.py), response models |
Thin. No business rules; never builds SQL beyond simple pagination. |
Service (app/services) |
Business logic and policy: auth.py (login, lockout, tokens, password flows), users.py (RBAC policy), dashboards |
Raises domain exceptions (app.core.exceptions), never HTTPException. |
CRUD (app/crud) |
Atomic database operations | No HTTP. No authorization, except ToDo visibility (see below). |
Model (app/models) |
SQLModel tables and DTOs (Create / Update / Public) | app/models/__init__.py registers every table for Alembic. |
Core (app/core) |
Settings, security, error format, logging, tracing, rate limits | No imports from the layers above, except that the unhandled-error handler in exceptions.py writes to system_log through CRUD. |
User-management authorization lives in app/services/users.py. ToDos have no service module: their endpoints call CRUD directly, and the visibility rules are in app/crud/todo.py (see ADR 0004).
❗ Error Handling¶
Services raise AppError subclasses (BadRequestError, AuthenticationError, PermissionDeniedError, NotFoundError, ConflictError, LockedError). app/core/exceptions.py turns them, along with HTTP and validation errors, into RFC 9457 Problem Details responses:
{"type": "about:blank", "title": "Not Found", "status": 404, "detail": "User not found", "instance": "/api/v1/users/…"}
For 422 responses, detail is the list of field errors. PostgreSQL cannot store NUL (\u0000) in text, and unpaired surrogates (such as \ud800) cannot be encoded as UTF-8. Request bodies and query filters containing them are rejected with 422 (app/models/validators.py); where the error echoes the input, surrogates are replaced with U+FFFD. A login username containing NUL gets the normal invalid-credentials response. Unhandled exceptions return a generic 500 and are written to the system_log table with the stack trace and request ID.
🔁 Request Lifecycle¶
- RequestContextMiddleware assigns or propagates
X-Request-ID, binds it (and lateruser_id/trace_id) to every log line, and adds security headers (CSP,nosniff,X-Frame-Options, HSTS instagingandproduction). - TrustedHost / GZip / CORS run when configured.
- ActivityLoggerMiddleware records one
user_activityrow after the response is sent. Probe, metrics and docs paths, andOPTIONSrequests, are skipped. - Route + dependencies authenticate the token (type, signature,
iss/aud,token_version) and check the role.
On AWS Lambda (ADR 0005), two more run outermost:
- CloudFrontOriginMiddleware (
ORIGIN_VERIFY_SECRET) rejects requests without the secretX-Origin-Verifyheader with403, and sets the client IP fromCloudFront-Viewer-Address. - CompleteAfterAppMiddleware (
DEFER_RESPONSE_UNTIL_COMPLETE) holds the last body chunk until steps 3 and 4 have finished, because Lambda freezes once the response is complete.
Endpoints send email with app.core.email.queue_email. It uses BackgroundTasks by default, or SQS when EMAIL_QUEUE_URL is set (a worker function, app.aws.worker, sends the message).
All middleware is pure ASGI (no BaseHTTPMiddleware).
🛡️ Observability¶
- Logs: Structlog JSON outside
local(console renderer locally). Uvicorn and library logs share the same pipeline. Every line carriesrequest_id. - Metrics: Prometheus at
/metrics(not in the OpenAPI schema). - Tracing: OpenTelemetry for FastAPI and SQLAlchemy, enabled by
OTEL_EXPORTER_OTLP_ENDPOINT. - Errors: Sentry (opt-in via
SENTRY_DSN) with configurable sampling and no PII. - Probes:
/health/live(process) and/health/ready(database).
🗄️ Data¶
- PostgreSQL 18 via async SQLAlchemy and
psycopg3, with a pooled engine, statement timeout andapplication_name. - Alembic migrations are the only way the schema changes. The test suite runs every migration and fails on model/migration drift.
- Audit tables (
user_activity,system_log) are pruned bypython -m app.db.maintenance(AUDIT_RETENTION_DAYS).
See ADRs for the reasoning behind the main decisions.