Skip to content

Receivers

The platform delivers work to your application over HTTP: dispatch jobs (an event fanned out by a subscription, or a job created directly) and scheduled-job firings (a cron tick). The FlowCatalyst module mounts the two endpoints for you, checks the delivery signature, and calls the handlers you register.

Route Carries Answers
POST /fc/dispatch one dispatch job (default receiver) 200 ack or defer, 422 reject, 503 retry
POST /fc/dispatch/{endpoint} one dispatch job for a named independent subscriber or process manager (not released yet) 200 ack or defer, 422 reject, 503 retry
POST /fc/scheduled-jobs one scheduled-job firing 202 at once; the job runs in the background

The prefix is flowcatalyst.receivers.path (default /fc). The routes need the HTTP module and carry no session and no request context requirement, because the signature is the authentication. Point the dispatch connection’s (or the job’s) target URL on the platform at these routes; the framework does not set it for you, except for a scheduled job’s target when flowcatalyst.subscription-target-base-url is set (sync).

Only a receiver that has a handler answers. An application that registers no dispatch handler answers 404 NOT_FOUND on /fc/dispatch without looking at the signature, and likewise for /fc/scheduled-jobs. flowcatalyst.receivers.enabled: false removes both routes even when handlers exist, and a disabled module (flowcatalyst.enabled: false) mounts nothing either (applications that only want the token).

How the platform produces these calls is described in Dispatch jobs, Scheduled jobs and Delivery. The signature scheme is in Webhook signatures. The normative text is the FlowCatalyst specification.

Register handlers when the application starts; registration closes once start-up has checked it. A duplicate or malformed registration is an error at once, which fails start-up.

Receivers is a service the module provides. Register in your module’s boot:

public final class BillingModule implements Module {
@Override
public String id() {
return "billing";
}
@Override
public void boot(App app) {
Receivers receivers = app.get(Receivers.class);
Database db = app.get(Databases.class).defaultInstance();
receivers.onDispatch(
"orders:billing:invoice:created",
(Context ctx, DispatchDelivery d) -> {
OnceResult<Integer> sent = d.once(db, "send-invoice", tx -> send(tx, d.jobId()));
return DispatchResult.ack();
});
receivers.onScheduledJob("nightly-export", (ctx, firing) -> JobResult.success());
}
}

send(tx, ...) is your own method taking the open java.sql.Connection. The order of FlowCatalystModule against your module does not matter, because handlers are looked up per request.

Independent subscribers on named endpoints

Section titled “Independent subscribers on named endpoints”

When multiple independent modules or process managers within one service need to subscribe to the same event type — each with its own platform subscription, dispatch pool, retry budget and DLQ — register them on named dispatch endpoints (POST /fc/dispatch/{endpoint}):

receivers.onDispatch("billing", "orders:sales:order:placed", (ctx, d) -> ...);
receivers.onDispatch("audit-notice", "orders:sales:order:placed", (ctx, d) -> ...);

Each named endpoint mounts its own POST /fc/dispatch/{endpoint} route (unregistered endpoints answer 404 before signature verification).

A dispatch pattern is an exact event type (orders:billing:invoice:created), a family ending in :* on a segment boundary (orders:billing:*), or *. The most specific wins: exact, then the longest family, then *. orders:* does not match orders itself. Segments are [A-Za-z0-9._-]+. A scheduled-job code is [A-Za-z0-9._:-]{1,186}.

Every handler receives a request context:

  • the client is the client code (the platform’s client identifier such as acme, never the clt_... id) from the {id}:{code} of the delivery’s X-FlowCatalyst-Client header, or the platform client (_platform, which no real client identifier can equal) for a platform-scoped dispatch job and for every scheduled job;
  • the application is flowcatalyst.application;
  • the correlation id is the envelope’s when it is printable ASCII (no spaces) of at most 200 characters, else generated;
  • the execution id is the dispatch job id or the scheduled-job instance id;
  • the principal and cause are described next.

A dispatch job your own use case wrote in a client’s context comes back as that client: the outbox writes the context’s client as the job’s clientCode, the platform resolves it and sends the header, and the receiving handler’s context (and so any use case it runs) is that client. A job written in the _platform context, or with no client, arrives as _platform. See the write path.

