Skip to content

Dispatch scheduler

The dispatch scheduler turns PENDING dispatch jobs into messages on a queue. It claims due jobs from msg_dispatch_jobs in delivery order, holds back the ones that must wait, publishes one small pointer message per job to the job’s destination queue, and marks each published job QUEUED. The router consumes those messages and calls the platform’s delivery callback, which does the real delivery.

It is the internal/platform/scheduler package, switched on with FC_SCHEDULER_ENABLED (alias DISPATCH_SCHEDULER_ENABLED, default off; fcdev turns it on). It is not the scheduled-job scheduler, which fires cron jobs and lives in internal/platform/scheduledjob/scheduler.

flowchart LR
  FO["Fan-out<br/>(stream processor)"] -->|insert PENDING| DJ[("msg_dispatch_jobs")]
  API["Dispatch-job API<br/>outbox, functions, ingestion"] -->|insert PENDING| DJ
  DJ -->|claim| S["Dispatch scheduler<br/>(leader only)"]
  S -->|pointer message| Q[["Queue per tenant and priority<br/>SQS FIFO or Postgres"]]
  S -->|mark QUEUED| DJ
  Q --> R["Router"]
  R -->|"POST /api/dispatch/process"| CB["Delivery callback"]
  CB -->|deliver| T["Target endpoint"]
  CB -->|"COMPLETED, retry, FAILED"| DJ

The message carries no payload. It holds the job id, the delivery-callback URL as its mediation target, a signed token, the resolved pool code, the dispatch mode and the message group. Everything else stays in the job row, so a payload edited by an operator, or a credential rotated on a connection, takes effect on the next attempt.

Scheduler.Run starts three goroutines: the pending-job poller (with its lanes), the stale-recovery loop and the backlog sampler. All three check the leader gate before doing any work.

flowchart LR
  subgraph Leader["Leader process"]
    P["PendingJobPoller<br/>claim and hold-backs"] -->|"hash of group mod N"| L1["lane 0"]
    P --> L2["lane 1"]
    P --> Ln["lane N-1"]
    L1 & L2 & Ln -->|"Publish batch"| PUB["DispatchPublisher<br/>SQS or Postgres"]
    L1 & L2 & Ln -->|"MarkQueued, optimistic"| DB[("msg_dispatch_jobs")]
    ST["StaleQueuedJobPoller<br/>every 60 s"] --> DB
    BL["Backlog sampler<br/>every 30 s"] --> DB
  end

A claim is one plain SELECT of msg_dispatch_jobs, with no lock, no transaction and no write (dispatchjob.ClaimPendingSQL):

SELECT id, created_at, message_group, sequence, scheduled_for, subscription_id,
dispatch_pool_id, client_id, mode, queue, updated_at
FROM msg_dispatch_jobs
WHERE status = 'PENDING'
AND (scheduled_for IS NULL OR scheduled_for <= NOW())
AND (subscription_id IS NULL OR subscription_id <> ALL($2)) -- paused connections, via subscriptions
AND (message_group IS NULL OR message_group <> ALL($3)) -- groups just found held
AND id <> ALL($4) -- this process's in-flight jobs
AND (connection_id IS NULL OR connection_id <> ALL($5)) -- paused connections, named directly
AND (dispatch_pool_id IS NULL OR dispatch_pool_id <> ALL($6)) -- suspended or archived pools
ORDER BY message_group NULLS LAST, sequence, created_at, id
LIMIT $1

The order (message_group, sequence, created_at, id) is delivery order. It is served by one index, idx_dispatch_jobs_status_group (status, message_group, sequence, created_at, id), as a merge of ordered index scans across the monthly partitions, so the claim never sorts. The scheduler’s own connection pool sets plan_cache_mode = force_custom_plan (scheduler.PoolRuntimeParams) so a cached generic plan can never replace that ordered scan.

Because the claim writes nothing, a claimed job is still PENDING in the table. What keeps it out of the next claim is the poller’s in-memory in-flight set, passed as $4. A process that dies mid-publish leaves its claims simply PENDING, and the next leader claims them again. Nothing has to be unlocked or reset.

