Skip to content

Message router

The message router moves messages from queues to HTTP endpoints. It polls every queue it is configured for, routes each message to a dispatch pool, applies that pool’s concurrency and rate limit, keeps the messages of an ordered group in order, delivers over HTTP, and turns each answer into one action on the broker: acknowledge, retry in place, defer or release.

For the platform’s own dispatch jobs the “endpoint” is the platform’s delivery callback, /api/dispatch/process, which loads the job and delivers it to the real target (see the dispatch scheduler). The router itself knows nothing about jobs, clients or subscriptions. It is a general message router that the platform configures.

It is the internal/router and internal/queue packages, switched on with FC_ROUTER_ENABLED (alias MESSAGE_ROUTER_ENABLED, default off). It needs no database of its own.

The concept pages cover what pools, ordering and delivery mean to a producer and a consumer: dispatch pools, ordering and delivery. This page is how the router is built.

flowchart LR
  CFG["ConfigSource<br/>polls FLOWCATALYST_CONFIG_URL"] -->|"pools and queues"| M["Manager"]
  subgraph Broker
    Q1[["queue A"]]
    Q2[["queue B"]]
  end
  M -->|"one consumer per queue, long-poll"| Q1 & Q2
  M -->|"route by poolCode"| P1["Pool: concurrency, rate limit,<br/>per-group FIFO buffers"]
  M --> P2["Pool"]
  P1 & P2 --> MED["Mediator: circuit breaker,<br/>host client slots, bounded retry burst"]
  MED -->|HTTP POST| T["Endpoint"]
  P1 & P2 -.->|"ack, nack, defer via the source consumer"| Q1 & Q2
  IFT["InFlightTracker"] -.-> M & P1 & P2
Component Responsibility
Server Process lifecycle: supervisors, leader-gating, drain on shutdown, load-balancer registration
Manager Owns the consumers, pools and queues. Polls, deduplicates at route time, picks the pool
Pool A passive worker set: concurrency cap, rate limit, per-group FIFO buffers. Decides the broker action for each outcome
Mediator Delivery: circuit breakers per endpoint, HTTP client slots per host, a bounded retry burst, classification of the response
InFlightTracker Duplicate suppression, receipt-handle freshness, input to stall detection
ConfigSource Polls the configuration document(s), merges them, reconciles pools and queues in place
LifecycleManager Supervises consumers, warning clean-up and coordinated shutdown

Two boundaries carry the design:

  • A pool does not own a queue. The manager polls every queue and routes each message to the pool its poolCode names. One queue feeds many pools and one pool serves many queues, so every acknowledgement travels back to the consumer the message actually arrived on.
  • The mediator decides what an answer means; the pool decides what that means for the broker.
sequenceDiagram
  participant C as Consumer
  participant M as Manager
  participant P as Pool
  participant D as Mediator
  participant E as Endpoint
  C->>M: poll batch
  M->>M: register in tracker, drop duplicate copies
  M->>P: submit (by poolCode)
  alt pool buffer full
    P-->>C: defer with a reserved delay
  else admitted
    P->>P: IMMEDIATE runs now, ordered modes join the group FIFO
    P->>D: deliver (concurrency slot, rate-limit token)
    D->>E: POST (up to 3 attempts in a burst)
    E-->>D: answer
    D-->>P: outcome
    P-->>C: ack, retry in place, or release the group
  end
  1. Poll and deduplicate. Each consumer long-polls its queue. At route time the manager registers the message in the in-flight tracker; a copy that arrives while another copy owns the pipeline is acknowledged and dropped. Two more layers back this up (a process-time check and an SQS pending-delete guard). It rests on one contract every backend must keep: the broker’s message id is stable across redeliveries. SQS uses MessageId, PostgreSQL the row id and NATS the stream sequence.
  2. Pick the pool. poolCode names it. An unknown code falls back to DEFAULT-POOL with a routing warning. A code ending in -DEFAULT-POOL is a per-client fallback that the router synthesises on demand (concurrency 20, no rate limit) and removes after an hour without traffic (FC_ROUTER_SYNTH_POOL_IDLE_SECS). With FC_ROUTER_STRICT_ROUTING=true a message with no pool code, no dispatch mode, or an ordered mode without a group is treated as malformed and acknowledged instead.
  3. Admit or push back. A pool whose buffer is at capacity (max(concurrency × 40, 100)) hands the message back with a deferral for a delay it computes (below). It is not a failure.
  4. Branch on mode. IMMEDIATE dispatches concurrently, one goroutine per message, bounded by the pool’s semaphore. NEXT_ON_ERROR and BLOCK_ON_ERROR join their group’s FIFO buffer, drained by a single drainer per group. An ordered message with no group also dispatches concurrently: ungrouped messages would otherwise all share one empty group key and one drainer.
  5. Deliver. The mediator checks the endpoint’s circuit breaker, waits for a token from the pool’s rate limiter, borrows an HTTP client slot for the host, and delivers. It retries a bounded burst itself (3 attempts, 1 s and 2 s apart) for transient failures, so the pool always sees the verdict after those retries, never a first response.
  6. Resolve. The pool turns the outcome into exactly one broker action and, for an ordered group, decides whether the rest of the group continues.

