Skip to content

Database operations

PostgreSQL is FlowCatalyst’s only system of record. Queues, Redis and the processes themselves can be lost and rebuilt; the database cannot. This page covers how the platform changes its schema, how it keeps its large tables bounded, and what you watch and tune.

Prefix Holds Grows with
tnt_, app_, iam_, oauth_ Clients, applications, principals, roles, OAuth clients, identity providers, sessions and tokens Users and configuration (small)
msg_events, msg_events_read Events and their read projection Traffic (partitioned)
msg_dispatch_jobs, msg_dispatch_jobs_read, msg_dispatch_job_attempts Dispatch jobs, their projection and every delivery attempt Traffic × subscriptions (partitioned)
msg_payloads Event and dispatch-job payloads, as text, when the payload table is switched on (below) Traffic (partitioned)
msg_scheduled_job_instances, ..._logs Scheduled-job firing history Firings (partitioned)
msg_subscriptions, msg_connections, msg_dispatch_pools, … Messaging definitions Configuration (small)
aud_logs The audit log Administrative changes and application audit entries (not pruned)
iam_login_attempts Sign-in history Logins (quarterly partitions, 3 years)
ing_ Ingestion definitions, leases, state, metrics, failures, traces Ingestion traffic (retention sweeps)
fng_ Functions, versions, aliases, trace logs Functions and traces
fw_push_, push_ Push outbox, log and settings Pushes (24-hour log retention)
queue_messages The Postgres broker’s queue In-flight dispatch pointers (deleted when acknowledged)
outbox_messages Outbox rows drained by the platform’s own outbox processor, when used Unsent rows (deleted when sent)
goose_db_version The migration ledger Migrations

The SQL migrations are embedded in the binary and applied with goose every time a database-backed fc-server process starts, before it serves anything. They are forward-only: there are no down migrations. After them the seeder brings the built-in roles, permissions and event types up to date.

A bootstrap step runs first and makes the goose ledger agree with the schema actually present, so a database migrated by an earlier tracker is never re-migrated and a migration is never recorded without its effect. It only ever un-marks entries whose effect is missing, so goose applies them again.

What this means for you:

  • Start one process first. The migration run takes no lock across processes. When a release carries migrations, let one fc-server process start and finish (migrations applied in its log) before the others start, rather than starting every replica at once. A process whose migration run fails exits with migrations failed, and your orchestrator restarts it.
  • Read the release’s notes for ops scripts. A migration that would lock a large table for long is shipped with an optional script in scripts/ops/ to run with psql before the deploy (for example an online index build). The migration then finds the work done and does nothing. The script header says when it is needed, how long it takes and how to re-run it.
  • Some scripts run after the deploy. scripts/ops/109-dispatch-group-per-subscription.sql, for example, re-keys old dispatch jobs and must run only after every platform instance runs the new code. Again, the header says so.
  • A failed migration leaves the previous schema. Each migration runs in its own transaction unless it is marked otherwise (online index builds cannot run in one). Fix the cause and start a process again.

FlowCatalyst’s policy, which its own migrations follow and which you should follow for any manual change, is that nothing may block writes on a large table for long. PostgreSQL has native online forms for almost everything:

Change Do this
Add an index CREATE INDEX CONCURRENTLY outside a transaction. A failed build leaves an INVALID index: drop it concurrently and run again
Add an index on a partitioned table CREATE INDEX ... ON ONLY <parent>, then CREATE INDEX CONCURRENTLY on each partition, then ALTER INDEX <parent_index> ATTACH PARTITION <partition_index>
Add NOT NULL, a foreign key or a check Add a NOT VALID constraint, then VALIDATE CONSTRAINT
Backfill In batches of a few thousand rows by key range, committing each, throttled and resumable
Anything that rewrites the table Add a new column, backfill, switch, drop; or an external tool. Plan it

Set lock_timeout (for example SET lock_timeout = '5s') before any DDL on a busy table, so a statement that cannot get its lock fails fast instead of queueing every other query behind it. “Large” means anything that grows with traffic: the events, dispatch-job, attempt, audit and login-attempt tables. See online schema changes.

Eight tables are partitioned by month on created_at (UTC), with partitions named <table>_YYYY_MM: msg_events, msg_events_read, msg_dispatch_jobs, msg_dispatch_jobs_read, msg_dispatch_job_attempts, msg_payloads, msg_scheduled_job_instances and msg_scheduled_job_instance_logs.

The partition manager, part of the stream processor, keeps them:

  • Ahead: it creates the current month and the next FC_STREAM_PARTITION_MONTHS_FORWARD (3) months.
  • Behind: it drops a partition once its whole month ended more than FC_STREAM_PARTITION_RETENTION_DAYS (90) days ago, or FC_STREAM_PARTITION_RETENTION_DAYS_SCHEDULED_JOBS (30) for the scheduled-job history. Dropping a partition is instant and leaves no bloat, unlike deleting rows.
  • When: at start-up and every FC_STREAM_PARTITION_TICK_HOURS (24), on the stream processor’s leader only.

