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) when
REDIS_HOSTis set for shared cache and JWT denylist
- Single-tenant (no organization scoping in audit or RBAC)
- Async audit via BullMQ when
REDIS_HOSTis set; synchronous fallback otherwise - Scheduled purge: expired sessions + audit logs older than
AUDIT_RETENTION_DAYS(default 90) - Swagger intentionally exposed for integration workflows
- Set
REDIS_HOSTin every production/replica deployment — without it, RBAC permission cache and JWT denylist are per-process (in-memory fallback) - Global API prefix defaults to
/api(configurable viaAPI_PREFIX)
| Layer | Technology |
|---|---|
| Framework | NestJS |
| Database | PostgreSQL + TypeORM |
| Cache | Redis when REDIS_HOST is set; in-memory (per process) otherwise |
| 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.
This repository was built with intensive Claude Code assistance (Anthropic API, BYOK mode). A detailed estimate — methodology, assumptions, and dated pricing — is in Economia de Desenvolvimento e Custo de Tokens de IA (PT-BR).
Headline figures (pricing verified July 2026):
| Metric | Estimate |
|---|---|
| Codebase size | ~6,900 TS lines (123 files, 28 specs, 8 NestJS modules) |
| Manual build time (senior, TDD, security-hardened) | ~79 dev-days (~3.6 months) |
| Human steering effort with Claude Code | ~8 dev-days |
| Development time saved | ~70 dev-days (~3.2 months of 1 senior engineer) |
| Compression factor | ~8–12× |
| AI token cost (central estimate, ~15M tokens) | ~$130–$150 |
| Token-cost ROI vs. saved senior labor (US) | ~250–900× |
Cross-check: Anthropic's enterprise benchmark (~$13/dev-active-day) × ~10 steering dev-days ≈ ~$130, consistent with the central estimate.
| Language | Links |
|---|---|
| English | Architecture · Authentication · RBAC · Configuration · Observability · Security |
| Português | Arquitetura · Autenticação · RBAC · Configuração · Observabilidade · Segurança · Economia de Dev com IA |
(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.
# Local development (exposes DB/Redis ports)
npm run docker:up
# Production-like (no host port exposure)
npm run docker:up:prodThis 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 |
| Economia de desenvolvimento com IA | Tempo poupado, custo de tokens, ROI |
| 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 |