GetClaps
Ücretsiz DenetimFiyatlandırmaSözlükAkademi
  1. Ana sayfa
  2. /Akademi
  3. /L03 · Data: PostgreSQL, tenants, exact money, and doing things exactly once

Ana sayfa / Akademi / L03 · Data: PostgreSQL, tenants, exact money, and doing things exactly once

L03Bölüm A · TemellerTemelKod doğrulama tarihi: 2026-12-04

Data: PostgreSQL, tenants, exact money, and doing things exactly once

How PostgreSQL keeps every customer workspace apart, stores money to the exact kuruş, evolves through append-only migrations, and guarantees each job runs once.

18 dk·3572 kelime·6 soru·34 terim·docs/lessons/03-data.md
Ön koşul:L01 · The big picture: what we are building and how the pieces fit
Tüm derslere dön
●

Ders içerikleri İngilizce yayınlanır (OD-23)

Sayfa çerçevesi Türkçe ve İngilizce olarak sunulur. Teknik ders metinleri, kod örnekleri ve kendini sına soruları doğrudan ortak kaynak dosyalarından İngilizce okunur; hukuk ve ürün terimlerinde Türkçe karşılıklar yer alır.

0%
▲Yanıtlanan sorular
0 / 6
—
○Doğruluk oranı
Henüz yanıt yok

Bu dersteki bölümler

  1. 1.Why this matters
  2. 2.The ideas
  3. 3.How this repository does it
  4. 4.What went wrong once
  5. 5.Try it yourself
  6. 6.Check yourself
  7. 7.Words to know
  8. 8.Go deeper

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

treat the database as the final referee, not a passive filing cabinet. Even when application code has a bug, PostgreSQL still enforces whose rows you may see, how money adds up, and which state transitions are legal.

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.

text
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.

text
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.Pool

If 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 byAccess to vault.*Bound by FORCE RLS
Migration ownerMigration loginpnpm db:migrateYes (DDL owner)Table owner (bypass only when superuser)
{product}_app{product}_app_loginWeb API and workerNone (42501)Yes (NOBYPASSRLS)
{product}_vault_executor{product}_vault_loginVault ops and dispatchScoped vault tablesYes (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:

  1. Pin search_path explicitly (SET search_path = pg_catalog, public, pg_temp) so a temporary table cannot shadow built-in or public objects.
  2. Revoke TEMP on the database and CREATE on public from PUBLIC and all runtime roles.
  3. Run REVOKE ALL ON FUNCTION ... FROM PUBLIC and grant EXECUTE only to the exact role that needs it.
○

Note

how the vault encrypts tokens at rest (AES-256-GCM, DEKs, and AAD binding) belongs to Lesson 05. Here we focus on why the app role cannot reach vault.* tables at all.

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:

ConceptAvoidProduct ruleExample
Money amount12000.00 (float)BIGINT / BigInt minor unit1200000 kuruş (1_200_000n)
Tax or fee rate0.045 (float)Integer basis point (10,000 = 100%)450 bps (4.50%)
Missing COGS or 0/00 or 0.0xNull in DB, — on screencogs_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

KPI formulas such as ROAS, contribution margin, and Event Match Quality belong to Lesson 07.

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_id acts as a fencing token so a stale worker's late UPDATE matches 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 returns 409 IDEMPOTENCY_KEY_REUSED on payload mismatch. On range-partitioned tracking_events, where PostgreSQL requires the partition key (occurred_at) in every unique index, a non-partitioned side table (tracking_event_keys) holds PRIMARY KEY (workspace_id, destination, event_name, event_id) inserted via ON 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 same BEGIN ... COMMIT block as the CRM deal update so a worker dispatches it reliably after commit.
text
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 asynchronously

State 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_grants rejects 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), enforces expires_at > starts_at, and pairs with a composite foreign key (workspace_id, engagement_id) pointing to engagements(workspace_id, id).
  • A trigger checks cross-row rules and state transitions: on approval_requests, BEFORE INSERT OR UPDATE triggers keep intent immutable, reject extending expires_at, require active owner or admin membership to decide, and enforce legal status moves; on audit_log, order_adjustments, and the safeguarded payment ledger, immutability triggers reject every UPDATE and DELETE.