What the claim excludes, and why each exclusion is in SQL rather than in Go:

Excluded Source Why in the query
Not yet due (scheduled_for in the future) Retry backoff, deferral, hold The row is not deliverable yet
Subscription whose connection is PAUSED PausedConnectionCache, refreshed every 60 s Paused rows must not fill the LIMIT window and starve the rows behind them
Job naming its own PAUSED connection The same cache (fn.dispatch jobs carry connection_id and no subscription) As above
Dispatch pool SUSPENDED or ARCHIVED dispatchpool.NewHeldPoolCache, 60 s As above
Groups remembered as held heldGroups: 5 s memory, at most 10,000 groups Stops a batch-full of held rows at the head of the order being claimed again and again
Jobs already in flight in this process The in-flight set The claim is a read; this exclusion is what makes it a claim

The poller asks for at most min(FC_SCHEDULER_BATCH_SIZE, FC_SCHEDULER_BUFFER_CAPACITY) rows, and only as many as it holds permits for. Permits bound the jobs between a claim and a lane finishing them to FC_SCHEDULER_BUFFER_CAPACITY. The poller blocks only when that many are in flight; it never waits for a publish. It claims again at once while claims come back full, and sleeps one poll interval (1 s) after a short claim, an empty submission, an error or a failed publish.

Two checks stay in Go because they are positional: a job waits only behind an earlier job of its own group.

BLOCK_ON_ERROR hold-back. For each group in the claim, one batch query (dispatchjob.GroupHoldersSQL) finds the group’s earliest holder: a job that is FAILED (or the legacy ERROR), or a PENDING job sitting out a retry backoff (scheduled_for in the future). A BLOCK_ON_ERROR job positioned after its group’s holder is not submitted and stays PENDING. IMMEDIATE and NEXT_ON_ERROR jobs are never held. QUEUED and PROCESSING siblings do not hold a group: the whole eligible run of a group goes to the router in one go, and the router’s per-group FIFO buffer delivers it in order. Treating them as holders would reduce every ordered group to one job per poll.

The comparison is by position (sequence, created_at, id), not by “the group contains a held job”. A backed-off job whose backoff has expired would otherwise hold back itself, and the group would never move again. A job with no message group never holds anything.

The starvation warning. A full claim that submits nothing is the signature of starvation: the LIMIT window is full of held rows. The poller logs dispatch poller claimed a full batch and submitted none of it at most once a minute, and remembers the held groups for 5 seconds so the next claims reach the rows behind them.

Submitted jobs go to lanes: FC_SCHEDULER_DISPATCHERS independent workers (default 10). A message group always goes to the same lane (FNV-1a hash of the group, modulo the lane count), so one lane publishes a group’s jobs in claim order. Ungrouped jobs carry no ordering and are spread round-robin.

A lane takes one job (blocking), drains up to 99 more without blocking (a lane batch of 100), and then:

  1. Drops any job the ordering rule says must not go (below).
  2. Publishes the batch with one DispatchPublisher.Publish call.
  3. Marks exactly the published jobs QUEUED with one bulk UPDATE (Lifecycle.MarkQueued), optimistic on the updated_at each claim read.
  4. Settles: removes the batch from the in-flight set, records any poison marks, and returns its permits.

Publish before mark. A job published and then not marked is merely published twice later; the duplicate is dropped by the router or skipped by the callback. A job marked QUEUED and never published would sit with no message until stale recovery found it.

Optimistic mark. The router can deliver a job, and the callback can reschedule it to PENDING (a retry, a deferral, a group hold), before the lane’s UPDATE runs. A status check alone would then set QUEUED on a job that has no message on the queue. The UPDATE therefore matches only rows still PENDING and at the updated_at the claim saw. Every lifecycle transition stamps updated_at, so any move at all makes the mark miss (counted as fc_scheduler_mark_queued_not_updated_total).