Every handler runs as the application’s service principal, of kind SERVICE, and the delivered message is the cause. A use case a handler runs therefore writes events and an audit row that say who did it and why:

Context field Dispatch job Scheduled-job firing
principal the service principal the same
principal kind SERVICE SERVICE
causation id the job id (X-Dispatch-Job-Id) the instance id
execution id the job id the instance id
permissions empty empty

In the outbox that becomes each event’s causationId and its contextData entries principalId and executionId, and the audit row’s principalId. The platform’s audit entry has no causation field, so the job id reaches the events, not the audit row.

Where the id comes from. The sub of the client-credentials token the module already fetches with flowcatalyst.client-id and client-secret: the platform puts the service account’s principal id there and type: SERVICE beside it. It is read once per token and picked up again when the token is renewed. The token came straight from the platform’s token endpoint, so its signature is not checked.

No principal, no handler. When the token cannot be fetched, or does not name a service principal (its type is USER because the configured credentials are a person’s developer credentials, it has no sub, or it is not a JWT), the receivers run nothing:

  • a dispatch job is answered 503 UNAVAILABLE and the platform retries it;
  • a scheduled-job firing is answered the same 503 instead of 202, so the platform delivers it again; no completion is reported;
  • the reason is logged at ERROR with the job id (never the token); at start-up the module logs the principal it will use at INFO, or the reason it has none at WARN;
  • the flowcatalyst health check is down with the reason while a receiver has handlers.

A use case can admit receiver runs by the kind of principal:

UseCase.named("send-invoice", SendInvoice.class, InvoiceSent.class)
.authorize(
(ctx, cmd) ->
ctx.principalKind() == PrincipalKind.SERVICE
? Optional.empty()
: Optional.of(UseCaseError.authorization("NOT_A_SERVICE", "only the service sends invoices")))

Which account signs a delivery is the platform’s choice: the service account of the job’s connection when the job names one, else, for a job with no subscription, the oldest active service account of the application named by the job code’s first segment. The receiver’s signing secret must be that account’s (why there can be two secrets).

All under flowcatalyst.receivers.. Durations are 30s, 10m and so on. Secrets come from the environment, for example FLOWCATALYST_RECEIVERS_SIGNING_SECRET; see Configuration.

Key Type Default Meaning
enabled boolean true false mounts neither route, even when handlers are registered (start-up warns).
path string /fc Prefix of the routes; literal segments, no trailing /.
signing-secret secret none The shared secret the platform signs deliveries with; used by each receiver that has none of its own.
bearer-token secret none The shared optional bearer token. When effective, Authorization: Bearer must match as well as the signature.
dispatch.signing-secret secret shared one Secret for the dispatch receiver only.
dispatch.bearer-token secret shared one Bearer token for the dispatch receiver only.
scheduled-jobs.signing-secret secret shared one Secret for the scheduled-job receiver only.
scheduled-jobs.bearer-token secret shared one Bearer token for the scheduled-job receiver only.
require-signature boolean true false accepts unsigned deliveries (start-up logs a warning).
dispatch-timeout duration 25s How long a dispatch handler may run. Keep it below the job’s timeout (platform default 30 s).
job-timeout duration 10m How long a scheduled job may run when its firing carries no timeoutSeconds.
job-lock-lease duration 10m Lease of the scheduled-job overlap lock, 1 s to 24 h; refreshed every third of it.
once-retention duration 30d How long once records are kept before the purge deletes them. Keep it longer than the platform can redeliver a job.
once-purge-interval duration 1h How often the background purge runs.
completion-retry-delay duration 1s Wait before the first retry of a failed completion call, 0 to 1 m; doubles.

Dispatch jobs are signed by the service account of the subscription, or of its connection. Scheduled jobs are signed by the application’s service account. They may be different accounts with different secrets. Set the shared signing-secret when one account does both; set the per-receiver secrets when they differ (the shared one is then optional). A receiver uses its own secret when it is set and not blank, else the shared one; the bearer tokens fall back the same way, each independently of the secret.

At start-up, a receiver that has handlers needs a non-blank effective secret when require-signature is true, or start-up fails naming the receiver’s key. A receiver with no handlers needs no secret and answers 404. In Go, deliveries are answered 503 until start-up has checked the registrations (a receiver with handlers needs a secret; exclusive scheduled jobs need a default lock store; the routes must have been taken from Routes()).