○

Note

the full business meaning of Propose -> Approve -> Execute and its human guardrails belongs to Lesson 08.

How this repository does it

Every mechanism above maps directly to live code in this checkout:

  • Tenant transactions: tenant-tx.ts validates workspaceId, actorId, and actorKind with Zod, executes BEGIN, SET LOCAL ROLE {product}_app, and set_config(..., true) for all three variables, and calls client.release(true) if ROLLBACK fails.
  • Schema and forced RLS: schema.sql defines 31 base tables, 7 partition tables, and 23 forced-RLS tenant tables verified by schema-contract.ts. app_has_workspace_access(target_ws) checks app.workspace_id plus either system_worker, an active workspace_memberships row, or an active non-revoked marketer_grants row tied to a funded or active engagement within [starts_at, expires_at). Raw crm_contacts uses app_has_workspace_scope(target_ws, 'crm:read_contacts') so marketers are denied PII by default.
  • Role bootstrap and timeouts: init-roles.sql creates {product}_app_login (limit 100) and {product}_vault_login (limit 50) with NOSUPERUSER NOBYPASSRLS, sets lock_timeout = '5s', statement_timeout = '30s', and idle_in_transaction_session_timeout = '30s', revokes TEMP, CREATE on public, and PUBLIC EXECUTE on all SECURITY DEFINER and trigger functions, and aborts if any catalog check fails.
  • Connection pool safety: pool.ts redacts 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.ts takes advisory lock 74208101, loads schema.sql as 0001_baseline_schema.sql plus 0002 through 0014 from packages/db/migrations, checks constant-time SHA-256 digests in public.schema_migrations, and commits each pending file atomically. At boot, schema-guard.ts reads schema_migrations (via 0005_schema_migrations_app_read.sql) and refuses production start-up on behind, unreadable, or unreachable.
  • Exact money and tax math: turkish-tax.ts computes all amounts in BigInt kuruş (1_200_000n tevkifat threshold) and integer basis points (2000, 3000, 100, commission tiers 1000/800/600/450/300) via mulBpsHalfUp.
  • Queues, deduplication, outbox, and crash recovery: 0009_tracking_event_keys_and_dispatch_lease.sql and signals-crm-repo.ts implement tracking_event_keys, dispatch_lease_id fencing, FOR UPDATE SKIP LOCKED, and conversion_feedback_queue. Migrations 0003_approval_intent_integrity.sql, 0013_real_approval_execution.sql, and 0014_execution_progress_and_recovery.sql lock approval intent, guard execution_write_started_at, and provide recover_stuck_approval_executions (FOR UPDATE SKIP LOCKED).
◆

Not built yet

three items remain open on this branch as of 2026-12-04. First, OD-22 approved dropping the legacy global unique constraint on approval_requests.idempotency_key in planned migration 0015 (AGENTS.md rule 20), but 0015 has not been created yet (packages/db/migrations/ ends at 0014), so the global constraint still sits beside the per-workspace index from 0013. Second, role-aware RLS across all tables beyond the approval triggers (finding P-7) is not built yet; member role distinctions mostly live in application code. Third, nothing is deployed to production or serving live customer databases yet (OD-04, OD-05).

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

a unique constraint missing workspace_id leaks existence facts across tenants even when FORCE ROW LEVEL SECURITY hides every row from SELECT.

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:

bash
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:

bash
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

when running live PostgreSQL tests later, set PG_BIN_DIR if needed and always use the isolated helpers rather than port 5432 or a running development cluster.

Check yourself

0 / 6

Q1.Why does every tenant table declare FORCE ROW LEVEL SECURITY in addition to ENABLE ROW LEVEL SECURITY?

Q2.Why must withTenantTransaction use set_config('app.workspace_id', $1, true) instead of a plain session-level SET?

Q3.What happens if a buggy API route running as {product}_app_login executes SELECT * FROM vault.oauth_connections?

Q4.Why did migration 0009 place the canonical event deduplication key on tracking_event_keys instead of directly on tracking_events?

Q5.Why is an unknown product cost (cogs_minor) stored as NULL and displayed as — instead of 0?

Q6.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

34
additive migration