Every outcome collapses to one of three actions: acknowledge (the message is finished), retry in place (it stays in this process; the broker cannot see it) or release (it, and its whole ordered group, go back to the broker with a delay).

Answer Action Why
2xx Acknowledge Delivered
2xx with {"ack": false} Retry in place on the deferred curve (5 s to 60 s), or release at exactly the named delay The endpoint is healthy and saying “later”. With notBefore or delaySeconds, on a broker that honours a delayed return, the message is released at once with that delay
3xx Acknowledge Not followed: a 301, 302 or 303 would turn the POST into a GET and drop the body, and the target would repeat it every time
4xx (except 429) Acknowledge A client error; retrying cannot change the answer
429 Retry in place, honouring Retry-After The endpoint is reachable and pacing
500, 501, 505 and up Acknowledge, after a single attempt The application ran and answered; sending the same message again cannot help. A warning records the dropped message
502, 503, 504 Release the group (after the burst) Never reached a working application
Connection error or timeout Release the group The same class as a gateway error
Circuit breaker open Release the group No attempt was made
A duplicate copy Acknowledge Another copy owns the pipeline

For the platform’s dispatch jobs the callback absorbs delivery failures itself: it records the attempt, reschedules or fails the job, and answers 200 {"ack": true}. Its only ack: false answers mean “not yet” (a job whose not_before is ahead, or a delivery still in progress elsewhere), and it answers 503 when it could not handle the call. So for dispatch jobs, retries and modes are enforced by the platform; the router’s outcome handling governs messages whose failures it can see.

In-place retry is bounded. A message may be retried in place at most 10 times (maxInPipelineAttempts, on a curve from 100 ms to 5 minutes). Past that it is released with its backoff as the delay. Unbounded, an endpoint answering 429 or ack: false for ever would pin the message and its whole group in memory, beyond the reach of the broker’s expiry and dead-letter handling.

After a release, the cadence is the broker’s (visibility timeout or ack wait), not the router’s curve; the circuit breaker is what protects the endpoint from the redelivery rate. Every backend honours the release delay: SQS through ChangeMessageVisibility, PostgreSQL by making the row visible later, NATS through NakWithDelay.

ack: false does not trip the breaker. It is a deliberate deferral by a healthy endpoint, not a failure. See ack=false means deferral.

One breaker per endpoint, tripped by failure rate, not a count: it opens when at least half of the last 100 calls failed, once at least 10 calls are buffered. It stays open for 5 seconds after the last failure, then lets trial requests through; 3 consecutive successes close it, and any failure re-opens it. The dashboard lists breakers, and an operator can reset one or all (/monitoring/circuit-breakers).

The three modes share the same FIFO buffer and in-order delivery. They differ only in what a terminal failure does to the rest of the group:

Mode On a terminal failure of the head
IMMEDIATE No group; messages dispatch concurrently
NEXT_ON_ERROR The group moves on to the next message. The default when no mode is given
BLOCK_ON_ERROR The group stops; the untried successors are acknowledged off the queue, not released