A dispatch job is not only an event. The platform has two kinds, EVENT (made from an event by a subscription) and TASK (created directly, for example through its batch endpoint), and for both it sets X-Event-Type to the job’s code. A handler registered for a code receives a TASK job with that code exactly as it receives an event of that type; patterns work the same. How to create such a job is on the module page.

The body is the platform’s envelope, or the raw payload for a dataOnly subscription. The job id and type always come from the headers X-Dispatch-Job-Id and X-Event-Type, which are required; X-FlowCatalyst-Client: {id}:{code} is optional. A malformed header or envelope is 400 VALIDATION and no handler runs. The signature covers the body, so the envelope’s clientCode, but not the client header: a delivery whose header names another client than its envelope’s clientCode is refused for good, 400 CLIENT_MISMATCH, and no handler runs. Only both present and different is a mismatch (an envelope without clientCode, a data-only body, or no header is not one).

A handler receives the request context and a delivery with: the job id, event type, attempt number (empty for data-only), source, subject, message group, correlation id, client, whether the body is data-only, the parsed data and the raw body that was verified. It returns one of three results:

Result Java Go Response Meaning to the platform
Acknowledge DispatchResult.ack() Ack{} 200 {"ack":true} Done.
Defer defer() or defer(Duration) Defer{Delay} 200 {"ack":false,"delaySeconds":n} Not now; reschedule without spending retry budget. Default delay 30 s (Go: DefaultDefer); rounded up to whole seconds.
Reject reject(reason) Reject{Reason} 422 with FlowCatalyst-Outcome: reject Terminal; never retried. The reason is returned after cleaning (non-blank, cut to 500 characters in Go), so never put internals in it.
Situation Response Platform behaviour
Handler returned ack, defer or reject 200 / 200 / 422 As above.
Handler threw (Go: returned an error or panicked), exceeded dispatch-timeout, or returned nothing 503 UNAVAILABLE, fixed message Transient: retried with the platform’s backoff up to the job’s max retries. The cause is logged at ERROR with the job and correlation ids and never returned.
No handler for the type 422 reject no handler for <type> Terminal: a job that can never succeed must not retry.
Bad or missing signature, or bearer 401 UNAUTHENTICATED with details.reason The platform treats 401 and 403 as terminal, so a wrong secret shows at once.
Malformed headers or envelope 400 VALIDATION
Receivers not yet ready, or stopping 503 UNAVAILABLE Retried.
The service principal cannot be resolved 503 UNAVAILABLE, no handler runs Retried. Signature, validation and the no-handler reject come first and need no principal.

A handler that wants a terminal failure returns reject explicitly; throwing is how it says “try again”. On a timeout the handler is cancelled (Java: its virtual thread is interrupted; Go: its context is cancelled and the goroutine is left to finish, tracked, and shutdown waits for it within the drain), but the request does not wait for it to stop, so write handlers that notice cancellation.

A handler can run more than once for one job (a timeout after a commit, a lost response, a retry after a 503). Make it idempotent. The delivery’s job id is the idempotency key, and once does the bookkeeping: it runs the work at most once per (handler name, job id), in one transaction with the record in table fw_dispatch_once.

OnceResult<Integer> first = d.once(db, "send-invoice", tx -> send(tx, "dj_1"));
OnceResult<Integer> second = d.once(db, "send-invoice", tx -> send(tx, "dj_1"));
// first is Ran(1), second is AlreadyDone

work receives the open java.sql.Connection (READ COMMITTED, not auto-commit; it must not commit). The handler name is [A-Za-z0-9._:-]{1,200}.

A record of (handler name, job id) is inserted in the same transaction as the work, so either both commit or neither does. A repeat skips the work (Java: OnceResult.AlreadyDone). A concurrent repeat waits for the first and then skips, or runs if the first rolled back. If the work throws (Go: returns an error or panics), everything rolls back and the failure propagates, so the platform retries. The table is created by the module’s migration set flowcatalyst on the default database.