A rule that each new database migration only adds changes and never edits an already shipped migration file.

Veri ve PostgreSQLSözlükte incele
application roleTR: uygulama rolü

The low-privilege database identity used by the running API and worker, bound by row-level security and barred from the vault.

Veri ve PostgreSQLSözlükte incele
basis pointbpsTR: baz puan

One hundredth of one percent, used to store tax, fee, and guardrail rates as exact whole numbers.

Veri ve PostgreSQLSözlükte incele
BYPASSRLS

A PostgreSQL role attribute that lets a role skip every row-level security policy on every table.

Veri ve PostgreSQLSözlükte incele
CHECK constraintTR: CHECK kısıtı

A rule attached to a database table that every inserted or updated row must satisfy, or PostgreSQL rejects the write with code 23514.

Veri ve PostgreSQLSözlükte incele
connection poolTR: bağlantı havuzu

A reusable set of open PostgreSQL connections lent to one request at a time instead of reconnecting on every query.

Veri ve PostgreSQLSözlükte incele
migration (database)

A numbered SQL file that applies one ordered, repeatable structural change to the database.

Veri ve PostgreSQLSözlükte incele
role (database)TR: veritabanı rolü

A named identity inside PostgreSQL that owns objects, holds privileges, and may or may not log in.

Veri ve PostgreSQLSözlükte incele
rowTR: satır

One individual record stored in a database table, holding one value (or null) for each column.

Veri ve PostgreSQLSözlükte incele
table (database)TR: tablo

A named collection of structured rows sharing the same columns, constraints, and security policies.

Veri ve PostgreSQLSözlükte incele
transaction (database)TR: işlem

A group of SQL statements bracketed by BEGIN and COMMIT that either all succeed together or all undo on ROLLBACK.

Veri ve PostgreSQLSözlükte incele
trigger (database)TR: tetikleyici

Database code that PostgreSQL runs automatically before or after a row is inserted, updated, or deleted.

Veri ve PostgreSQLSözlükte incele
explicit URL tenant scoping

Carrying the workspace identifier explicitly in every workspace URL path rather than storing an active workspace in a cookie.

Veri ve PostgreSQLSözlükte incele
fencing token

A fresh identifier issued with each job claim that a worker must still match when writing back its outcome.

Veri ve PostgreSQLSözlükte incele
floating pointTR: kayan nokta

The binary number format (IEEE 754) used by JavaScript number, which cannot represent most decimal fractions exactly.

Veri ve PostgreSQLSözlükte incele
FOR UPDATE SKIP LOCKED

A PostgreSQL SELECT clause that locks candidate queue rows and skips any row another worker already locked.

Veri ve PostgreSQLSözlükte incele
FORCE ROW LEVEL SECURITYFORCE RLS

A PostgreSQL table option that makes row-level security apply even to the role that owns the table.

Veri ve PostgreSQLSözlükte incele
idempotency key

A caller-supplied token attached to a write request so the server recognizes retries of the same intent.

Veri ve PostgreSQLSözlükte incele
lease

A time-bounded claim on a queued row that automatically becomes reclaimable if the worker crashes.

Veri ve PostgreSQLSözlükte incele
migration ledger

The public.schema_migrations table recording every applied migration's version, filename, SHA-256 digest, and timestamp.

Veri ve PostgreSQLSözlükte incele
minor unit

The smallest indivisible unit of a currency, such as kuruş or cents, stored as an exact integer.

Veri ve PostgreSQLSözlükte incele
null

The explicit marker for a missing or unknown value in SQL and JSON, always displayed as — and never replaced with zero.

Veri ve PostgreSQLSözlükte incele
pool poisoning

Returning a broken or dirty database connection to a connection pool so the next request inherits leftover state or a failed transaction.

Veri ve PostgreSQLSözlükte incele
PostgreSQLPG

The open-source relational database engine (version 18 or newer) that stores all durable product state.

Veri ve PostgreSQLSözlükte incele
row-level securityRLSTR: satır düzeyi güvenlik

A PostgreSQL policy attached to a table that evaluates every read and write row by row to decide what the caller may see or change.

Veri ve PostgreSQLSözlükte incele
schema guard

