Sending events

Sending events

The caller side of the engine. Report profiles and events with JourneyClient or JourneyQueue, register push devices, merge visitors into users, and call the HTTP API from any language.

This page is for the service that knows what users do: an api server, a webhook handler, a job. At the end it will report profiles and events to the engine, register push devices, read and change subscriptions, and retry safely. TypeScript callers use sendwend/client; anything else calls the same HTTP API, documented at the end.

Three ways in

PathImportUse it when
JourneyClientsendwend/clientA TypeScript service calling the engine over HTTP
JourneyQueuesendwend/clientA producer on Cloudflare that must not lose a report or wait for the engine
HTTPnoneAny other language, or a script

All three carry the same unit: a batch of one profile patch and the events that belong to it.

Create the client

sendwend/client is plain fetch with no dependencies.

ts
import { contract } from '@acme/workflow-contract';
import { JourneyClient } from 'sendwend/client';

export const journeys = new JourneyClient({
  contract,
  origin: 'https://workflow.acme.test',
  token: process.env.WORKFLOW_API_TOKEN,
});
OptionMeaning
originThe engine's public origin. A trailing slash is ignored
tokenIts API_TOKEN, sent as Authorization: Bearer <token>. Omit it against an open local instance
contractThe shared defineContract(...). Types event names, payloads and profile patches, and checks them before anything is sent
fetchA fetch implementation, the global one by default. Wrap it to add a timeout or tracing

With a contract, a payload or profile patch it refuses throws JourneyValidationError before the request, with issues naming the field paths. A request that fails throws JourneyClientError with path, status and body, so a caller can log it without failing the request that triggered the report. How the token is checked is on Authentication.

Report with ingest

ingest is the one way to report. The profile and the events it belongs to travel as one batch:

ts
await journeys.ingest({
  userId: user.id,
  profile: { email: user.email, name: user.name },
  events: [
    {
      event: 'login',
      payload: { method: 'google' },
      id: `login-${session.id}`,
    },
  ],
});

The engine checks the whole batch first: one bad part refuses all of it, so a producer never has half a report applied. Then it applies the batch in a fixed order:

  1. If both userId and visitorId are given, the visitor merges into the user.
  2. The profile patch is merged.
  3. The events are recorded in order, each one waking waiting journeys and starting triggered ones.

That order is the reason to send the profile with the event. With separate calls, an email step could run before the address arrives and settle as no_recipient. Identify the properties a journey reads before, or with, the event that starts it.

The answer says what happened:

json
{
  "profile": {
    "ok": true,
    "props": { "email": "ada@acme.test", "name": "Ada" },
    "woke": 0,
    "started": []
  },
  "events": [{ "id": "login-s_81", "stored": true, "woke": 0, "started": [] }]
}

Each event result names the id it was recorded under, stored: false when that id was already in the log, how many waiting journeys it woke, and the journeys it started.

Profile rules

  • Values are scalars: string, number or boolean. Nested objects are refused with a 400.
  • null removes a property. It is the only way to unset one.
  • The patch is merged, not replaced: properties the patch does not name stay as they are.
  • Each property keeps the value with the latest at. The client stamps the batch with the time it was built, so a redelivered batch cannot put an old email address back.
  • With a contract, the patch is checked against its profile schema. Declare a field optional(...) when your app does not write it for every user a journey can reach (contract).

Event rules

  • event names an event the contract declares. Names starting with $ are reserved.
  • ts is epoch milliseconds, a non-negative integer no later than five minutes ahead of the engine's clock. The client fills in now when it is omitted.
  • A payload may be at most 128 KiB as JSON (MAX_EVENT_PAYLOAD_BYTES). A larger one refuses the batch. A triggering event's payload travels with the journey instance for its whole life, and the runtimes cap those parameters.
  • A userId cannot begin with visitor:.

Give each event an id

id is the occurrence's identity for that user, and sending the same id twice records it once. This matters because every count- and window-based condition reads the event log: a second copy of one event silently changes what a journey decides.

Only the sender knows whether two deliveries describe one occurrence or two, so the engine never guesses. An event without an id gets a fresh one and counts as its own occurrence. JourneyClient fills in a random id when you leave it out, which means calling ingest again after a timeout records the event twice. Pass an id you can reproduce:

ts
events: [
  { event: 'purchase', payload: { value: 49 }, id: `order-${order.id}-paid` },
];

Use something that identifies the occurrence, not the event name: a row id from your own system, an upstream webhook's delivery id, a message id from your queue. The unique key is (user_id, event_id), so two users may reuse an id without either losing an event. A retried batch is safe end to end: a property older than the stored one is skipped, a stored event id is skipped, and the journeys a first attempt failed to start are started by the retry.

Visitors and merging

Three ids, with different jobs:

IdWhat it saysAt sign-out
userIdWhich accountNo longer sent
visitorIdWho this is before signing inMust be replaced
deviceIdWhich device holds a push tokenStays

visitorId is any stable id for one client, as long as it changes when a user signs out. Journeys and events belong to a user or a visitor, never to a device: one device can pass between people.

ts
await journeys.ingest({ visitorId, events }); // not signed in
await journeys.ingest({ userId, visitorId, profile, events }); // signed in: the visitor merges

Naming both ids says this visitor is this user. Their events, profile, devices and opt-outs move to the user, once, and a later report of that visitor reaches the user. A visitor already linked stays with its first user. Their running journeys carry on as the user's, except one the user is already in, which stops.

A visitor enters a workflow only if its trigger asks for them (trigger.event(e.browse, { visitors: true })). Visitors have no address, so such a journey reaches them by push. Segments are about users: visitors are not swept and do not enter segment triggers. A visitor who never signs in is deleted 90 days after they were last heard from, unless a journey of theirs is still running.

Devices

ts
await journeys.registerDevice({ deviceId, userId, token, platform: 'ios' });
await journeys.unbindDevice(token); // signed out: the token stays, bound to nobody
await journeys.removeDevice(token); // forget it for good

Call registerDevice on every registration. A token moves to its latest owner, and a deviceId seen with a new token replaces the old one. Registering wakes journeys waiting on reachable('push'). platform is ios, android or web; for web, token is the browser's PushSubscription as JSON, and its endpoint must belong to a known push service. A device row holds only its current owner, so call unbindDevice at sign-out, then register again with the new visitorId.

When a journey push is tapped, report the message_id it carried:

ts
await journeys.messageOpened(userId, messageId);

Subscriptions

The engine keeps the opt-out record, topic by channel, and is its one source of truth:

ts
const { email, push } = await journeys.getSubscriptions(userId);
// email: { all: true, topics: { product_updates: false, tips: true } }

await journeys.setSubscriptions(userId, {
  email: { topics: { product_updates: true } },
});
await journeys.setSubscriptions(userId, { push: { all: false } }); // no promotional pushes

A patch changes only what it names. all: false opts out of the whole channel and masks every topic; all: true clears only that channel-wide opt-out, so a topic switched off on its own stays off until named. With a contract, an undeclared topic is refused before the request.

A preference page opened from an email footer has no session. It reads the m query parameter of the preferencesUrl link and goes by the message instead of the user:

ts
const { email, push, message } = await journeys.getSubscriptionsByMessage(m);
await journeys.setSubscriptionsByMessage(m, {
  email: { topics: { [message.topic]: false } },
});

A 404 (JourneyClientError with status 404) is an expired link. The message id is the capability, so proxy these calls through your own api and rate-limit them there. The rules are on delivery.

Erasing a user

ts
const { erased, pending } = await journeys.forgetUser(userId);
await journeys.forgetVisitor(visitorId); // a visitor who never signed in

Once this resolves the request is durable. erased: false means a running journey would not stop yet, and the engine's scheduled sweep finishes the job. From then on the user is refused with a 410 on /ingest and /devices, now and later. What is deleted is on Postgres.

JourneyQueue on Cloudflare

JourneyQueue sends the same batch through a Cloudflare Queue, for a producer that must neither lose a report nor wait for the engine:

ts
import { JourneyQueue } from 'sendwend/client';

const queue = new JourneyQueue({ contract, queue: env.JOURNEY_QUEUE });
await queue.ingest({
  userId,
  visitorId,
  profile: { email, name },
  events: [{ event: 'login', payload: { method }, id: rowId, ts }],
});

