Why this matters
Every customer business shares one PostgreSQL database with other customer businesses, while hired marketers work across several client workspaces in the same browser. One forgotten query filter could expose another shop's deals, one floating-point calculation could break a Turkish tax split by a kuruş, and one careless retry could count a conversion or apply a budget change twice. Putting the core rules inside PostgreSQL itself makes whole classes of silent mistakes impossible to ship.
In plain words
The ideas
Tables, rows, and transactions
A relational database such as PostgreSQL organizes data into named tables like strict accounting ledgers. Each horizontal line is a row describing one concrete record (one workspace, one approval request, or one conversion), and every row shares typed columns (uuid, bigint, timestamptz, text, bytea, jsonb).
Real business operations rarely touch a single row. When a new business finishes onboarding, the system creates the workspace, inserts the creator as its owner, and logs the creation in audit_log. A crash between step one and step two would leave an ownerless workspace. A transaction wraps all related statements between BEGIN and COMMIT: either every write lands together, or ROLLBACK undoes every single one.
BEGIN
1. INSERT INTO public.workspaces ...
2. INSERT INTO public.workspace_memberships (..., role = 'owner')
3. INSERT INTO public.audit_log ...
COMMIT --> all three appear together (or ROLLBACK undoes all three)This repository requires PostgreSQL 18 or newer for native time-ordered uuidv7() primary keys and strict forced row-level security. Under AGENTS.md rule 20, there is no ClickHouse, Kafka, Kubernetes, or ORM: all durable state, sessions, and job queues live in PostgreSQL and are queried with explicit parameterised SQL.
Tenants and why a WHERE clause is never enough
A tenant is one customer business whose data must stay strictly separated from every other business on the same server; here each tenant is a workspace identified by workspace_id. Relying on a WHERE clause (WHERE workspace_id = $1) on every query fails quietly the first time one new report or job forgets that filter.
A second cross-tenant trap lives in the browser. A hired marketer may keep four competing shops open in adjacent tabs. If the product stored an "active workspace" in a session cookie, switching shops in Tab 2 would redirect a click in Tab 1 into the wrong customer's account. Explicit URL tenant scoping pins every page to /w/:workspaceId/... and every API call to /v1/w/:workspaceId/..., while the cookie authenticates only the person. Any optional X-Workspace-Id header must appear once and match the URL UUID.
Row-level security, FORCE RLS, and SET LOCAL
Real tenant isolation lives inside PostgreSQL via row-level security (RLS). A policy attached to a table runs automatically on every row a query touches: USING filters reads, updates, and deletes so foreign rows disappear even without a WHERE clause, and WITH CHECK aborts inserts or updates that name another workspace.
ENABLE ROW LEVEL SECURITY alone still exempts the table's owner role. Adding FORCE ROW LEVEL SECURITY binds the table owner as well, leaving only superusers and roles with BYPASSRLS exempt.
To tell policies which workspace and actor a request belongs to, every transaction sets three variables called the tenant context: app.workspace_id, app.actor_id, and app.actor_kind. Because requests borrow shared connections from a connection pool, code must never use a session-level SET, which outlives the transaction and leaks into the next caller. Instead, SET LOCAL (SET LOCAL ROLE and set_config(name, value, true)) scopes every setting to the open transaction so PostgreSQL wipes it on COMMIT or ROLLBACK.
Request (/v1/w/ws-A/deals)
--> borrow connection from pg.Pool
--> BEGIN
--> SET LOCAL ROLE {product}_app
--> set_config('app.workspace_id' / 'app.actor_id' / 'app.actor_kind', ..., true)
--> SELECT * FROM public.crm_deals (RLS returns ws-A rows only)
--> COMMIT (context vanishes automatically)
--> return clean connection to pg.PoolIf a network error interrupts ROLLBACK, returning that broken connection would cause pool poisoning for the next request. Whenever ROLLBACK throws, the helper calls client.release(true) to destroy the socket and open a clean replacement.
Database roles, privileges, and SECURITY DEFINER
PostgreSQL enforces least privilege by splitting processes across distinct database roles:
Role group (NOLOGIN) | Login role (LOGIN) | Used by | Access to vault.* | Bound by FORCE RLS |
|---|---|---|---|---|
| Migration owner | Migration login | pnpm db:migrate | Yes (DDL owner) | Table owner (bypass only when superuser) |
{product}_app | {product}_app_login | Web API and worker | None (42501) | Yes (NOBYPASSRLS) |
{product}_vault_executor | {product}_vault_login | Vault ops and dispatch | Scoped vault tables | Yes (NOBYPASSRLS) |
The application role ({product}_app) runs with NOSUPERUSER, NOBYPASSRLS, and zero privileges on vault.* or auth.* tables. Even if an application route had a severe SQL bug, PostgreSQL blocks direct reads of encrypted tokens or session rows with error code 42501 (insufficient privilege).
When the application needs one tightly bounded action on restricted tables — validating a session hash, creating a first workspace during onboarding, or reading non-secret OAuth status labels — a SECURITY DEFINER function provides one audited doorway running with its owner's privileges. Every SECURITY DEFINER function follows three hardening rules:
- Pin search_path explicitly (
SET search_path = pg_catalog, public, pg_temp) so a temporary table cannot shadow built-in orpublicobjects. - Revoke
TEMPon the database andCREATEonpublicfromPUBLICand all runtime roles. - Run
REVOKE ALL ON FUNCTION ... FROM PUBLICand grantEXECUTEonly to the exact role that needs it.
Note
Migrations as an append-only ledger
Schema structure evolves through numbered migrations (0001, 0002, ...) applied in order. Under additive migrations (AGENTS.md rule 20), shipped migration files are never edited; every new change ships as a new file. PostgreSQL tracks applied files in the migration ledger (public.schema_migrations) with each file's normalized SHA-256 checksum, aborting immediately if a previously applied file changed on disk.
At boot, the schema guard compares public.schema_migrations (SELECT-only for {product}_app) against shipped files before accepting traffic or claiming jobs. If a production database is behind, unreadable, or unreachable, the process logs one fatal line naming pnpm db:migrate and exits. Rule 20 records one explicit owner exception (OD-22): planned migration 0015 to drop the superseded global unique constraint on approval_requests.idempotency_key.
Exact money: minor units, basis points, and honest nulls
JavaScript numbers use binary floating point (IEEE 754), where base-10 decimals cannot be stored exactly (0.1 + 0.2 === 0.30000000000000004). Across invoices, 20% KDV, 3/10 tevkifat, and 1% e-commerce withholding, floating-point drift breaks accounting equations.
AGENTS.md rule 8 therefore forbids floating point for money and rates:
| Concept | Avoid | Product rule | Example |
|---|---|---|---|
| Money amount | 12000.00 (float) | BIGINT / BigInt minor unit | 1200000 kuruş (1_200_000n) |
| Tax or fee rate | 0.045 (float) | Integer basis point (10,000 = 100%) | 450 bps (4.50%) |
| Missing COGS or 0/0 | 0 or 0.0x | Null in DB, — on screen | cogs_minor IS NULL |
Rates multiply with exact integer half-up rounding ((amount * bps + 5000n) / 10000n), while budget step limits use exact ceiling division so 20.01% rounds up to 2,001 bps and fails a 2,000-bps cap. Keeping unknown values as NULL rather than 0 stops missing product costs (cogs_minor) from inflating reported profit.
Note
Doing things exactly once: queues, leases, idempotency, and outbox
Networks drop responses and multiple workers poll simultaneously. Four PostgreSQL patterns turn retries into single effects:
- Non-blocking queue claims: workers select pending rows with FOR UPDATE SKIP LOCKED so each worker skips rows another transaction already locked and claims a disjoint batch.
- Leases and fencing tokens: workers never hold a DB lock across slow HTTP calls. Instead, the claim transaction writes a timed lease (
dispatch_lease_id,dispatch_lease_until) and commits. If the worker dies, another reclaims the row after expiry;dispatch_lease_idacts as a fencing token so a stale worker's lateUPDATEmatches zero rows and fails safely. - Idempotency keys and side tables: write APIs take a per-workspace idempotency key
(workspace_id, idempotency_key)that replays the original response (idempotent_replay: true) on identical retries and returns409 IDEMPOTENCY_KEY_REUSEDon payload mismatch. On range-partitionedtracking_events, where PostgreSQL requires the partition key (occurred_at) in every unique index, a non-partitioned side table (tracking_event_keys) holdsPRIMARY KEY (workspace_id, destination, event_name, event_id)inserted viaON CONFLICT DO NOTHING. - Transactional outbox: updating a table and calling an outside API in two steps risks silent loss or orphan events. The transactional outbox inserts the outbound feedback job (
conversion_feedback_queue) in the exact sameBEGIN ... COMMITblock as the CRM deal update so a worker dispatches it reliably after commit.
BEGIN
UPDATE public.crm_deals SET stage = 'won' WHERE id = $dealId ...
INSERT INTO public.conversion_feedback_queue (workspace_id, idempotency_key, ...)
ON CONFLICT (workspace_id, idempotency_key) DO NOTHING
COMMIT --> background worker claims and dispatches asynchronouslyState kept honest by the database
Constraints and triggers keep records valid against every caller, job, and refactor:
- A CHECK constraint validates every row on write:
marketer_grantsrejects eight banned scopes (oauth:connect,oauth:connect_or_export,oauth:export_token,crm:export_pii,billing:manage,members:manage,ads:execute_without_approval,workspace:delete), enforcesexpires_at > starts_at, and pairs with a composite foreign key(workspace_id, engagement_id)pointing toengagements(workspace_id, id). - A trigger checks cross-row rules and state transitions: on
approval_requests,BEFORE INSERT OR UPDATEtriggers keep intent immutable, reject extendingexpires_at, require active owner or admin membership to decide, and enforce legal status moves; onaudit_log,order_adjustments, and the safeguarded payment ledger, immutability triggers reject everyUPDATEandDELETE.
Note
How this repository does it
Every mechanism above maps directly to live code in this checkout:
- Tenant transactions:
tenant-tx.tsvalidatesworkspaceId,actorId, andactorKindwith Zod, executesBEGIN,SET LOCAL ROLE {product}_app, andset_config(..., true)for all three variables, and callsclient.release(true)ifROLLBACKfails. - Schema and forced RLS:
schema.sqldefines 31 base tables, 7 partition tables, and 23 forced-RLS tenant tables verified byschema-contract.ts.app_has_workspace_access(target_ws)checksapp.workspace_idplus eithersystem_worker, an activeworkspace_membershipsrow, or an active non-revokedmarketer_grantsrow tied to afundedoractiveengagement within[starts_at, expires_at). Rawcrm_contactsusesapp_has_workspace_scope(target_ws, 'crm:read_contacts')so marketers are denied PII by default. - Role bootstrap and timeouts:
init-roles.sqlcreates{product}_app_login(limit 100) and{product}_vault_login(limit 50) withNOSUPERUSER NOBYPASSRLS, setslock_timeout = '5s',statement_timeout = '30s', andidle_in_transaction_session_timeout = '30s', revokesTEMP,CREATEonpublic, andPUBLIC EXECUTEon allSECURITY DEFINERand trigger functions, and aborts if any catalog check fails. - Connection pool safety:
pool.tsredacts credentials from URIs and attaches'error'listeners to both the pool and every checked-out client so a server restart (57P01) or socket reset (ECONNRESET) never crashes Node.js. - Migrations and boot check:
migrate.tstakes advisory lock74208101, loadsschema.sqlas0001_baseline_schema.sqlplus0002through0014frompackages/db/migrations, checks constant-time SHA-256 digests inpublic.schema_migrations, and commits each pending file atomically. At boot,schema-guard.tsreadsschema_migrations(via0005_schema_migrations_app_read.sql) and refuses production start-up onbehind,unreadable, orunreachable. - Exact money and tax math:
turkish-tax.tscomputes all amounts inBigIntkuruş (1_200_000ntevkifat threshold) and integer basis points (2000,3000,100, commission tiers1000/800/600/450/300) viamulBpsHalfUp. - Queues, deduplication, outbox, and crash recovery:
0009_tracking_event_keys_and_dispatch_lease.sqlandsignals-crm-repo.tsimplementtracking_event_keys,dispatch_lease_idfencing,FOR UPDATE SKIP LOCKED, andconversion_feedback_queue. Migrations0003_approval_intent_integrity.sql,0013_real_approval_execution.sql, and0014_execution_progress_and_recovery.sqllock approval intent, guardexecution_write_started_at, and providerecover_stuck_approval_executions(FOR UPDATE SKIP LOCKED).
Not built yet
What went wrong once
Migrations that only ran inside tests
Until Wave 45, the migration runner existed in packages/db, yet no command or start-up path ran it outside tests (finding P-9 in INDEPENDENT-REVIEW-2026-12-02.md). Wave 45 added pnpm db:migrate, pnpm db:status, pnpm db:verify, and schema-guard.ts, then discovered {product}_app lacked read permission on public.schema_migrations. Migration 0005_schema_migrations_app_read.sql granted SELECT only so the API can verify its schema without ever editing the ledger.
A global idempotency key that leaked across tenants
approval_requests.idempotency_key was unique across the entire table rather than per workspace (finding A-5). One workspace submitting a key already used by another got a collision revealing that another tenant held that key, while normal retries got 409 instead of replaying the original result. Wave 48 (0013_real_approval_execution.sql) added the per-workspace unique index and idempotent_replay: true, reported A-5 as partly closed rather than quietly breaking AGENTS.md rule 20, and escalated to the owners, who recorded OD-22 in OWNER-DECISIONS.md authorizing planned migration 0015.
Warning
Concurrent queries on one connection and an unhandled pool crash
Wave 45 caught two connection bugs. First, an API handler ran Promise.all over two queries on one checked-out transaction client; because one PostgreSQL connection runs one statement at a time, queries inside withTenantTransaction must be awaited sequentially. Second, restarting PostgreSQL (57P01) emitted an unhandled 'error' event on pg.Pool and crashed Node.js (finding P-12). Adding pool and client 'error' listeners in pool.ts (tested in pool-connection-errors.test.ts) lets the API survive database restarts cleanly.
Schema realities in event ingestion and PostgreSQL 17 slipping past tests
In Wave 47, building 0009_tracking_event_keys_and_dispatch_lease.sql required three documented deviations from the brief: adding event_name so Purchase never collides with InitiateCheckout, using lease columns on queued rows instead of altering a baseline CHECK, and adding non-partitioned tracking_event_keys because PostgreSQL requires the partition key in every unique index on a partitioned table. In Wave 48, 181 copy-pasted test database finders (14 of which accepted PostgreSQL 17, finding V-4) were collapsed into one shared helper (pg-local.mjs) that checks the server version and requires 18+.
Try it yourself
These read-only checks inspect repository files without touching any running server, database port, or external API.
Step 1: Count forced-RLS tables in the baseline schema
Run this read-only Node check from the repository root against schema.sql:
node -e "const fs=require('fs'),s=fs.readFileSync('docs/schema.sql','utf8');console.log({base:[...s.matchAll(/^CREATE TABLE\s+\S+\s*\(/gm)].length,partitions:[...s.matchAll(/^CREATE TABLE\s+\S+\s+PARTITION OF/gm)].length,enableRls:[...s.matchAll(/ENABLE ROW LEVEL SECURITY/g)].length,forceRls:[...s.matchAll(/FORCE ROW LEVEL SECURITY/g)].length});"You should see 31 base tables, 7 partition tables, 23 ENABLE ROW LEVEL SECURITY, and 23 FORCE ROW LEVEL SECURITY.
Step 2: Trace transaction-local context and pool safety
Open tenant-tx.ts and verify that withTenantTransaction runs SET LOCAL ROLE {product}_app, passes true as the third argument to set_config for all three context variables, and calls client.release(true) when ROLLBACK throws.
Step 3: Compare floating point with exact BigInt kuruş math
Run this pure Node snippet (no database needed) to observe why AGENTS.md rule 8 bans floating point for money:
node -e "console.log('float 0.1 + 0.2 === 0.3:', 0.1 + 0.2 === 0.3, 'raw:', 0.1 + 0.2); const minor = 1200000n, vatBps = 2000n, tevkifatBps = 3000n; const vat = (minor * vatBps + 5000n) / 10000n; const tevkifat = (vat * tevkifatBps + 5000n) / 10000n; console.log({ minor, vat, tevkifat, payableVat: vat - tevkifat });"0.1 + 0.2 === 0.3 prints false, while BigInt yields exact kuruş (1200000n, 240000n, 72000n, 168000n).
Step 4: Inspect migrations and the boot schema guard
List packages/db/migrations (0001 through 0014; 0015 is not created yet) and read decideSchemaGuard in schema-guard.ts to confirm production returns proceed: false on behind, unreadable, and unreachable.
Note
Check yourself
0 / 6Why does every tenant table declare FORCE ROW LEVEL SECURITY in addition to ENABLE ROW LEVEL SECURITY?
Why must withTenantTransaction use set_config('app.workspace_id', $1, true) instead of a plain session-level SET?
What happens if a buggy API route running as {product}_app_login executes SELECT * FROM vault.oauth_connections?
Why did migration 0009 place the canonical event deduplication key on tracking_event_keys instead of directly on tracking_events?
Why is an unknown product cost (cogs_minor) stored as NULL and displayed as — instead of 0?
A dispatch worker claims a queued event with a 300-second lease, stalls for 400 seconds while another worker reclaims it, and then tries to mark it sent. What stops it from overwriting the newer worker's state?
Words to know
34Go deeper
- Contracts and decisions:
AGENTS.md(rules 6, 7, 8, 10, 13, 20),ADR-0004,OWNER-DECISIONS.md(OD-22), andINDEPENDENT-REVIEW-2026-12-02.md(findings A-5, P-7, P-9, P-12, S-6, V-4). - Database source:
schema.sql,init-roles.sql,tenant-tx.ts,pool.ts,migrate.ts, andschema-guard.ts. - Archived lessons absorbed here:
archived lesson 01 on multi-tenant RLS and fencingandarchived lesson 15 on distributed state machines, idempotency, and outbox. - Official PostgreSQL docs: Row Security Policies, Explicit Locking, Table Partitioning, and Writing SECURITY DEFINER Functions Safely.