Because whole months are dropped, the data on disk spans between the retention and the retention plus a month. With the defaults, between about 90 and 120 days of events and jobs.

Things to know about retention:

  • It removes everything older, in every status. A dispatch job that failed and was never dealt with disappears with its month. Requeue or resolve failures well within the retention window.
  • Keep the dispatch-job read window inside it. FC_DISPATCH_JOB_MAX_WINDOW_DAYS (31) bounds list queries; keep it at or below the partition retention.
  • Raising the retention keeps partitions longer from the next pass on. Lowering it drops the older ones at the next pass.

Other retention is row-level and runs on every process with the platform API enabled:

Data Kept By
OAuth codes and tokens, OIDC login state, passkey ceremonies, portal login flows Until they expire The auth purger, every minute
Expired email PINs, expired trusted devices and expired password-reset tokens Until they expire The auth purger, every minute
Password-reset approval requests Until 90 days after they end The auth purger, every minute
Rate-limit counters (PostgreSQL store) The longest window plus 10 minutes The auth purger
Login history (iam_login_attempts) 3 years, as whole quarterly partitions The auth purger
Field-worker sign-in history FC_FIELD_LOGIN_ATTEMPT_RETENTION_DAYS (90) The auth purger
Idempotency keys of SDK-created dispatch jobs 7 days A sweep every 10 minutes
Function trace records FC_FUNCTIONS_TRACE_RETENTION_DAYS (30) A sweep every FC_FUNCTIONS_TRACE_PRUNE_INTERVAL_MINUTES (60)
Ingestion metrics and failures; test requests; traces; job keys 30 days; 1 day; FC_INGESTION_TRACE_RETENTION_DAYS (7); 7 days The hourly ingestion sweep, FC_INGESTION_RETENTION_MAX_CHUNKS × 10,000 rows per table per run
Untagged function versions The newest FC_FUNCTIONS_KEEP_VERSIONS (20) per function Pruned after each publish
Push log FC_PUSH_RETENTION (24 hours) The push gateway
Audit log (aud_logs) For ever Nothing. See database growth

Until the payload table is switched on, a payload is stored in the row it belongs to: msg_events.data (JSONB) and msg_dispatch_jobs.payload (text), and fan-out copies it into one job per matching subscription. The payload table moves each payload into its own row of msg_payloads, written once and never updated, which the event and its jobs point at (payload_id), so a payload is stored once however many jobs it fans out to. It is stored as text, the bytes the producer sent. A payload above a size can also be offloaded to an object store, in which case its msg_payloads row holds a reference instead of the data. Delivery and detail reads resolve the reference; the scheduler, the queue and the projections never touch the store, and a subscriber always receives the whole payload.

It is on in two independent steps, each safe to stop after:

  1. FC_PAYLOAD_TABLE_WRITES=true makes the writers (event ingest, the platform’s own events, dispatch jobs and payload edits) write msg_payloads rows. It is off by default. Every instance reads both row shapes whatever the setting, so turn it on only once every instance of the deployment runs a release that does (see upgrades). Rolling back past such a release is unsafe once rows are written. With it on, a payload that is not UTF-8 text, or larger than the largest accepted, is refused.
  2. FC_PAYLOAD_STORE (optional) turns offloading on: s3://bucket/prefix or file:///abs/path. Payloads larger than FC_PAYLOAD_OFFLOAD_MIN_BYTES (5120 bytes by default, at least 2048) are compressed (zstd, FC_PAYLOAD_CODEC) and written to the store. Set it on every instance. The largest payload accepted then rises from FC_PAYLOAD_INLINE_MAX_BYTES (1 MiB) to FC_PAYLOAD_MAX_BYTES (5 MB), so subscribers of event types with large payloads must accept a body that size. If the store cannot be written, a payload up to FC_PAYLOAD_INLINE_MAX_BYTES is kept in the database instead, and a larger one is refused with a retryable error.

FC_PAYLOAD_CACHE_BYTES (64 MiB) sizes an in-process cache of resolved payloads, and FC_INGEST_BATCH_MAX_BYTES (16 MiB) caps the batch routes’ request bodies. Keep the outbox processor’s FC_OUTBOX_MAX_REQUEST_BYTES at or below half of that, and raise the platform’s cap before the processor’s. Every variable is in the environment reference.