A release takes the whole group. Releasing only the failed head would leave its successors buffered here, and the head would come back behind them on redelivery. Both ordered brokers then redeliver a group in order: SQS FIFO orders by MessageGroupId, and the PostgreSQL queue makes only the earliest eligible row of each group claimable (an earlier row that is claimed, or released with a delay, keeps the rest of its group back). Ordered work on a standard, non-FIFO SQS queue would reorder on release.

Why BLOCK_ON_ERROR acknowledges the successors. Released successors would come back on the broker’s own timer, which has nothing to do with the failure being fixed. By then the head would have been acknowledged, so the first successor would become the new head and be delivered: exactly what the mode exists to prevent. Nothing is lost by acknowledging, because the queue copy is a delivery attempt, not the data. For dispatch jobs the rows stay in the platform; the router reports the acknowledged siblings to POST /api/dispatch/settled (when FC_ROUTER_PLATFORM_URL is set), which returns them to PENDING, and the platform’s reaper is the backstop. See BLOCK_ON_ERROR.

An endpoint can also ask the router to flush a group by answering 2xx with {"flushGroup": true}. The router then acknowledges that group’s further messages without calling the endpoint, for delaySeconds (default 60 seconds, at most 5 minutes); the first message after the window is a probe. This is a per-group circuit breaker that only the target may trip, and it is safe only when the target already holds the records and will re-drive them itself: a target whose messages carry the only copy of the payload must never set it. Active suppressions are listed at /monitoring/group-flushes, and an operator can lift one early.

Back-pressure without head-of-line blocking

Section titled “Back-pressure without head-of-line blocking”

One queue feeds many pools. If a consumer stopped polling whenever any pool it fed was full, one slow pool at concurrency 1 with a large backlog would stall its client’s whole queue and starve every other pool on it. The router avoids that in three ways.

The consumer keeps polling while any pool its last batch fed has room, and, with all of them full, while its per-queue deferral budget lasts (FC_ROUTER_DEFERRAL_BUDGET, default 15,000). It pauses only when every pool is full and the budget is spent, and wakes when a pool frees up or the earliest deferral comes due. The budget exists because a deferred message is still in flight from the broker’s point of view, and SQS FIFO stops delivering from a queue at 20,000 messages in flight. SQS FIFO serves oldest first, so the budget must cover the slow pool’s backlog to reach the messages behind it. A backlog beyond about 15,000 on a shared FIFO queue needs its own queue.

A message for a full pool is deferred with a reservation. The pool measures its completion rate over the last five minutes and keeps a cursor of when the last deferred message was told to return. Each new deferral is booked one slot (1/rate) after the later of that cursor and the buffer’s own drain time. Deferred messages therefore come back spaced at the pool’s pace, in the order they were deferred, each bouncing about once. There is deliberately no early return: an early return finds the pool still full and re-books at the back of the schedule.

The horizon caps a reservation at FC_ROUTER_DEFERRAL_MAX_DELAY_SECONDS (one hour), with backward jitter over its last quarter so a long tail trickles in. A reservation is not recalled: if a pool’s concurrency is raised mid-backlog, already-deferred messages still return on the old schedule, bounded by the horizon.

Every backend counts the redelivery. SQS increments ApproximateReceiveCount (a redrive policy counts it against maxReceiveCount); NATS spends a delivery attempt and holds an ack-pending slot for the whole delay, which is why the router’s NATS consumers default to unlimited max-deliver and max-ack-pending: the router owns give-up, and a finite cap would silently drop work that was never attempted. A deferred copy keeps its tracker entry, so a second copy of the same message arriving meanwhile (for example the platform republishing a job left QUEUED too long) is dropped as a duplicate.

Not addressed here: one slow group monopolising a shared pool’s buffer. A message group that slow belongs in its own pool. See the router is a poller.

A pool’s rate limit is a token bucket in deliveries per minute, with a burst of one minute’s worth. A delivery that finds the bucket empty waits inside the pool, holding its concurrency slot, with nothing in flight to the endpoint. On the dashboard such a pool looks busy (workers at full concurrency) but idle (nothing mediating). The tell is the pool’s Rate Limited count and is_rate_limited in /monitoring/pools. See dispatch pools and the runbook pool draining slowly.