Publishing is not all-or-nothing: SQS answers per entry. If job j of group g is not published, later jobs of g may already be claimed, in the lane’s channel or in a claim running at that moment, and must not overtake j. The poller and the lanes share a claim generation counter and a poison mark per group (lane.go):

  • A lane that leaves jobs of g unpublished first removes the batch from the in-flight set (from that moment j, still PENDING, is claimable again), then, holding the in-flight set’s mutex (the one every claim’s snapshot takes), reads the current generation P and sets poison[g] = P in one step. Reading P before taking the mutex left a window in which a claim could pass the check and publish g’s later jobs ahead of j.
  • A job of g whose claim generation is at or below poison[g] is dropped when it reaches a lane. It stays PENDING and is claimed again.
  • A claim with a higher generation took its in-flight snapshot after j was removed, so it returns j again, in order. The first job past the mark clears it.
  • A claim that excluded a doomed job of g (its snapshot still held it) does not submit g’s later jobs at all (skippedADoomedJob).

A drop does not renew the mark: renewing it would livelock whenever the poller claims faster than a lane drains. Marks are forgotten after 10 minutes without the group being seen.

The SQS publisher adds two rules of its own. A chunk of 10 (the SendMessageBatch limit) never holds two jobs of one group: chunks are built round-robin by group, and the chunks for one queue are sent one after another. And once a group fails within a Publish call, its later jobs in that call are reported unpublished without being sent. A group is therefore either delivered in claim order or cut off at its first failure, never reordered.

The platform composes one queue per (tenant, priority) (dispatchqueue.ComposeName):

Part Value
Prefix FC_DISPATCH_QUEUE_PREFIX, for example FC-staging. Required when the type is SQS; the server refuses to start without it
Tenant The job’s client identifier (_, . and space become -), or the reserved platform tenant for a job with no client
Priority The job’s own queue (DEFAULT or HIGH_PRIORITY) when it names one, else its subscription’s, else DEFAULT
Suffix .fifo for SQS (the composed name is checked against the SQS length limit)

FC_DISPATCH_QUEUE_TYPE=SQS publishes to SQS FIFO queues, created on first use; the account and region come from FC_DISPATCH_QUEUE_URL (or FC_DISPATCH_QUEUE_REGION). Any other value, including unset, publishes to the built-in Postgres broker (queue_messages), which is what fcdev runs.

The same resolver names the queues in the configuration document the platform serves to the router (GET /api/dispatch/router-config), so the queue a job is published to and the queue the router listens on cannot drift apart. The queue type is the only difference between development and production; the names are composed the same way.

