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
| Path | Import | Use it when |
|---|---|---|
JourneyClient | sendwend/client | A TypeScript service calling the engine over HTTP |
JourneyQueue | sendwend/client | A producer on Cloudflare that must not lose a report or wait for the engine |
| HTTP | none | Any 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.
| Option | Meaning |
|---|---|
origin | The engine's public origin. A trailing slash is ignored |
token | Its API_TOKEN, sent as Authorization: Bearer <token>. Omit it against an open local instance |
contract | The shared defineContract(...). Types event names, payloads and profile patches, and checks them before anything is sent |
fetch | A 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:
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:
- If both
userIdandvisitorIdare given, the visitor merges into the user. - The profile patch is merged.
- 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:
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.
nullremoves 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
profileschema. Declare a fieldoptional(...)when your app does not write it for every user a journey can reach (contract).
Event rules
eventnames an event the contract declares. Names starting with$are reserved.tsis 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
payloadmay 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
userIdcannot begin withvisitor:.
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:
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:
| Id | What it says | At sign-out |
|---|---|---|
userId | Which account | No longer sent |
visitorId | Who this is before signing in | Must be replaced |
deviceId | Which device holds a push token | Stays |
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.
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
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:
Subscriptions
The engine keeps the opt-out record, topic by channel, and is its one source of truth:
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:
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
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:
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:
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 path | Body | Answers |
|---|---|---|
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/:userId | none | { email: { all, topics }, push: { all, topics } } |
PUT /subscriptions/:userId | { email?: { all?, topics? }, push?: { all?, topics? } } | The new state |
GET /subscriptions/by-message/:messageId | none | The same, plus message: { channel, topic } |
PUT /subscriptions/by-message/:messageId | The same patch | As 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:
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
| Status | Meaning |
|---|---|
| 400 | The body is not JSON, a field is malformed, or the contract refused the batch (error, plus issues with field paths) |
| 401 | Missing or wrong credentials |
| 404 | No such route, or a by-message id that names no copy (never sent, erased, or transactional) |
| 405 | The path exists but not for this method |
| 409 | A deploy refused (see versioning) |
| 410 | The user has an erasure tombstone |
| 503 | Production without API_TOKEN, or the database lacks tables or columns (problems lists them) |
| 500 | Anything else; details go to the engine's log, not the response |
A contract refusal looks like this, and nothing was stored, woken or started:
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.