This is the multi-page printable view of this section.
Tutorials
- 1: Connect a Redis client
- 2: Roll back SQL and Redis together
- 3: Binary keys and values
- 4: 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:
- Connect a Redis client — authenticate over RESP2 and RESP3, switch logical databases with
SELECT, and write and read keys. - Roll back SQL and Redis together — modify a SQL table row and a Redis key in one PostgreSQL transaction and roll both back.
- Binary keys and values — store and read raw byte sequences containing
NUL(\x00) bytes throughredis.command_bin. - Transactional outbox — commit business rows and Redis Stream events in one transaction, then consume and acknowledge them idempotently with
XREADGROUPandXACK.
1 - Connect a Redis client
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:
Enter the password for the pgredis_app PostgreSQL role, then run the following commands at the prompt:
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:
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 the pgredis_demo database and pgredis_app role from Quick start. Connect with psql as the application role:
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:
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:
Next, see Transactional outbox to commit business rows and Redis Stream events together.
3 - Binary keys and values
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:
The GET query returns 24320d0a00ff0d0a:
24320d0ais the RESP bulk string header$2\r\n(2 bytes).00ffis the exact two-byte payload.0d0ais 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
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.
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:
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:
Grant access on the outbox schema to pgredis_app:
2. Produce an order and Stream event in one transaction
Connect with psql as pgredis_app:
Assign a stable request_id UUID to the business operation and call place_order inside a READ COMMITTED transaction:
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_orderagain with the samerequest_idand identicalpayloadbytes returns the originalevent_idwithout appending a duplicate Stream entry. - A concurrent duplicate waits on the
ordersprimary key until the first transaction finishes. - Passing a different payload for the same
request_idraises SQLSTATE22023. - Rolling back the SQL transaction removes the
ordersrow, theeventsmapping 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:
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:
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_orderreturnstrueand requiresXACKto acknowledge1pending entry (ifXACKreturns:0,apply_orderraises an exception and rolls backshipments). - On a repeated call after commit,
apply_orderreturnsfalsewithout inserting a second shipment.
Verify the committed shipment row:
4. Recover after worker failures or lost commit replies
- Worker crash before
COMMIT: Ifworker-1stops beforeapply_ordercommits, inspect its pending entries withXREADGROUP GROUP shipping worker-1 COUNT 10 STREAMS pgredis:outbox:orders 0, or let another worker reclaim idle entries withXAUTOCLAIM/XCLAIM, then callapply_orderwith the reclaimedrequest_idandevent_id. KeepXREADGROUPandXAUTOCLAIMoutside the SQL transaction, and never send a standaloneXACKbeforeapply_order. - Lost
COMMITreply: If the network drops duringCOMMIT, the client can safely re-runplace_order(request_id, payload)orapply_order(request_id, event_id)on a new connection. The primary-key lock waits for any still-running transaction and resolves the duplicate deterministically.