The router learns its pools and queues only from configuration documents it polls: FLOWCATALYST_CONFIG_URL, a comma-separated list of URLs. Documents merge by code, first definition winning; a later definition of the same code with different settings is logged as a conflict and ignored. The platform serves its own document at GET /api/dispatch/router-config: its dispatch pools (client pools namespaced {client}-{pool}, platform pools platform-{pool}) and its per-tenant, per-priority queues. The per-client -DEFAULT-POOL codes are omitted because the router synthesises them.

Setting Effect
FC_ROUTER_CONFIG_INTERVAL_SECONDS Re-fetch interval (default 30 s). The platform’s document carries an ETag and answers 304, so a short interval is cheap. In the same process the platform also nudges the router whenever a client, pool or subscription is written
FC_ROUTER_CLIENT_ID, FC_ROUTER_CLIENT_SECRET, FC_ROUTER_PLATFORM_URL client_credentials for fetching the platform’s document. The token is sent only to URLs on the platform’s origin, never to other config services in the list. Setting one of id and secret without the other, or either without the platform URL, stops the server at start-up

Reconfiguration is in place. A pool that config still wants is re-capped and re-rate-limited where it stands; a queue whose definition is unchanged is left alone. A removed pool stops receiving new messages at once and drains its buffer in the background. A removed or changed queue’s consumer stops polling at once but lingers until nothing in flight refers to it, so buffered messages can still be acknowledged. A queue that does not exist yet (the platform creates a client’s queue on its first publish) gets no consumer and no warning until it appears.

Backend Used for Ordering Notes
SQS FIFO Production on AWS Per MessageGroupId Up to 20,000 in flight per queue. Release and deferral use ChangeMessageVisibility
PostgreSQL (queue_messages) fcdev, and deployments without a managed queue Only the earliest eligible row of a group is claimable The table is created by the platform, never by the router
NATS JetStream Deployments on NATS Redelivery of a deferred group is not ordered by the broker; reservations are spaced at least a second apart Does not honour a delayed return for ordered heads, so delay-bearing deferrals retry in place instead. Each pool also keeps a hand-back gate that remembers, per ordered group, the members it handed back, and admits a member only when none ahead of it is still out, so the router keeps a handed-back group in order itself (in memory, within one pool and one process)

The router does not extend a message’s visibility while it works. It lets the window lapse and recognises the redelivery (the tracker adopts the fresher receipt handle): the same path a crashed router relies on, exercised all the time.

Start-up launches the supervisors first (notifier, stall detector, queue-health monitor, in-flight reaper, broker-stats refresher) and then the pools. With FC_STANDBY_ENABLED=true, the router runs a Redis election on FC_STANDBY_LOCK_KEY (default fc:server:leader; the lock lives 30 seconds and is refreshed every 10) and starts pools only while it is the leader. The per-group drainer is in-process, so two active routers would deliver a group’s messages concurrently.

Shutdown, and leadership loss, run in order:

  1. Deregister from the load balancer (with FC_ALB_ENABLED), so no new traffic arrives.
  2. Stop polling. Messages already routed keep running: a consumer carries two cancellations, one for its poll loop and one for its work, and only the first is used here.
  3. Drain: wait for the tracker to empty, up to FC_DRAIN_TIMEOUT_SECONDS (60).
  4. Stop the lifecycle manager, the manager, then the election.

A pool stopped this way flushes its buffered messages and releases their tracker entries, so the broker’s redeliveries are accepted cleanly by the next leader rather than dropped as duplicates.

Delivery timeouts. A delivery may take up to 15 minutes (the mediator’s timeout); that is a contract with endpoints, and the platform’s stale-recovery thresholds are sized around it. FLOWCATALYST_DEV_MODE=true uses 30 seconds and HTTP/1.1 instead. HTTP/2 connections are pinged after 30 seconds of read silence and closed if the ping is not answered in 15 (FC_ROUTER_HTTP2_READ_IDLE_TIMEOUT_SECONDS, FC_ROUTER_HTTP2_PING_TIMEOUT_SECONDS), so a dead connection is found in under a minute.

Mounted on the API listener under FC_ROUTER_HTTP_PREFIX (/router), protected by Basic authentication (FC_ROUTER_AUTH_USER, FC_ROUTER_AUTH_PASS; AUTH_MODE=NONE turns it off):