Once ingest resolves the batch is durable. A rejection means it was not queued, and the caller decides what follows (a 5xx so its own client retries, say). The batch is checked against the contract and its ids and timestamps are fixed before it is queued, so every redelivery is the same report.

The producer declares the queue as a producer binding, and the engine Worker exports journeys.queue and consumes it with a dead letter queue:

json
// the producer's wrangler.jsonc
"queues": { "producers": [{ "binding": "JOURNEY_QUEUE", "queue": "journey" }] }

// the engine's wrangler.jsonc
"queues": {
  "consumers": [{ "queue": "journey", "max_retries": 8, "dead_letter_queue": "journey-dead" }]
}

The consumer handles one batch at a time and retries a failed one with a backoff from 30 seconds, doubling up to 15 minutes. A batch the contract refuses is retried the same way and logged with its field paths: the contract is the engine's version of it, so a producer deployed ahead of the engine passes once the engine catches up, and what never passes ends in the dead letter queue rather than dropped. Only a batch for an erased user is acknowledged unapplied.

Delivery is at least once and in no guaranteed order. Event ids absorb repeats and each profile property keeps its latest at, so send what must stay in order as one batch. The queue settings are on Cloudflare.

The HTTP surface

Callers that are not TypeScript use the API directly. Every route except GET /health and /t/... needs the bearer. Bodies are JSON.

Method and pathBodyAnswers
POST /ingest{ userId?, visitorId?, profile?, at?, events? }{ profile?, events }
POST /devices{ deviceId?, userId?, visitorId?, token, platform }{ ok: true, woke }
POST /devices/unbind{ token }{ ok: true, woke }
POST /devices/remove{ token }{ ok: true, woke }
POST /messages/opened{ userId, messageId }{ ok: true, recorded }
GET /subscriptions/:userIdnone{ email: { all, topics }, push: { all, topics } }
PUT /subscriptions/:userId{ email?: { all?, topics? }, push?: { all?, topics? } }The new state
GET /subscriptions/by-message/:messageIdnoneThe same, plus message: { channel, topic }
PUT /subscriptions/by-message/:messageIdThe same patchAs the GET
POST /users/forget{ userId } or { visitorId }{ ok: true, erased, pending }

POST /ingest needs at least one of userId and visitorId, and at least one of profile and events. Each event is { event, payload?, ts?, id? }; at is when the profile was read, in epoch milliseconds. A full request:

bash
curl -X POST https://workflow.acme.test/ingest \
  -H "authorization: Bearer $API_TOKEN" \
  -H 'content-type: application/json' \
  -d '{"userId":"u_123","profile":{"email":"ada@acme.test","name":"Ada"},
       "events":[{"id":"sign_up:u_123","event":"sign_up","payload":{"method":"google"}}]}'

The host adds operational routes, also behind the bearer: GET /bundle, POST /bundle/deploy, POST /segments/sweep, GET /preview/<key>?props=<JSON> and POST /deploy. They are covered on the host pages.

Status codes

StatusMeaning
400The body is not JSON, a field is malformed, or the contract refused the batch (error, plus issues with field paths)
401Missing or wrong credentials
404No such route, or a by-message id that names no copy (never sent, erased, or transactional)
405The path exists but not for this method
409A deploy refused (see versioning)
410The user has an erasure tombstone
503Production without API_TOKEN, or the database lacks tables or columns (problems lists them)
500Anything else; details go to the engine's log, not the response

A contract refusal looks like this, and nothing was stored, woken or started:

json
{
  "error": "event 'nps_sent' (nps-42) refused by the contract",
  "issues": [{ "path": "score", "message": "<zod's message for the field>" }]
}

Pitfalls

  • Separate identify and track calls. There is no separate identify endpoint; send the profile in the batch with the event that needs it.
  • Retrying without ids. A retry without the first attempt's ids records the events twice and changes what count and window conditions decide.
  • Reporting from the browser. The bearer grants the whole API, deploys included. Report from your backend and keep the token there.
  • Rolling out enforcement. A host can run with contractMode: 'report' to log what the contract would refuse instead of answering 400, which is how to check real producers before turning enforcement on.