Cloudflare
Deploy the engine as a Cloudflare Worker on Cloudflare Workflows, with Postgres through Hyperdrive, Email Sending, Queues and a cron trigger, where `wrangler deploy` is the whole deploy.
This page is for a team deploying the engine on Cloudflare. At the end you will have a Worker that serves the API, runs every journey as a Cloudflare Workflows instance, keeps its data in your Postgres through Hyperdrive, sends email through Cloudflare Email Sending, consumes reports from a queue, and runs the segment sweep on a cron. How the runner relates to the IR is on architecture.
What runs where
| Piece | Cloudflare product | Holds |
|---|---|---|
| The API | Worker fetch | /ingest, devices, subscriptions, tracking, the bundle |
| Each journey | Workflows | One instance per entry: durable steps, sleeps, wake-ups |
| The data | Hyperdrive, Postgres | Events, profiles, the entry ledger, reporting, the routes |
| Email Sending | The send_email binding | |
| Reports from your api | Queues | JourneyQueue batches, with a dead letter queue |
| The segment sweep | Cron trigger | Segment membership, clock-only entries, date triggers |
Workflows is the execution engine only. The workflow definitions are data (IR in Postgres), so one Workflow binding and one runner class run every journey.
Prerequisites
- A Workers paid plan (Workflows' limits below are the paid plan's).
- A Postgres database reachable from Hyperdrive, Postgres 15 or later (the
suppressiontable usesUNIQUE NULLS NOT DISTINCT). - The engine's tables created by your migrations. See Postgres.
The Worker entry
journeyWorker returns everything the Worker exports:
| Member | Export it as | Does |
|---|---|---|
Runner | The class_name of the Workflow binding | The one generic runner every journey instance executes |
fetch | default.fetch | The HTTP API |
scheduled | default.scheduled | The segment sweep, on the cron trigger |
queue | default.queue | The JourneyQueue consumer |
sweep | Not exported | The sweep, for calling yourself |
store is called per request and per workflow run with the config's database ({ schema }, workflow by default). postgresJsStore opens one connection with a 2-second idle timeout and closes it after the request or run, because a Worker cannot share a socket across requests and Hyperdrive keeps the real pool next to the database.
Other options: env (a zod schema over vars and secrets, checked on first run), observer, messages, runtime, contractMode: 'report' and authorize. authorize is covered on Authentication.
wrangler.jsonc
| Entry | Required | Why |
|---|---|---|
nodejs_compat | Yes | The bearer check uses node:crypto's timingSafeEqual; postgres.js and react-dom need Node APIs |
workflows | Yes | Binding JOURNEY, the runner class |
hyperdrive | Yes | Binding HYPERDRIVE, the engine's Postgres. localConnectionString is what wrangler dev uses |
version_metadata | Recommended | Binding CF_VERSION_METADATA: each new version makes its own bundle live |
send_email | When sending through Cloudflare Email | Binding EMAIL |
queues.consumers | When producers use JourneyQueue | Export queue too |
triggers.crons | Yes, in practice | Without it, segments entered by the clock alone, date triggers and maintenance never run. Export scheduled |
The reference monorepo also sets "placement": { "mode": "smart" } so the Worker runs near the database, since every step is a few round trips to Postgres, and serves the Worker only on a custom domain ("workers_dev": false, "preview_urls": false, a routes entry with custom_domain: true).
Environment
| Variable | Purpose |
|---|---|
API_TOKEN | Bearer for every route but /health and /t/... (a secret) |
WORKFLOW_ORIGIN | Public origin for email tracking and push delivery reports |
ENVIRONMENT | Which runtime entry and APNs environment apply; production when unset |
APNS_PRIVATE_KEY_BASE64 | The APNs .p8 key, base64 |
GOOGLE_APPLICATION_CREDENTIALS_BASE64 | The Firebase service account JSON, base64 |
VAPID_PUBLIC_KEY, VAPID_PRIVATE_KEY | The Web Push key pair |
APNS_RELAY_ORIGIN | Development only: the local APNs relay |
Secrets go in with wrangler secret put, and locally in .dev.vars. Never put them in the config.
Hyperdrive to Postgres
Create a Hyperdrive configuration for the engine's database and turn its query caching off (caching: { disabled: true } on the Hyperdrive config). The engine reads wake subscriptions, profiles and segment membership right after writing them, and a cached answer up to 60 seconds old misses wakes and decides on stale data.
One database schema per Worker. The routing tables (trigger, segment, the live deployment row) are global, so two Workers on one schema swap each other's routes on every deploy. Give staging and production their own database: { schema } or their own database.
Pass email explicitly; a Worker whose workflows send email without a transport fails at startup.
- Cloudflare Email Sending:
cloudflareEmailTransport({ binding: env.EMAIL })with thesend_emailbinding.wrangler devonly simulates it and writes the rendered email to a file.cloudflareEmailTransport({ accountId, apiToken })sends through the REST API instead, which works outside a Worker too. - Amazon SES:
sesEmailTransport({ region, credentials })fromsendwend/transports/ses, with credentials from the Worker's env, since a Worker has no execution role.
Cloudflare Email rejects a List-Unsubscribe header with a non-TLS URI, so the one-click unsubscribe header is only sent with an https WORKFLOW_ORIGIN. wrangler dev on http://localhost sends none. Which provider sends is independent of where the workflow runs; the delivery rules are on delivery.
Queues
Create the queue and its dead letter queue once, before the first deploy:
Export journeys.queue and declare the consumer as above. The consumer handles one batch at a time and retries a failed one with a backoff from 30 seconds, doubling up to 15 minutes, until max_retries hands it to the dead letter queue. A batch the contract refuses is retried the same way, so a producer deployed ahead of the engine passes once the engine catches up. Only a batch for an erased user is acknowledged unapplied. With max_retries: 8 the backoff covers roughly an hour of outage. The producer side is on Sending events.
Create the tables
Nothing creates or alters the engine's tables at runtime. Generate them and migrate before the first deploy:
If the tables are missing or behind, POST /bundle/deploy answers 503 listing every missing table or column, and a new version that tries to apply its own bundle logs the failure and retries a minute later. See Postgres.
Deploy
sendwend plan holds the bundle against the journeys still running and exits non-zero on a problem (versioning). Run it in CI ahead of wrangler deploy: on Cloudflare a published version's code serves at once, so the host's own 409 comes too late to protect a running journey from a template change.
wrangler deploy makes the bundle live
The journeys are compiled into the Worker, so a new version carries its own bundle. With the CF_VERSION_METADATA binding, each new version makes that bundle live by itself, with nothing to call afterwards:
- The first request, cron run or queue batch an isolate serves reads which version's bundle is live (one row,
deployment) and applies its own only over an older version, in the same transaction that records it. - Isolates of the old version keep serving for a few seconds after a deploy; they can never put their routes back. Until the new version first runs, events follow the old routes.
- The check runs once per isolate, in the background. A failure, such as migrations not applied, is logged and retried a minute later. If the bundle would break in-flight journeys, the routes are left alone and the error is logged;
POST /bundle/deploy?force=1applies it anyway. - With a gradual deployment, the newest version's bundle goes live as soon as that version serves its first request, whatever share of traffic it has.
Without the binding, call POST /bundle/deploy with the bearer after every deploy that changes a journey.
Rolling back
wrangler rollback restores an older version, which does not apply itself over the newer one. Call POST /bundle/deploy after a rollback: it applies the running version's bundle whatever is live and records that version as the live one, so a newer version that serves again later puts its own bundle back.
Local development
Set ENVIRONMENT=development in .dev.vars to run open and in fast-forward (timeScale). wrangler dev (workerd) cannot make HTTP/2 subrequests, which APNs requires: run startApnsRelay from sendwend/apns-relay in Node and point APNS_RELAY_ORIGIN at it. A deployed Worker needs no relay, and production ignores the variable.
Workflows limits
On the paid plan:
- An instance's wall time is unlimited.
- A single
step.sleeplasts at most 365 days. - 10,000 steps per instance by default, configurable up to 25,000. Sleeps do not count, but every wait attempt costs a few steps.
- A step's result is at most 1 MiB.
- A completed instance's state is kept 7 days by default, and up to 30 on a paid plan.
The engine sits within these on its side too: an event payload is at most 128 KiB as JSON, because a triggering event's payload travels in the instance's parameters for the whole journey.
Deployment notes
- Authorization. Set
API_TOKEN, or passauthorize. A production Worker without either answers 503 on everything but/healthand/t/.... The tracking routes stay public by design. See Authentication. POST /deployis closed in production. The Worker carries its bundle, so a hand-posted bundle answers 409. Deploy by publishing a version.- The cron is the upkeep. The sweep spends a bounded time (about 30 seconds on the segments, as much on date triggers) and the next one carries on where it stopped. A 15-minute cron starts a date-triggered send within 15 minutes; run it more often around a large send if that matters.
- Erasure.
POST /users/forgetstops the user's instances (terminate) and deletes their data only once each is known stopped. An instance that will not stop answerserased: false, and the cron retries it. - Click classification. On Cloudflare the engine knows the requesting network, so clicks from cloud and mail-security networks are classified as machine clicks. AWS and Node do not have that signal.
- Observability. The reference monorepo enables Workers Logs and uploads source maps, and watches for
[workflow] version … is livein the logs after a deploy.