Skip to content

βš™οΈ Backend Architecture ​

Structuring backend applications for reliability and scalability.

Project structure ​

src/
β”œβ”€β”€ modules/
β”‚   β”œβ”€β”€ auth/
β”‚   β”‚   β”œβ”€β”€ auth.controller.ts
β”‚   β”‚   β”œβ”€β”€ auth.service.ts
β”‚   β”‚   β”œβ”€β”€ auth.repository.ts
β”‚   β”‚   └── auth.types.ts
β”‚   β”œβ”€β”€ users/
β”‚   └── orders/
β”œβ”€β”€ shared/
β”‚   β”œβ”€β”€ middleware/
β”‚   β”œβ”€β”€ errors/
β”‚   β”œβ”€β”€ utils/
β”‚   └── types/
β”œβ”€β”€ config/
β”‚   β”œβ”€β”€ database.ts
β”‚   β”œβ”€β”€ env.ts
β”‚   └── logger.ts
└── server.ts

Layer responsibilities ​

LayerDoesDoesn't
ControllerParse request, validate input, return responseBusiness logic, DB queries
ServiceBusiness logic, orchestrationHTTP concerns, direct DB access
RepositoryData access, queriesBusiness logic, HTTP

Authentication patterns ​

PatternBest for
JWT (stateless)APIs, mobile apps, microservices
Session (stateful)Traditional web apps, SSR
OAuth2 / OIDCThird-party login, SSO
API keysService-to-service, public APIs

Middleware pipeline ​

Request β†’ Rate Limit β†’ Auth β†’ Validation β†’ Handler β†’ Error Handler β†’ Response

Logging ​

  • Use structured logging (JSON)
  • Include request ID for tracing
  • Log levels: error, warn, info, debug
  • Log at boundaries: incoming request, outgoing response, external calls
  • Never log sensitive data (passwords, tokens, PII)

Health checks ​

GET /health         β†’ 200 { status: 'ok' }
GET /health/ready   β†’ 200 { db: 'ok', cache: 'ok', queue: 'ok' }

Graceful shutdown ​

  1. Stop accepting new requests
  2. Finish in-flight requests (with timeout)
  3. Close database connections
  4. Close message queue connections
  5. Exit process

Pergame Knowledge Base