01. The Problem: The Perpetual Re-Invention of Business Plumbing
Every non-trivial business application—whether an ERP, a multi-branch clinic management platform, a supply chain dashboard, or a restaurant back-office system—requires the exact same foundational primitives before any domain-specific features can be written:
- Scattered Identity & Session Management: Engineers routinely hack together ad-hoc JWT or session handlers that lack cryptographically secure token invalidation, password reset flows, or refresh mechanics.
- Brittle Multi-Tenancy: Organization and branch segregation is frequently treated as an afterthought, leading to catastrophic cross-tenant data leaks when queries miss filtering parameters.
- ORM Bloat & N+1 Overhead: Heavy object-relational mapping frameworks obscure database execution, introduce runtime reflection overhead, and generate slow, unoptimized SQL queries under high concurrent loads.
- Missing Compliance Audits: Traceability is omitted or added as an ad-hoc logging statement, leaving critical financial mutations and privilege escalations without an immutable audit trail.
02. Architectural Solution: Strict Modular Boundaries in Go
The Enterprise Core Backend operates as a cohesive, reusable foundation designed to sit underneath any commercial SaaS or business software. Rather than a monolithic codebase or an over-abstracted microservices swarm, the repository enforces strict module separation inside internal/modules/:
// internal/modules/authHandles user session lifecycles, cryptographically secure password hashing (Argon2id/bcrypt), JWT claim validation, and hardened password recovery state machines.
// internal/modules/orgModels multi-tenant hierarchies: Parent Organizations (Holdings), Operating Companies, and decentralized physical Units/Branches.
// internal/modules/rbacEnforces fine-grained, contextual Role-Based Access Control, separating administrative platform oversight from operational tenant permissions.
// internal/modules/auditCaptures immutable, structured security events (who performed what action, on which resource, at what timestamp, from which IP) directly into append-only PostgreSQL tables.
“Building enterprise systems is not about reinventing authentication or tenant tables for every client. It is about building a rock-solid, type-safe backbone once so every subsequent business module builds on a validated foundation.”— Vinicius Pontual, Architecture Whitepaper
03. Database Strategy: pgx/v5 Connection Pooling & Compiled SQL via sqlc
To maintain high throughput and predictable execution, this backend replaces runtime ORMs with pure, compiled SQL. Raw SQL queries are written in migrations/ and compiled by sqlc into idiomatic, fully type-safe Go structs:
// Example sqlc Compiled Query in Go
func (q *Queries) InsertAuditEvent(ctx context.Context, arg InsertAuditEventParams) (AuditLog, error) {
row := q.db.QueryRow(ctx, insertAuditEvent,
arg.OrganizationID,
arg.UserID,
arg.Action,
arg.Resource,
arg.Payload,
arg.IPAddress,
)
var i AuditLog
err := row.Scan(&i.ID, &i.OrganizationID, &i.UserID, &i.Action, &i.CreatedAt)
return i, err
}
Database connection pooling is handled by pgxpool, configuring maximum connection lifespans, idle thresholds, and health checks to sustain high request concurrency without exhausting PostgreSQL socket limits.
04. Codebase Organization: The Internal Package Pattern
The repository follows standard Go software engineering conventions to enforce compilation boundaries and prevent package circularity:
.
├── cmd/api/ // Main application entrypoint (HTTP server bootstrap)
├── internal/
│ ├── platform/ // Shared infrastructure (config, db, logger, server)
│ └── modules/ // Autonomous business domains
│ ├── auth/ // Password hashing, JWT issuance & verification
│ ├── users/ // User account lifecycles and profiles
│ ├── org/ // Tenant companies, holdings, and locations
│ ├── rbac/ // Roles, permissions, and policy evaluation
│ └── audit/ // Append-only security audit trail
├── migrations/ // Raw SQL migration files (golang-migrate)
└── sqlc.yaml // Code generation configuration
05. Security Invariants & Operational Defense
The core implements defensive standards out of the box:
- Multi-Tenant Data Isolation: Every database query touching organizational state enforces strict tenant foreign key constraints (
WHERE org_id = $1), validated via HTTP middleware before execution reaching the repository layer. - Structured Contextual Logging: Implements Go's standard
log/sloglibrary, attaching request IDs, tenant IDs, and execution durations to all system logs for centralized ingestion. - Immutable Audit Logging: Audit records are write-only. No application role or service account possesses SQL update or delete privileges over the audit ledger.
- Lightweight HTTP Layer: Uses
go-chi/chi/v5for sub-millisecond route matching with zero memory allocations, avoiding framework-level lock-in.
06. Specifications & Development Workflow
System dependencies and toolchain prerequisites:
| Layer | Component / Library | Technical Purpose |
|---|---|---|
| Runtime | Go 1.22+ | High-concurrency compiled backend binary with minimal memory footprint. |
| Persistence | PostgreSQL 15+ | ACID-compliant relational database with JSONB support for audit payloads. |
| DB Driver / Pool | jackc/pgx/v5 | High-performance PostgreSQL driver and connection pooling. |
| Code Generation | sqlc | Compiles raw SQL into safe, idiomatic Go code with zero runtime reflection. |
| HTTP Router | go-chi/chi/v5 | Composable, lightweight HTTP routing with standard library compatibility. |
golang-migrate in migrations/sqlc generate


