Stream processor
The stream processor is the part of the platform that reacts to what has just been written to the messaging tables. It runs four independent loops in one subsystem:
| Loop | Reads | Writes | Purpose |
|---|---|---|---|
Fan-out (event_fan_out) |
New rows in msg_events |
PENDING rows in msg_dispatch_jobs |
Match each event against the active subscriptions and raise one dispatch job per match |
Event projection (event_projection) |
New rows in msg_events |
msg_events_read |
Keep the read-optimised copy of events that the console and the list APIs query |
Dispatch-job projection (dispatch_job_projection) |
New or changed rows in msg_dispatch_jobs |
msg_dispatch_jobs_read |
The same for dispatch jobs, including every status change |
| Partition manager | The catalogue | Monthly partitions | Create partitions ahead of time and drop expired ones |
It is the internal/stream package, switched on with FC_STREAM_PROCESSOR_ENABLED (alias
STREAM_PROCESSOR_ENABLED, default off). Each loop has its own toggle, on by default, so the
top-level switch is enough: FC_STREAM_FAN_OUT_ENABLED, FC_STREAM_EVENTS_ENABLED,
FC_STREAM_DISPATCH_JOBS_ENABLED and FC_STREAM_PARTITION_MANAGER_ENABLED (old name
FC_STREAM_PARTITIONS_ENABLED).
flowchart LR
ING["Event ingest<br/>POST /api/events, batch"] --> EV[("msg_events")]
EV -->|"fanned_out_at IS NULL"| FO["Fan-out"]
FO -->|"PENDING jobs"| DJ[("msg_dispatch_jobs")]
EV -->|"projected_at IS NULL"| EP["Event projection"]
EP --> EVR[("msg_events_read")]
DJ -->|"new or updated since projected"| DP["Dispatch-job projection"]
DP --> DJR[("msg_dispatch_jobs_read")]
DJ --> SCH["Dispatch scheduler"]
PM["Partition manager"] -.->|"create and drop monthly partitions"| EV & DJ & EVR & DJR
The projector loop
Section titled “The projector loop”Fan-out and both projections are stream.Projectors: a loop that calls a Step(batchSize) and
picks its next sleep from the result.
| Result of a step | Next sleep |
|---|---|
| A full batch | None: loop at once, so a backlog drains at full speed |
| A partial batch | 100 ms |
| Nothing to do | 1 s |
| An error | 5 s (logged and counted, never fatal) |
Every step is one transaction. Progress is tracked on the source rows, not in a separate
checkpoint: a nullable timestamp column (fanned_out_at, projected_at) is stamped in the same
transaction as the output is written. A crash before commit leaves the rows unstamped, and the next
step does the work again; a crash after commit has nothing left to redo. There is no offset to lose
and no second store to keep consistent.
Fan-out
Section titled “Fan-out”Each step:
- Loads the active subscriptions from a cache (
msg_subscriptionswithstatus = 'ACTIVE', joined to their event-type patterns), refreshed everyFC_STREAM_FAN_OUT_SUBS_REFRESH_SECS(5 s). A failed refresh keeps the previous set rather than stopping fan-out. - Claims up to 200 events with
fanned_out_at IS NULL, oldestcreated_atfirst, withFOR UPDATE SKIP LOCKED, stampingfanned_out_at = NOW()in the same statement. - Matches every event against every subscription and builds the jobs.
- Inserts the jobs as
PENDINGthrough the dispatch-job lifecycle (Lifecycle.CreateFanOut), in the same transaction, and commits.
With no active subscriptions at all, a fast path stamps a batch of events as fanned out without opening the longer transaction.
Matching
Section titled “Matching”A subscription matches an event when:
- one of its event-type patterns matches the event’s type, segment by segment: the patterns and the
type must have the same number of
:-separated segments, and*matches any one segment (orders:sales:*:*matchesorders:sales:order:placed); and - the subscription has no client, or its client is the event’s client. An event with no client matches only subscriptions with no client.
An event whose type no subscription matches is stamped and raises nothing. It is still stored and still projected, so it shows in the event list.
What a raised job carries
Section titled “What a raised job carries”| Job field | From |
|---|---|
code |
The event type |
target_url, data_only, mode, dispatch_pool_id, sequence, timeout_seconds, max_retries, queue, service_account_id |
The subscription |
descriptor |
The subscription’s name (shown on the dispatch-job grid) |
payload |
The event’s data |
metadata |
The event’s context data, verbatim |
event_id, source, subject, correlation_id, client_id, created_at |
The event |
message_group |
<subscription id>:<event group>, or none when the event has no group. A composed group longer than the column holds uses a SHA-256 digest of the event group instead |
not_before |
Event created_at plus the subscription’s delaySeconds, when set |
expires_at |
Event created_at plus the subscription’s maxAgeSeconds, when set |
idempotency_key |
<event id>:<subscription id> |
Two of these choices matter for behaviour:
- The group is per subscriber. Prefixing the event’s group with the subscription id means one
subscriber’s failed
BLOCK_ON_ERRORjob holds back only that subscriber’s later jobs for the same group. Other subscribers to the same events keep flowing. See ordering. - Delay and age limits are made absolute at fan-out. Editing a subscription’s
delaySecondsormaxAgeSecondslater does not move jobs already raised. The delivery callback enforces both (see the dispatch scheduler).
The job’s created_at is the event’s created_at, so an event and its jobs land in the same
monthly partition and age out together.
The projections
Section titled “The projections”Events and dispatch jobs are written to write tables (msg_events, msg_dispatch_jobs) shaped
for the write path and the scheduler, and read through read tables (msg_events_read,
msg_dispatch_jobs_read) shaped and indexed for the console’s grids and filters. The list,
filter-option and by-event reads in internal/platform/event and internal/platform/dispatchjob
query the read tables; a lookup of one job for an operator action reads the write table.
| Projection | Claims | Writes |
|---|---|---|
| Events | Up to 100 events with projected_at IS NULL, oldest first, FOR UPDATE SKIP LOCKED |
An INSERT … ON CONFLICT DO NOTHING into msg_events_read, with application, subdomain and aggregate split out of the type, then projected_at on the source |
| Dispatch jobs | Up to 100 jobs with projected_at IS NULL OR updated_at > projected_at |
An upsert into msg_dispatch_jobs_read (status, attempts, timings, error, the is_completed and is_terminal flags, connection), then projected_at on the source |
Every status change stamps updated_at on the job, so the dispatch-job projection follows a job
through its whole lifecycle. The read table leaves out the payload, which is read from the write
table when one job is opened. Both projections keep the source row’s created_at, so read rows land
in the same partition as their source and are dropped with it. The dispatch-job projection bounds
its statements by the claimed rows’ created_at range, so they touch only the partitions involved.
Read-after-write lag. Lists are eventually consistent with writes: a new event or a status change appears after the next projection step, normally well under a second, and longer while a large backlog drains.
The partition manager
Section titled “The partition manager”msg_events, msg_events_read, msg_dispatch_jobs, msg_dispatch_jobs_read,
msg_dispatch_job_attempts, msg_scheduled_job_instances and msg_scheduled_job_instance_logs
are partitioned by month on created_at, with partitions named <table>_YYYY_MM. The manager runs
one pass at start-up and then every FC_STREAM_PARTITION_TICK_HOURS (24). Each pass, for every
parent:
- Creates the current month’s partition and the next
FC_STREAM_PARTITION_MONTHS_FORWARD(3), withCREATE TABLE IF NOT EXISTS … PARTITION OF, so it is idempotent. - Drops every monthly partition whose whole range ended before the retention cutoff:
FC_STREAM_PARTITION_RETENTION_DAYS(90) for events, jobs and attempts, andFC_STREAM_PARTITION_RETENTION_DAYS_SCHEDULED_JOBS(30) for scheduled-job history. A partition only goes once all of it is past the cutoff, so the data on disk floats between the retention period and one month more.
A parent that is not partitioned in this database is skipped. Partitions whose names do not follow the monthly pattern are left alone.
Why no extension. Partition maintenance is plain Go issuing DDL, not pg_partman or pg_cron.
Managed PostgreSQL services decide which extensions they allow on their own schedule, and doing it in
process gives identical behaviour in fcdev’s embedded PostgreSQL and in production. See
no PostgreSQL extensions.
Leader-gating and HA
Section titled “Leader-gating and HA”The whole stream processor shares one election, on <FC_STANDBY_LOCK_KEY>:stream. Without
standby every copy is the leader, so run one. A non-leader’s loops idle and claim nothing.
Why one leader. The claims use FOR UPDATE SKIP LOCKED, so several copies would never process
the same row twice. Ordering is the problem. Two fan-out workers taking different batches of events
could commit a later event’s jobs before an earlier event’s jobs in the same group, and the
scheduler would then see the later one first. Keeping fan-out single-active, with the dispatch
scheduler also single-active, keeps a group’s jobs in event order. The partition manager is gated
because only one node should run DDL; its statements are idempotent either way.
On failover the new leader simply claims whatever is unstamped. Nothing is held in memory that has to be rebuilt, apart from the subscription cache, which loads on the first step.
Health
Section titled “Health”Each loop registers a stream.Health that records whether it is running, how many rows it has
processed, its error count and its last poll time. When the router runs in the same process, its
API reports them (the router’s stream-health monitoring endpoint), so one dashboard shows both. A
loop counts as healthy while it is running; a loop that keeps failing is still “running”, so watch
the error count and the logs (projector step error), not only the flag.
Tunables
Section titled “Tunables”| Variable | Default | Effect |
|---|---|---|
FC_STREAM_PROCESSOR_ENABLED |
false |
Run the stream processor |
FC_STREAM_FAN_OUT_ENABLED, FC_STREAM_EVENTS_ENABLED, FC_STREAM_DISPATCH_JOBS_ENABLED, FC_STREAM_PARTITION_MANAGER_ENABLED |
true |
Each loop |
FC_STREAM_BATCH_SIZE |
per loop | One batch size for all three projector loops |
FC_STREAM_FAN_OUT_BATCH_SIZE |
200 |
Fan-out batch (wins over the global value) |
FC_STREAM_EVENTS_BATCH_SIZE |
100 |
Event projection batch |
FC_STREAM_DISPATCH_JOBS_BATCH_SIZE |
100 |
Dispatch-job projection batch |
FC_STREAM_FAN_OUT_SUBS_REFRESH_SECS |
5 |
How stale the subscription set may be |
FC_STREAM_PARTITION_MONTHS_FORWARD |
3 |
Months of partitions created ahead |
FC_STREAM_PARTITION_RETENTION_DAYS |
90 |
Retention for events, jobs and attempts |
FC_STREAM_PARTITION_RETENTION_DAYS_SCHEDULED_JOBS |
30 |
Retention for scheduled-job history |
FC_STREAM_PARTITION_TICK_HOURS |
24 |
How often the partition manager runs |
See the environment reference.
Failure behaviour
Section titled “Failure behaviour”| Situation | What happens |
|---|---|
| A step fails (database error, constraint) | The transaction rolls back, nothing is stamped, the loop waits 5 s and tries again; the same rows are claimed again |
| The process dies mid-step | The open transaction is lost; the rows are unstamped and the next leader processes them |
| A subscription is created or edited | Fan-out sees it within the cache period (5 s); events already fanned out are not revisited |
| A subscription is paused | Fan-out loads only ACTIVE subscriptions, so events that arrive while it is paused raise no job for it and are not delivered later. Pausing its connection instead keeps raising jobs, which wait PENDING; see subscriptions and connections |
| Fan-out falls behind | Events wait unstamped; nothing is lost, and dispatch starts later. Raise the batch size or look at database latency |
| A partition is missing when a row arrives | The insert fails. The manager creates months ahead to prevent this; if it has been off for months, run it (or start the stream processor) before writing |
| Standby enabled but Redis unreachable | The election fails closed: no copy is leader, and fan-out and projections stop until it recovers |
Why it is built this way
Section titled “Why it is built this way”- Write tables and read tables. The write tables stay narrow and indexed for the claim and the scheduler; the read tables carry the denormalised columns and indexes the console’s filters need. The projection decouples the two, at the cost of a short read lag.
- Progress lives on the rows. A stamped timestamp in the same transaction as the output gives exactly-once effects per row without a separate offset store.
- Fan-out after the fact, not at ingest. Event ingest stores the event and returns; matching and job creation happen in a separate, retryable step. A burst of events is absorbed by the table, and a subscription bug cannot fail an ingest call.
- Decisions: leader-gated processors, no PostgreSQL extensions, event schemas are not enforced.
Read next
Section titled “Read next”- Events and event types and subscriptions and connections.
- Dispatch scheduler: what happens to the jobs fan-out raises.
- Data model and storage: the tables, partitions and retention.
- Ordering and message groups.