Skip to Content
ArchitectureData Ownership

Data ownership

Which system holds each record, which identifier names it, how one identifier turns into another, and what happens when the match is missing. The backend keeps very little state of its own: almost every primary record lives upstream, a few small tables live in PostgreSQL, and short-lived state lives in Keyv stores. Terms are defined in the Glossary; the tables of the local database are on Persistence, the cache namespaces on Caching.

Ownership map

Solid arrows are declared relations. Dashed arrows are joins made in application code: the two columns hold the same value, but nothing in a database enforces it.

Identity and ownership

One row per identifier. Scope says where the value is meaningful. Conversion is how the backend gets from one identifier to the next. Missing match is what happens when the lookup finds nothing.

Identifier / entityScopeConversionOwner / storeReaders / writersMissing-match behaviour
clientId (client record)Repliers account of the deploymentFrom an email or phone: RepliersClients.filter with operator OR. From a token: sub. From a CRM person: externalIdRepliers clientsCreated by signup, OAuth first sign-in, agent create-client and the CRM sync/webhook workers (RepliersClients.create); read by UserService.infoOTP login with no match: 404 User not found. OAuth with no client and no agent: a client is created
JWT subOne tokenSet by AuthService.useOtp, useRepliersToken, OAuthService (client: clientId; agent: agentId); embedLogin sets noneThe token itself (RS256, not stored)Issued by AuthService.generateToken; read by every route as ctx.state["user"].subAbsent on the embed token: routes that need it receive undefined. Absent for guests: maybeClientId returns undefined
jtiOne tokenRandom UUID per issueKeyv namespace blocklist (BlocklistRepository), only after logout or refreshWritten by logout, refresh; read by isRevoked in the JWT middleware on every strict or passthrough requestA token without jti is revoked; an unknown jti is valid
Client emailRepliers client; ACL, assets and social rowsctx.state["user"].email (token claim)Repliers clients.email; copied into the tokenKeys acl, assets and social rows (see below)No row: acl falls back to the token’s role, then User; assets and social return empty
agentIdRepliers accountClient record field agentId; OAuth agent sub; config.repliers.clients.defaultAgentIdRepliers agentsUserService.agent, RepliersAgents.get/filter, AgentService.checkClientGuest or no client: the default agent
FUB person idFollow Up Boss accountStored as the Repliers client externalId; webhook and sync match with externalId and email or phone, ORFollow Up Boss peopleRead by BossService.getPeople; copied into people_sync.people_id and webhooks.payloadWebhook or sync: no client found, a client is created. Delete webhook: no client found, error stored in webhooks.status and the job fails. Events: falls back to a FUB lookup by email, then fails silently (detached)
FUB user idFollow Up Boss accountStored as the Repliers agent externalId; sent as assignedUserIdFollow Up Boss usersBossService.getUsers (OAuth agent login, claim external.fub_id); RepliersAgents.filter({ externalId }) in the webhook workerWebhook: the default agent. Contact: assignedTo carries the agent’s name instead. Events: the FUB user is looked up by the agent’s name, and no assignment is sent when none matches
externalIdRepliers client or agentSame value as the two rows above, as a string in filters and a number in the create DTORepliersWritten by SyncService.processUpsert, BossWebhooksService.processPeopleUpsert; read by EventsCollectionService, routes/user/boss.ts, the agent estimate-sent noteTag route: 404 User not found. Estimate-sent note: falls back to email, returns quietly with neither
mlsNumberOne boardPrefix added to requests and stripped from responses when settings.mlsNumberPrefix is set (src/services/listings/mlsNumberPrefix.ts)Repliers listings (upstream form)Listings, favorites, autosuggest and the featured-listings paths of src/services/repliers/Prefix unset: values pass unchanged
boardIdRepliersRequest array defaults to settings.defaults.boardId; event collection falls back to its own default boardRepliers listingsValidators in src/validate/listings.ts, the scrubber gate (scrubbing.board_ids), event collectionMissing in the request: the preset or environment default
addressKeyRepliersPassed through, not computedRepliers buildings and listingsBuildingsService.single, listings filterThe upstream answers; nothing is derived locally
estimateIdRepliersOwnership: a user must equal estimate.clientId, an agent must equal the agentId of that client (EstimateService.checkOwnership)Repliers estimatesroutes/estimate.ts, routes/agent.tsA guest estimate has no clientId: the ownership check fails for every caller
searchIdRepliersSearchesService.delete looks the id up in the caller’s searches firstRepliers saved searchesroutes/searches.tsNot in the list: 400 You are not owner of that searchId
favoriteIdRepliersFavoritesService.delete looks the id up in the caller’s unfiltered favorites firstRepliers favoritesroutes/favorites.tsNot in the list: 400 You are not owner of that favoriteId
Featured listings slugOne deploymentsettings.featuredListings maps a slug to the clientId whose favorites are publishedPreset or SETTINGS_FEATURED_LISTINGS plus Repliers favoritesFavoritesService.featuredListings; cache cleared by add / delete of that clientUnknown slug: 404 Featured listing not found
OTP code and cooldownOne deploymentCode to { clientId }; key otp_sent_<clientId> holds the send timeKeyv namespace otpWritten by AuthService.sendOtp; read and deleted by useOtpUnknown or used code: 403; resend inside the cooldown: 403 with Retry-After
acl.emailLocal databaseMatched by exact email in AclRepository.getUserAclPostgreSQL aclRead when a token is issued; no code in the repository inserts rowsNo row: role from the token claim, then User
assets key (id, email, type)Local databaseEmail from the tokenPostgreSQL assetsAssetsRepository; insert ignores duplicatesDuplicate id: 409; none: empty list
social key (email, type)Local databaseEmail from the tokenPostgreSQL socialSocialRepository (provider tokens, upsert on the key)None: no provider tokens returned
vtour.id and owner_idLocal databaseowner_id is the sub of the admin who created the tourPostgreSQL vtourVtourRepositoryUnknown slug: 404 (ctx.assert(vtour, 404) in the vtour param handler)
sync.id, people_sync.id, webhooks.idLocal databasepeople_sync.sync_id has a foreign key to sync.id; the rest are application joinsPostgreSQLSyncRepository, PeopleSyncRepository, WebhooksRepository; status text is written by the workerFailed jobs keep the error text in status