A start-up check comparing public.schema_migrations against shipped migration files so production refuses to boot behind the code.

Veri ve PostgreSQLSözlükte incele
search_path

The ordered list of schemas PostgreSQL searches when an SQL statement references an unqualified table or function name.

Veri ve PostgreSQLSözlükte incele
SECURITY DEFINER function

A PostgreSQL function that runs with its owner's privileges rather than its caller's, acting as a narrow, audited doorway into restricted tables.

Veri ve PostgreSQLSözlükte incele
SET LOCAL

A PostgreSQL command (and the true flag on set_config) that scopes a setting or role change strictly to the current transaction.

Veri ve PostgreSQLSözlükte incele
tenantTR: kiracı

One customer business whose records share a database server with other customers while staying strictly isolated from them.

Veri ve PostgreSQLSözlükte incele
tenant context

The three transaction-local PostgreSQL settings (app.workspace_id, app.actor_id, app.actor_kind) telling RLS who is acting and in which workspace.

Veri ve PostgreSQLSözlükte incele
tenant isolationTR: kiracı yalıtımı

The guarantee that one workspace can never read, infer, or modify another workspace's data even when application code has a bug.

Veri ve PostgreSQLSözlükte incele
transactional outbox

Writing an outbound job row inside the exact same database transaction as the business change so the two can never drift apart.

Veri ve PostgreSQLSözlükte incele
WHERE clauseTR: WHERE koşulu

The filter part of an SQL query that selects which rows match, helpful for performance but insufficient alone for tenant isolation.

Veri ve PostgreSQLSözlükte incele

Go deeper

  • Contracts and decisions: AGENTS.md (rules 6, 7, 8, 10, 13, 20), ADR-0004, OWNER-DECISIONS.md (OD-22), and INDEPENDENT-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, and schema-guard.ts.
  • Archived lessons absorbed here: archived lesson 01 on multi-tenant RLS and fencing and archived 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.
◆

NOT LEGAL OR TAX ADVICE · Açık karar kapıları dürüstlüğü

Bu müfredat öğrenme amaçlıdır; hukuk veya vergi danışmanlığı değildir. #3 hukuk ve mali müşavir onayı, #21 keşif görüşmeleri, OD-01 marka tescil kontrolü ve canlı dağıtım henüz tamamlanmamıştır. ISO-27001 / SOC 2: UNOBTAINED. Sıfır canlı müşteri veya canlı reklam harcaması iddia edilmez.

Önceki ders: L02Sonraki ders: L04

L03 · Part A · foundation · Verified 2026-12-04 · 18 min

Data: PostgreSQL, tenants, exact money, and doing things exactly once

How PostgreSQL keeps every customer workspace apart, stores money to the exact kuruş, evolves through append-only migrations, and guarantees each job runs once.

Bu müfredat öğrenme amaçlıdır; hukuk veya vergi danışmanlığı değildir. #3 hukuk ve mali müşavir onayı, #21 keşif görüşmeleri, OD-01 marka tescil kontrolü ve canlı dağıtım henüz tamamlanmamıştır. ISO-27001 / SOC 2: UNOBTAINED. Sıfır canlı müşteri veya canlı reklam harcaması iddia edilmez.

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

treat the database as the final referee, not a passive filing cabinet. Even when application code has a bug, PostgreSQL still enforces whose rows you may see, how money adds up, and which state transitions are legal.

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.Pool