Field Value
id The job id
mediationTarget FC_DISPATCH_PROCESSING_ENDPOINT (default http://localhost:<FC_API_PORT>/api/dispatch/process)
authToken HMAC-SHA256 of the job id (below)
poolCode The resolved, client-namespaced pool code: {client}-{pool}, platform-{pool}, {client}-DEFAULT-POOL or platform-DEFAULT-POOL. This is what puts a pool’s concurrency and rate limit into force
dispatchMode IMMEDIATE, NEXT_ON_ERROR or BLOCK_ON_ERROR. Without it the router would treat every job as unordered
messageGroupId The job’s message group. For an event-raised job it is <subscription id>:<event group>, so each subscriber is ordered separately

On SQS the MessageGroupId is the job’s group, or its own id when it has none. The MessageDeduplicationId is the job id plus a nonce that is fresh for each Publish call: stale recovery deliberately republishes, and a reused id would let SQS swallow that second, intended copy inside its five-minute dedup window. The platform’s own status machine is the only deduplication authority.

Each message carries HMAC-SHA256(jobId) under a key derived from FLOWCATALYST_APP_KEY with HKDF (info = "fc-dispatch-auth"). The router forwards it as a bearer token, and /api/dispatch/process verifies it in constant time before touching the job. A caller that can reach the callback but did not get the message from the queue cannot make the platform deliver a job. Without FLOWCATALYST_APP_KEY the scheduler refuses to start rather than sign with a known value. Signing and verification happen in the platform, so the derived key is never shared.

The scheduler’s part ends at QUEUED. The delivery callback then:

  • settles an expired job (expires_at reached: the subscription’s maxAgeSeconds, or an expiresAt given at creation) as EXPIRED, without delivering or counting an attempt;
  • returns a job to PENDING (no attempt spent) when its pool is suspended or archived, or when a BLOCK_ON_ERROR sibling ahead of it is now held. This mirrors the claim-time hold-back for messages that were already on the queue when the group blocked;
  • hands a job back to the router when its not_before (the subscription’s delaySeconds) is still ahead, answering ack: false with the time to come back. Each such deferral stamps the job (AwaitNotBefore), and a long delay is served as holds of at most 5 minutes, so stale recovery never mistakes a held message for a lost one;
  • otherwise claims the job (PROCESSING, with a lease), delivers, and records the outcome.

Retries are driven by scheduled_for, not by the queue: the callback always acknowledges and reschedules, so exactly one component, this scheduler, ever re-publishes a job. See delivery and dispatch jobs for the outcomes.

stateDiagram-v2
  PENDING --> QUEUED: lane published and marked
  QUEUED --> PENDING: stale, 15 min untouched
  QUEUED --> PROCESSING: callback claim
  PROCESSING --> PROCESSING: lease expired, a later copy takes over
  PROCESSING --> PENDING: stale, 75 min without an outcome
  QUEUED --> PENDING: stranded behind a failed head
Loop Where it runs Cadence What it does
Stale recovery (StaleQueuedJobPoller) Scheduler, leader only Every 60 s QUEUED untouched for 15 minutes goes back to PENDING (a message lost after the broker accepted it, or a mark that failed after a publish). PROCESSING untouched for 75 minutes goes back to PENDING, with the reason in last_error (a dead attempt whose message never comes back)
Stranded-sibling reaper (dispatchjob.RunReaper) Every platform replica (not leader-gated: each sweep is a guarded conditional UPDATE) Every 2 min Returns QUEUED and PROCESSING members of a BLOCK_ON_ERROR group whose head is FAILED to PENDING. PROCESSING rows updated in the last 45 minutes are presumed live and left alone. This is the backstop for the router’s settled hook (POST /api/dispatch/settled)
Job-key retention Every platform replica Every 10 min Prunes the idempotency keys of SDK-created jobs past retention

The 15-minute QUEUED threshold is a trade-off. A message the router has parked for capacity can sit QUEUED longer than that; reverting it publishes a second copy, which the router drops (the original is still in its pipeline) or the callback skips. That cost was accepted in return for recovering a genuinely lost message in 15 minutes rather than 75. PROCESSING stays at 75 minutes because the router allows up to 15 minutes for one delivery attempt.

The poller, the stale-recovery loop and the backlog sampler run only on the leader. With FC_STANDBY_ENABLED=true the scheduler runs its own Redis election on the lock key <FC_STANDBY_LOCK_KEY>:scheduler (default fc:server:leader:scheduler), independent of the router’s and the stream processor’s elections. Without standby every copy considers itself the leader, so run exactly one.

Why single-active. Per-group order depends on in-process state: the in-flight set, the poison marks and the group-to-lane mapping. Two schedulers claiming the same table would each publish some of a group’s jobs, and nothing could keep them in order. Within the leader, lanes give parallelism across groups without giving it up within a group.

An election that cannot start fails closed (never leader). Standby is on, so other replicas exist, and an ungated fallback would let every replica claim at once.

On failover the new leader starts with an empty in-flight set and claims whatever is PENDING. Jobs the old leader published but had not yet marked are published again; jobs it marked QUEUED are already on the queue. Both are the at-least-once duplicates the router and callback already absorb. On shutdown a lane finishes the batch it is sending (10 seconds of grace after shutdown begins, at most 2 minutes per batch) and marks it; whatever is still buffered stays PENDING.

Variable Default Effect
FC_SCHEDULER_ENABLED false Run the scheduler in this process
FC_SCHEDULER_DISPATCHERS 10 Number of lanes (parallel publishers). More lanes help when many groups are active and the broker round trip dominates
FC_SCHEDULER_BATCH_SIZE 500 Most rows one claim asks for
FC_SCHEDULER_BUFFER_CAPACITY 1000 Most jobs between a claim and a lane finishing them; also each lane’s channel size
FC_SCHEDULER_DB_MAX_CONNECTIONS dispatchers + 2 The scheduler’s own connection pool, separate from the API’s so dispatch never competes with requests
FC_DISPATCH_PROCESSING_ENDPOINT http://localhost:<FC_API_PORT>/api/dispatch/process The callback URL stamped on every message. Set it when the router runs in another process
FC_DISPATCH_QUEUE_TYPE Postgres SQS for SQS FIFO queues
FC_DISPATCH_QUEUE_PREFIX none Queue name prefix; required for SQS
FC_DISPATCH_QUEUE_URL, FC_DISPATCH_QUEUE_REGION none Where the SQS account and region come from
FLOWCATALYST_APP_KEY none Required: the callback-token key is derived from it

Fixed in code: poll interval 1 s, lane batch 100, pause and pool caches 60 s, stale thresholds 15 and 75 minutes, stale scan every 60 s. Every variable is in the environment reference.

Situation What happens
The broker rejects some or all of a batch Those jobs stay PENDING and their groups are poisoned for the claims already made; the poller backs off one poll interval and claims them again in order
The QUEUED update fails after a publish Logged; the jobs are published again by a later claim (duplicates are absorbed downstream)
The database is slow or unreachable A claim is bounded at 30 s and a mark at 10 s; errors are logged and the poller backs off
No database pool The scheduler runs a no-op publisher with a loud warning. Never run production like this
FC_DISPATCH_QUEUE_TYPE=SQS without a prefix The server refuses to start
FLOWCATALYST_APP_KEY unset The scheduler logs an error and does not start; jobs stay PENDING
A connection is paused Its jobs stay PENDING, unclaimed, until it is resumed, then go out in group order
A dispatch pool is suspended Its jobs stay PENDING; any already queued are returned to PENDING by the callback
The leader dies Another replica wins the election and claims what is PENDING; see leader failover

All on the metrics port; see the metrics reference.

Metric Watch for
fc_scheduler_pending_backlog_jobs A backlog that keeps growing (counted up to 100,001, sampled by the leader every 30 s)
fc_scheduler_pending_oldest_age_seconds The age of the first due job in claim order: the clearest “dispatch is behind” signal
fc_scheduler_last_successful_poll_timestamp_seconds Stops moving when no leader is claiming
fc_scheduler_held_groups, fc_scheduler_paused_subscriptions, fc_scheduler_paused_connections Jobs that are waiting on purpose
fc_scheduler_jobs_skipped_held_total, fc_scheduler_jobs_dropped_poisoned_total Ordering doing its job; a sustained rate points at a failed group head or a failing broker
fc_scheduler_jobs_unpublished_total Broker rejections
fc_scheduler_stale_jobs_recovered_total{status} Lost messages or dead attempts; a steady rate deserves a look
fc_scheduler_claim_duration_seconds, fc_scheduler_lane_publish_duration_seconds Database or broker latency
fc_scheduler_buffer_in_use, fc_scheduler_inflight_jobs A buffer pinned at capacity means the lanes, not the claim, are the bottleneck

A read, not a locking claim. An earlier design claimed with SELECT … FOR UPDATE SKIP LOCKED. A single active scheduler needs no row locks to keep claimers apart, and a plain read holds nothing while a publish is in progress, so a slow broker cannot pin database locks.

The queue table was tried and retired. Migrations 066 and 067 introduced msg_dispatch_queue: a small, unpartitioned table holding one row per PENDING job, kept exact by the lifecycle, for the scheduler to claim from. Migration 068 removed it. A small table that swings between empty and very full is the query planner’s worst case: when its statistics said “empty”, every statement that joined it was planned as a scan, while the large partitioned job table never misleads the planner in that way. What survived from that work: the lifecycle as the single owner of status (every transition is one guarded UPDATE in dispatchjob/lifecycle.go), the lanes, and the index idx_dispatch_jobs_status_group, which serves the claim, the hold-backs and the sweeps without partial indexes.

Pointers, not payloads. Keeping the payload in the database keeps queue messages small and the job row authoritative: edits, credentials, delay and expiry are read at delivery time.

Decisions: leader-gated processors, BLOCK_ON_ERROR, the router is a poller, time-windowed dispatch reads.