# Transactional outbox

> Commit business rows and Stream events together, then consume and acknowledge them.

---

LLMS index: [llms.txt](/llms.txt)

---

This tutorial implements a transactional outbox using `examples/outbox.sql` from the pgredis source repository (Apache-2.0). A producer inserts an order row and appends a Redis Stream entry with `XADD` in one PostgreSQL transaction; a consumer reads from a Stream consumer group over RESP, then writes its shipment row and runs `XACK` in one PostgreSQL transaction.

> [!NOTE]
> On commit `715827aa0` (Linux arm64, PostgreSQL 18.6, 2026-10-21), the `examples/outbox.sql` integration suite passed all `46/46` checks across each of the 4 authentication and protocol profiles (`native` and `redis-acl` × `RESP2` and `RESP3`), covering rollback, savepoints, binary payloads, concurrent deduplication, consumer takeover and lost `COMMIT` replies.

## 1. Install the outbox schema and consumer group {#prepare}

Use the `pgredis_demo` database and `pgredis_app` role from [Quick start](/docs/redis/quickstart/). Make sure logical database `0` does not already contain the key `pgredis:outbox:orders` and that schema `pgredis_outbox_demo` does not exist.

Connect as a superuser (`postgres`) and run `examples/outbox.sql`:

```sh
psql -X -h 127.0.0.1 -p 5432 -U postgres -d pgredis_demo \
  -v ON_ERROR_STOP=1 -f examples/outbox.sql
```

The script creates three tables (`orders`, `events`, `shipments`), two `SECURITY INVOKER` functions (`place_order`, `apply_order`), and the Stream consumer group `shipping` on `pgredis:outbox:orders`:

```sql
CREATE SCHEMA pgredis_outbox_demo;

CREATE TABLE pgredis_outbox_demo.orders (
    request_id uuid PRIMARY KEY,
    payload bytea NOT NULL
);

CREATE TABLE pgredis_outbox_demo.events (
    request_id uuid PRIMARY KEY REFERENCES pgredis_outbox_demo.orders,
    event_id text NOT NULL UNIQUE
);

CREATE TABLE pgredis_outbox_demo.shipments (
    request_id uuid PRIMARY KEY REFERENCES pgredis_outbox_demo.orders,
    payload bytea NOT NULL
);
```

Grant access on the outbox schema to `pgredis_app`:

```sql
GRANT USAGE ON SCHEMA pgredis_outbox_demo TO pgredis_app;
GRANT SELECT, INSERT ON ALL TABLES IN SCHEMA pgredis_outbox_demo TO pgredis_app;
GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA pgredis_outbox_demo TO pgredis_app;
```

## 2. Produce an order and Stream event in one transaction {#produce}

Connect with `psql` as `pgredis_app`:

```sh
psql -X -h 127.0.0.1 -p 5432 -U pgredis_app -d pgredis_demo \
  -v ON_ERROR_STOP=1
```

Assign a stable `request_id` UUID to the business operation and call `place_order` inside a `READ COMMITTED` transaction:

```sql
\set request_id '00000000-0000-0000-0000-000000000001'
BEGIN ISOLATION LEVEL READ COMMITTED;
SELECT pgredis_outbox_demo.place_order(
  :'request_id'::uuid,
  convert_to('{"item":"book","quantity":1}', 'UTF8')
) AS event_id \gset
COMMIT;
\echo :event_id
```

`place_order` inserts into `orders`, calls `redis.command(ARRAY['XADD', 'pgredis:outbox:orders', '*', 'request_id', p_request::text])`, and stores the returned Stream entry ID in `events`:

- Calling `place_order` again with the same `request_id` and identical `payload` bytes returns the original `event_id` without appending a duplicate Stream entry.
- A concurrent duplicate waits on the `orders` primary key until the first transaction finishes.
- Passing a different payload for the same `request_id` raises SQLSTATE `22023`.
- Rolling back the SQL transaction removes the `orders` row, the `events` mapping and the Stream entry together.

## 3. Consume and acknowledge the event {#consume}

In a separate terminal, connect with `redis-cli` and read the next unread entry for consumer group `shipping`:

```sh
redis-cli -h 127.0.0.1 -p 6379 --user pgredis_app --askpass
```

```text
> SELECT 0
OK
> XREADGROUP GROUP shipping worker-1 COUNT 1 BLOCK 5000 STREAMS pgredis:outbox:orders >
```

Record the returned Stream entry ID (for example `1761955200000-0`) and the `request_id` field. Complete the `XREADGROUP` call before starting the consumer's SQL transaction. Until acknowledged, the entry stays in the group's Pending Entries List (PEL).

In your `psql` session, apply the order and acknowledge the Stream entry in one SQL transaction:

```sql
\set request_id '00000000-0000-0000-0000-000000000001'
\prompt 'Stream entry ID: ' event_id
BEGIN ISOLATION LEVEL READ COMMITTED;
SELECT pgredis_outbox_demo.apply_order(:'request_id'::uuid, :'event_id');
COMMIT;
```

`apply_order` checks that `event_id` matches `events`, copies the order payload into `shipments` (`ON CONFLICT DO NOTHING`), and calls `XACK` inside the same transaction:

- On the first execution, `apply_order` returns `true` and requires `XACK` to acknowledge `1` pending entry (if `XACK` returns `:0`, `apply_order` raises an exception and rolls back `shipments`).
- On a repeated call after commit, `apply_order` returns `false` without inserting a second shipment.

Verify the committed shipment row:

```sql
SELECT request_id, convert_from(payload, 'UTF8')
FROM pgredis_outbox_demo.shipments;
```

## 4. Recover after worker failures or lost commit replies {#recovery}

- **Worker crash before `COMMIT`:** If `worker-1` stops before `apply_order` commits, inspect its pending entries with `XREADGROUP GROUP shipping worker-1 COUNT 10 STREAMS pgredis:outbox:orders 0`, or let another worker reclaim idle entries with `XAUTOCLAIM` / `XCLAIM`, then call `apply_order` with the reclaimed `request_id` and `event_id`. Keep `XREADGROUP` and `XAUTOCLAIM` outside the SQL transaction, and never send a standalone `XACK` before `apply_order`.
- **Lost `COMMIT` reply:** If the network drops during `COMMIT`, the client can safely re-run `place_order(request_id, payload)` or `apply_order(request_id, event_id)` on a new connection. The primary-key lock waits for any still-running transaction and resolves the duplicate deterministically.

---

Backlinks:

- [SQL API](/docs/redis/reference/sql/)
- [Streams and consumer groups](/docs/redis/reference/streams/)
- [Transactions and retries](/docs/redis/reference/transactions/)
- [Tutorials](/docs/redis/tutorial/)
- [Roll back SQL and Redis together](/docs/redis/tutorial/sql-rollback/)
