# Delivery

> How an outcome reaches every case that listens, exactly as reliably as the data it describes, in Sypnia Cloud and self-hosted.

Applies to: the Sypnia engine (open source, self-hosted) and Sypnia Cloud (paid service).  
Source: https://cases.docs.sypnia.com/runtime/delivery/

For agents: Transactional outbox: when an outcome has listeners, the area's service (@sypnia/cases, or the Rust crate sypnia-cases) inserts it into sypnia_cases.outbox in the same Postgres transaction as the case's rows (no event without data, no data without event); only the server writes it: a case some case listens to runs through POST /_cases/<id> of its area's service, never from the browser or over the Data API. A declared failure undoes the run's own writes; its event (when someone listens) and the delivery's record still commit. Four tables in the app's own database, schema sypnia_cases: subscriptions (who listens to which event, written by every service when it starts; emit writes an outbox row only when a subscription exists; mode on|on_all, filter, order_by, correlation key, window, max_attempts, backoff, loop max), outbox (event id uuid v7, seq, name, payload, trace, causation, depth, source case, created_at, dispatched_at), deliveries (event id, subscriber case, seq, state pending|running|done|dead, attempts, retry settings copied from the subscription, next_at, lease locked_until, order_key, corr_key, outcome, last_error), processed_events (subscriber, event id or idempotency key, outcome; event ids kept 7 days, idempotency keys 24 h). Envelope: id (uuid v7), name, data, occurred_at, key, traceparent, cause (chain of case ids), depth; data at most 256 KB (bigger: a Sypnia Files path). Fast path: right after commit the service publishes the rows it wrote and marks them sent; sweep: every minute, rows unsent after 30 s. On AWS (Sypnia Cloud, or Run's engine in your account): EventBridge bus per app environment → one SQS queue per subscriber (FIFO with message group = order_by key) with its DLQ → the subscriber area's service. Without AWS: a background task in each area service (a tokio task in Rust services), woken by Postgres LISTEN/NOTIFY, deliveries rows as the queues. Fan-out per subscriber; at-least-once; retries: max attempts 5 by default, the first one included (1 to 20), waits after attempts 1–4 about 1 s, 10 s, 1 min, 10 min, then 1 h from the fifth on (case field retries: { max, backoff }: backoff is the first wait, doubled each time up to 1 h); then dead letter (state dead / DLQ), visible on the map and in Telemetry; `cases dead-letters list|show|replay|drop`. Idempotent consumers: processed_events checked in the same transaction as the subscriber's run, so a second delivery does nothing. Ordering only by order_by key. Delivery to the caller and to Telemetry never goes through the outbox.

When a case ends in an outcome that other cases listen to, the outcome has to reach each of them, once in effect, even if a server restarts at the worst moment. Sypnia Cases does this with patterns proven for decades: a **transactional outbox**, a **queue per listener**, **retries** with **dead letters**, and listeners that **ignore an event they already handled**. You declare the listener; the runtime does the rest.

## The outbox

An outcome is saved **in the same transaction as the data it describes**. When «Pause deliveries» writes its pause and ends in `DeliveriesPaused`, both go into the database together, or neither does:

- no event about a pause that was never saved;
- no saved pause whose event is lost.

The outbox is written **only on the server**: by the area's service, in the same Postgres transaction as the case's rows. A case that some case listens to never runs from a browser or over the Data API; its screen calls `POST /_cases/<case-id>` on the area's service, with the person's Sypnia Data session, and the case runs there under the project's row-level security ([Runners](https://cases.docs.sypnia.com/sypnorm/runners#a-case-someone-listens-to-runs-on-the-server)).

The runtime writes the outbox row only when some case listens to that outcome. Delivery to the person waiting and to Telemetry never goes through the outbox.

A declared failure undoes the run's own writes: the case's body runs under a savepoint that the failure rolls back. The failure's event, when some case listens to it, and the record of the delivery still commit.

### The tables

The runtime keeps four tables in your app's own database, in the schema `sypnia_cases`, next to your data (a [Sypnia Data](https://data.docs.sypnia.com/) project, or any Postgres 14+):

| Table              | Holds                                                                                                                                                                                                                                                                                                                                                                                                              |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `subscriptions`    | who listens to what, before any listener runs: one row per listening case and event, with its kind (`on` or `on_all`), filter, `order_by`, correlation key and window, retries and loop limit. Every area's service writes its subscriptions when it starts (a TypeScript service the whole map's, a Rust service its own cases'), and an outcome gets an outbox row only when a subscription for its event exists |
| `outbox`           | every outcome someone listens to: its event id, its place in the order of writing (`seq`), name, payload, trace, causation chain, depth, the case that emitted it, when it was written and when it was handed on                                                                                                                                                                                                   |
| `deliveries`       | one row per event and listener, its queue: state (`pending`, `running`, `done`, `dead`), attempts and the retry settings copied from the subscription, when to try next, the lease of the run that holds it (`locked_until`), its ordering and correlation keys, the outcome it ended in, the last error                                                                                                           |
| `processed_events` | what each listener already handled: the event id (kept 7 days), or, for an `external` start, the idempotency key (kept 24 hours), and the outcome it ended in                                                                                                                                                                                                                                                      |

Your app's database role may read them; only the runtime writes them.

## From the outbox to every listener

### 1. Fast path

Right after the transaction commits, the area's service hands the rows it just wrote to their listeners and marks them sent. Listeners usually hear the event within a second.

### 2. Sweep

If that hand-off is lost (the service stopped right after the commit), the sweep, every minute, publishes every outbox row still unsent after 30 seconds. Nothing depends on the fast path working.

### 3. Fan-out

The dispatcher gives **each listener its own copy**, in its own queue. A slow or failing listener never holds back the others.

### 4. The listener runs

The listening area's service takes its delivery, checks `processed_events`, runs the case in one transaction, and records the event as handled in that same transaction. Its own outcomes go to the outbox, and the chain goes on.

### In Sypnia Cloud and without AWS

The behaviour is the same; the pieces underneath differ.

|                       | On AWS: Sypnia Cloud, or Sypnia Run's engine in your account                                          | Without AWS: Docker or your own server                                                                                                     |
| --------------------- | ----------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| Fast path             | the service publishes right after the commit                                                          | the service writes each listener's delivery right after the commit, and a Postgres `NOTIFY` wakes the listening services' background tasks |
| Sweep                 | every minute, rows unsent after 30 seconds                                                            | the same, from the background task                                                                                                         |
| The bus               | an Amazon EventBridge bus per app environment                                                         | Postgres itself                                                                                                                            |
| Queue per listener    | an Amazon SQS queue per listening case, with its dead-letter queue; FIFO when the case has `order_by` | the rows of `deliveries` for that case                                                                                                     |
| Who runs the listener | the queue invokes the listening area's service                                                        | the background task of the listening area's service, which takes its rows with `FOR UPDATE SKIP LOCKED`                                    |

The background task is part of `@sypnia/cases` in every area's service; in a service written in Rust, such as Telemetry's engine, it is a tokio task of the `sypnia-cases` crate. There is no extra program to run: start your areas' services against the same Postgres and events flow between them.

### What each event carries

```json
{
  "id": "0193f6c2-7a1e-7c3b-9d2a-5e8f1b4c6a70",
  "name": "weather.check-weather.RainExpected.v1",
  "data": { "from": "2026-11-18T15:00:00-05:00" },
  "occurred_at": "2026-11-18T13:00:04Z",
  "key": null,
  "traceparent": "00-7c2e9a4b1d8f4e6a9b3c5d7e1f2a4b6c-a1b2c3d4e5f60718-01",
  "cause": ["check-weather"],
  "depth": 1
}
```

`data` is the outcome's payload, at most 256 KB; for something bigger, put it in [Sypnia Files](https://files.docs.sypnia.com/) and send its path. `key` is the value of the start's `order_by` field, when it has one. `cause` and `depth` are how loops are stopped ([Loops](https://cases.docs.sypnia.com/runtime/loops)).

## Retries

A delivery whose run ends in an error nobody declared is tried again: **5 attempts** in all, the first one included. The wait grows: about 1 second after the first attempt, 10 seconds after the second, 1 minute after the third and 10 minutes after the fourth; when a case allows more than 5 attempts, it waits 1 hour from the fifth on. A declared failure is never retried: it is an answer.

A case can change its retries:

`cases/deliveries/tell-the-baker.case.yaml`

```yaml
retries: { max: 8, backoff: 30s }
```

`max` is the number of attempts, the first one included, from 1 to 20 (5 when the case says nothing), and `backoff` the first wait, doubled each time up to one hour.

## Dead letters

When the attempts run out, the event goes to that listener's **dead letters**: the row in `deliveries` turns `dead` (self-hosted) or the message moves to its dead-letter queue (Sypnia Cloud). Nothing is thrown away. The dead letters of each listener show on the map, on the arrow of the [event graph](https://cases.docs.sypnia.com/map/outcomes-and-events#the-event-graph), and Telemetry opens a problem for them, with the trace of the run that failed.

```bash
npx @sypnia/cases dead-letters list                       # every listener with dead letters
npx @sypnia/cases dead-letters show deliveries.tell-the-baker
npx @sypnia/cases dead-letters replay deliveries.tell-the-baker   # after the fix, send them again
npx @sypnia/cases dead-letters drop deliveries.tell-the-baker --event <id> --reason "sent by phone"
```

On Sypnia Run, `run cases dlq tell-the-baker` and `--replay` do the same from Run's command line.

Replaying is safe: a listener that already handled an event does nothing the second time.

## Getting an event twice does what getting it once does

Delivery is **at least once**: after a crash in the wrong place, an event can arrive twice. Every listener is idempotent by construction. Before running, the runtime looks for the event id in `processed_events`, and it records the event there in the same transaction as the run's own changes. A second delivery finds it and does nothing; the first outcome stands.

An `external` start works the same way with its idempotency key, so Rappi sending the same order twice bakes it once and gets the first answer back both times.

## Order

Events reach a listener in any order, unless the case asks for order with `order_by`:

```yaml
starts:
  event:
    on: [orders.order-for-tomorrow.OrderPlaced.v1, orders.cancel-order.OrderCancelled.v1]
    order_by: order_id
```

Then events with the same `order_id` arrive one at a time, in the order they happened; events of different orders still run side by side. Ask for order only when the case needs it: it is slower.

## What you see

- **On the map:** each arrow of the event graph with its queue length, its retries and its dead letters.
- **In Telemetry:** the whole chain as one trace, from the first case to the last listener, with each delivery's wait and attempts.
- **In the terminal:** `npx @sypnia/cases deliveries <listener>` lists recent deliveries and their state.