With a use case. The work can run a use case in the same transaction (Java: useCases.run(useCase, context, command, Tx.of(connection)); Go: Defined.RunJoined(ctx, cx, cmd, tx)), so the record, the use case’s writes and its outbox rows commit or roll back together. What does not compose: an HTTP call, an email or a message send inside the work is in no transaction (a rollback does not unsend it), and a read through the pool does not see the work’s uncommitted writes. Send the job id as the idempotency key on such calls.

Retention. Rows older than once-retention (30 days by default, measured with the application’s clock against processed_at) are deleted by a background task: at start-up and then every once-purge-interval, in batches of 5 000 rows. With several replicas a run takes a service lock without waiting and skips when another replica has it; with no lock store it just runs, because the delete is idempotent. If a job is redelivered after its record was purged, the work runs again, so keep the retention longer than the platform’s retry horizon.

The platform’s HTTP timeout for a firing is 10 s, so the receiver answers 202 {"ok":true} immediately and runs the handler in the background. An unknown job code is 404 NOT_FOUND; a malformed envelope is 400 VALIDATION; 503 while starting or stopping and when the service principal cannot be resolved.

A scheduled-job handler receives the context and a firing (job id and code, instance id, scheduledFor, firedAt, trigger kind, correlation id, payload, whether it tracks completion, timeout, whether it is concurrent, a fencing token, and log(...)) and returns a result: success (optionally with a value sent as JSON), or failure with a message. A throw (Go: a returned error), or no result, is a failure. log(level, message) appends a line to the instance’s log on the platform, best effort, never failing the handler.

Overlap protection is yours, not the platform’s. Unless the firing says concurrent (absent means false), the run takes the lock scheduled-job:{jobCode} (service scope) from the default lock store, with a lease of job-lock-lease refreshed while the handler runs. Pass the firing’s fencing token on to what you write if a stale run must be rejected there (Locks). Start-up therefore fails when such a handler is registered and no lock store is configured: use a database or Redis store across replicas, and the memory store only for one process.

A handler that is safe to overlap with itself (or protects itself, say with the fencing token or a database constraint) can be registered without the lock:

receivers.onScheduledJob(CODE, (ctx, firing) -> JobResult.success(), JobOptions.alwaysConcurrent());

Such handlers do not count when start-up checks for a lock store. The job must be defined on the platform with concurrent true. If a firing arrives with concurrent false (or absent), the handler is not run: the application was asked for an exclusive run and has no lock to give one. The firing is logged at ERROR, and when it tracks completion it is reported FAILURE {skipped:true, reason:"not-registered-for-exclusive-run"}, so the mismatch shows on every tick until the definition or the registration is fixed.

When the job tracks completion, the outcome is reported to the platform; when it does not, nothing is.

What happened Reported
Handler returned a result SUCCESS with the value as JSON (omitted when null; over 10 000 characters it becomes {truncated:true, preview}).
Failure result or a throw FAILURE {error: m} (the exception message, or its class name when blank).
Always-concurrent handler, firing says concurrent=false Handler not run; FAILURE {skipped:true, reason:"not-registered-for-exclusive-run"}.
Lock held by another run Handler not run; FAILURE {skipped:true, reason:"lock-held"}.
Lock store unavailable Handler not run (no exclusion means no run); FAILURE.
Lock lost while running Handler cancelled; FAILURE.
Timeout (timeoutSeconds, else job-timeout) Handler cancelled; FAILURE {error:"timed out after 10s"} at once, while the lock stays held until the handler really returns.
Application stopping Handler cancelled; FAILURE; the module waits up to app.shutdown.drain.

The completion call is retried by the runner itself: three retries after the first attempt, so at most four calls, waiting completion-retry-delay, then twice that, then four times that. After the last failure it is logged at ERROR and dropped; the platform overwrites an earlier report for the same instance, so a late success is safe. The SDK’s own transport retry is switched off for these calls (Java uses a second SDK client built with no retries; Go switches it off), because the two layers would otherwise multiply to up to 16 calls. Log lines are a single best-effort call each.

An application that uses the module only for its service-account token, the definition sync or the health check (an ingestor, say) registers no handlers and does not expose receivers:

  • A receiver with no handler answers 404 NOT_FOUND, the same body as an unknown route, before the signature is looked at. No secret is needed.
  • To remove the two routes entirely, set flowcatalyst.receivers.enabled: false (environment variable FLOWCATALYST_RECEIVERS_ENABLED). Then nothing is mounted and every method on /fc/... is 404, even if a module registers handlers; start-up logs a WARN naming those handlers, because the platform can then never deliver to them. None of the start-up checks for receivers (secret, lock store, routes) apply while receivers are disabled.

