# Backend AI Agent Instructions (`apps/backend`) > **Tech Stack:** Go 1.23+, Chi v5 Router, pgx/v5 PostgreSQL Pool, Redis v9, GORM/SQL > **Role:** Single Source of Truth for Business Rules, Database Schema, and RBAC --- ## 1. Core Engineering Principles 1. **Modular Monolith**: Code is partitioned into domain modules under `internal/` (e.g. `auth`, `rbac`, `inventory`, `sales`, `cashier`, `purchasing`, `accounting`, `warehouses`, `uploads`). Modules interact through clean service interfaces and database transactions. 2. **Context Propagation & Cancellation**: Always pass `ctx context.Context` into database queries, external API calls, and long-running routines. If a client disconnects, queries must be canceled promptly to preserve VPS CPU cycles. 3. **Database Connection Pool**: Pool limits are governed in `pkg/database/database.go` (`MaxConns=25`, `MinConns=2`). Never create ad-hoc database connections outside the managed pool. 4. **Transaction Integrity**: Financial mutations, stock adjustments, and order state transitions MUST execute within a database transaction (`database.WithTx(ctx, pool, ...)`). Roll back immediately on error. 5. **Decimals for Money**: NEVER use `float64` for prices, totals, taxes, or payments. Always use `github.com/shopspring/decimal` with 2 decimal precision. --- ## 2. API Routing & Error Handling - **Router**: Go Chi router initialized in `cmd/server/main.go`. - **Response Format**: Use standard envelope helpers in `pkg/httpresponse`: - Success: `httpresponse.OK(w, data)` or `httpresponse.OKPaginated(w, data, meta)` - Error: `httpresponse.Error(w, r, status, code, message)` - **Safe Error Masking**: Never expose internal database error details or SQL syntax errors to clients. Use `httpresponse.SafeError`. - **OpenAPI & Catalog Sync**: - New endpoints must be documented in `docs/openapi.yaml`. - New permissions must be declared in `internal/modules/rbac/catalog.go`. - Run `pnpm drift:check` from repository root after changing routes or permissions. --- ## 3. Testing Requirements - Run all backend tests: `go test -v ./...` (or from monorepo root: `pnpm test:backend`). - Race condition testing: `go test -race ./...`. - Never disable failing unit tests or mock away real database schema constraints in tests.