If 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 byAccess to vault.*Bound by FORCE RLS
Migration ownerMigration loginpnpm db:migrateYes (DDL owner)Table owner (bypass only when superuser)
{product}_app{product}_app_loginWeb API and workerNone (42501)Yes (NOBYPASSRLS)
{product}_vault_executor{product}_vault_loginVault ops and dispatchScoped vault tablesYes (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:

  1. Pin search_path explicitly (SET search_path = pg_catalog, public, pg_temp) so a temporary table cannot shadow built-in or public objects.
  2. Revoke TEMP on the database and CREATE on public from PUBLIC and all runtime roles.
  3. Run REVOKE ALL ON FUNCTION ... FROM PUBLIC and grant EXECUTE only to the exact role that needs it.
○

Note

how the vault encrypts tokens at rest (AES-256-GCM, DEKs, and AAD binding) belongs to Lesson 05. Here we focus on why the app role cannot reach vault.* tables at all.

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:

ConceptAvoidProduct ruleExample
Money amount12000.00 (float)BIGINT / BigInt minor unit1200000 kuruş (1_200_000n)
Tax or fee rate0.045 (float)Integer basis point (10,000 = 100%)450 bps (4.50%)
Missing COGS or 0/00 or 0.0xNull in DB, — on screencogs_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

KPI formulas such as ROAS, contribution margin, and Event Match Quality belong to Lesson 07.

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_id acts as a fencing token so a stale worker's late UPDATE matches 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 returns 409 IDEMPOTENCY_KEY_REUSED on payload mismatch. On range-partitioned tracking_events, where PostgreSQL requires the partition key (occurred_at) in every unique index, a non-partitioned side table (tracking_event_keys) holds PRIMARY KEY (workspace_id, destination, event_name, event_id) inserted via ON 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 same BEGIN ... COMMIT block 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 asynchronously

State 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_grants rejects 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), enforces expires_at > starts_at, and pairs with a composite foreign key (workspace_id, engagement_id) pointing to engagements(workspace_id, id).
  • A trigger checks cross-row rules and state transitions: on approval_requests, BEFORE INSERT OR UPDATE triggers keep intent immutable, reject extending expires_at, require active owner or admin membership to decide, and enforce legal status moves; on audit_log, order_adjustments, and the safeguarded payment ledger, immutability triggers reject every UPDATE and DELETE.
○

Note

the full business meaning of Propose -> Approve -> Execute and its human guardrails belongs to Lesson 08.

How this repository does it

Every mechanism above maps directly to live code in this checkout:

  • Tenant transactions: tenant-tx.ts validates workspaceId, actorId, and actorKind with Zod, executes BEGIN, SET LOCAL ROLE {product}_app, and set_config(..., true) for all three variables, and calls client.release(true) if ROLLBACK fails.
  • Schema and forced RLS: schema.sql defines 31 base tables, 7 partition tables, and 23 forced-RLS tenant tables verified by schema-contract.ts. app_has_workspace_access(target_ws) checks app.workspace_id plus either system_worker, an active workspace_memberships row, or an active non-revoked marketer_grants row tied to a funded or active engagement within [starts_at, expires_at). Raw crm_contacts uses app_has_workspace_scope(target_ws, 'crm:read_contacts') so marketers are denied PII by default.
  • Role bootstrap and timeouts: init-roles.sql creates {product}_app_login (limit 100) and {product}_vault_login (limit 50) with NOSUPERUSER NOBYPASSRLS, sets lock_timeout = '5s', statement_timeout = '30s', and idle_in_transaction_session_timeout = '30s', revokes TEMP, CREATE on public, and PUBLIC EXECUTE on all SECURITY DEFINER and trigger functions, and aborts if any catalog check fails.
  • Connection pool safety: pool.ts redacts 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.ts takes advisory lock 74208101, loads schema.sql as 0001_baseline_schema.sql plus 0002 through 0014 from packages/db/migrations, checks constant-time SHA-256 digests in public.schema_migrations, and commits each pending file atomically. At boot, schema-guard.ts reads schema_migrations (via 0005_schema_migrations_app_read.sql) and refuses production start-up on behind, unreadable, or unreachable.
  • Exact money and tax math: turkish-tax.ts computes all amounts in BigInt kuruş (1_200_000n tevkifat threshold) and integer basis points (2000, 3000, 100, commission tiers 1000/800/600/450/300) via mulBpsHalfUp.
  • Queues, deduplication, outbox, and crash recovery: 0009_tracking_event_keys_and_dispatch_lease.sql and signals-crm-repo.ts implement tracking_event_keys, dispatch_lease_id fencing, FOR UPDATE SKIP LOCKED, and conversion_feedback_queue. Migrations 0003_approval_intent_integrity.sql, 0013_real_approval_execution.sql, and 0014_execution_progress_and_recovery.sql lock approval intent, guard execution_write_started_at, and provide recover_stuck_approval_executions (FOR UPDATE SKIP LOCKED).
◆

Not built yet

