Backend Shell Reference
Consulting-format master framework for modular backend architecture, authorization, and
operational delivery
Document Type Technical Standard / Consulting Framework
Reusable backend shell standard for
Positioning
operational full-stack applications
Internal engineering reference and reusable
Use Case consulting delivery model for FastAPI-based
backend systems
Aligned with the frontend shell model and the AWS-native application delivery standard.
Page 1
1. Document purpose and scope
1.1 Purpose of the document
Define one reusable backend shell standard for serious operational applications.
1.2 Scope
This document standardizes backend architecture, backend module structure, bootstrap
and application factory model, router aggregation model, DB access structure,
authorization model, shared technical layers, testing structure, and operational alignment
with Docker and AWS-native production.
1.3 What this document freezes
It freezes the backend engineering method.
1.4 What this document does not freeze
It does not freeze business logic, workflows, or module-specific rules.
2. Core principles and fixed decisions
2.1 Consulting-grade backend objective
The backend must be structured as a serious operational system, not as a small
improvised API.
2.2 Reproducibility over improvisation
The backend must be extendable and runnable deterministically by another machine and
another developer.
2.3 Platform vs domain separation
The shell owns platform behavior. Modules own business behavior.
2.4 Services own business logic
Business rules must live in services, not in routes.
2.5 Shared technical concerns stay centralized
Configuration, DB session handling, token validation, error handling, and logging stay
centralized.
2.6 Authentication is externalized
Authentication is handled by Cognito, not by the backend.
2.7 Backend acts as a resource server
The backend validates Cognito tokens and enforces authorization.
Page 2
2.8 Infrastructure compatibility without infrastructure pollution
The backend must align with Docker, AWS, Cognito, Secrets Manager, CloudWatch, and
RDS without leaking infrastructure clutter into domain modules.
3. Reference backend model
3.1 Standard backend use cases
Examples include downtime logging, maintenance systems, inventory tools, quality
systems, production reporting, ERP-adjacent applications, industrial dashboards, and later
ML-enabled operational systems.
3.2 Standard backend role
The backend is responsible for API exposure, business logic execution, validation,
persistence orchestration, authorization enforcement, operational endpoints, and
integration support.
3.3 Standard backend communication model
Frontend communicates with backend over HTTP APIs; backend communicates with
PostgreSQL through ORM and migrations; Cognito provides identity; backend validates
tokens and applies access rules.
3.4 Standard backend module concept
A backend module is a business domain with its own router, service layer, repository layer,
schemas, models, and domain dependencies.
4. Standard technology stack
4.1 API framework
FastAPI and Uvicorn.
4.2 Validation and serialization
Pydantic.
4.3 Persistence
SQLAlchemy and Alembic.
4.4 Database target
PostgreSQL.
4.5 Testing
pytest.
4.6 Runtime compatibility
Docker and Docker Compose.
Page 3
4.7 Production compatibility
ECR, EC2, SSM, ALB, Cognito, Secrets Manager, CloudWatch, and RDS PostgreSQL.
5. Unified backend architecture standard
5.1 Overall backend architecture
The backend is composed of app entrypoint, bootstrap, core, DB, security, shared,
registry, modules, health, tests, and migrations.
5.2 Backend responsibilities
The backend must own request handling, service execution, DB access orchestration,
access enforcement, and operational readiness endpoints.
5.3 Backend anti-patterns to avoid
Avoid route-level business logic, duplicated technical helpers, scattered module
registration, per-module DB setup, ad hoc authorization logic, and infrastructure-specific
code inside business modules.
6. Backend shell architecture standard
6.1 Backend design objective
The backend shell must act as a reusable host platform for domain modules.
6.2 Architectural layers
Bootstrap layer, core layer, DB layer, security layer, shared layer, module layer, registry
layer, and health layer.
6.3 Entry point rule
`[Link]` must stay thin and only expose the ASGI app.
6.4 App factory rule
Real initialization belongs in the app factory.
6.5 Shell-owned responsibilities
App creation, middleware, exception handlers, settings loading, DB wiring, token
validation plumbing, authorization helpers, router aggregation, and health endpoints.
6.6 Module-owned responsibilities
Domain routes, domain services, domain repositories, domain models, domain schemas,
and domain rules and workflows.
Page 4
7. Standard folder structure
7.1 Root backend structure
backend/
app/
bootstrap/
core/
db/
security/
shared/
registry/
modules/
health/
[Link]
tests/
alembic/
[Link]
[Link]
Dockerfile
7.2 Bootstrap structure
`app_factory.py`, `[Link]`, `exception_handlers.py`, and `[Link]`.
7.3 Core structure
`[Link]`, `[Link]`, `[Link]`, and `[Link]`.
7.4 DB structure
`[Link]`, `[Link]`, and `[Link]`.
7.5 Security structure
`token_validation.py`, `[Link]`, `[Link]`, `[Link]`, and
`role_mapping.py`.
7.6 Shared structure
API helpers, contracts, generic types, and reusable utilities.
7.7 Module structure
`[Link]`, `[Link]`, `[Link]`, `[Link]`, `[Link]`, `[Link]`,
`[Link]`, and `[Link]`.
8. Bootstrap and application factory standard
8.1 `[Link]`
Single responsibility: expose `app = create_app()`.
Page 5
8.2 App factory responsibilities
Instantiate FastAPI, load settings, register middleware, register exception handlers, include
health routes, include module routes, and attach lifecycle hooks.
8.3 Middleware registration
Define global middleware only at shell level.
8.4 Exception handler registration
Centralize exception mapping and response formatting.
8.5 Lifecycle registration
Use startup and shutdown coordination only through shell bootstrap.
9. Core layer standard
9.1 Configuration model
Use typed centralized settings.
9.2 Configuration families
App metadata, environment, DB connection, CORS, Cognito parameters, logging, feature
flags, and external services.
9.3 Shared technical constants
Only technical constants belong here.
9.4 Shared technical exceptions
Define reusable technical exceptions centrally.
9.5 Logging model
Define one reusable logging standard for the backend.
10. DB layer standard
10.1 DB responsibilities
Engine creation, session management, declarative base, and DB dependency injection.
10.2 Session discipline
Modules must reuse centralized session logic.
10.3 Alembic discipline
Migrations remain centralized and explicit.
10.4 DB anti-patterns
Do not create engines or sessionmakers inside modules.
Page 6
11. Security and authorization standard
11.1 Identity model
Authentication is externalized to Cognito.
11.2 Backend security role
The backend validates tokens and enforces authorization.
11.3 Token validation responsibilities
Signature validation, issuer validation, audience or client validation where relevant,
expiration checks, and safe claims parsing.
11.4 Principal resolution
Convert token claims into an internal principal model.
11.5 Role mapping
Map Cognito claims or groups into backend access roles when needed.
11.6 Authorization model
Use roles, permissions, and access rules defined by the backend.
11.7 Security dependencies
Provide reusable route dependencies such as current principal, required role, and required
permission.
11.8 Security anti-patterns
Avoid backend login logic, duplicated token validation logic, blind trust in frontend route
hiding, and relying only on Cognito configuration for business authorization.
12. Shared layer standard
12.1 Shared API helpers
Pagination, response helpers, sorting and filtering utilities, and standardized error payload
support.
12.2 Shared contracts
Repository contracts where justified, service result contracts, paginated result contracts,
and reusable audit metadata structures.
12.3 Shared utils
Only truly generic utilities belong here.
12.4 Shared layer anti-pattern
No domain-specific logic in shared helpers.
Page 7
13. Module architecture standard
13.1 Module objective
A module represents one business domain.
13.2 Module responsibilities
Endpoint exposure for the domain, business workflows, persistence access, validation and
schema ownership, and domain-specific dependencies.
13.3 Router standard
Routes must remain thin.
13.4 Service standard
Services are the mandatory home for business logic.
13.5 Repository standard
Repositories own persistence access, not business rules.
13.6 Schema standard
Schemas define create, update, read, list, and query structures.
13.7 Model standard
Models define persistence entities.
13.8 Module anti-patterns
Avoid business logic in routes, SQL mixed directly into services everywhere, module-
owned infrastructure wiring, and duplicated response patterns.
14. Module registration standard
14.1 Registration principle
Modules must plug into the shell through a stable definition contract.
14.2 Module definition contract
Each module should export a standard definition object.
14.3 Registry responsibility
The registry is the single source of truth for installed modules.
14.4 Router aggregation rule
The shell includes module routers from the central registry.
14.5 Registration anti-patterns
Do not scatter module imports and route inclusion randomly across the project.
Page 8
15. Health and operational endpoints standard
15.1 Minimum endpoints
`/health`.
15.2 Optional endpoints
`/ready` and `/version`.
15.3 Operational role
These belong to the platform, not to modules.
15.4 Infrastructure alignment
These endpoints must align with Docker health checks, ALB health checks, and operational
diagnostics.
16. Error handling and response standard
16.1 Error handling objective
Define one consistent error strategy for the entire backend.
16.2 Exception categories
Validation, token or auth failure, permission denial, not found, conflict, and internal error.
16.3 Response philosophy
Choose and freeze one response philosophy: plain REST style or wrapped response style.
16.4 Recommendation
Keep CRUD responses simple and use metadata wrappers only where useful.
16.5 Error anti-pattern
Do not let each module invent its own error payload shape.
17. Testing and quality standard
17.1 Test structure
`tests/unit`, `tests/integration`, and `tests/api`.
17.2 Minimum test focus
Service logic, critical workflows, authorization-sensitive endpoints, validation behavior, and
health endpoint behavior.
17.3 Manual validation
Still required for critical flows, role-based access checks, and deployment verification.
Page 9
17.4 Quality anti-pattern
Do not reduce testing to endpoint smoke checks only.
18. Configuration and environment standard
18.1 Configuration principle
Configuration must be explicit, typed, and environment-specific.
18.2 Environment families
Local native, Docker-local, CI/CD, and production.
18.3 Local config
Use local env files only.
18.4 Production config
Use Secrets Manager and IAM-authorized retrieval.
18.5 Forbidden practices
Avoid production secrets in repo, ad hoc undocumented server-side secrets, and mixed
local/production conventions.
19. Infrastructure alignment standard
19.1 Runtime alignment
The backend must run cleanly in Docker and Docker Compose.
19.2 CI/CD alignment
It must support GitHub Actions build and ECR publishing.
19.3 Deployment alignment
It must be compatible with EC2 plus SSM deployment.
19.4 Public access alignment
It must support ALB health checks and public routing model.
19.5 Auth alignment
It must support Cognito token validation.
19.6 Operations alignment
It must support CloudWatch logging, metrics, and Secrets Manager-based configuration.
19.7 Database alignment
It must support PostgreSQL locally and RDS PostgreSQL in production.
Page 10
20. Reproducibility freeze points
20.1 Freeze points
Folder structure, layer responsibilities, module contract, registry model, response strategy,
security model, config contract, DB session model, and operational endpoints must remain
stable once adopted.
21. Deliverables by phase
21.1 Backend shell deliverables
App factory, core config, DB setup, security layer, registry, health route, and first module
skeleton.
21.2 Module deliverables
Router, service, repository, schemas, and models.
21.3 CI/CD deliverables
Docker build path, image publishing readiness, and environment contract clarity.
21.4 Production deliverables
Health check compatibility, Cognito compatibility, Secrets Manager compatibility,
CloudWatch compatibility, and PostgreSQL/RDS readiness.
22. Decision guardrails
22.1 Must always be done
Keep routes thin, centralize token validation, centralize DB sessions, register modules
through one registry, keep `[Link]` minimal, and define health endpoints early.
22.2 Must never be done
Do not implement custom login logic in backend when Cognito owns authentication; do not
duplicate access logic across modules; do not create per-module DB setup; do not let
shared layer absorb domain logic; do not let every project redefine shell structure.
22.3 Optional depending on app complexity
Advanced permission granularity, audit trail helpers, feature flags, event bus integration,
and ML-specific module extensions.
23. Final reference workflow
23.1 Workflow
Frame backend scope, create shell skeleton, define config and environment contract,
define DB layer, define Cognito-compatible security layer, define app factory, define
Page 11
module registry, add health endpoints, build first real module, validate routing,
authorization, and persistence flow, freeze shell conventions, then expand modules.
24. Final positioning
24.1 Positioning
This Backend Shell Reference is designed to function as the default technical method for
serious consulting-grade backend systems. Its objective is disciplined execution,
repeatability, modularity, authorization clarity, and controlled alignment with the broader
frontend and AWS-native delivery framework.
Page 12