Skip to content

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.

Scan to open this page
https://mimus.pgsty.com/docs/redis/tutorial/sql-rollback/