Skip to Content
ArchitecturePersistence

Persistence

The backend keeps a small PostgreSQL database for data that has no upstream home: roles, per-user assets, social tokens, virtual tours and the CRM sync log. Everything else (listings, clients, agents, favorites, searches, estimates) lives upstream; see Data ownership for the ownership map. Short-lived state (blocklist, OTP, caches) is in Keyv, not here.

PostgreSQL is accessed through knex. The connection is part of AppConfig (config.db); src/knexfile.ts re-exports it, so migrations and the running app share one configuration. src/repository/ is the only place that holds knex queries.

Connection

SettingOriginBehaviourSource
DATABASE_URLenvUsed as connectionString when set; otherwise the individual variables applysrc/config.ts (db.connection)
DB_HOST, DB_PORT, DB_USER, DB_PASSWORD, DB_NAMEenvDefaults localhost, 5432, postgres, postgrespw, replierssrc/config.ts (db.connection)
DB_USE_SSLenvOnly the exact value true turns TLS onsrc/config.ts (db.connection.ssl)
Poolcodemin: 1, max: 5 per process; the server and the worker are separate processes with a pool eachsrc/config.ts (db.pool)
Client creationcodeOne Knex instance per process (instanceCachingFactory: every container, child containers included, gets the same one); nothing in src/ attempts a connection at startupsrc/providers/db.ts

TLS to a managed database

Managed PostgreSQL services that require TLS refuse unencrypted connections. Set DB_USE_SSL=true for those and leave it unset for a local database. How environment values and presets combine is on Configuration resolution.

What lives in the database

Local persistence

TableMigrationKeys / relationsReadersWritersCleanupSource
acl20240817170531_zero.tsPK email; role smallint (UserRole). No FKAclRepository.getUserAcl, from AuthService.generateToken (skipped when the flag is on)None in src/: rows are created outside the applicationNonesrc/repository/acl.ts, src/services/auth.ts
assets20240817183922_user_assets.tsPK (id, email, type); data jsonb. email is an application key, no FKAssetsRepository.getAssets (GET /api/user/assets/:type)createAsset insert, conflict ignored (POST /api/user/assets/:type); removeAsset delete (POST /api/user/assets/:type/remove)Explicit delete onlysrc/repository/assets.ts, src/services/user/assets.ts, src/routes/user/assets.ts
vtour20240825164157_vtour.tsPK id (the slug); owner_id bigint nullable, no FK; data jsonbVtourRepository.getOne: GET /api/vtour/:slug and the slug param handler of the PUT and DELETE routescreate (POST /api/vtour, conflict ignored), update (PUT), remove (DELETE)Explicit delete onlysrc/repository/vtour.ts, src/services/vtour.ts, src/routes/vtour.ts
social20240922132113_social.tsPK (email, type); tokens jsonb. No FKSocialRepository.getUserTokens (GET /api/user/social and /:provider, and the refresh route)createTokens upsert (callback route), updateAccessToken rewrites tokens.access_token in place (refresh route), deleteTokens delete (DELETE /api/user/social/:provider)Explicit delete onlysrc/repository/social.ts, src/services/user/social.ts, src/routes/user/social.ts
sync20250112155921_sync.tsPK id identity; last_processed_at nullablegetLatestSync and getSyncs exist but nothing calls themSyncRepository.startSync insert (POST /api/agent/boss/people); updateLastProcessedAt update (worker)Nonesrc/repository/sync.ts, src/services/agent.ts, src/services/sync.ts
people_sync20250112160526_sync_people.tsPK id identity; sync_id FK to sync(id); user_id, people_id, agent_id, client_id plain bigintPeopleSyncRepository.getById (worker people.upsert)createPeople insert in the sync transaction; update sets client_id and status (worker)Nonesrc/repository/people_sync.ts, src/services/agent.ts, src/services/sync.ts
webhooks20250202212534_webhooks.tsPK id identity; type is the event name (peopleCreated, peopleUpdated, peopleDeleted); no FKNone: only the ids returned by the insert are usedWebhooksRepository.create (POST /api/webhooks/boss/people); update sets status (worker)Nonesrc/repository/webhooks.ts, src/services/boss/webhook.ts

Every table has created_at timestamp without time zone defaulting to CURRENT_TIMESTAMP; vtour and social also have updated_at. Migrations are timestamped knex files in src/migrations/, each with a down; the directory is the fixed path ./migrations in config.db.migrations.

D08 — Entity relationships

Only one relation is declared in the schema. Dotted lines connect tables that share the same key value (the token’s email); no code joins them and the database enforces nothing. Id columns such as user_id or client_id hold Follow Up Boss or Repliers ids.

vtour and webhooks have no relation in the diagram: vtour.owner_id is the sub claim of the admin who created the tour (see Data ownership), and a webhooks row reaches its job only through the id carried in the NATS message.

Keyv vs SQL