Reading the register

  • sub is not a type. The same claim is a clientId for clients and an agentId for OAuth agents. Code that needs a client id from an agent token must take it from the route (/agent/client/:clientId), not from sub; agent routes can borrow an agent id from a signed client link (?s=), see Authentication.
  • Matching a CRM person is by externalId first, then by email or phone. The sync worker matches externalId, email and phone together with OR; the webhook worker matches externalId together with the email (or the phone when there is no email).
  • Email is the key of local per-user data, not clientId. Changing the email of a Repliers client therefore detaches its acl, assets and social rows.

Where each kind of state lives

StateStoreSurvives a restartShared across processes
Clients, agents, favorites, saved searches, estimates, messages, listingsRepliers (upstream)YesYes
People and usersFollow Up BossYesYes
Roles, assets, tours, social tokens, sync jobs, webhook logPostgreSQLYesYes
OTP codes and cooldown, token blocklist, result cachesKeyvOnly with REDIS_KEYV_ENABLE=trueOnly with REDIS_KEYV_ENABLE=true
SessionThe JWT in the browserUntil expNot stored

Keyv stores own their data

A repository class name does not imply SQL. BlocklistRepository is a repository over the Keyv store keyv.blocklist, and the OTP state is held by AuthService directly on keyv.otp; neither touches PostgreSQL.

StoreProviderKeyValueLifetimeCleanup
otpsrc/providers/keyv.otp.tsThe one-time code{ clientId }AUTH_OTP_TTL_MS (default 10 min); deleted on useExpiry
otp (cooldown)sameotp_sent_<clientId>send time in msAUTH_OTP_RESEND_TTL_MS (default 1 min)Expiry
blocklistsrc/providers/keyv.blocklist.tsjtithe token’s expThe token’s remaining lifetimeExpiry; cleanupExpired does nothing
Result cachesCacheFactory in src/lib/decorators/cached.tsJSON.stringify of the method arguments{ data, created }Per-namespace TTL from the environmentExpiry; only the featured-listings namespace is also cleared by code

The result-cache namespaces, their keys and TTLs are in the Cache state register. Each namespace has its own Keyv instance created once per process. Without REDIS_KEYV_ENABLE=true every instance is in memory: an OTP issued by one process is unknown to another, a revoked token is revoked only where it was revoked, and everything disappears on restart.

Persistence off

APP_DISABLE_PERSISTENCE=true is read in exactly two places: AuthService.generateToken (src/services/auth.ts) skips its whole ACL block, so no role is resolved and no role-based lifetime applies: OTP, email-token and OAuth-client tokens carry no role claim, and only the embed and OAuth-agent flows, which set Agent themselves, issue one. The db:migrate:prod script skips migrations. No repository checks the flag and the db provider builds its Knex client either way, so the other database-backed features (assets, social tokens, tours, CRM sync, webhook log) still query the database. Per-flow consequences: Authentication — Variation.

Gotchas

  1. sub changes meaning with the token. Source: src/services/auth.ts (AuthService.useOtp, AuthService.embedLogin), src/services/oauth.ts (OAuthService.agentLogin).
  2. A role in the acl table beats the role the login flow chose. Source: src/services/auth.ts (AuthService.generateToken, acl?.role || payload["role"]).
  3. Local per-user rows are keyed by email. Source: src/repository/assets.ts (AssetsRepository), src/repository/social.ts (SocialRepository), src/repository/acl.ts (AclRepository).
  4. A token without jti is rejected as revoked. Source: src/providers/middleware/jwt/config.ts (middleware.jwt.config, isRevoked).
  5. Blocklist and OTP state are per process unless Redis-backed Keyv is enabled. Source: src/providers/keyv.blocklist.ts (keyv.blocklist), src/providers/keyv.otp.ts (keyv.otp).
  6. Ownership of favorites and searches is checked by reading the caller’s list. The check looks for the id in the list the service reads for the caller before it calls the delete. Source: src/services/searches.ts (SearchesService.getAll, SearchesService.delete), src/services/favorites.ts (FavoritesService.delete).
  7. Guest estimates belong to nobody. Source: src/services/estimate.ts (EstimateService.checkOwnership).
  8. externalId is typed differently on each side. Number in RplClientsCreateDto, string in RplClientsFilterDto and in the client record. Source: src/services/repliers/clients.ts (RplClientsCreateDto, RplClientsFilterDto).

Evidence

ClaimSource (file and symbol)
Client, agent, favorite, search and estimate CRUD all go to Replierssrc/services/repliers/{clients,agents,favorites,searches,estimate}.ts (RepliersBase.request)
Seven local tables, one foreign keysrc/migrations/* (people_sync.sync_id references sync(id))
Blocklist and OTP on Keyvsrc/repository/blocklist.ts, src/providers/keyv.blocklist.ts, src/providers/keyv.otp.ts
Role precedence and persistence flagAuthService.generateToken in src/services/auth.ts
externalId linksSyncService.processUpsert, BossWebhooksService.processPeopleUpsert, EventsCollectionService.getPersonId
Prefix codecsrc/services/listings/mlsNumberPrefix.ts
Not established by this checkoutThe uniqueness of externalId, and whether Repliers enforces ownership on its side

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

Last updated on