Architecture
The monorepo's apps, the shared library, and the exact path a request takes through the server.
The Naalya backend is a NestJS monorepo: several apps in one repository, sharing one set of dependencies and one pile of common code. The split exists because not all work is request work: answering HTTP should be fast, while email, audit writes, and external syncs are slow and retryable, so they run in separate processes.
Four things to hold in your head:
server: the HTTP API that answers the Hub and the website.workerandaudit: background processes. They do not calllisten.ehr: a second HTTP API for the clinic, with its own database.libs/shared(imported as@app/shared): code the apps reuse.
This map shows who talks to whom, from the people at the top to the background apps at the bottom. The clinic API (ehr) is left out: it only talks to its own database.
Default project is server
Projects are declared in nest-cli.json; the default is server, so pnpm start:dev with no arguments runs the API. The worker and audit apps have their own scripts. If a command "does nothing," check which project it targeted.
Repo layout
apps/
server/ → the schools HTTP API
worker/ → background job processor
audit/ → audit-log microservice
ehr/ → clinic HTTP API
libs/
shared/ → code shared across the apps (@app/shared)
database/
migrations/ → Hub TypeORM migrations
ehr-migrations/ → clinic TypeORM migrations
emails/ → React Email templatesEach app is self-contained, with its own main.ts and root module. Apps never import each other: the only shared code comes through @app/shared.
What the apps talk to
The stores below, plus Gotenberg for PDF. In development, Redis, Centrifugo, and Gotenberg are what task infra starts. Hub Postgres and RabbitMQ are not in that command. See Getting Started.
| Service | Role | Reached through |
|---|---|---|
| Postgres (Hub) | School domain rows. DATABASE_URL. Not a container in either compose file. | TypeORM, DatabaseModule.forRoot, synchronize: false |
| Postgres (clinic) | Clinic rows. EHR_DATABASE_URL. Local container ehr-postgres only when you start the EHR infra. | The clinic app's own TypeORM config |
| RabbitMQ | Nest microservice transport (QUEUES.WORKER, QUEUES.AGENT, QUEUES.AUDIT, QUEUES.AGENT_TOOL). RABBIT_MQ_URL. Not in compose. | Nest microservice clients |
| Redis | BullMQ, cache, the instance list, collaborative documents, Pip run ownership, and the shared rate-limit windows. REDIS_URL, CACHE_REDIS_URL. The server, worker, and audit apps each construct RedisService. | BullMQ in AppModule, and Several copies |
| Centrifugo | Websocket broker for realtime. | RealtimeService, CENTRIFUGO_URL |
| Gotenberg | HTML to PDF. GOTENBERG_URL defaults to http://localhost:3010. | The worker PDF path |
There is also a type bus: the server publishes shared TypeScript types at /.well-known/chowbea.json, which the Education Hub generates from. Types that never appear on a REST body, websocket payloads, domain enums, cross there instead of through Swagger. See How Chowbea works.
The apps
| App | Boot file | Listens on | Hosts |
|---|---|---|---|
| server | apps/server/src/main.ts bootstrap | configService.get('port') ?? 8000, prefix api/v1 | Domain modules under apps/server/src/app, plus CollabService.attach |
| worker | apps/worker/src/main.ts | No HTTP listen. Consumes QUEUES.WORKER and QUEUES.AGENT | Jobs, and the Rover agent graph |
| audit | apps/audit/src/main.ts | No HTTP listen. Consumes QUEUES.AUDIT | Audit-log consumer |
| ehr | apps/ehr/src/main.ts | EHR_PORT default 8100, prefix api/v1 | Clinic HTTP API |
server: Express 5 HTTP server. Its root module apps/server/src/app/app.module.ts wires the database, the Redis/BullMQ connection, and one feature module per domain. You add a feature module and register it here. Every route sits under api/v1 (so a users route is /api/v1/users). The exception is /queues*, excluded so Bull Board stays at /queues. Controller prefixes are listed on HTTP surface.
worker does not serve HTTP. Alongside its processors it hosts the Rover agent graph, which reaches school data by calling back into the server over RabbitMQ rather than opening its own database connection for that path. That seam is described in How the AI system works. The queue name constant is QUEUES.WORKER. This page does not guess the broker's string name. The chat, small-talk, slide-reader, and illustration clients in that graph call OpenAI with OPENAI_API_KEY. That was read at main 6bfb9f6b and re-read on the default branch staging ed0e56f8. A search of that tree finds no OPENROUTER_API_KEY. Deployment was not verified. The keys are on Config and environment. The system map above does not draw that hop.
audit consumes QUEUES.AUDIT and does not call listen.
ehr is a separate Nest application with ehrEnvSchema. Do not point it at DATABASE_URL. Its dev Postgres container is ehr-postgres.
BullMQ is Redis. RabbitMQ is the Nest microservice transport. Earlier revisions of this page treated them as one queue. They are not.
libs/shared
@app/shared is exposed through one barrel file (libs/shared/src/index.ts). Import from the package name, never a deep path:
import { BaseRepository, UserType, generateSlug } from '@app/shared';| Group | What you'll find |
|---|---|
| Database | DatabaseEntity, BaseRepository, DatabaseModule, cursor-pagination helpers |
| Config | config, validateConfig, env types |
| API helpers | MessageResponseDto, ErrorResponseDto, Swagger error decorators |
| Enums | UserType, ApplicationStatus, ScopeLevel, DepartmentRole, ... |
| Queue contracts | queue names, job-payload types, microservice tokens |
Permissions live on a subpath
The CASL Action / Resource enums and PermissionScopeModule come from @app/shared/permission, not the top-level barrel. An Action import that "can't be found" is usually pointed at @app/shared.
Path aliases
Defined in tsconfig.json (and mirrored in the Vitest configs). Use them before reaching for a relative ../ chain.
"paths": {
"@app/shared": ["libs/shared/src"],
"@app/shared/*": ["libs/shared/src/*"],
"@server/*": ["apps/server/src/*"],
"@worker/*": ["apps/worker/src/*"]
}Rule of thumb: @app/shared for anything reused across apps, @server/* for paths inside the server app.
Request lifecycle
A request to the server app passes through a fixed assembly line before reaching your handler. Order is set in main.ts (middleware, pipe), app.module.ts and audit-log.module.ts (filter, interceptor) and auth.module.ts (guards).
| Stage | Job |
|---|---|
| Middleware | Plain Express, runs before Nest. tenantContextMiddleware resolves the active school into AsyncLocalStorage so BaseRepository auto-scopes by schoolId: see Multi-tenancy. |
| Guards | Five APP_GUARDs: logged in → user type → system role → CASL permission → feature flag. Short-circuit on first failure. Details → Auth & Permissions. |
| ValidationPipe | Runs the controller DTO's class-validator rules; bad input becomes a clean 400, never a crash. |
| Handler | Your controller method. The only stage you usually write. |
| AuditInterceptor | The only global interceptor: writes an audit row for handlers marked @Audit. See Auditing. |
| Request log | pino-http writes one line per request when it finishes, with the request ID and any error. See Error handling and logging. |
| Exception filter | AllExceptionsFilter formats throws into the standard error shape and records 5xx errors on the OpenTelemetry trace. Runs only on failure. |
Guard order is load-bearing
Authentication (JwtAuthGuard) runs before authorization (PermissionsGuard) and the chain stops on the first false. Don't assume a later guard ran.
Where to go next
Module Anatomy
Open one feature module and see how a controller, service, and entity fit together.
Auth & Permissions
The full rules behind the five guards and the CASL permission model.
Queues & Messaging
BullMQ jobs on Redis, RabbitMQ messages, and which app consumes each.
Several copies
Redis, collab, Pip ownership, and the replica header when more than one API process is running.
Getting Started
Get the monorepo installed and the server running on your machine.