For S3, the platform’s role needs s3:PutObject and s3:GetObject on arn:aws:s3:::<bucket>/<prefix>/* and s3:ListBucket on the bucket, limited to that prefix, and nothing that deletes or reconfigures. Without s3:ListBucket, S3 answers a missing key with 403 instead of 404, and the platform treats an object that is gone as an unreadable store and retries the job instead of failing it. Keep the bucket private and encrypted. The platform never deletes objects from S3. Set a lifecycle rule on the prefix that expires objects after the partition retention plus 35 days (a monthly partition keeps a row up to 31 days past the retention), which is 125 days at the default 90-day retention, and change it whenever you change the retention. The platform neither creates the rule nor checks for it: a bucket without one keeps every payload for ever.

{
"ID": "fc-payloads",
"Status": "Enabled",
"Filter": { "Prefix": "<prefix>/v1/" },
"Expiration": { "Days": 125 }
}

A file:// store is cleaned by the partition manager’s daily pass, after the same period, and the process that runs the partition manager must see the same directory as the processes that write payloads.

Switching offload off. Set FC_PAYLOAD_OFFLOAD_MIN_BYTES=0: nothing new is offloaded, and what is stored stays readable. Wait one retention period plus a month, until every row that refers to the store has been dropped, and only then remove FC_PAYLOAD_STORE. Removing it earlier makes those payloads unreadable (their jobs are not delivered, and reads show them as unavailable). A threshold of 0 also lowers the largest payload accepted to FC_PAYLOAD_INLINE_MAX_BYTES.

Health. A process that runs the platform API answers GET /health/payload-store with the store’s state as JSON and always 200: status is NOT_CONFIGURED (healthy: no store is set), UP, or DEGRADED when a store write or read failed in the last five minutes. The state comes from real operations, not a probe. A store that is down does not make the process unready: ingestion goes on, payloads up to FC_PAYLOAD_INLINE_MAX_BYTES are kept in the database, and fc_payload_inline_fallback_total and fc_payload_store_errors_total rise. Alert on DEGRADED or on those counters.

The console’s event and dispatch-job lists, and the filtered API lists, read msg_events_read and msg_dispatch_jobs_read. The stream processor projects each new or changed row into them, a batch at a time. If the stream processor stops, delivery of jobs already created continues, but new events are not fanned out to subscriptions, and the lists stop showing new events and status changes until it resumes and catches up. Its lag is a database query away (below).

Each fc-server process opens:

Pool Size Notes
Main The larger of 4 and the number of CPUs the process sees, unless the connection URL sets pool_max_conns Serves the API, the delivery callback, projections, fan-out and housekeeping
Dispatch scheduler FC_SCHEDULER_DB_MAX_CONNECTIONS, default FC_SCHEDULER_DISPATCHERS + 2 (12) Only where the scheduler is enabled; its connections use planner settings tuned for the claim query
Push gateway FC_PUSH_DB_POOL_MAX (10) Only where the gateway is enabled
Postgres broker consumers Opened by the router per queue Only with the Postgres broker

Set pool_max_conns explicitly on the API tier (in FC_DATABASE_URL), for example 20 to 50 per replica, and size PostgreSQL’s max_connections for the total across all replicas plus headroom. The default of 4 on a small container is too few for a busy API process: some request paths read through the pool while they hold a transaction, so a pool that is far too small can stall under concurrent writes. With Secrets Manager credentials the connection string is composed for you and cannot carry pool_max_conns, so the default applies; prefer a full URL where pool size matters.

Storage is dominated by the partitioned tables. Per event, roughly:

  • the event row and its read-projection row, each with the payload;
  • per matching subscription, one dispatch job (with its own copy of the payload), one projection row (without it), and one attempt row per delivery attempt, each holding up to 64 KiB of the consumer’s response body.

Multiply by daily volume and by the retention plus a month, then add indexes (budget at least as much again for the busy tables) and headroom for autovacuum. Measure on real traffic early: payload sizes and consumer response bodies vary more than anything else.

The write load is mostly inserts plus a few status updates per job. Dispatch-job status changes and the Postgres broker’s queue rows churn the most; keep autovacuum on (the default) and watch dead-tuple counts on msg_dispatch_jobs partitions and queue_messages.

All of these use indexes the platform already has. Add a created_at bound to anything that touches the dispatch-job table so that only recent partitions are read.

-- Events not yet fanned out to subscriptions (stream processor lag)
SELECT count(*), min(created_at) FROM msg_events WHERE fanned_out_at IS NULL;
-- Events and jobs not yet projected for the console lists
SELECT count(*), min(created_at) FROM msg_events WHERE projected_at IS NULL;
SELECT count(*), min(created_at) FROM msg_dispatch_jobs WHERE projected_at IS NULL;
-- Dispatch jobs by status over the last day
SELECT status, count(*) FROM msg_dispatch_jobs
WHERE created_at > now() - interval '1 day' GROUP BY status;
-- Partitions and their sizes
SELECT c.relname, pg_size_pretty(pg_total_relation_size(c.oid))
FROM pg_inherits i JOIN pg_class c ON c.oid = i.inhrelid
JOIN pg_class p ON p.oid = i.inhparent
WHERE p.relname IN ('msg_events', 'msg_dispatch_jobs', 'msg_dispatch_job_attempts')
ORDER BY c.relname;
-- The latest applied migration
SELECT max(version_id) FROM goose_db_version WHERE is_applied;