Not every repository is SQL. BlocklistRepository (src/repository/blocklist.ts) wraps the keyv.blocklist Keyv store: create stores the revoked jti with a TTL equal to the token’s remaining lifetime, isRevoked is has, and cleanupExpired is a stub that returns true (expiry is the TTL). There is no blocklist table. Keyv stores are in memory per process unless REDIS_KEYV_ENABLE is set; see Keyv stores own their data. The other six repositories take the db Knex instance and are SQL.

Running without a database

APP_DISABLE_PERSISTENCE (app.disable_persistence) is not a universal switch. It is read in exactly two places:

ReaderEffect when trueSource
AuthService.generateTokenSkips the acl lookup: no role from acl, no per-role expiry overridesrc/services/auth.ts
db:migrate:prod scriptExits before running migrations. It reads the environment variable, not the merged preset value, so a preset and the variable can disagreepackage.json (db:migrate:prod)

No repository, route or worker handler checks the flag, and the db provider builds its Knex client either way. What each consumer does with the flag on and no reachable database, read from the code and not executed:

ConsumerTouches the databaseWith persistence off
Token issue (AuthService.generateToken)acl readSkipped by the flag, so it works; role consequences on Authentication
Logout, refresh, revocation checkNone (Keyv)Works; unaffected by the flag
/api/user/assets/...assetsNot guarded. The query rejects; the error is not an ApiError, so the global error middleware answers 500 Internal Server Error
/api/user/social/...social (the provider URL route does not query)Same 500 on every route that reads or writes tokens
/api/vtourvtourSame 500; GET, PUT and DELETE already fail in the slug param handler
POST /api/agent/boss/peoplesync, people_syncWhen Follow Up Boss returns people, fails at startSync, before any message is published; an empty result returns { synced: 0 } first. GET /api/agent/boss/people reads only Follow Up Boss and works
POST /api/webhooks/boss/peoplewebhooksThe insert rejects, no NATS message is published and the request fails
Worker people.upsert, people.create, people.update, people.deletepeople_sync, webhooksLookups and status updates reject; the handler throws

With the flag on, assets, social links, tours, the people sync and the Follow Up Boss webhooks still run their queries. No code path checks the flag outside the two readers above.

Migrations

CommandWhat it doesSource
npm run db:migrateknex migrate:latest against src/knexfile.tspackage.json
npm run db:migrate:testSame with DB_PORT=5555 and test.envpackage.json
npm run db:migrate:prodReads the raw shell variable APP_DISABLE_PERSISTENCE, not the preset value. true skips; unset or false runs db:jsts_check, then knex:prod migrate:latest against the compiled dist/knexfile.js; any other value fails the commandpackage.json
npm run knex migrate:make <name>Creates a timestamped migrationpackage.json (knex)

db:jsts_check (scripts/jsts_check.sh) compares the file counts of src/migrations and dist/migrations; when they differ and no terminal is attached it runs npm run build itself, so a release step compiles before it migrates. As a release step, any APP_DISABLE_PERSISTENCE value other than true, false or unset (for example TRUE) makes the script exit non-zero without migrating, which fails the release.

Transaction boundaries

Every repository call is a single autocommit statement except one flow. AgentService.syncBossPeople opens a transaction in SyncRepository.startSync (inserting one sync row), inserts all people_sync rows through it in PeopleSyncRepository.createPeople, commits (only the commit is written; there is no rollback path), and only then publishes one people.upsert message per row. Later status changes (people_sync.status, sync.last_processed_at) are separate statements in the worker. WebhooksRepository.create inserts all events of one webhook in one statement and the messages are published after it. A publish failure after the insert leaves rows in PENDING; nothing re-publishes them.

Gotchas

  1. The flag does not disable the database features. Only token issuing and migrations read it. Source: src/services/auth.ts (AuthService.generateToken), package.json (db:migrate:prod).
  2. Roles come only from pre-existing acl rows. Source: src/repository/acl.ts (AclRepository.getUserAcl).
  3. VtourRepository.update never sets updated_at. The column keeps its insert value. Source: src/repository/vtour.ts (VtourRepository.update).

Evidence

ClaimSource (file and symbol)
Seven tables; only people_sync.sync_id has a foreign keysrc/migrations/* (REFERENCES sync(id) in 20250112160526_sync_people.ts)
Flag read only in token issue and the migrate scriptsrc/services/auth.ts (generateToken), package.json (db:migrate:prod); no other reader of disable_persistence in src/
Blocklist is Keyv-backedsrc/repository/blocklist.ts, src/providers/keyv.blocklist.ts
Knex is created lazily; nothing checks the connectionsrc/providers/db.ts (instanceCachingFactory)
Non-ApiError failures answer 500src/app.ts (error middleware, final branch)
TLS optionsrc/config.ts (db.connection.ssl)

Verified against portal-backend 997ae3e, 2026-10-20.

Last updated on