One difference between the languages: with enabled true and no handler, Java registers the path, so a GET gets 405 with Allow: POST; Go routes only a receiver that has handlers, so every method is 404.

Security properties of the signature check

Section titled “Security properties of the signature check”

The check is the platform’s webhook signature: hex HMAC-SHA256 over timestamp + rawBody with the secret, in the headers X-FlowCatalyst-Signature and X-FlowCatalyst-Timestamp. It runs before any handler, and before the body is read into one.

  • It fails closed: no secret configured means refusal (with require-signature true).
  • The timestamp (ISO or Unix seconds, compared in whole seconds) must be within 300 s in the past or 60 s in the future of the application’s clock.
  • The signature is compared in constant time; the bearer token is compared as SHA-256 digests.
  • A signature, timestamp or Authorization header sent twice is refused (DUPLICATE_HEADER).
  • The body is read once and those same bytes are verified, parsed and given to the handler.
  • A refusal is 401 with details.reason set to one of MISSING_SECRET, MISSING_SIGNATURE, MISSING_TIMESTAMP, INVALID_TIMESTAMP, TIMESTAMP_EXPIRED, TIMESTAMP_IN_FUTURE, INVALID_SIGNATURE, MISSING_BEARER, INVALID_BEARER or DUPLICATE_HEADER; logged as a WARN naming the code and the correlation id, never a header value or a secret.
  • With require-signature: false an unsigned delivery is accepted, and a signed one is still verified when a secret is configured. The bearer gate applies whenever a token is configured. The platform sends unsigned deliveries when it cannot resolve credentials, so leave require-signature true unless the routes are reachable only from a trusted network.

The platform stand-in serves the token endpoint and records the completion and log calls a scheduled job makes. Helpers sign what the platform signs: the hex HMAC-SHA256 of the timestamp header’s text followed by the body, keyed with the secret, with the timestamp taken from the clock you gave the application, so the application must be built with an injected clock for the timestamp to be inside the tolerance.

FakePlatform (the module’s test-jar) serves the token endpoint; ReceiverTesting signs and sends. The application is built with FLOWCATALYST_BASE_URL pointing at the fake, FLOWCATALYST_RECEIVERS_SIGNING_SECRET and an injected InstantSource.

TestResponse r =
ReceiverTesting.dispatch(client, SECRET, now, "dj_1", TYPE, "clt_1:acme", envelope); // client header null: platform-scoped
TestResponse fired = ReceiverTesting.scheduledJob(client, SECRET, now, firingJson); // 202 when accepted

You rarely need to write the envelope yourself. ReceiverTesting.Delivery builds what the platform sends from what your application wrote to its outbox: Delivery.ofJob(payload) from a DISPATCH_JOB row’s payload and Delivery.ofEvent(payload, jobId) from an EVENT row’s payload, as the platform delivers the event to a subscription. deliver signs and sends it; fire(...) does the same for a scheduled-job firing. From the tickets example:

String item = pg.query("SELECT payload FROM outbox_messages WHERE type = 'DISPATCH_JOB'");
TestResponse r = ReceiverTesting.deliver(Receiving.client(app), SECRET, NOW, ReceiverTesting.Delivery.ofJob(item));
ReceiverTesting.deliver(client, Deliveries.SECRET, now.get(), ReceiverTesting.Delivery.ofEvent(event.toString(), jobId));
TestResponse fired = ReceiverTesting.fire(client, Deliveries.SECRET, now.get(), TicketsDefinitionsModule.SLA_SWEEP, "si_1");

The fake resolves a client the way the platform does, with one stand-in: the platform id of client code acme is clt_acme, so the client header is clt_acme:acme. A job or event without a client code (or with _platform) gets no client header. ReceiverTesting.signature, timestamp, headers and Delivery.headers are there when a test sends the request some other way, such as a real socket.

Wrong secrets, missing signatures and the other refusals are the framework’s own tests; yours only need the happy path and your handler’s results. A worked service using all of this is the support tickets tutorial.