Path What
/monitoring/dashboard The live dashboard: pools, queues, in-flight messages, breakers
/monitoring/pools, /monitoring/pool-stats, /monitoring/mediating Pool state, including is_rate_limited, and what is being delivered right now
/monitoring/queues, /monitoring/queue-stats, /monitoring/consumer-health, /monitoring/broker-stats Queue and consumer state
/monitoring/health, /monitoring/warnings, /monitoring/stream-health Overall health, recent warnings, and the stream processor’s loops when it runs in the same process
/monitoring/in-flight-messages (and /detail, /{messageId}/ack) What is in the pipeline; an operator can acknowledge a stuck message
/monitoring/blocked-groups Live message groups across pools, including pools still draining
/monitoring/circuit-breakers (and /reset-all, /{name}/reset) Breaker state and reset
/monitoring/group-flushes Active group suppressions, with a clear action
/monitoring/standby-status Which instance holds the lock
/health/live, /health/ready, /health/startup Probes
/metrics Prometheus metrics for the router
/debug/ pprof and a full dump, only with FC_DEBUG_ENDPOINTS_ENABLED and authentication

SIGQUIT writes the same dump (workers, held groups, every goroutine) to stderr and keeps running; a second SIGQUIT within 5 seconds dumps and exits.

Variable Default Effect
FC_ROUTER_ENABLED false Run the router
FLOWCATALYST_CONFIG_URL none Configuration documents (comma-separated). Without one the router has no queues or pools
FC_ROUTER_CONFIG_INTERVAL_SECONDS 30 Config re-fetch interval
FC_ROUTER_DEFERRAL_BUDGET 15000 Deferred messages one queue may have out before polling pauses
FC_ROUTER_DEFERRAL_MAX_DELAY_SECONDS 3600 The reservation horizon
FC_ROUTER_SYNTH_POOL_IDLE_SECS 3600 Idle time before a synthesised fallback pool is removed
FC_ROUTER_STRICT_ROUTING false Acknowledge malformed messages instead of falling back
FC_DRAIN_TIMEOUT_SECONDS 60 Drain bound on shutdown and leadership loss
FC_ROUTER_PLATFORM_URL none Where to report settled BLOCK_ON_ERROR siblings, and the platform the router credentials belong to
FC_NOTIFY_WEBHOOK_URL, FC_NOTIFY_MIN_SEVERITY, FC_NOTIFY_BATCH_INTERVAL_SECONDS none, WARNING, package default Warning notifications to a webhook
FC_ALB_ENABLED and FC_ALB_* off Register the leader with a load-balancer target group
FLOWCATALYST_DEV_MODE false 30-second delivery timeout and HTTP/1.1

Pool concurrency and rate limits are not environment variables: they come from the dispatch pools in the configuration document. See the environment reference.

Situation What happens
An endpoint is down (502 to 504, connection errors) The burst fails, the group is released with a delay, the breaker opens if the failure rate crosses 50%, and the broker redelivers
An endpoint answers 500 One attempt, then acknowledged with a warning; for dispatch jobs the callback has already recorded the failure and scheduled the retry
A pool is full New messages for it are deferred on the pool’s schedule; other pools on the same queue keep flowing
An endpoint defers for ever After 10 in-place retries the message is released to the broker, whose expiry and dead-letter policy then apply
The router crashes Unacknowledged messages become visible again after their visibility timeout and are redelivered; duplicates are absorbed by the platform callback
The leader loses its Redis lock It stops polling, drains, and releases its buffers; a standby that takes the lock starts its pools
The config URL is unreachable The last good configuration stays in force; the fetch is retried
A configured queue does not exist yet No consumer and no warning; it is picked up when it appears

Served at <prefix>/metrics: fc_messages_submitted_total, fc_messages_rejected_total, fc_messages_processed_total, fc_rate_limit_exceeded_total, fc_mediation_duration_seconds, fc_consumer_polls_total, fc_consumer_errors_total, fc_queue_messages_total, fc_circuit_breaker_calls_total and fc_router_panics_recovered_total, labelled by pool or queue. See the metrics reference and monitoring.