three items remain open on this branch as of 2026-12-04. First, OD-22 approved dropping the legacy global unique constraint on approval_requests.idempotency_key in planned migration 0015 (AGENTS.md rule 20), but 0015 has not been created yet (packages/db/migrations/ ends at 0014), so the global constraint still sits beside the per-workspace index from 0013. Second, role-aware RLS across all tables beyond the approval triggers (finding P-7) is not built yet; member role distinctions mostly live in application code. Third, nothing is deployed to production or serving live customer databases yet (OD-04, OD-05).

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

a unique constraint missing workspace_id leaks existence facts across tenants even when FORCE ROW LEVEL SECURITY hides every row from SELECT.

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

when running live PostgreSQL tests later, set PG_BIN_DIR if needed and always use the isolated helpers rather than port 5432 or a running development cluster.

Words to know

  • Additive migration
  • Application role
  • Basis point
  • BYPASSRLS
  • CHECK constraint
  • Connection pool
  • Database migration
  • Database role
  • Database row
  • Database table
  • Database transaction
  • Database trigger
  • Explicit URL tenant scoping
  • Fencing token
  • Floating point
  • FOR UPDATE SKIP LOCKED
  • FORCE ROW LEVEL SECURITY
  • Idempotency key
  • Lease
  • Migration ledger
  • Minor unit
  • Null
  • Pool poisoning
  • PostgreSQL
  • Row-level security
  • Schema guard
  • search_path
  • SECURITY DEFINER function
  • SET LOCAL
  • Tenant
  • Tenant context
  • Tenant isolation
  • Transactional outbox
  • WHERE clause

Go deeper

  • Contracts and decisions: AGENTS.md (rules 6, 7, 8, 10, 13, 20), ADR-0004, OWNER-DECISIONS.md (OD-22), and INDEPENDENT-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, and schema-guard.ts.
  • Archived lessons absorbed here: archived lesson 01 on multi-tenant RLS and fencing and archived 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.

Kendini sına soru özeti ve yanıt anahtarı

Q1. Why does every tenant table declare FORCE ROW LEVEL SECURITY in addition to ENABLE ROW LEVEL SECURITY?

Answer: B

In PostgreSQL, ENABLE ROW LEVEL SECURITY still exempts the table owner; FORCE ROW LEVEL SECURITY binds the owner too (only superusers and BYPASSRLS roles remain exempt). It neither speeds up scans (A) nor encrypts columns (C).

Q2. Why must withTenantTransaction use set_config('app.workspace_id', $1, true) instead of a plain session-level SET?

Answer: A

Pooled connections are reused across workspaces. Plain SET is legal inside BEGIN (so B is wrong) and stays active on the connection afterward, risking cross-tenant leakage; passing true makes it transaction-local.

Q3. What happens if a buggy API route running as {product}_app_login executes SELECT * FROM vault.oauth_connections?

Answer: C

Schema vault and its tables are revoked from PUBLIC and {product}_app, so PostgreSQL fails immediately with 42501. Silent empty reads (B) come from RLS on public tables, whereas vault.* is blocked earlier by role privileges.

Q4. Why did migration 0009 place the canonical event deduplication key on tracking_event_keys instead of directly on tracking_events?

Answer: B

Requiring occurred_at inside a unique index lets a late replay with a shifted timestamp enter another month's partition. Non-partitioned tracking_event_keys holds PRIMARY KEY (workspace_id, destination, event_name, event_id) across all months. RLS tables support unique indexes normally (A).

Q5. Why is an unknown product cost (cogs_minor) stored as NULL and displayed as — instead of 0?

Answer: B

Treating unknown cost as zero distorts every profit calculation shown to the business owner; NULL (rendered as —) keeps missing data explicit. Both bigint (A) and BigInt (C) support zero natively.

Q6. 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?

Answer: B

Row locks from FOR UPDATE SKIP LOCKED end at COMMIT (so A is wrong). When the second worker reclaims the expired lease it writes a fresh dispatch_lease_id, so the stale worker's fenced update matches zero rows and returns false.

GetClaps Kurucu Akademisi · Tarayıcı açılışında ağ çağrısı yapılmaz; ilerleme yalnızca cihazındaki yerel depolamada tutulur.