Cloudflare

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

PieceCloudflare productHolds
The APIWorker fetch/ingest, devices, subscriptions, tracking, the bundle
Each journeyWorkflowsOne instance per entry: durable steps, sleeps, wake-ups
The dataHyperdrive, PostgresEvents, profiles, the entry ledger, reporting, the routes
EmailEmail SendingThe send_email binding
Reports from your apiQueuesJourneyQueue batches, with a dead letter queue
The segment sweepCron triggerSegment 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 suppression table uses UNIQUE NULLS NOT DISTINCT).
  • The engine's tables created by your migrations. See Postgres.
bash
pnpm add sendwend zod react react-dom postgres
pnpm add -D wrangler @sendwend/studio

The Worker entry

ts
// src/index.ts
import { type JourneyEnv, journeyWorker } from 'sendwend/cloudflare';
import { postgresJsStore } from 'sendwend/postgres-js';
import { cloudflareEmailTransport } from 'sendwend/transports/cloudflare-email';
import config from '../workflow.config';

interface Env extends JourneyEnv {
  HYPERDRIVE: { connectionString: string };
  EMAIL: NonNullable<JourneyEnv['EMAIL']>;
}

const journeys = journeyWorker<Env>({
  config,
  store: (env, database) =>
    postgresJsStore(env.HYPERDRIVE.connectionString, database),
  email: (env) => cloudflareEmailTransport({ binding: env.EMAIL }),
});

/** The wrangler `workflows` binding's class_name. */
export const AcmeJourneyRunner = journeys.Runner;

export default {
  fetch: journeys.fetch,
  scheduled: journeys.scheduled,
  queue: journeys.queue,
};

journeyWorker returns everything the Worker exports:

MemberExport it asDoes
RunnerThe class_name of the Workflow bindingThe one generic runner every journey instance executes
fetchdefault.fetchThe HTTP API
scheduleddefault.scheduledThe segment sweep, on the cron trigger
queuedefault.queueThe JourneyQueue consumer
sweepNot exportedThe 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

json
{
  "name": "acme-workflow",
  "main": "src/index.ts",
  "compatibility_date": "2026-09-12",
  "compatibility_flags": ["nodejs_compat"],
  "workflows": [
    {
      "name": "acme-journey",
      "binding": "JOURNEY",
      "class_name": "AcmeJourneyRunner"
    }
  ],
  "hyperdrive": [
    {
      "binding": "HYPERDRIVE",
      "id": "<hyperdrive id>",
      "localConnectionString": "postgres://postgres:pw@localhost:5432/acme"
    }
  ],
  "version_metadata": { "binding": "CF_VERSION_METADATA" },
  "send_email": [{ "name": "EMAIL" }],
  "queues": {
    "consumers": [
      {
        "queue": "journey",
        "max_retries": 8,
        "dead_letter_queue": "journey-dead"
      }
    ]
  },
  "vars": {
    "ENVIRONMENT": "production",
    "WORKFLOW_ORIGIN": "https://workflow.acme.test"
  },
  "triggers": { "crons": ["*/15 * * * *"] }
}
EntryRequiredWhy
nodejs_compatYesThe bearer check uses node:crypto's timingSafeEqual; postgres.js and react-dom need Node APIs
workflowsYesBinding JOURNEY, the runner class
hyperdriveYesBinding HYPERDRIVE, the engine's Postgres. localConnectionString is what wrangler dev uses
version_metadataRecommendedBinding CF_VERSION_METADATA: each new version makes its own bundle live
send_emailWhen sending through Cloudflare EmailBinding EMAIL
queues.consumersWhen producers use JourneyQueueExport queue too
triggers.cronsYes, in practiceWithout 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

VariablePurpose
API_TOKENBearer for every route but /health and /t/... (a secret)
WORKFLOW_ORIGINPublic origin for email tracking and push delivery reports
ENVIRONMENTWhich runtime entry and APNs environment apply; production when unset
APNS_PRIVATE_KEY_BASE64The APNs .p8 key, base64
GOOGLE_APPLICATION_CREDENTIALS_BASE64The Firebase service account JSON, base64
VAPID_PUBLIC_KEY, VAPID_PRIVATE_KEYThe Web Push key pair
APNS_RELAY_ORIGINDevelopment 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.

Email

Pass email explicitly; a Worker whose workflows send email without a transport fails at startup.

  • Cloudflare Email Sending: cloudflareEmailTransport({ binding: env.EMAIL }) with the send_email binding. wrangler dev only 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 }) from sendwend/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:

bash
wrangler queues create journey
wrangler queues create journey-dead

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:

bash
pnpm exec sendwend generate --out src/db/workflow.ts   # then let drizzle-kit write the migration

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

bash
wrangler secret put API_TOKEN
pnpm exec sendwend plan --database-url $DATABASE_URL
wrangler 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=1 applies 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.

bash
curl -X POST https://workflow.acme.test/bundle/deploy -H "authorization: Bearer $API_TOKEN"

Local development

bash
wrangler dev
curl -X POST http://localhost:8787/bundle/deploy   # once, after start and after changing a journey

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.sleep lasts 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 pass authorize. A production Worker without either answers 503 on everything but /health and /t/.... The tracking routes stay public by design. See Authentication.
  • POST /deploy is 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/forget stops the user's instances (terminate) and deletes their data only once each is known stopped. An instance that will not stop answers erased: 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 live in the logs after a deploy.