A reference NestJS backend architecture designed for regulated and security-sensitive environments — payments, healthcare, enterprise SaaS, and AI-driven systems where auditability and resilience are non-negotiable.
This is not a boilerplate.
It is a security-first backend foundation shaped by real production constraints.
Ramos de Souza Janones
Senior Full-Stack Engineer — Node.js | NestJS | Distributed Systems | LLMs in Production
I design secure, scalable, audit-ready backend systems for regulated and high-risk domains.
Most backend templates optimize for speed.
This architecture optimizes for:
- Security reviews
- Compliance readiness
- Auditability
- Failure containment
- Production resilience
- Horizontal scalability
It reflects patterns used in environments where:
- Financial transactions cannot fail silently
- Healthcare data must remain traceable
- Authentication must resist token replay attacks
- AI integrations require structured observability
- Private key signs tokens (server only)
- Public key verifies tokens (safe to distribute)
- Prevents symmetric secret leakage risks
- Compatible with distributed validation
- Access token: 15 minutes
- Refresh token: 7 days
- Rotation with reuse detection enabled
- If a compromised refresh token is reused:
- Entire session family is revoked
- Event is logged
- Incident becomes traceable
- No silent compromise.
- Every mutation recorded
- Correlation ID per request
- No update/delete on audit records
- Designed for traceability and forensic review
- Feature → Permission → RolePermission → Role → User
- Permissions stored in DB
- No hardcoded roles
- Changes take effect immediately
- All mutations guarded
- Startup validation via Joi
- Production refuses to boot without:
PRIVATE_KEYPUBLIC_KEYDB_SSL=trueALLOWED_ORIGINSdefined
- No silent misconfiguration.
- Rate limiting: 100 req / 15 min per IP
- Helmet security headers
- Strict CORS (production required)
- ValidationPipe (whitelist + forbidNonWhitelisted)
- Account lockout: 5 attempts → 15-minute lock
- Password change revokes all active sessions
synchronize: falsein production- Designed to pass internal security review.
- Structured logging with Pino
- Correlation ID propagation
- Liveness & Readiness endpoints
- Docker health checks aligned with readiness
- Graceful shutdown on SIGTERM
- Connection pooling (configurable)
- Horizontal scaling supported (stateless JWT)
- Single-tenant (Organization entity placeholder only)
- Swagger intentionally exposed for integration workflows
- Migrations only — no schema sync in production
| Layer | Technology |
|---|---|
| Framework | NestJS |
| Database | PostgreSQL + TypeORM |
| Cache | Redis |
| Auth | JWT RS256 |
| Validation | Class Validator + Joi |
| Logging | Pino |
| API Docs | Swagger |
This architecture reflects experience in:
- Payment systems (including PIX-related flows)
- Healthcare platforms
- Stripe integrations
- AI system refactoring
- LLM + RAG pipelines in production
When integrating AI into regulated systems, structured logs, correlation IDs, and audit trails stop being optional. They become operational requirements.
| Language | Links |
|---|---|
| English | Architecture · Authentication · RBAC · Configuration · Observability · Security |
| Português | Arquitetura · Autenticação · RBAC · Configuração · Observabilidade · Segurança |
(See /docs directory)
- Configure
.env - Generate RSA keys
- Run migrations
- Seed RBAC
- Change admin credentials
- Start application
cp .env.example .env
openssl genrsa -out private.pem 2048
openssl rsa -in private.pem -pubout -out public.pem
yarn install
yarn migration:run
yarn seed:rbac
yarn devImportant: Change the seed admin password after first deploy.
This repository can be used as:
- A secure backend reference implementation
- An RBAC foundation
- A JWT rotation example
- An audit-ready architecture blueprint
- A starting point for regulated SaaS systems
If you are building or modernizing a backend that must survive:
- Security review
- Compliance audits
- Production incidents
- AI integration risks
Let's connect.
| Seção | Descrição |
|---|---|
| Construído por | Autor e links de contato |
| Por que esta arquitetura existe | Motivação e contexto |
| Princípios de design | JWT RS256, rotação, auditoria, RBAC, fail-fast |
| Modelo de segurança | Rate limit, lockout, CORS, validação |
| Observabilidade e resiliência | Pino, health checks, graceful shutdown |
| Restrições de arquitetura | Single-tenant, Swagger, migrations |
| Stack tecnológica | NestJS, PostgreSQL, Redis, JWT |
| Contexto real | Pagamentos, healthcare, AI |
| Documentação | Links para docs em inglês e português |
| Quick Start | Passos para rodar o projeto |
| Para líderes de engenharia | Casos de uso do repositório |
| Contato | Website e LinkedIn |