Skip to content

This is the multi-page printable view of this section.

Return to the regular view of this page

Tutorials

Connect clients, roll back Redis writes with SQL, store binary data and build a transactional outbox.

These tutorials use the pgredis_demo database and pgredis_app role created in Quick start, with PostgreSQL listening on 127.0.0.1:5432 and the pgredis gateway listening on 127.0.0.1:6379.

Work through the examples in order:

  1. Connect a Redis client — authenticate over RESP2 and RESP3, switch logical databases with SELECT, and write and read keys.
  2. Roll back SQL and Redis together — modify a SQL table row and a Redis key in one PostgreSQL transaction and roll both back.
  3. Binary keys and values — store and read raw byte sequences containing NUL (\x00) bytes through redis.command_bin.
  4. Transactional outbox — commit business rows and Redis Stream events in one transaction, then consume and acknowledge them idempotently with XREADGROUP and XACK.

1 - Connect a Redis client

Authenticate with redis-cli or a driver, then write and read a key.

Complete Quick start first. This tutorial uses redis-cli, the pgredis_app role and the pgredis_demo database with the gateway listening on 127.0.0.1:6379 (or 56379 if started with the default -listen flag).

Open a RESP2 session

Connect with redis-cli and authenticate as pgredis_app:

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

Enter the password for the pgredis_app PostgreSQL role, then run the following commands at the prompt:

> PING
PONG
> SET pgredis:demo:client ready
OK
> GET pgredis:demo:client
"ready"
> SELECT 1
OK
> EXISTS pgredis:demo:client
(integer) 0
> SELECT 0
OK
> DEL pgredis:demo:client
(integer) 1
> QUIT
OK

SELECT 1 switches the current connection to logical database 1. Because pgredis:demo:client was created in logical database 0, EXISTS in database 1 returns 0. Switching back to SELECT 0 finds and deletes the key.

Use RESP3

The gateway supports both RESP2 and RESP3 on the same listener. Pass -3 to redis-cli (or send HELLO 3) to negotiate RESP3:

redis-cli -3 -h 127.0.0.1 -p 6379 --user pgredis_app --askpass

Both protocol versions read and write the same PostgreSQL tables.

Handle lost responses

Each standalone command commits in PostgreSQL before the gateway writes the reply to the client socket. If the network drops after PostgreSQL commits but before the client reads the reply, the write has already taken effect. Do not blindly retry non-idempotent commands such as INCR or LPUSH; see Disconnects and unknown outcomes.

2 - Roll back SQL and Redis together

Use one PostgreSQL transaction for a business row and a Redis key.

Use the pgredis_demo database and pgredis_app role from Quick start. Connect with psql as the application role:

psql -h 127.0.0.1 -p 5432 -U pgredis_app -d pgredis_demo

Run and roll back a transaction

Create a temporary SQL table, then start a transaction that inserts a business row and sets a Redis key before rolling back:

CREATE TEMP TABLE pgredis_demo_row(id integer PRIMARY KEY, state text);
BEGIN;
INSERT INTO pgredis_demo_row VALUES (42, 'ready');
SELECT redis.command(ARRAY['SET', 'pgredis:demo:42', 'ready']);
SELECT redis.command(ARRAY['GET', 'pgredis:demo:42']);
ROLLBACK;

SELECT count(*) FROM pgredis_demo_row;
SELECT convert_from(redis.command(ARRAY['EXISTS', 'pgredis:demo:42']), 'UTF8');

After ROLLBACK, SELECT count(*) FROM pgredis_demo_row; returns 0 and the decoded EXISTS reply is :0\r\n (the key does not exist). The temporary table remains because it was created before BEGIN, while both the SQL row insert and the Redis SET were rolled back together.

How it works

redis.command and redis.command_bin execute inside the caller’s PostgreSQL transaction (READ COMMITTED isolation level) and write directly to the extension’s WAL-logged tables. Separate requests sent over a RESP gateway connection run in their own transactions and do not join an open psql transaction.

Clean up the temporary table when finished:

DROP TABLE pgredis_demo_row;

Next, see Transactional outbox to commit business rows and Redis Stream events together.

3 - Binary keys and values

Store and read byte-exact keys and values through RESP and redis.command_bin.

PostgreSQL text values cannot contain NUL (\x00) bytes or invalid UTF-8 sequences, whereas Redis keys and values are arbitrary byte strings. Use redis.command_bin(bytea[], integer) from SQL (or raw binary arguments over RESP) to store and read arbitrary bytes without text conversion.

Send and read raw bytes

Connect to pgredis_demo as pgredis_app (psql -h 127.0.0.1 -p 5432 -U pgredis_app -d pgredis_demo) and pass bytea[] arguments containing \x00 and \xff bytes:

BEGIN;
SELECT redis.command_bin(ARRAY[
  'SET'::bytea, decode('006bff', 'hex'), decode('00ff', 'hex')
]);
SELECT encode(redis.command_bin(ARRAY[
  'GET'::bytea, decode('006bff', 'hex')
]), 'hex');
ROLLBACK;

The GET query returns 24320d0a00ff0d0a:

  • 24320d0a is the RESP bulk string header $2\r\n (2 bytes).
  • 00ff is the exact two-byte payload.
  • 0d0a is the trailing \r\n.

Keep the interface binary

Always use redis.command_bin(bytea[], integer) when keys, values, hash fields, set members, sorted-set members or Pub/Sub channel names can contain NUL bytes or non-UTF-8 payloads. Parse the outer RESP frame in bytea before interpreting the payload bytes, and do not pass binary payloads through PostgreSQL text or JSON string conversions.

4 - Transactional outbox

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

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

Use the pgredis_demo database and pgredis_app role from Quick start. 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:

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:

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:

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

Connect with psql as pgredis_app:

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:

\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

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

redis-cli -h 127.0.0.1 -p 6379 --user pgredis_app --askpass
> 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:

\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:

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

4. Recover after worker failures or lost commit replies

  • 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.