Skip to Content
Workspace

Database design

One Postgres database with a schema and a login role per module, forward-only migrations, ids and codes, and the core tables of the work schema.

Workspace stores everything in one Postgres 16 database, workspace, with one schema per module. Each module connects as its own login role that can reach only its own schema. There are no foreign keys between schemas, no workspace column and no row-level security (ADR-0015, ADR-0023).

Module handlerone transactionRows + outbox rowCOMMIT, then NOTIFYOutbox relayclaims, SKIP LOCKEDEvent busin processConsumersper groupdead_eventsafter 5 triesfailsdlq replayPostgreSQL · one database · schema and login role workspace_<module> per moduleidentityplatformchatworkhomeemployeeaisearchwebA module's role can use only its own schema; cross-module data goes through APIs or events.search is a rebuildable projection (reindex); the outbox is the replay copy, kept 3 days.No workspace column anywhere: one installation is one company (ADR-0023).12 consumer groups: home projector, search indexer, platform webhooks and audit, employee, chat, work, ai.At least once, idempotent through processed_events; no ordering across topics.as the module's role
Every module writes its own schema; events carry changes between them.

Schemas

SchemaModuleMain aggregates
identityidentitymembers, roles and grants, teams, AI agents, API keys, sign-in events, audit
platformplatformthe workspace row and its config, master data, webhooks, the audit trail
workworkprojects and boards, tasks, docs and spaces, drive, whiteboards, calendar and meetings, approvals, goals, agent workflows
chatchatchannels, messages (threads, reactions, pins), attachments, polls, scheduled messages, co-editing drafts
employeeemployeeemployees and departments, attendance, leave, holidays, announcements
homehomeper-person read model ("Needs you", activity), notifications, push, reminders, preferences
aiaiusage, costs and budgets, AI conversations, content views, policy, connections
searchsearcha rebuildable copy of searchable rows (full-text, typo correction)
webthe web appserver-side sessions, keyed by a hash of the cookie

Every table of every schema is documented in docs/database, one page per schema.

Roles

RoleCan log inUsed for
workspace_owneryesOwns every schema; runs migrations, each relay's LISTEN and the job locks. Never used for requests
workspace_<m>_rwnoEverything module <m> may do: USAGE on its schema and the grants in its baseline
workspace_<m>yesWhat the server connects as for module <m> (WORK_DATABASE_URL…), member of <m>_rw only, search_path = <m>, public
workspace_search_readernoLets chat's search endpoint read the search schema: the one deliberate exception
workspace_maintenancenoOwns the narrow SECURITY DEFINER functions (prune, claim the outbox) that do what a module role may not

Because unqualified names resolve in the module's own schema, never schema-qualify your own module's objects, and never reach for another module's: its role cannot, by design.

One workspace, and the singleton key

An installation holds exactly one company, so keys are the entity's own (PRIMARY KEY (id), UNIQUE (code)). Settings that exist once (the workspace config, each module's workspace_settings projection, ai_policy…) use a key that allows one row at most:

singleton boolean NOT NULL DEFAULT true CHECK (singleton) PRIMARY KEY
-- writes: INSERT … ON CONFLICT (singleton) DO UPDATE …

Ids, codes and time

  • Ids are ULIDs stored as text (newId() in @workspace/shared): unique, sortable by creation time.
  • Codes people read (T-041, P-003, D-012) are never primary keys. They come from transactional counters (work.code_counters) with formats from the workspace config. Links use the code (/app/work/tasks/T-041); the id opens the same page.
  • Time is timestamptz everywhere, named *_at; calendar-day facts use date. "Today" is computed in the workspace's time zone, projected into each module's workspace_settings.
  • Status enums are text with a CHECK, never Postgres enum types, so widening one is a plain migration.

The work schema

The largest schema, and the one most features touch.

projectsid PK · code UNIQUEname · status · due_atowner_id · team_id (by value)board_columnsid PK · project_id FKstatus · position · wip_limitdocumentsid PK · code UNIQUEproject_id · visibilitycurrent_versiondocument_versionsdocument_id FK · versioncontent · format · author_idtasksid PK · code UNIQUE (T-041)project_id FK · column_id · rankstatus · priority · due_atassignee_id · owner_id (by value)parent_id · custom_fields jsonbworkflow_id FKtask_dependenciespredecessor_id → successor_idtask_comments · activitytask_id FK · author_idhistory, pruned by retentionagent_workflowsid PK · name · categoryrunner: server | localsteps jsonb · templatetask_agent_runsid PK · task_id FK CASCADEstatus · current_stepsteps jsonb (a copy)started_by · claimed_bytask_agent_run_questionsrun_id · step_index · roundquestions · answers jsonbUNIQUE (run, step, round)1 : n1 : n1 : nn : n1 : nname copied1 : nworkflow_id1 : nNo foreign keys leave the schema: user, department and channel ids are references by value to other modules.
The core of the work schema. Foreign keys stay inside it; people are referenced by id.
TableWhat to know
tasksstatus is todo · in_progress · review · done · cancelled; rank is a lexicographic order within a column; column_id is kept in step with the project by the trigger tasks_column_sync; source jsonb records where a task came from (a chat message, a meeting); version for optimistic updates
board_columnsA project's columns, each mapped to a status, with an optional WIP limit. Moving a card changes its status
task_dependenciespredecessor_id → successor_id, never the same task
documents, document_versionsVersioned pages; visibility private · project · workspace · space
agent_workflowsA workflow: ordered steps (jsonb), runner server or local, an optional template key
task_agent_runsOne run on a task; steps is a copy made at start, so editing a workflow never rewrites history
task_agent_run_questionsThe questions an AI step asked and the answers, one row per (run, step, round)

The other schemas follow the same patterns. Two worth knowing early: ai.ai_usage records every model call with the work it served (a task, a document), and ai.ai_content_views logs every time someone opens a recorded conversation, which the person can see.

Migrations

migrate(ownerUrl, dir, schema) (backend/packages/service-kit/src/migrate.ts) connects as workspace_owner, sets the module's search_path, and applies every *.sql file in backend/server/migrations/<module>/ not yet in <schema>.schema_migrations, sorted by name, each in its own transaction. It runs when a module starts and when you run pnpm migrate.

Each schema starts from 001_baseline.sql. New changes are new files:

-- backend/server/migrations/work/020_task_estimate.sql (an example, not in the repository)
ALTER TABLE tasks ADD COLUMN IF NOT EXISTS estimate_hours numeric(6,2);
ALTER TABLE tasks DROP CONSTRAINT IF EXISTS tasks_estimate_check;
ALTER TABLE tasks ADD CONSTRAINT tasks_estimate_check CHECK (estimate_hours IS NULL OR estimate_hours >= 0);
  • NNN_short_name.sql, three digits, after the highest number in that folder.
  • Forward-only: there are no down migrations. Never edit a file that has been applied.
  • Idempotent where possible: IF NOT EXISTS, CREATE OR REPLACE, drop a CHECK before re-adding a wider one.
  • New tables get their grants from the default privileges set at the end of the baseline; narrow them with REVOKE when the role must not update or delete.
  • Backfills are plain UPDATE or INSERT … SELECT in the same file.

Transactions and request context

  1. The principal middleware runs every request inside runWithContext({ actorId, requestId }, fn) (AsyncLocalStorage); audit rows and log lines read it.
  2. Writes that belong together run in withTransaction(pool, fn): BEGIN, your function, COMMIT or ROLLBACK. Business rows and their outbox event commit together or not at all.
  3. No session state may outlive a transaction (the optional PgBouncer runs in transaction mode), so nothing is SET outside one.

Connections

The server opens one small pool per module role (work and chat 15, the others 10), about 95 connections in all, plus one LISTEN connection per relay. Postgres runs with max_connections=200; PgBouncer is an optional profile for a shared or managed database.

On this page