Skip to content

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

Return to the regular view of this page

Redis

Redis commands through the pgredis gateway, with data in PostgreSQL tables.

Redis clients send Redis 7.2.4 standalone commands to the pgredis gateway. The gateway runs each command in the pg_redis extension, which keeps every key in ordinary PostgreSQL tables. The same commands are callable from SQL, so a Redis write can commit or roll back together with business rows.

Status
Release candidate. pgredis 0.1.0; candidate v0.1.0-rc1 (2026-11-08): local tag on 2f8ee8d6a, packages from 11411411d. Not published. Extension schema 0.54, ABI 3.
Port
6379 in the Mimus plan; the gateway defaults to 127.0.0.1:56379
Gateway
pgredis, Go: RESP2/RESP3, TLS, authentication, sessions, MULTI queues, pools
Extension
pg_redis, C, schema redis; needs superuser and shared_preload_libraries (background expiry worker)
Kernel patch
none; runs on stock PostgreSQL 18
Licence
Apache-2.0; code derived from Redis 7.2.4 keeps its BSD-3-Clause notices

How Redis maps onto PostgreSQL

  • Data types are WAL-logged tables: redis._keyspace holds the binary key, type, value and expiry; _hash, _list, _set, _zset and the _stream* tables hold the rest.
  • Each command is one PostgreSQL transaction. The reply leaves only after commit. EXEC runs the whole queue in one transaction. A reply whose outcome is unknown is never replayed.
  • SQL: redis.command(text[], db) and redis.command_bin(bytea[], db) call the same core and join the caller’s transaction (READ COMMITTED only).
  • Pub/Sub and blocking commands use tables plus NOTIFY wake-ups and leases.
  • Write commands other than plain GET/SET run one at a time per database; WAL flush latency limits their throughput.

Try it

CREATE TEMP TABLE demo_row(id integer PRIMARY KEY, state text);
BEGIN;
INSERT INTO demo_row VALUES (42, 'ready');
SELECT redis.command(ARRAY['SET', 'demo:42', 'ready']);
ROLLBACK;  -- the row and the Redis key both disappear
SELECT convert_from(redis.command(ARRAY['EXISTS', 'demo:42']), 'UTF8');  -- :0

Out of scope

Lua scripting, Functions, Cluster, Sentinel, Redis replication, AOF/RDB files, maxmemory eviction and modules. Redis ACL mode is Beta and incomplete. The extension needs superuser and preload, so it does not install on managed PostgreSQL services.

Source and credit

pgredis is developed by PGSTY and pgredis contributors. Redis is a trademark of Redis Ltd.; Mimus is not affiliated with Redis Ltd.

Pages in this section adapt the pgredis companion documentation, © PGSTY and pgredis contributors, CC BY 4.0; see Licence and attribution.

1 - Quick start

Install pgredis 0.1.0, configure PostgreSQL, start the gateway and run PING, SET and GET.

This guide sets up pgredis 0.1.0 (extension schema 0.54, ABI 3, candidate v0.1.0-rc1) against a local PostgreSQL 18 instance and runs PING, SET and GET through redis-cli and SQL. Check Compatibility first to confirm that your workload only uses supported commands.

Note

v0.1.0-rc1 (2026-11-08, commit 11411411d72ab45456904cc602cefbb13b68ff25) is an unpublished release candidate. No public download is available yet; install from a locally built development archive or build directly from source.

Prerequisites

  • Debian 13 (amd64 or arm64) for development archives, or a Linux / macOS build host for source builds.
  • PostgreSQL 18 (tested on 18.6) with pg_config (postgresql-server-dev-18 on Debian).
  • Superuser access to a dedicated PostgreSQL instance that you can configure and restart (pg_redis requires superuser = true and shared_preload_libraries).
  • Python 3 (when running install.py from a development archive) and redis-cli.

1. Install the gateway and extension

If you have a v0.1.0-rc1 development archive (pgredis-0.1.0-pg18.6-debian13-amd64.tar.gz or pgredis-0.1.0-pg18.6-debian13-arm64.tar.gz), verify its SHA-256 hash before extracting (d72fdcb4f40d429e5b650d0671105c923db7ceb4425b50f68d45eea0d61e2ba8 for amd64; 4dcc546ef4c0562eb0b69500c0bbb43f664c3b955259ccde92900ef52e269cd7 for arm64):

pgredis_archive=pgredis-0.1.0-pg18.6-debian13-amd64.tar.gz
sha256sum "$pgredis_archive"
tar -xzf "$pgredis_archive" install.py
python3 -E install.py "$PWD/$pgredis_archive" \
  --pg-config /usr/lib/postgresql/18/bin/pg_config \
  --gateway-path /usr/local/bin/pgredis
pgredis -version

If you are installing from a source checkout instead of a development archive, build the Go gateway and C extension with make build and install the extension with make -C extension PG_CONFIG=/usr/lib/postgresql/18/bin/pg_config install.

pgredis -version must print pgredis 0.1.0.

2. Configure PostgreSQL

Add the following settings to postgresql.conf. If shared_preload_libraries already lists other modules, append pg_redis to the comma-separated list:

shared_preload_libraries = 'pg_redis'
pg_redis.maintenance_database = 'postgres'
pg_redis.maintenance_role = 'postgres'
max_prepared_transactions = 8
synchronous_commit = on

Add SCRAM authentication for the application role to pg_hba.conf before broader rules:

host  pgredis_demo  pgredis_app  127.0.0.1/32  scram-sha-256

Restart PostgreSQL so shared_preload_libraries and max_prepared_transactions take effect.

3. Create the database, extension and role

Connect to PostgreSQL as a superuser and create the database, extension and application role:

CREATE DATABASE pgredis_demo;
\connect pgredis_demo
CREATE EXTENSION pg_redis;
SET password_encryption = 'scram-sha-256';
CREATE ROLE pgredis_app LOGIN;
\password pgredis_app
GRANT CONNECT, TEMPORARY ON DATABASE pgredis_demo TO pgredis_app;
GRANT USAGE ON SCHEMA redis TO pgredis_app;
GRANT EXECUTE ON FUNCTION
  redis._authorize(), redis._abi_version(), redis._read(), redis._write(),
  redis._dispatch(bytea[], integer), redis._dispatch(bytea[], integer, integer),
  redis._dispatch_single(bytea[], integer, integer), redis._pool_reset(),
  redis.command(text[], integer), redis.command_bin(bytea[], integer)
TO pgredis_app;

Verify the installed extension schema version and ABI:

SELECT extversion FROM pg_extension WHERE extname = 'pg_redis';  -- 0.54
SELECT redis._abi_version();                                     -- 3

The grants above allow ordinary data commands, transactions, blocking commands and Pub/Sub, but do not grant Redis administration commands such as FLUSHALL, INFO, CONFIG or MONITOR.

4. Start the gateway and run commands

Start the gateway on port 6379 (the Mimus planned Redis port) against PostgreSQL on port 5432:

pgredis -listen 127.0.0.1:6379 -default-user pgredis_app \
  -pg 'postgres://127.0.0.1:5432/pgredis_demo?sslmode=disable'
Note

If you omit -listen and -pg, the pgredis binary defaults to 127.0.0.1:56379 and postgres://127.0.0.1:55432/pgredis. Pass explicit flags so the port and database match your instance.

In a second terminal, run PING, SET and GET with redis-cli:

redis-cli -p 6379 --user pgredis_app --askpass PING
redis-cli -p 6379 --user pgredis_app --askpass SET greeting hello
redis-cli -p 6379 --user pgredis_app --askpass GET greeting

Enter the pgredis_app password when prompted. The commands return PONG, OK and hello. Because the key is stored in pgredis_demo, SQL queries on the same database see it immediately:

SELECT convert_from(redis.command(ARRAY['GET', 'greeting']), 'UTF8');

Deployment notes

  • Non-loopback listeners require TLS. When -listen binds to a non-loopback address, you must pass -tls-cert and -tls-key or the gateway refuses to start.
  • One gateway per database. Run one pgredis gateway process per PostgreSQL database; multiple gateways sharing one database are not verified.
  • Write serialization. Write commands other than plain GET and SET take a per-database exclusive lock until commit; see Per-database serialization.
  • Schema upgrades. When upgrading from extension schema 0.52 or 0.53, replace the binaries and run ALTER EXTENSION pg_redis UPDATE TO '0.54'; in each database.

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

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

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

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

3 - Compatibility

Committed and Beta features, unsupported Redis features, differences and test results.

pgredis 0.1.0 (extension schema 0.54, ABI 3) targets Redis 7.2.4 standalone semantics with PostgreSQL 18 as the only persistent store. It is not a drop-in replacement for every Redis deployment. This page defines the support tiers, behavioral differences and source-bound test results.

Feature scope and support tiers

Committed

Committed features are covered by release-candidate regression checks:

CategoryScope
Data typesString, Hash, Set, ZSet and List, including blocking pops (BLPOP, BRPOP, BLMOVE, BRPOPLPUSH, BLMPOP, BZPOPMIN, BZPOPMAX, BZMPOP)
KeyspaceTTL and expiry, SCAN, SELECT (logical databases 0–15), DEL, EXISTS, TYPE, RENAME, COPY
TransactionsMULTI, EXEC, DISCARD, WATCH
Publish/SubscribeChannels, pattern subscriptions and sharded Pub/Sub (SSUBSCRIBE, SPUBLISH)
AdministrationSubsets of INFO, CONFIG and CLIENT
SQL APIredis.command(text[], integer) and redis.command_bin(bytea[], integer) in the same transaction as SQL tables
AuthenticationNative PostgreSQL role mode (AUTH maps to a LOGIN role; permissions enforced by extension entry points)
TransportRESP2 and RESP3; mandatory TLS on non-loopback listen addresses
Durabilitysynchronous_commit = on by default; the gateway replies only after PostgreSQL confirms commit

Beta

Beta features are included in 0.1.0 without a stability commitment; options and edge cases may change in later versions:

  • Streams and consumer groups (XADD, XREAD, XREADGROUP, XACK, XCLAIM, XAUTOCLAIM, XINFO).
  • Bitmap, HyperLogLog and Geo commands.
  • DUMP, RESTORE and MIGRATE.
  • Client-side caching (CLIENT TRACKING, CLIENT CACHING, CLIENT GETREDIR, CLIENT TRACKINGINFO).
  • MONITOR.
  • Redis ACL compatibility mode (-auth-mode redis-acl).

Unsupported

AreaBehavior and impact
Lua scripting and FunctionsEVAL, EVALSHA, FUNCTION and FCALL return an unknown-command error. Frameworks that call Lua in their default configuration do not work out of the box: Celery 5.6.3 / Kombu 5.6.2 calls EVALSHA during startup maintenance even on an empty broker, and Sidekiq 8.1.7 uses Lua in its default scheduled-job poller. The default redis-py lock acquires with SET NX PX and releases with EVALSHA; only TTL expiry works without Lua
Cluster and SentinelCLUSTER and SENTINEL commands are not implemented
Redis replicationREPLICAOF, SLAVEOF, SYNC and PSYNC are rejected. WAIT returns 0 replica acknowledgements and does not measure PostgreSQL WAL or standby state; use PostgreSQL replication for high availability
Redis persistence filesAOF and RDB files, SAVE, BGSAVE, BGREWRITEAOF, WAITAOF (numlocal=1) and DEBUG RELOAD are not supported; use PostgreSQL backup and recovery tools
Memory evictionmaxmemory eviction policies are not implemented
ModulesMODULE load/unload commands and Redis modules are not supported (MODULE LIST returns an empty list)
Multi-gatewayRunning multiple gateway processes against one PostgreSQL database is not verified
Redis 7.4+ commandsCommands introduced after Redis 7.2.4 (such as Hash field expiry HEXPIRE) are not implemented
Exactly-once deliveryWhen a commit outcome is unknown, the gateway closes the connection without replaying the command. Client libraries or frameworks that auto-retry on disconnect (including default producer retries in RQ, Sidekiq, Celery and Lettuce) can write duplicate items; deduplicate by business ID

Authentication and databases

Each pgredis gateway process connects to one PostgreSQL database. Redis SELECT switches among logical databases 0 through 15 inside that PostgreSQL database. Logical databases share the same PostgreSQL tables and do not provide tenant isolation; use separate PostgreSQL databases for tenant boundaries.

In the default native authentication mode, AUTH and HELLO ... AUTH verify PostgreSQL LOGIN credentials and PostgreSQL GRANT privileges control read, write and administrative entry points. In redis-acl mode (-auth-mode redis-acl), the gateway authenticates Redis ACL users and filters commands, key patterns and Pub/Sub channels, while the gateway’s PostgreSQL connection role remains the outer permission ceiling.

Data and transactions

Both the RESP gateway and SQL functions (redis.command, redis.command_bin) execute the same C command handlers in pg_redis. Every standalone RESP command runs in one PostgreSQL transaction and sends its reply only after commit.

Direct SQL calls join the caller’s transaction (READ COMMITTED only), so SQL table writes, Redis key mutations and queued notifications commit or roll back together. Inside MULTI/EXEC, the gateway queues commands in memory and submits the batch in a single PostgreSQL transaction on EXEC:

  • A Redis command error (such as WRONGTYPE or syntax errors) is recorded as an error element in the EXEC reply array, and the remaining commands in the batch still execute and commit.
  • A PostgreSQL system error (such as serialization failure, lock timeout or out-of-memory) aborts and rolls back the entire EXEC transaction.

Per-database serialization

Write commands other than plain GET and plain SET (without extra options) acquire a per-database exclusive lock and hold it until the PostgreSQL transaction commits, including the WAL flush. Writes to different keys in the same database therefore wait in line, and write throughput is bounded by the commit rate of the underlying storage. Plain GET and plain SET take a database shared lock plus a per-key lock and are not serialized across distinct keys.

This lock preserves cross-database invariants for shared objects and fixes the lock order for blocking handoffs, WATCH, notifications and CLIENT PAUSE. Removing it requires a full concurrency audit and is deferred beyond 0.1.0.

Measured on candidate v0.1.0-rc1 (commit 11411411d72ab45456904cc602cefbb13b68ff25, 2026-11-08, Linux container on AMD Ryzen AI MAX+ 395, 4 CPUs, 2 GiB RAM, no swap, PostgreSQL 18.6, fdatasync ~0.19 ms, redis-benchmark from Redis 7.2.4 with 50 clients, no pipelining, 10,000 random keys for SET/GET, 128-byte values, 50,000 requests, gateway pool size 4):

Workloadsynchronous_commit=onsynchronous_commit=off
SET (random keys)8,423 req/s, p50 5.215 ms20,056 req/s, p50 1.527 ms
GET (random keys)29,833 req/s, p50 0.807 ms32,787 req/s, p50 0.775 ms
INCR (one hot key)2,469 req/s, p50 19.2 ms6,207 req/s, p50 7.0 ms
LPUSH (one hot key, growing to 50,000 items)2,057 req/s, p50 23.6 ms4,902 req/s, p50 9.4 ms

On storage with slower WAL flushes, latency increases proportionally: on a host with fdatasync around 20 ms, a mixed workload with synchronous_commit=on measured a p50 of 477 ms. Check disk flush latency with pg_test_fsync before deployment.

Object metadata and List encoding

Starting in extension schema 0.54, two Redis object-fidelity features are disabled by default so reads do not write WAL and list appends do not rewrite full layout metadata:

  • Access heat tracking (pg_redis.object_heat_tracking = off by default):
    • Reading a key does not update LRU/LFU metadata. A plain GET writes no WAL and does not wait for a WAL flush under synchronous_commit = on.
    • OBJECT IDLETIME returns an explicit error stating that object access tracking is disabled.
    • OBJECT FREQ returns the same error when an LFU policy is selected, or the standard Redis error when a non-LFU policy is active.
    • DEBUG OBJECT reports only the lru timestamp recorded when the key was created, replaced or restored.
  • List layout tracking (pg_redis.list_layout_tracking = off by default):
    • LPUSH, RPUSH and LLEN use the redis._list_length cache added in schema 0.54; append cost stays flat as the list grows (in 0.53, single-hot-key LPUSH was 64.6 req/s in the same benchmark environment).
    • OBJECT ENCODING and DEBUG OBJECT estimate listpack versus quicklist from current elements using list-max-listpack-size, without modeling hysteresis after a list shrinks.
    • MEMORY USAGE omits list-layout metadata bytes.
    • Lists that had recorded layout history before turning the setting off drop that history on their next write; re-enabling pg_redis.list_layout_tracking later causes OBJECT ENCODING on those lists to return an unavailable-history error until the key is recreated.

Client-side caching

CLIENT TRACKING, CLIENT CACHING, CLIENT GETREDIR and CLIENT TRACKINGINFO support default tracking, BCAST with PREFIX, OPTIN, OPTOUT, NOLOOP and client-ID redirection:

  • RESP3 connections receive invalidation pushes on the same connection or a redirected RESP3 connection; RESP2 connections receive invalidation messages on __redis__:invalidate through a redirected connection subscribed to that channel.
  • Default tracking sends one single-element key array per invalidated key (even when MSET modifies multiple keys); BCAST groups keys by registered prefix, and a full-cache flush sends a null payload.
  • SQL writes and tracking invalidations commit or roll back together in the same PostgreSQL transaction.
  • CONFIG GET/SET tracking-table-max-keys bounds distinct tracked keys across logical databases (default 1,000,000). Trimming happens synchronously inside the transaction that lowers the limit or completes a tracked read. If the notification queue or tracking index overflows, pgredis invalidates the full cache or closes the lagging recipient connection.

Binary data and size limits

Keys, values, hash fields, set members, sorted-set members, stream entries and Pub/Sub channel names are stored as bytea and preserve arbitrary byte sequences, including embedded NUL (\x00) bytes. Sorted sets order members with equal scores by raw byte comparison (memcmp).

The maximum single command argument size is 512 MiB. On commit 715827aa0 (Linux arm64, 2026-10-21, 8 GiB container), SET, GET, SET GET and GETSET with 512 MiB binary values passed under default gateway and extension memory budgets across both authentication modes and RESP2/RESP3.

Disconnects and unknown outcomes

If a connection drops, times out or fails during commit or pool reset after a command has been sent to PostgreSQL, the commit outcome may be unknown. The gateway never replays a command whose outcome is uncertain; it closes the client connection or returns an explicit unknown-outcome error.

A PostgreSQL or gateway restart terminates active network sessions, clearing WATCH registrations, blocked waits and Pub/Sub or tracking routes. PostgreSQL crash recovery restores committed table data and TTL deadlines, not transient network state.

MIGRATE

MIGRATE is supported for standalone gateway calls (including binary keys, core data types, TTL, COPY, REPLACE, AUTH, AUTH2 and KEYS):

  • The extension checks permissions, locks source keys and serializes payloads in one SQL transaction; the gateway opens a TCP connection to the target and verifies AUTH, SELECT and RESTORE replies before deleting migrated source keys.
  • If a network failure or timeout occurs after the target accepts RESTORE or while the source commit is in flight, the target may already hold a copy while the source key remains. The gateway never replays MIGRATE or deletes target keys to compensate for a source rollback.
  • Calling MIGRATE inside MULTI/EXEC or through direct SQL returns NOKEY when all named source keys are missing, and returns an explicit scope error when any source key exists because remote network writes cannot roll back with a PostgreSQL transaction.
  • On commit 715827aa0 (Linux arm64, 2026-10-21), MIGRATE between two pgredis gateways backed by separate PostgreSQL databases passed 96 cases across 8 auth/protocol combinations; gateways sharing the same PostgreSQL database time out due to database-level locking.

MONITOR

MONITOR streams command observations from the current PostgreSQL database over RESP2 or RESP3:

  • Records become visible only after the outer PostgreSQL transaction commits; rolled-back transactions and rolled-back savepoints emit no MONITOR records.
  • Complete binary arguments are preserved with control bytes escaped, while passwords in AUTH, HELLO ... AUTH and MIGRATE ... AUTH/AUTH2 are redacted.
  • Each database maintains a volatile ring buffer capped at 4 MiB and 4,096 entries. If an observer falls behind and unread entries are overwritten, or if permissions are revoked or PREPARE TRANSACTION runs on a monitored session, the gateway closes the MONITOR connection so the caller detects the gap. MONITOR is not a persistent audit log.

Test results and delivery stages

Headline test results

The release regression on v0.1.0-rc1 (packages from 11411411d, recorded 2026-11-08) is on the Status page: seven-client smoke 338/338, core differential all pass, outbox 46/46 per profile, new installation and 0.52 → 0.54 upgrade pass, and the official subset (20 files, native RESP2, out-of-scope tags excluded) 1,090 pass, 6 fail, 4 files stopped early.

The full matrices below were not run on v0.1.0-rc1. Each result is bound to the commit, platform and date in the table:

SuiteBuild and platformDateResult
Official Redis 7.2.4 server matrix (39 files × RESP2/RESP3 = 78 profiles, Redis ACL)715827aa0, Linux arm64, PG 18.62026-10-212,311 pass / 35 fail / 48 abort / 4 filtered (2,312 / 34 / 48 / 4 in the 2026-10-22 run on 3d319b780)
Official Redis 7.2.4 external matrix (39 files × native/ACL × RESP2/RESP3 = 156 profiles)715827aa0, Linux arm64, PG 18.62026-10-213,936 pass / 56 fail / 64 abort / 28 filtered (plus 28 zero-invocation profiles)
Core SQL/RESP differential suite (4 RESP + 2 SQL profiles)715827aa0, Linux arm64, PG 18.62026-10-215,187 cases per RESP profile and 5,151 cases per SQL profile; all pass
Seven-client smoke (redis-cli, redis-py, go-redis, ioredis, Jedis, Lettuce, StackExchange.Redis)715827aa0, Linux arm64, PG 18.62026-10-21169 core checks per auth mode (338/338 pass; ioredis RESP2 only)
Official unit/tracking file0.53 package, Linux amd64, PG 18.62026-10-2954/58 pass; 4 fail (2 Lua/Functions, 1 maxmemory eviction, 1 count after failed EVAL)
Mixed-dataset PostgreSQL recovery (6 RESP/SQL profiles, 48 phases)e8cb31f5, Linux amd64, Debian 13, PG 18.62026-10-30246,784 assertions pass across normal restart, immediate shutdown WAL recovery and logical restore
TTL and restart recovery regression (26 deadline fixtures × RESP2/RESP3)0.53 package, Linux amd64, Debian 13, PG 18.62026-10-301,729/1,729 checks pass across 12 database restarts and 3 PG epochs
Transactional outbox (examples/outbox.sql, native/ACL × RESP2/RESP3)715827aa0, Linux arm64, PG 18.62026-10-2146/46 checks pass in each of 4 profiles
Application suites (Django/Go, RQ 2.12.0, Spring Session 4.1.1, Sidekiq 8.1.7, Celery 5.6.3)715827aa0, Linux arm64, PG 18.62026-10-21Django/Go 64/64 core pass; Spring 48 core + 24 recovery pass; RQ 26/28 core pass; Sidekiq 6 pass on RESP3 (Lua poller unsupported); Celery 0/4 (fails at startup EVALSHA)

Delivery stages (P0–P6)

The original P0–P6 stages remain the long-term engineering roadmap. Bounded checkpoint passes and the v0.1.0-rc1 MVP candidate do not complete P0–P6:

StageScope
P0Reference sources, command inventory, test ledger and acceptance contract
P1Native PostgreSQL role identity and secure vertical slice
P2Core data types and transactions
P3Blocking commands, Pub/Sub and keyspace events
P4First installable version and operational verification
P5Extended data types, Redis ACL and application framework coverage
P6Management commands, object encoding, serialization, server behavior and seven-client matrix

4 - Architecture

Gateway, extension and storage: how one semantic core serves RESP and SQL.

pgredis is a service API protocol consisting of two components running on stock PostgreSQL 18:

  • pgredis (Go gateway): accepts Redis client connections over TCP/TLS, parses RESP2 and RESP3 frames, handles authentication, maintains MULTI queues and session state, and manages per-identity PostgreSQL connection pools. Current source uses pgx v5.12.0 with a local read-budget patch; the v0.1.0-rc1 packages use v5.11.0.
  • pg_redis (PostgreSQL 18 C extension): implements Redis 7.2.4 standalone command semantics in schema redis, enforces privileges and lock order, runs a background expiry worker via shared_preload_libraries, and stores all keys in ordinary WAL-logged PostgreSQL tables.

SQL callers (redis.command and redis.command_bin) invoke the same C core directly inside their own PostgreSQL transaction.

flowchart LR
  Client["Redis client (RESP2 / RESP3)"] --> Gateway["pgredis Go gateway"]
  Gateway --> Core["pg_redis C extension"]
  SQL["SQL transaction (redis.command)"] --> Core
  Core --> Tables["PostgreSQL 18 tables and WAL"]

Component responsibilities

ComponentResponsibilities
pgredis Go gatewayRESP2/RESP3 framing, TLS termination, authentication (native and redis-acl), MULTI command queueing, blocking/Pub/Sub polling, output buffer budgets and pooled connection reset
pg_redis C extensionCommand execution, capability checks, database and key locking, binary key/member lookup, lazy and background expiry, tracking invalidation and MONITOR staging
PostgreSQL 18ACID transactions, write-ahead log (WAL), crash recovery, physical/logical backup and streaming replication

Section contents

  • Request path — how a RESP frame executes in a PostgreSQL transaction, commits, and resets its pooled backend connection.
  • Storage — the redis.* tables behind keys, collections, Streams, Pub/Sub, blocking waits and metadata.
  • Session lifecycle — how blocking operations, Pub/Sub subscriptions, expired keys and pooled connections are managed and cleaned up.

4.1 - Request path

From a RESP frame to a committed PostgreSQL transaction and back to the client.

For an ordinary command outside MULTI, the gateway executes the command inside a PostgreSQL transaction and waits for PostgreSQL to confirm the commit before writing the RESP reply to the client.

Ordinary command sequence

  1. The gateway parses the incoming RESP2 or RESP3 frame and enforces request-header and argument-size budgets.
  2. The gateway acquires a pooled PostgreSQL connection bound to the authenticated identity.
  3. The pg_redis extension verifies function ownership and role capabilities (redis._read(), redis._write(), redis._admin()) and acquires the required database and key locks.
  4. The extension takes a current snapshot and runs the C command handler against the redis.* tables.
  5. PostgreSQL commits the transaction (including a WAL flush when synchronous_commit = on).
  6. Once the commit ReadyForQuery frame arrives, the gateway sends the RESP reply to the client and resets the backend connection before returning it to the pool.

If the gateway cannot confirm the commit or complete the connection reset, it closes the client and backend connections without replaying the command.

Fast path for plain GET and SET

Plain GET and plain SET (without extra options) use the private redis._dispatch_single entry point:

  • Instead of taking the per-database exclusive lock used by other write commands, eligible requests take a database-level shared lock plus a per-key exclusive lock held until commit or rollback.
  • If a command encounters a condition that requires broader coordination (such as shared integer objects, expiry handling, tracking notifications or waking a blocked client), the extension discards the cached lookup and upgrades to the standard exclusive path.
  • Direct SQL calls (redis.command and redis.command_bin) join the caller’s SQL transaction and do not use the gateway-only single-call entry point.

Wire pipelining and pooled-connection reset

On the PostgreSQL wire protocol, the gateway sends the command invocation and the connection-reset call (redis._pool_reset()) in a single network flush while keeping their transaction boundaries separate:

  • For validated connections, ordinary GET/SET dispatch and redis._pool_reset() use PostgreSQL FunctionCall messages, each followed by its own ReadyForQuery response.
  • The first ReadyForQuery must report an idle transaction state (I) before the gateway writes the business reply to the Redis client. If a tentative result frame precedes a commit error, the gateway suppresses the reply, closes both connections and reports an unknown-outcome error.
  • The second ReadyForQuery confirms that redis._pool_reset() cleared all session-local state (temporary settings, advisory locks, notification listeners and execution context) and returned binary true.
  • If the reset step fails after the business transaction has already committed, the gateway keeps the confirmed reply sent to the client and discards the backend connection from the pool.

4.2 - Storage

The tables behind each Redis data type and how keys, expiry and streams are stored.

All durable Redis state lives in ordinary WAL-logged PostgreSQL tables inside schema redis. The Go gateway holds no persistent data of its own.

Keyspace and binary identity

Every Redis key has one row in redis._keyspace:

CREATE TABLE redis._keyspace (
    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    db integer NOT NULL CHECK (db BETWEEN 0 AND 15),
    digest bytea NOT NULL CHECK (octet_length(digest) = 32),
    key bytea NOT NULL,
    kind "char" NOT NULL DEFAULT 's',
    value bytea,
    expires bigint
) WITH (fillfactor = 85, autovacuum_vacuum_scale_factor = 0.02);

CREATE INDEX ON redis._keyspace (db, digest);
CREATE INDEX ON redis._keyspace (expires) WHERE expires IS NOT NULL;
  • Digest-indexed lookup: Unbounded binary keys (bytea, up to 512 MiB) never enter a PostgreSQL B-tree index directly. Instead, pg_redis indexes (db, digest) using a 32-byte SHA-256 digest, locks the digest bucket, and compares the full key bytes to resolve hash collisions safely.
  • Collection child rows: Hash fields (redis._hash), Set members (redis._set), ZSet members (redis._zset), Stream groups (redis._stream_group) and Stream consumers (redis._stream_consumer) use the same 32-byte digest + full bytea comparison rule, referencing redis._keyspace(id) with ON DELETE CASCADE.
  • Sorted sets: redis._zset stores score double precision (rejecting NaN) and breaks ties by comparing full member bytes.
  • Lists and length cache: redis._list orders elements by (kid, pos, id) without putting element value bytes in a B-tree. Schema 0.54 adds redis._list_length(kid, length), maintained by statement-level transition-table triggers on redis._list so LLEN, LPUSH and RPUSH read one row instead of counting every element.

Table inventory (schema 0.54)

CategoryTablesPurpose
Keyspace and Stringsredis._keyspaceLogical DB (0–15), 32-byte digest, binary key, type tag (s, h, l, S, z, x), inline payload (value for Strings, Bitmaps, HLL) and millisecond deadline (expires)
Hashesredis._hash(kid, digest, field, value) rows per hash field
Listsredis._list, redis._list_length(kid, pos, value) element rows and statement-trigger-maintained per-list length cache
Setsredis._set(kid, digest, member) rows per set member
Sorted sets ( and Geo)redis._zset(kid, digest, member, score) rows; Geo keys store 52-bit geohash integers as ZSet scores
Streamsredis._stream, redis._stream_entry, redis._stream_node, redis._stream_radix, redis._stream_group, redis._stream_consumer, redis._stream_pel, redis._stream_configStream metadata (last_id, max_deleted_id, entries_added), live entries, listpack nodes, radix tree prefixes, consumer groups, consumers and Pending Entries List (PEL)
Object metadataredis._object_encoding, redis._object_heat, redis._object_shared_heat, redis._object_reference, redis._object_configEncoding state, optional listpack/quicklist layout (pg_redis.list_layout_tracking), optional LRU/LFU heat (pg_redis.object_heat_tracking) and shared-integer tracking
Transactionsredis._transaction_session, redis._watch, redis._exec_context, redis._mutation_statsWATCH key versions, EXEC context and per-key mutation counters
Blocking commandsredis._blocked, redis._block_keys, redis._readyBlocked waiter registrations, watched keys per waiter and committed handoff replies
Pub/Subredis._pubsub_session, redis._pubsub_subscription, redis._pubsub_message, redis._notify_configSubscriber sessions, channel/pattern/shard bindings, message ring pages and keyspace-event configuration
Client trackingredis._tracking_client, redis._tracking_key, redis._tracking_prefix, redis._tracking_pending, redis._tracking_configClient-side caching sessions, tracked key digests, BCAST prefixes and queued invalidations
Auth and Redis ACLredis._acl_user, redis._acl_session, redis._acl_log, redis._acl_config, redis._acl_service, redis._auth_ticket, redis._auth_key_ticketRedis ACL users, rules, security log and session tickets
Diagnostics and controlredis._monitor_client, redis._client_pause_control, redis._debug_control, redis._output_config, redis._slowlog_config, redis._encoding_config, redis._hll_config, redis._runtime_identityMONITOR observers, CLIENT PAUSE deadlines, DEBUG PAUSE-CRON / SET-ACTIVE-EXPIRE state, output buffer limits, SLOWLOG settings and installation identity

Encoding history and Streams

redis._object_encoding stores per-key encoding metadata (int, embstr, raw, listpack, hashtable, intset, skiplist, stream), and COPY copies this representation state alongside the key. Deleting a key cascades to its child rows and encoding metadata; transaction and savepoint rollback restore both business values and encoding state.

Streams persist both live entries (redis._stream_entry) and physical listpack/radix structures (redis._stream_node, redis._stream_radix) so XTRIM approximate trimming and XINFO STREAM FULL reflect the recorded structure.

Runtime statistics versus durable rows

Keyspace modifications and dirty counters participate in PostgreSQL WAL transactions. Runtime command call counters (INFO commandstats, INFO stats) live in bounded shared memory partitioned by database OID and extension installation identity:

  • Rolling back a SQL transaction undoes all table writes and queued notifications, while the in-memory call counter records that the command handler ran.
  • Blocking command completion counters update only after the transaction that fixes the blocking result commits; repeated blocking_poll calls do not increment completion counts again.

4.3 - Session lifecycle

Connections, authentication, pooled sessions, blocking commands and subscriptions over time.

While keys and collections persist in PostgreSQL tables across restarts, blocking waits, Pub/Sub subscriptions, client-side caching routes and pooled connections carry session state that requires explicit lifecycle management.

Blocking commands and Pub/Sub

  • Blocking registrations (redis._blocked, redis._block_keys, redis._ready):
    1. When a blocking command (BLPOP, BLMOVE, BZPOPMIN, XREAD BLOCK, XREADGROUP BLOCK, WAIT) cannot be satisfied immediately, redis.blocking_begin records the waiter, logical database, opaque token, command arguments and reply protocol.
    2. When a producer writes to a watched key (or when the timeout expires), a single PostgreSQL transaction consumes the element and writes the wire-formatted reply into redis._ready, then sends a PostgreSQL NOTIFY wakeup.
    3. Inside MULTI/EXEC, waiters only see the final state after the entire EXEC batch completes; an item pushed and deleted within the same EXEC never escapes to a blocked reader.
    4. The gateway polls redis.blocking_poll to retrieve the stored reply without re-executing the pop, or calls redis.blocking_cancel on disconnect.
  • Pub/Sub and tracking routes (redis._pubsub_*, redis._tracking_*):
    1. redis.pubsub_open and redis.pubsub_change register subscriptions in PostgreSQL tables with a lease deadline.
    2. Publishers write message pages to redis._pubsub_message (and tracking invalidations to redis._tracking_pending) inside their transaction and emit NOTIFY.
    3. The gateway drains committed batches via redis.pubsub_poll. Lease expiry garbage-collects abandoned sessions if a gateway crashes, and bounded queue quotas close lagging subscribers when unread bytes exceed limits.

Key expiry and background maintenance

  • Lazy expiry: Any foreground command that accesses an expired key removes its physical row inside the current transaction (or treats it as missing on a read-only path).
  • Active background expiry: When pg_redis is loaded via shared_preload_libraries, a background coordinator discovers databases containing the extension and runs periodic workers that delete expired rows from redis._keyspace in batches, clean up expired blocking/Pub/Sub leases, trim tracking tables and compact mutation counters. PostgreSQL VACUUM later reclaims dead tuples.
  • Maintenance pause (DEBUG PAUSE-CRON 0|1): Administrators can pause periodic background maintenance in the current database by writing a postmaster-epoch-scoped control row in redis._debug_control. Workers check this row at the start of each maintenance cycle and skip background cleanup while paused, while foreground commands and lazy expiry continue normally. A PostgreSQL restart starts a new postmaster epoch and automatically resumes default background maintenance.

Pooled connection reuse and shutdown

  • Each client connection has a single output writer goroutine in the gateway.
  • A PostgreSQL backend connection returns to the gateway’s per-identity pool only after its business transaction commits and redis._pool_reset() confirms an idle, clean session (ReadyForQuery = I and binary true receipt).
  • Connections that encounter an unconfirmed commit, a reset error, a canceled context or an open transaction are closed and discarded from the pool.
  • Shutting down or restarting the gateway or PostgreSQL terminates active client connections. Restart recovery restores committed keys and TTL deadlines in PostgreSQL, while clients must reconnect and re-establish WATCH state, blocking waits and Pub/Sub or tracking subscriptions.

5 - Reference

Commands, data types, SQL API, transactions, Pub/Sub, Streams, configuration and limits.

This section documents the pgredis wire commands, PostgreSQL SQL functions, transaction and notification contracts, gateway flags, extension GUCs, and resource budgets.

Reference pages

  • Commands

    All 392 Redis 7.2.4 command and subcommand entries from spec/commands.json, grouped by family with implementation state.
  • Data types

    Strings, Hashes, Lists, Sets, Sorted Sets, Streams, Bitmaps, HyperLogLog, GEO, and object inspection commands.
  • SQL API

    redis.command, redis.command_bin, multi-transaction blocking and Pub/Sub session functions, and SQLSTATE error codes.
  • Transactions and retries

    MULTI/EXEC, WATCH, SQL transaction participation, and handling UNKNOWN outcomes after lost responses.
  • Pub/Sub and keyspace events

    Channel, pattern, and sharded subscriptions, notify-keyspace-events, and backpressure limits.
  • Streams and consumer groups

    Stream IDs, XADD/XRANGE/XTRIM, consumer groups, pending entries (XPENDING, XCLAIM, XAUTOCLAIM), and blocking reads.
  • Configuration

    pgredis gateway CLI flags, connection pools, pg_redis extension GUCs, and supported CONFIG GET/SET parameters.
  • Limits

    Request, reply, shared buffer, and backend workspace budgets, mutation-counter compaction, and tested 512 MiB capacity.

5.1 - Commands

The Redis 7.2.4 command inventory with implementation state per family.

This page is generated from spec/commands.json in the pgredis repository (v0.1.0-rc1, schema 0.54, commit 11411411d72ab45456904cc602cefbb13b68ff25), which tracks 392 Redis 7.2.4 command and subcommand entries:

  • 305 entries are marked partial-slice (implemented in the C extension, Go gateway, or both).
  • 87 entries are marked pending (32 Cluster, 22 Sentinel, 19 Scripting, and 14 Server commands that return explicit unsupported errors).
  • All 392 entries carry compatibility_verified: false in the specification file: partial-slice records implementation presence, not full certification. See Compatibility and Status for dated test results.

In the arity column, a positive integer is the exact argument count including the command word, and a negative integer is the minimum argument count (for example, -3 for SET means at least command, key, and value).

Summary by family

FamilyTotalpartial-slicependingExecution owner
String22220extension
Hash16160extension
List22220extension
Set17170extension
Sorted set35350extension
Stream25250extension
Bitmap770extension
GEO10100extension
HyperLogLog550extension
Keyspace34340extension
Transactions550gateway+extension
Pub/Sub15150extension
Connection26260extension, gateway, gateway+extension
Server766214extension
Cluster32032extension
Sentinel22022extension
Scripting23419extension

String

CommandArityOwnerImplementation
APPEND3extensionpartial-slice
DECR2extensionpartial-slice
DECRBY3extensionpartial-slice
GET2extensionpartial-slice
GETDEL2extensionpartial-slice
GETEX-2extensionpartial-slice
GETRANGE4extensionpartial-slice
GETSET3extensionpartial-slice
INCR2extensionpartial-slice
INCRBY3extensionpartial-slice
INCRBYFLOAT3extensionpartial-slice
LCS-3extensionpartial-slice
MGET-2extensionpartial-slice
MSET-3extensionpartial-slice
MSETNX-3extensionpartial-slice
PSETEX4extensionpartial-slice
SET-3extensionpartial-slice
SETEX4extensionpartial-slice
SETNX3extensionpartial-slice
SETRANGE4extensionpartial-slice
STRLEN2extensionpartial-slice
SUBSTR4extensionpartial-slice

Hash

CommandArityOwnerImplementation
HDEL-3extensionpartial-slice
HEXISTS3extensionpartial-slice
HGET3extensionpartial-slice
HGETALL2extensionpartial-slice
HINCRBY4extensionpartial-slice
HINCRBYFLOAT4extensionpartial-slice
HKEYS2extensionpartial-slice
HLEN2extensionpartial-slice
HMGET-3extensionpartial-slice
HMSET-4extensionpartial-slice
HRANDFIELD-2extensionpartial-slice
HSCAN-3extensionpartial-slice
HSET-4extensionpartial-slice
HSETNX4extensionpartial-slice
HSTRLEN3extensionpartial-slice
HVALS2extensionpartial-slice

List

CommandArityOwnerImplementation
BLMOVE6extensionpartial-slice
BLMPOP-5extensionpartial-slice
BLPOP-3extensionpartial-slice
BRPOP-3extensionpartial-slice
BRPOPLPUSH4extensionpartial-slice
LINDEX3extensionpartial-slice
LINSERT5extensionpartial-slice
LLEN2extensionpartial-slice
LMOVE5extensionpartial-slice
LMPOP-4extensionpartial-slice
LPOP-2extensionpartial-slice
LPOS-3extensionpartial-slice
LPUSH-3extensionpartial-slice
LPUSHX-3extensionpartial-slice
LRANGE4extensionpartial-slice
LREM4extensionpartial-slice
LSET4extensionpartial-slice
LTRIM4extensionpartial-slice
RPOP-2extensionpartial-slice
RPOPLPUSH3extensionpartial-slice
RPUSH-3extensionpartial-slice
RPUSHX-3extensionpartial-slice

Set

CommandArityOwnerImplementation
SADD-3extensionpartial-slice
SCARD2extensionpartial-slice
SDIFF-2extensionpartial-slice
SDIFFSTORE-3extensionpartial-slice
SINTER-2extensionpartial-slice
SINTERCARD-3extensionpartial-slice
SINTERSTORE-3extensionpartial-slice
SISMEMBER3extensionpartial-slice
SMEMBERS2extensionpartial-slice
SMISMEMBER-3extensionpartial-slice
SMOVE4extensionpartial-slice
SPOP-2extensionpartial-slice
SRANDMEMBER-2extensionpartial-slice
SREM-3extensionpartial-slice
SSCAN-3extensionpartial-slice
SUNION-2extensionpartial-slice
SUNIONSTORE-3extensionpartial-slice

Sorted set

CommandArityOwnerImplementation
BZMPOP-5extensionpartial-slice
BZPOPMAX-3extensionpartial-slice
BZPOPMIN-3extensionpartial-slice
ZADD-4extensionpartial-slice
ZCARD2extensionpartial-slice
ZCOUNT4extensionpartial-slice
ZDIFF-3extensionpartial-slice
ZDIFFSTORE-4extensionpartial-slice
ZINCRBY4extensionpartial-slice
ZINTER-3extensionpartial-slice
ZINTERCARD-3extensionpartial-slice
ZINTERSTORE-4extensionpartial-slice
ZLEXCOUNT4extensionpartial-slice
ZMPOP-4extensionpartial-slice
ZMSCORE-3extensionpartial-slice
ZPOPMAX-2extensionpartial-slice
ZPOPMIN-2extensionpartial-slice
ZRANDMEMBER-2extensionpartial-slice
ZRANGE-4extensionpartial-slice
ZRANGEBYLEX-4extensionpartial-slice
ZRANGEBYSCORE-4extensionpartial-slice
ZRANGESTORE-5extensionpartial-slice
ZRANK-3extensionpartial-slice
ZREM-3extensionpartial-slice
ZREMRANGEBYLEX4extensionpartial-slice
ZREMRANGEBYRANK4extensionpartial-slice
ZREMRANGEBYSCORE4extensionpartial-slice
ZREVRANGE-4extensionpartial-slice
ZREVRANGEBYLEX-4extensionpartial-slice
ZREVRANGEBYSCORE-4extensionpartial-slice
ZREVRANK-3extensionpartial-slice
ZSCAN-3extensionpartial-slice
ZSCORE3extensionpartial-slice
ZUNION-3extensionpartial-slice
ZUNIONSTORE-4extensionpartial-slice

Stream

CommandArityOwnerImplementation
XACK-4extensionpartial-slice
XADD-5extensionpartial-slice
XAUTOCLAIM-6extensionpartial-slice
XCLAIM-6extensionpartial-slice
XDEL-3extensionpartial-slice
XGROUP-2extensionpartial-slice
XGROUP CREATE-5extensionpartial-slice
XGROUP CREATECONSUMER5extensionpartial-slice
XGROUP DELCONSUMER5extensionpartial-slice
XGROUP DESTROY4extensionpartial-slice
XGROUP HELP2extensionpartial-slice
XGROUP SETID-5extensionpartial-slice
XINFO-2extensionpartial-slice
XINFO CONSUMERS4extensionpartial-slice
XINFO GROUPS3extensionpartial-slice
XINFO HELP2extensionpartial-slice
XINFO STREAM-3extensionpartial-slice
XLEN2extensionpartial-slice
XPENDING-3extensionpartial-slice
XRANGE-4extensionpartial-slice
XREAD-4extensionpartial-slice
XREADGROUP-7extensionpartial-slice
XREVRANGE-4extensionpartial-slice
XSETID-3extensionpartial-slice
XTRIM-4extensionpartial-slice

Bitmap

CommandArityOwnerImplementation
BITCOUNT-2extensionpartial-slice
BITFIELD-2extensionpartial-slice
BITFIELD_RO-2extensionpartial-slice
BITOP-4extensionpartial-slice
BITPOS-3extensionpartial-slice
GETBIT3extensionpartial-slice
SETBIT4extensionpartial-slice

GEO

CommandArityOwnerImplementation
GEOADD-5extensionpartial-slice
GEODIST-4extensionpartial-slice
GEOHASH-2extensionpartial-slice
GEOPOS-2extensionpartial-slice
GEORADIUS-6extensionpartial-slice
GEORADIUSBYMEMBER-5extensionpartial-slice
GEORADIUSBYMEMBER_RO-5extensionpartial-slice
GEORADIUS_RO-6extensionpartial-slice
GEOSEARCH-7extensionpartial-slice
GEOSEARCHSTORE-8extensionpartial-slice

HyperLogLog

CommandArityOwnerImplementation
PFADD-2extensionpartial-slice
PFCOUNT-2extensionpartial-slice
PFDEBUG3extensionpartial-slice
PFMERGE-2extensionpartial-slice
PFSELFTEST1extensionpartial-slice

Keyspace

CommandArityOwnerImplementation
COPY-3extensionpartial-slice
DEL-2extensionpartial-slice
DUMP2extensionpartial-slice
EXISTS-2extensionpartial-slice
EXPIRE-3extensionpartial-slice
EXPIREAT-3extensionpartial-slice
EXPIRETIME2extensionpartial-slice
KEYS2extensionpartial-slice
MIGRATE-6extensionpartial-slice
MOVE3extensionpartial-slice
OBJECT-2extensionpartial-slice
OBJECT ENCODING3extensionpartial-slice
OBJECT FREQ3extensionpartial-slice
OBJECT HELP2extensionpartial-slice
OBJECT IDLETIME3extensionpartial-slice
OBJECT REFCOUNT3extensionpartial-slice
PERSIST2extensionpartial-slice
PEXPIRE-3extensionpartial-slice
PEXPIREAT-3extensionpartial-slice
PEXPIRETIME2extensionpartial-slice
PTTL2extensionpartial-slice
RANDOMKEY1extensionpartial-slice
RENAME3extensionpartial-slice
RENAMENX3extensionpartial-slice
RESTORE-4extensionpartial-slice
SCAN-2extensionpartial-slice
SORT-2extensionpartial-slice
SORT_RO-2extensionpartial-slice
TOUCH-2extensionpartial-slice
TTL2extensionpartial-slice
TYPE2extensionpartial-slice
UNLINK-2extensionpartial-slice
WAIT3extensionpartial-slice
WAITAOF4extensionpartial-slice

Transactions

CommandArityOwnerImplementation
DISCARD1gateway+extensionpartial-slice
EXEC1gateway+extensionpartial-slice
MULTI1gateway+extensionpartial-slice
UNWATCH1gateway+extensionpartial-slice
WATCH-2gateway+extensionpartial-slice

Pub/Sub

CommandArityOwnerImplementation
PSUBSCRIBE-2extensionpartial-slice
PUBLISH3extensionpartial-slice
PUBSUB-2extensionpartial-slice
PUBSUB CHANNELS-2extensionpartial-slice
PUBSUB HELP2extensionpartial-slice
PUBSUB NUMPAT2extensionpartial-slice
PUBSUB NUMSUB-2extensionpartial-slice
PUBSUB SHARDCHANNELS-2extensionpartial-slice
PUBSUB SHARDNUMSUB-2extensionpartial-slice
PUNSUBSCRIBE-1extensionpartial-slice
SPUBLISH3extensionpartial-slice
SSUBSCRIBE-2extensionpartial-slice
SUBSCRIBE-2extensionpartial-slice
SUNSUBSCRIBE-1extensionpartial-slice
UNSUBSCRIBE-1extensionpartial-slice

Connection

CommandArityOwnerImplementation
AUTH-2gatewaypartial-slice
CLIENT-2extensionpartial-slice
CLIENT CACHING3extensionpartial-slice
CLIENT GETNAME2gatewaypartial-slice
CLIENT GETREDIR2extensionpartial-slice
CLIENT HELP2extensionpartial-slice
CLIENT ID2extensionpartial-slice
CLIENT INFO2extensionpartial-slice
CLIENT KILL-3extensionpartial-slice
CLIENT LIST-2extensionpartial-slice
CLIENT NO-EVICT3extensionpartial-slice
CLIENT NO-TOUCH3gateway+extensionpartial-slice
CLIENT PAUSE-3extensionpartial-slice
CLIENT REPLY3extensionpartial-slice
CLIENT SETINFO4gatewaypartial-slice
CLIENT SETNAME3gatewaypartial-slice
CLIENT TRACKING-3extensionpartial-slice
CLIENT TRACKINGINFO2extensionpartial-slice
CLIENT UNBLOCK-3extensionpartial-slice
CLIENT UNPAUSE2extensionpartial-slice
ECHO2gatewaypartial-slice
HELLO-1gatewaypartial-slice
PING-1gatewaypartial-slice
QUIT-1gatewaypartial-slice
RESET1gatewaypartial-slice
SELECT2gatewaypartial-slice

Server

CommandArityOwnerImplementation
ACL-2extensionpartial-slice
ACL CAT-2extensionpartial-slice
ACL DELUSER-3extensionpartial-slice
ACL DRYRUN-4extensionpartial-slice
ACL GENPASS-2extensionpartial-slice
ACL GETUSER3extensionpartial-slice
ACL HELP2extensionpartial-slice
ACL LIST2extensionpartial-slice
ACL LOAD2extensionpartial-slice
ACL LOG-2extensionpartial-slice
ACL SAVE2extensionpartial-slice
ACL SETUSER-3extensionpartial-slice
ACL USERS2extensionpartial-slice
ACL WHOAMI2extensionpartial-slice
BGREWRITEAOF1extensionpending
BGSAVE-1extensionpending
COMMAND-1extensionpartial-slice
COMMAND COUNT2extensionpartial-slice
COMMAND DOCS-2extensionpartial-slice
COMMAND GETKEYS-3extensionpartial-slice
COMMAND GETKEYSANDFLAGS-3extensionpartial-slice
COMMAND HELP2extensionpartial-slice
COMMAND INFO-2extensionpartial-slice
COMMAND LIST-2extensionpartial-slice
CONFIG-2extensionpartial-slice
CONFIG GET-3extensionpartial-slice
CONFIG HELP2extensionpartial-slice
CONFIG RESETSTAT2extensionpartial-slice
CONFIG REWRITE2extensionpartial-slice
CONFIG SET-4extensionpartial-slice
DBSIZE1extensionpartial-slice
DEBUG-2extensionpartial-slice
FAILOVER-1extensionpending
FLUSHALL-1extensionpartial-slice
FLUSHDB-1extensionpartial-slice
INFO-1extensionpartial-slice
LASTSAVE1extensionpartial-slice
LATENCY-2extensionpartial-slice
LATENCY DOCTOR2extensionpartial-slice
LATENCY GRAPH3extensionpartial-slice
LATENCY HELP2extensionpartial-slice
LATENCY HISTOGRAM-2extensionpartial-slice
LATENCY HISTORY3extensionpartial-slice
LATENCY LATEST2extensionpartial-slice
LATENCY RESET-2extensionpartial-slice
LOLWUT-1extensionpartial-slice
MEMORY-2extensionpartial-slice
MEMORY DOCTOR2extensionpartial-slice
MEMORY HELP2extensionpartial-slice
MEMORY MALLOC-STATS2extensionpartial-slice
MEMORY PURGE2extensionpartial-slice
MEMORY STATS2extensionpartial-slice
MEMORY USAGE-3extensionpartial-slice
MODULE-2extensionpartial-slice
MODULE HELP2extensionpartial-slice
MODULE LIST2extensionpartial-slice
MODULE LOAD-3extensionpending
MODULE LOADEX-3extensionpending
MODULE UNLOAD3extensionpending
MONITOR1extensionpartial-slice
PSYNC-3extensionpending
REPLCONF-1extensionpending
REPLICAOF3extensionpending
RESTORE-ASKING-4extensionpending
ROLE1extensionpartial-slice
SAVE1extensionpending
SHUTDOWN-1extensionpending
SLAVEOF3extensionpending
SLOWLOG-2extensionpartial-slice
SLOWLOG GET-2extensionpartial-slice
SLOWLOG HELP2extensionpartial-slice
SLOWLOG LEN2extensionpartial-slice
SLOWLOG RESET2extensionpartial-slice
SWAPDB3extensionpartial-slice
SYNC1extensionpending
TIME1extensionpartial-slice

Cluster

CommandArityOwnerImplementation
ASKING1extensionpending
CLUSTER-2extensionpending
CLUSTER ADDSLOTS-3extensionpending
CLUSTER ADDSLOTSRANGE-4extensionpending
CLUSTER BUMPEPOCH2extensionpending
CLUSTER COUNT-FAILURE-REPORTS3extensionpending
CLUSTER COUNTKEYSINSLOT3extensionpending
CLUSTER DELSLOTS-3extensionpending
CLUSTER DELSLOTSRANGE-4extensionpending
CLUSTER FAILOVER-2extensionpending
CLUSTER FLUSHSLOTS2extensionpending
CLUSTER FORGET3extensionpending
CLUSTER GETKEYSINSLOT4extensionpending
CLUSTER HELP2extensionpending
CLUSTER INFO2extensionpending
CLUSTER KEYSLOT3extensionpending
CLUSTER LINKS2extensionpending
CLUSTER MEET-4extensionpending
CLUSTER MYID2extensionpending
CLUSTER MYSHARDID2extensionpending
CLUSTER NODES2extensionpending
CLUSTER REPLICAS3extensionpending
CLUSTER REPLICATE3extensionpending
CLUSTER RESET-2extensionpending
CLUSTER SAVECONFIG2extensionpending
CLUSTER SET-CONFIG-EPOCH3extensionpending
CLUSTER SETSLOT-4extensionpending
CLUSTER SHARDS2extensionpending
CLUSTER SLAVES3extensionpending
CLUSTER SLOTS2extensionpending
READONLY1extensionpending
READWRITE1extensionpending

Sentinel

CommandArityOwnerImplementation
SENTINEL-2extensionpending
SENTINEL CKQUORUM3extensionpending
SENTINEL CONFIG-4extensionpending
SENTINEL DEBUG-2extensionpending
SENTINEL FAILOVER3extensionpending
SENTINEL FLUSHCONFIG2extensionpending
SENTINEL GET-MASTER-ADDR-BY-NAME3extensionpending
SENTINEL HELP2extensionpending
SENTINEL INFO-CACHE-3extensionpending
SENTINEL IS-MASTER-DOWN-BY-ADDR6extensionpending
SENTINEL MASTER3extensionpending
SENTINEL MASTERS2extensionpending
SENTINEL MONITOR6extensionpending
SENTINEL MYID2extensionpending
SENTINEL PENDING-SCRIPTS2extensionpending
SENTINEL REMOVE3extensionpending
SENTINEL REPLICAS3extensionpending
SENTINEL RESET3extensionpending
SENTINEL SENTINELS3extensionpending
SENTINEL SET-5extensionpending
SENTINEL SIMULATE-FAILURE-3extensionpending
SENTINEL SLAVES3extensionpending

Scripting

CommandArityOwnerImplementation
EVAL-3extensionpending
EVALSHA-3extensionpending
EVALSHA_RO-3extensionpending
EVAL_RO-3extensionpending
FCALL-3extensionpending
FCALL_RO-3extensionpending
FUNCTION-2extensionpartial-slice
FUNCTION DELETE3extensionpending
FUNCTION DUMP2extensionpending
FUNCTION FLUSH-2extensionpartial-slice
FUNCTION HELP2extensionpending
FUNCTION KILL2extensionpending
FUNCTION LIST-2extensionpending
FUNCTION LOAD-3extensionpending
FUNCTION RESTORE-3extensionpending
FUNCTION STATS2extensionpending
SCRIPT-2extensionpartial-slice
SCRIPT DEBUG3extensionpending
SCRIPT EXISTS-3extensionpending
SCRIPT FLUSH-2extensionpartial-slice
SCRIPT HELP2extensionpending
SCRIPT KILL2extensionpending
SCRIPT LOAD3extensionpending

5.2 - Data types

Strings, hashes, lists, sets, sorted sets, streams, bitmaps, HyperLogLog and geo.

pgredis implements command families for the core Redis 7.2.4 data types and derived structures inside PostgreSQL 18 tables. Every key has one metadata row in redis._keyspace and stores its payload in the matching typed table. See Storage for the underlying table layout and Commands for the per-command list.

Core types

TypeBacking tablePrimary useRepresentative commands
Stringredis._stringByte sequences, integers, floats, or bitmapsSET, GET, MSET, MGET, INCR, INCRBYFLOAT, LCS
Hashredis._hashField/value maps under one keyHSET, HGET, HMGET, HGETALL, HINCRBY, HRANDFIELD, HSCAN
Listredis._list, redis._list_lengthOrdered sequences of elements (duplicates allowed)LPUSH, RPUSH, LPOP, LRANGE, LINDEX, LINSERT, BLMOVE, BLPOP
Setredis._setUnordered collections of unique membersSADD, SREM, SMEMBERS, SISMEMBER, SUNION, SINTER, SSCAN
Sorted setredis._zsetUnique members ordered by float8 score, then raw member bytesZADD, ZRANGE, ZREM, ZSCORE, ZRANK, ZUNIONSTORE, BZPOPMIN
Streamredis._stream, redis._stream_group, redis._stream_pelAppend-only entries ordered by (ms, seq) ID with consumer groupsXADD, XRANGE, XREAD, XGROUP, XREADGROUP, XACK, XAUTOCLAIM

Keys, string values, hash fields, list elements, set members, and sorted-set members are stored as bytea and preserve arbitrary binary sequences, including NUL (\x00) bytes. When calling from SQL with non-UTF-8 or NUL-containing bytes, use redis.command_bin.

Bitmaps, GEO, and HyperLogLog

  • Bitmaps: SETBIT, GETBIT, BITCOUNT, BITPOS, BITOP, and BITFIELD / BITFIELD_RO operate on the underlying String value in redis._string (redis._bitmap helpers), preserving byte-exact compatibility with GET and SET.
  • GEO: GEOADD, GEODIST, GEOHASH, GEOPOS, GEORADIUS, GEORADIUSBYMEMBER, GEOSEARCH, and GEOSEARCHSTORE store 52-bit geohash integers as scores inside redis._zset. Radius and box queries, result limits, ASC/DESC ordering, and destination key writes are supported; manually inserted scores outside the valid GEO domain differ from Redis in edge-case error reporting.
  • HyperLogLog: PFADD, PFCOUNT, and PFMERGE store the Redis 7.2.4 sparse and dense HLL representations inside String values (HYLL header), so GET and SET can read or restore raw HyperLogLog state directly.

Object operations

  • DUMP and RESTORE: DUMP serializes a single key in Redis RDB v11 payload format with a 64-bit CRC64 checksum, and RESTORE reconstructs the key (REPLACE, ABSTTL, IDLETIME, FREQ). They operate on individual keys and do not read or write whole-instance .rdb or AOF files; use PostgreSQL backup tools for database backups.
  • OBJECT and DEBUG OBJECT: OBJECT ENCODING reports the Redis-compatible encoding name (int, embstr, raw, listpack, hashtable, skiplist, stream). OBJECT IDLETIME and OBJECT FREQ require pg_redis.object_heat_tracking = on, and exact listpack/quicklist transition tracking requires pg_redis.list_layout_tracking = on (both default to off so ordinary reads and list writes avoid extra metadata updates; see Compatibility).

5.3 - SQL API

redis.command, redis.command_bin, sessions for blocking and Pub/Sub, errors and savepoints.

The pg_redis extension exposes SQL functions in schema redis so PostgreSQL transactions, stored procedures, and triggers can execute Redis commands in the same transaction as relational tables. Every function returns wire-formatted RESP replies as bytea.

For step-by-step examples, see SQL rollback, Binary keys and values, and Transactional outbox.

Command functions

FunctionArgumentsDescription
redis.command(text[], integer DEFAULT 0)Command and arguments as text[], followed by logical database number (0..15)Executes one command and returns a RESP2 reply as bytea.
redis.command_bin(bytea[], integer DEFAULT 0)Command and arguments as bytea[], followed by logical database number (0..15)Binary-safe entry point for NUL (\x00) bytes or non-UTF-8 payloads; returns a RESP2 reply as bytea.
SELECT encode(redis.command(ARRAY['PING']), 'hex');
-- 2b504f4e470d0a (+PONG\r\n)

SELECT convert_from(redis.command(ARRAY['GET', 'example:key'], 1), 'UTF8');
-- Reads example:key from logical database 1

Calling redis.command invokes redis.command_bin internally, so the calling PostgreSQL role requires USAGE ON SCHEMA redis, EXECUTE on both functions, and EXECUTE on the required capability marker (redis._read(), redis._write(), or redis._admin()). See Authentication and permissions for the complete GRANT list.

Errors, savepoints, and transaction scope

  • Shared transaction: Both functions execute inside the caller’s READ COMMITTED PostgreSQL transaction (REPEATABLE READ and SERIALIZABLE are rejected). Even when invoked from a SQL SELECT, a mutating command such as SET writes rows and requires redis._write().
  • SQLSTATE codes: Redis command errors (such as WRONGTYPE or syntax errors) raise SQLSTATE RD001. Commands blocked by CLIENT PAUSE raise SQLSTATE RD002. PostgreSQL engine errors (such as deadlocks or constraint failures) retain their native PostgreSQL SQLSTATE codes.
  • Savepoint recovery: Because an unhandled RD001 aborts the current SQL transaction block, wrap fallible Redis calls in a SAVEPOINT (or a PL/pgSQL BEGIN ... EXCEPTION WHEN SQLSTATE 'RD001' THEN ... END block) to recover without losing earlier SQL work.
  • Per-call database index: The db parameter applies only to that function call. Executing SELECT inside redis.command does not change the logical database for subsequent SQL calls.

Blocking and Pub/Sub session API

Ordinary SQL calls cannot hold a transaction open while waiting for another transaction to publish a message or push a list item. For blocking commands (BLPOP, BLMOVE, BZPOPMIN, XREAD BLOCK, XREADGROUP BLOCK, WAIT) and Pub/Sub subscriptions across multiple SQL transactions, use the session functions:

FunctionPositional parametersReturn value (bytea)
redis.blocking_begin(bytea[], bytea, integer DEFAULT 0)args, token, db=0Registers a blocking command with RESP2 reply encoding; returns a 2-element RESP2 array [flag, result].
redis.blocking_begin(bytea[], bytea, integer, integer)args, token, db, protocolRegisters a blocking command with explicit reply protocol (2 or 3); returns [flag, result].
redis.blocking_poll(bytea, integer DEFAULT 0)token, db=0Polls for completion and renews the lease; returns [flag, result].
redis.blocking_cancel(bytea, integer DEFAULT 0)token, db=0Deletes the registration and returns +OK\r\n.
redis.pubsub_open(bytea, integer DEFAULT 2)token, protocol=2Opens a Pub/Sub session with protocol 2 or 3; returns +OK\r\n.
redis.pubsub_change(bytea, bytea[])token, argsApplies a subscription command (SUBSCRIBE, UNSUBSCRIBE, PSUBSCRIBE, SSUBSCRIBE, etc.); returns [count, frames].
redis.pubsub_poll(bytea)tokenDequeues pending messages in the current transaction; returns [count, frames].
redis.pubsub_cancel(bytea)tokenCloses the Pub/Sub session and deletes queued messages; returns +OK\r\n.

Parameter and lifecycle rules:

  • token is a unique 32-byte bytea generated by the caller for each blocking wait or Pub/Sub session. All subsequent poll, change, and cancel calls must use the same LOGIN and active role.
  • For blocking operations, [flag, result] has flag = 0 (with a null bulk string) while waiting, and flag = 1 once fulfilled. Register with blocking_begin and commit first, then call blocking_poll in subsequent transactions. Repeated polls after completion return the fixed result without popping a second element.
  • For Pub/Sub, pubsub_poll deletes delivered rows from redis._pubsub_event inside the caller’s transaction; rolling back that transaction restores the messages to the queue.

5.4 - Transactions and retries

MULTI, EXEC, WATCH, commit outcomes and when a client may retry.

SQL callers and Redis wire clients share the same PostgreSQL storage tables and WAL, but they enter transactions through different boundaries.

MULTI, EXEC, and WATCH

MULTI starts a command queue in the Go gateway. EXEC dispatches the queued commands inside a single PostgreSQL READ COMMITTED transaction. An idle MULTI or WATCH session on a client connection does not hold an open PostgreSQL transaction in the background.

ConditionBehavior on EXEC
Unknown command or wrong arity while queuingQueuing records the syntax error and EXEC aborts the queue with -EXECABORT Transaction discarded because of previous errors.
Runtime command error inside EXEC (for example WRONGTYPE)That slot in the EXEC array reply contains the error frame; sibling commands in the queue still execute and commit, matching Redis.
Watched key modified before EXECEXEC returns a null array reply (*-1\r\n in RESP2, _\r\n in RESP3) and applies no changes.
PostgreSQL engine error (such as deadlock or out-of-workspace error)The entire PostgreSQL transaction rolls back so no partial EXEC state persists.
  • WATCH on existing and missing keys: WATCH registers key digests in redis._watch. If another client creates and then deletes a watched missing key (or modifies a key and restores its previous value), row triggers record the revision change and EXEC detects the conflict.
  • Deterministic command time and wakeups: All commands inside one EXEC batch share a single timestamp for key expiry checks. Blocked clients waiting on keys touched by EXEC observe the final committed state after the entire queue finishes.

SQL transactions

Multiple calls to redis.command and redis.command_bin inside BEGIN ... COMMIT join the caller’s outer SQL transaction:

  • Relational table rows, Redis key mutations, and queued Pub/Sub / tracking / blocking notifications commit or roll back atomically. See the SQL rollback tutorial.
  • Only READ COMMITTED transaction isolation is supported. Calling redis.command under REPEATABLE READ or SERIALIZABLE raises an explicit error because internal lock-wait re-reads require fresh statement snapshots.
  • Mixing SQL row locks and Redis key mutations across concurrent transactions in different orders can form a PostgreSQL deadlock. PostgreSQL aborts one participant with SQLSTATE 40P01; applications should handle deadlock retries at the transaction boundary.

Handling lost responses (UNKNOWN outcomes)

When a client sends a mutating command (INCR, LPOP, PUBLISH, XADD, EXEC) and the network connection drops or times out before the reply arrives, the PostgreSQL transaction may have already committed. Reconnecting and running PING only proves that the new socket works; it cannot reveal whether the previous write committed.

  • Gateway behavior: When a connection becomes uncertain (read/write timeout, PostgreSQL link drop, or output buffer overflow), the gateway closes the client socket and retires the backend connection without automatically re-running the command.
  • Client library retry pitfalls: Many Redis client libraries enable automatic command retries by default. In Linux acceptance tests (aade9dfa0, 2026-10-15), a default redis-py 6.4.0 client (which defaults to 3 retries) repeated an INCR after a dropped reply and incremented the counter to 2. Setting Retry(NoBackoff(), 0) sent the command once and raised a connection error, leaving the caller responsible for resolving the UNKNOWN state. Even with zero connection retries, redis-py’s Redis.transaction() helper catches WatchError and re-runs its callback when an EXEC reply is lost.
  • Safe retry patterns: For non-idempotent operations, either disable automatic client retries and inspect application state before retrying, or record an idempotency key / outbox row in the same transaction (as shown in the Transactional outbox tutorial).

5.5 - Pub/Sub and keyspace events

Channels, patterns, sharded Pub/Sub and keyspace notifications.

pgredis implements Redis Pub/Sub channels (SUBSCRIBE, UNSUBSCRIBE, PUBLISH), pattern subscriptions (PSUBSCRIBE, PUNSUBSCRIBE), standalone sharded Pub/Sub (SSUBSCRIBE, SUNSUBSCRIBE, SPUBLISH), introspection (PUBSUB CHANNELS, PUBSUB NUMSUB, PUBSUB NUMPAT, PUBSUB SHARDCHANNELS, PUBSUB SHARDNUMSUB), and keyspace notifications (notify-keyspace-events).

Subscriptions and transactional delivery

  • Commit-ordered registration: The gateway confirms SUBSCRIBE, PSUBSCRIBE, or SSUBSCRIBE only after PostgreSQL commits the subscription registration in redis._pubsub_session. Any PUBLISH or SPUBLISH committed afterwards reaches the subscriber.
  • Transactional publishing: Because PUBLISH inserts into redis._pubsub_event inside the publisher’s PostgreSQL transaction, rolling back a SQL transaction or aborting EXEC discards any messages published inside that transaction. Publishing the same payload twice in committed transactions delivers two distinct messages.
  • Sharded Pub/Sub scope: SSUBSCRIBE, SUNSUBSCRIBE, and SPUBLISH operate within the standalone PostgreSQL database; they do not route messages across a Redis Cluster.
  • SQL session API: SQL callers use redis.pubsub_open, redis.pubsub_change, redis.pubsub_poll, and redis.pubsub_cancel. Commit the subscription transaction before publishing from another connection. pubsub_poll deletes delivered messages in its own transaction, and a rollback restores them.

Keyspace notifications

CONFIG SET notify-keyspace-events <flags> enables keyspace (__keyspace@<db>__:<key>) and keyevent (__keyevent@<db>__:<event>) notifications across all 16 logical Redis databases in the current PostgreSQL database (requires redis._admin() capability):

  • Changes to notify-keyspace-events and emitted notifications participate in SQL transactions and MULTI/EXEC commit or rollback.
  • Notifications reflect committed database mutations; they do not prove that a subscriber socket finished reading the frame.
  • When a key with a TTL expires, read queries hide the key immediately at expires_at <= clock_timestamp(), while the expired keyspace notification is emitted when either a foreground command or the background maintenance worker physically deletes the expired row. See Expiry and session lifecycle.

Backpressure and session limits

Pub/Sub sessions and queued messages in redis._pubsub_session and redis._pubsub_event are bounded by admission limits:

ResourceDefault limit
Session lease TTL120 seconds
Queued message payload per client1 MiB
Queued message frames per client1,024
Total retained Pub/Sub payload across sessions64 MiB
Active Pub/Sub sessions4,096
Total subscription registrations16,384

Additionally, CONFIG SET client-output-buffer-limit enforces pubsub class hard and soft buffer limits (default 32 MiB hard, 8 MiB soft for 60 seconds; see Configuration). When a slow or stalled subscriber exceeds its queue or output buffer limit, pg_redis marks the route failed, logs a pg_redis Pub/Sub route failure decision entry in the PostgreSQL server log, and the gateway closes the client connection. Disconnected clients must reconnect and re-subscribe; Pub/Sub subscriptions and unread queues are transient session state and are not restored across server restarts or pg_dump backups.

5.6 - Streams and consumer groups

XADD, XREAD, consumer groups, pending entries and acknowledgements.

A Redis Stream stores append-only entries ordered by a two-part identifier (milliseconds-sequence). Each entry contains an ordered list of binary field/value pairs. Consumer groups allow multiple workers to partition a stream, track unacknowledged work in a Pending Entries List (PEL), and transfer stalled entries.

For an end-to-end transactional example combining SQL tables with Redis Streams, see the Transactional outbox tutorial.

Entries, IDs, and trimming

  • Full 128-bit ID domain: Stream IDs consist of two unsigned 64-bit integers (ms-seq). pgredis preserves the full uint64 range for both components inside redis._stream.
  • Entry payload fidelity: Field/value pairs retain their exact insertion order, duplicate field names within the same entry, and arbitrary binary bytes (including NUL).
  • Write, read, and trim commands: Use XADD to append entries (NOMKSTREAM, MAXLEN, MINID), XRANGE and XREVRANGE to query ID intervals (-, +, exclusive ( bounds, COUNT), XLEN to read the entry count, and XDEL or XTRIM to remove entries.
  • Approximate trimming and XSETID: Approximate trimming (MAXLEN ~ or MINID ~) follows internal stream node boundaries configured by stream-node-max-entries and stream-node-max-bytes, so it may retain more entries than the requested threshold. XSETID updates stream metadata (last_generated_id, entries_added, max_deleted_entry_id) without inserting an entry or waking blocked readers.

Consumer groups and pending entries

  • Group lifecycle: XGROUP CREATE (MKSTREAM, ENTRIESREAD), XGROUP SETID, XGROUP DESTROY, XGROUP CREATECONSUMER, and XGROUP DELCONSUMER manage consumer group state in redis._stream_group.
  • Reading and acknowledging: XREADGROUP GROUP <group> <consumer> ... STREAMS <key> > delivers new entries and records them in redis._stream_pel unless NOACK is specified. XACK removes acknowledged entries from the PEL.
  • Inspecting and claiming stalled work: XPENDING inspects unacknowledged entries by ID range, idle time (IDLE), and consumer. XCLAIM and XAUTOCLAIM transfer ownership of pending entries to another consumer and increment delivery counters.
  • Deleted entries in the PEL: If an entry is deleted with XDEL while still referenced in redis._stream_pel, historical XREADGROUP (0) or XCLAIM calls return a nil/empty payload for that ID, matching Redis 7.2.4. Known gaps in v0.1.0-rc1: XINFO GROUPS computes lag from stream length rather than adjusting for XDEL, and XAUTOCLAIM has one cursor formatting difference when draining an empty queue (99/101 in unit/type/stream-cgroups; see Status).

Blocking reads

  • RESP connections: XREAD BLOCK <ms> and XREADGROUP BLOCK <ms> wait for matching XADD commits. Inside MULTI/EXEC, BLOCK options run non-blockingly as immediate reads; external clients blocked on a stream wake only after an EXEC batch or SQL transaction commits.
  • SQL transactions: Ordinary redis.command calls cannot block and commit a caller’s transaction while waiting. SQL callers use redis.blocking_begin, redis.blocking_poll, and redis.blocking_cancel across transactions.
  • Restart behavior: Stream entries, consumer group offsets (last_delivered_id), and PEL records persist in PostgreSQL WAL and survive restarts and pg_dump / pg_restore, whereas active BLOCK network waits are transient and require clients to reconnect.

5.7 - Configuration

Gateway flags and pg_redis settings with defaults.

Configuration is split between command-line flags on the pgredis Go gateway executable (cmd/pgredis/main.go) and database-level settings managed by PostgreSQL and the pg_redis extension (v0.1.0-rc1, schema 0.54, commit 11411411d72ab45456904cc602cefbb13b68ff25).

Gateway CLI flags

FlagDefaultDescription
-listen127.0.0.1:56379RESP listener address (Mimus assigns 6379 in standard deployments).
-pgpostgres://127.0.0.1:55432/pgredis?sslmode=disablePostgreSQL connection URL without credentials.
-auth-modenativeAuthentication mode: native (PostgreSQL roles) or redis-acl (redis._acl_user).
-acl-service-user(empty)Bound PostgreSQL LOGIN role used when -auth-mode redis-acl is active.
-acl-service-password-file(empty)File containing the ACL service role password (one trailing newline stripped); falls back to PGREDIS_ACL_SERVICE_PASSWORD.
-default-userappPostgreSQL LOGIN role used for single-argument AUTH <password> in native mode.
-client-default-resp2Initial wire protocol for new connections and RESET (2 or 3).
-max-clients1024Maximum concurrent RESP client connections.
-max-pools8Maximum cached PostgreSQL identity connection pools.
-pool-size4Maximum PostgreSQL backend connections per identity pool (1..2147483647).
-tls-cert(empty)Server TLS certificate path (required when -listen is non-loopback).
-tls-key(empty)Server TLS private key path (required when -listen is non-loopback).
-max-bulk-bytes536870912 (512 MiB)Maximum bytes for a single request bulk argument.
-max-frame-bytes1074790400 (1 GiB + 1 MiB)Maximum sum of argument bytes in a single request frame.
-max-reply-bytes1074790400 (1 GiB + 1 MiB)Maximum wire bytes for a complete reply, including EXEC child replies.
-max-input-bytes2147483648 (2 GiB)Shared budget across connections for live input payloads and bookkeeping.
-max-output-bytes2147483648 (2 GiB)Shared budget across connections for live replies, workspace, and bookkeeping.
-max-pg-read-bytes2147483648 (2 GiB)Shared budget for PostgreSQL receive buffers and DataRow metadata.
-max-pg-message-bytes1073741822 (1 GiB - 2 B)Maximum bytes in a single PostgreSQL wire message body.
-frame-read-timeout30sDeadline to finish reading a frame after its first byte arrives.
-command-timeout30sPer-command execution timeout against PostgreSQL.
-write-timeout10sDeadline for writing a reply frame to the client socket.
-tls-handshake-timeout5sDeadline for completing a client TLS handshake.
-versionfalsePrint pgredis 0.1.0 and exit.

The -pg URL must never contain a password. In native mode, clients supply their PostgreSQL role credentials via AUTH or HELLO ... AUTH. In redis-acl mode, the gateway connects with -acl-service-user and verifies per-user hashes inside redis._acl_user.

Connection pools and default protocol

  • Identity-isolated pools: The gateway isolates connection pools by database and authenticated principal (-max-pools 8, -pool-size 4). Active checkout references prevent pool eviction, and up to 4 additional short-lived connections are permitted for credential verification. Connections return to a pool only after transaction state and session state (redis._pool_reset()) are cleanly reset; any uncertain connection is closed immediately.
  • Default RESP version: -client-default-resp 3 starts new connections in RESP3 mode instead of RESP2. HELLO 2 or HELLO 3 switches the active connection protocol, AUTH preserves it, and RESET restores the gateway’s -client-default-resp default.

PostgreSQL extension GUCs

Configure these PostgreSQL GUCs in postgresql.conf (or with ALTER DATABASE ... SET as a superuser):

GUCDefaultContextDescription
pg_redis.maintenance_database'postgres'postmaster (shared_preload_libraries)Target database where the background maintenance worker reclaims expired keys and leases.
pg_redis.maintenance_role'postgres'postmaster (shared_preload_libraries)PostgreSQL role used by the background maintenance worker.
pg_redis.object_heat_trackingoffsuperuserWhen on, every key access updates LRU/LFU metadata in redis._object_heat so OBJECT IDLETIME and OBJECT FREQ report live values (causing plain reads to write WAL).
pg_redis.list_layout_trackingoffsuperuserWhen on, newly created Lists track exact Redis listpack/quicklist encoding transitions on every write.

Redis CONFIG GET and CONFIG SET

pg_redis persists selected Redis runtime settings inside PostgreSQL tables so they participate in SQL transactions, savepoints, and pg_dump backups:

ParameterDefaultBacking tableEffect
notify-keyspace-events"" (disabled)redis._configEnables keyspace (K) and keyevent (E) Pub/Sub notifications.
slowlog-log-slower-than10000 (10 ms)redis._slowlog_configMicrosecond threshold for recording entries in redis._slowlog (negative disables).
slowlog-max-len128redis._slowlog_configMaximum retained slowlog entries.
latency-tracking-info-percentiles"50 99 99.9"redis._slowlog_configSpace-separated percentile list formatted in INFO latencystats.
acllog-max-len128redis._acl_configMaximum entries retained in redis._acl_log for ACL LOG.
requirepass""redis._acl_configPassword for the Redis default ACL user (does not alter PostgreSQL LOGIN roles).
acl-pubsub-default"resetchannels"redis._acl_configDefault Pub/Sub channel policy (resetchannels or allchannels) for new ACL users and RESET.
tracking-table-max-keys1000000redis._tracking_configMaximum tracked keys in redis._tracking_key before earlier entries are evicted and invalidated.
client-output-buffer-limit"normal 0 0 0 slave 268435456 67108864 60 pubsub 33554432 8388608 60"redis._output_configPer-class <hard> <soft> <seconds> output buffer limits (replica is accepted as an alias for slave).
hash-max-listpack-entries, hash-max-listpack-value, list-max-listpack-size, list-compress-depth, set-max-intset-entries, set-max-listpack-entries, set-max-listpack-value, zset-max-listpack-entries, zset-max-listpack-value, stream-node-max-bytes, stream-node-max-entriesRedis 7.2.4 defaultsredis._configThresholds used for OBJECT ENCODING reporting and approximate XTRIM node boundaries.

Client output buffer limits and route logs

  • client-output-buffer-limit accounting: normal limits apply to ordinary, MONITOR, and tracking-only connections (0 0 0 disabled by default); pubsub limits apply to subscribed connections (32 MiB hard, 8 MiB soft for 60 seconds by default). Accounting sums retained Go reply bytes plus unread rows in redis._pubsub_event or the MONITOR ring. Exceeding a hard or sustained soft limit closes the connection without sending an extra error frame.
  • Server-side route failure log: When a Pub/Sub or tracking route fails a capacity, message-count, single-message-size, or identity check, pg_redis writes a pg_redis Pub/Sub route failure decision message to the PostgreSQL server log containing the failure reason, database OID, XID, and tuple position, while omitting tokens, channel names, and payloads.

5.8 - Limits

Size, memory, connection and output limits of the gateway and extension.

Gateway limits bound request frames, reply frames, and PostgreSQL wire buffers in the pgredis Go process. Extension limits bound temporary workspace allocations, shared-memory rings, and session tables inside PostgreSQL 18. Neither replaces OS or PostgreSQL cluster-wide memory limits (shared_buffers, work_mem, container cgroup limits).

Gateway buffer limits

ResourceFlagDefault limit
Single bulk argument-max-bulk-bytes512 MiB (536,870,912 bytes)
Total argument bytes in one request frame-max-frame-bytes1 GiB + 1 MiB (1,074,790,400 bytes)
Unauthenticated request header (AUTH pending)Built-in10 arguments, 16,384 bytes per bulk argument
Complete wire reply (including EXEC array)-max-reply-bytes1 GiB + 1 MiB (1,074,790,400 bytes)
Shared live input payload and bookkeeping-max-input-bytes2 GiB (2,147,483,648 bytes)
Shared live output payload and workspace-max-output-bytes2 GiB (2,147,483,648 bytes)
Shared PostgreSQL receive buffer budget-max-pg-read-bytes2 GiB (2,147,483,648 bytes)
Single PostgreSQL wire message body-max-pg-message-bytes1 GiB - 2 B (1,073,741,822 bytes)
  • Local pgx read-budget patch: During make build, scripts/prepare_pgx.py applies patches/pgx-v5.11.0-read-budget.patch to the Go driver so oversized PostgreSQL wire messages and shared -max-pg-read-bytes budgets are enforced before allocating full message bodies in memory.
  • Post-commit output rejection: A mutating SQL statement can commit inside PostgreSQL before the gateway rejects an oversized reply against -max-reply-bytes or -max-output-bytes. Callers that lose a connection or receive an output-budget error must treat the write outcome as UNKNOWN.

Extension workspace and session limits

ComponentDefault limitBehavior when exceeded
Per-backend C workspace and reply budget2 GiBRaises a PostgreSQL error and rolls back the statement or savepoint.
Shared preload memory budget (shared_preload_libraries)2 GiBBounds shared allocations across backends.
MONITOR shared-memory ring4 MiB / 4,096 entriesDrops stalled MONITOR cursors that fall behind the ring head.
Pub/Sub queue per client1 MiB / 1,024 framesMarks the session failed and closes the subscriber connection.
Total retained Pub/Sub payload64 MiB (4,096 sessions, 16,384 subscriptions)Rejects new publications/registrations and fails overflowing routes.

In SET ... GET and GETSET, the C extension releases the temporary replacement copy as soon as storage consumes it and before constructing the old-value reply, allowing full 512 MiB replacements within the default 2 GiB backend budget.

Mutation counter compaction

pg_redis tracks logical key mutations across backends using per-backend counter rows so concurrent writers do not contend on a single sequence row:

  • Once the counter table reaches 64 rows, the background maintenance worker compacts up to 64 unlocked rows per pass into a single retained row while preserving the exact SQL SUM.
  • Rows locked by active or prepared transactions (PREPARE TRANSACTION) are skipped, and any batch whose sum would overflow bigint is left untouched.
  • Compaction bounds the number of rows modified per maintenance pass; dead row versions are reclaimed by standard PostgreSQL VACUUM.

Verified 512 MiB capacity baseline

On Linux (3fc740ca5, 2026-10-15, 4 CPUs, 8 GiB RAM, no swap, PostgreSQL 18.6), the installed gateway and extension passed the full 512 MiB String suite across native and redis-acl authentication modes in both RESP2 and RESP3:

  • Verified byte-for-byte across 16 large write/replace requests (SET, SET ... GET, GETSET), 24 large replies, 32 direct SQL state observations, and clean PostgreSQL restart readbacks without OOM.
  • All tested 512 MiB keys had no TTL; large-value crash recovery with finite TTLs and multi-client concurrent 512 MiB streams require separate evaluation. See Status for current performance and test coverage.

6 - Operations

Install, build, secure, upgrade, back up and recover pgredis.

A pgredis deployment runs as two components alongside PostgreSQL 18: the pg_redis C extension inside the database server and the stateless pgredis Go gateway on the Redis wire port. Because all persistent state lives in PostgreSQL tables and write-ahead logs, day-two operations use standard PostgreSQL tooling for roles, upgrades, backups, and crash recovery.

Guides

  • Install

    Install pgredis and pg_redis from a Linux development archive, enable the extension, and verify the deployment.
  • Build from source

    Required compilers, headers, Makefile targets, and test suites for building pgredis and pg_redis from source.
  • Authentication and permissions

    Configure native PostgreSQL role authentication, Redis ACL mode, SQL capability grants, and TLS listeners.
  • Upgrade and recovery

    Run ALTER EXTENSION pg_redis UPDATE, configure the background maintenance worker, and back up or restore data.

6.1 - Install

Install the gateway and extension from a package, and what to check afterwards.

pgredis is currently at release candidate v0.1.0-rc1 (product version 0.1.0, extension schema 0.54, ABI 3, commit 11411411d72ab45456904cc602cefbb13b68ff25, 2026-11-08). No public download URL or apt/rpm repository is published yet. Install either from a local Linux development archive built for PostgreSQL 18.6 or by building from source.

Candidate packages

The v0.1.0-rc1 development archives target Debian 13 (trixie) and PostgreSQL 18.6 from PGDG:

ArchivePlatformSize (bytes)SHA-256
pgredis-0.1.0-pg18.6-debian13-amd64.tar.gzLinux x86_64, glibc 2.419,321,730d72fdcb4f40d429e5b650d0671105c923db7ceb4425b50f68d45eea0d61e2ba8
pgredis-0.1.0-pg18.6-debian13-arm64.tar.gzLinux aarch64, glibc 2.418,574,4194dcc546ef4c0562eb0b69500c0bbb43f664c3b955259ccde92900ef52e269cd7

Each archive contains these members at its top level:

  • bin/pgredis — the Redis wire gateway executable
  • lib/pg_redis.so — the PostgreSQL 18 C extension library (ABI 3)
  • share/extension/pg_redis.control and share/extension/pg_redis--*.sql — the base script (0.1) and upgrade scripts through 0.54
  • licenses/ — project, Redis and dependency licence files
  • install.py and manifest.json — the installer and the file list with SHA-256, size and mode of every member

Install files

  1. Verify the archive checksum

    Check the archive hash before unpacking:

    pgredis_archive=pgredis-0.1.0-pg18.6-debian13-amd64.tar.gz
    sha256sum "$pgredis_archive"
    mkdir pgredis-package
    tar -xzf "$pgredis_archive" -C pgredis-package
  2. Run the installer

    install.py checks that the host is Debian 13 on x86_64 or aarch64, that pg_config --version reports PostgreSQL 18.6, and that every member matches manifest.json. Then it installs the binary and extension files:

    sudo python3 -E pgredis-package/install.py \
      "$PWD/$pgredis_archive" \
      --pg-config /usr/lib/postgresql/18/bin/pg_config \
      --gateway-path /usr/local/bin/pgredis

    The installer copies pgredis into /usr/local/bin/pgredis, pg_redis.so into pg_config --pkglibdir, and the control and SQL files into pg_config --sharedir/extension.

  3. Create the extension in PostgreSQL

    Connect to the target PostgreSQL 18 database as a superuser and create the extension:

    CREATE EXTENSION pg_redis;
    SELECT extversion FROM pg_extension WHERE extname = 'pg_redis';
    SELECT redis._abi_version();

    Confirm that extversion returns 0.54 and redis._abi_version() returns 3.

Start and verify

Start the gateway against the target database. Mimus assigns port 6379 to Redis (pgredis defaults to -listen 127.0.0.1:56379 and -pg postgres://127.0.0.1:55432/pgredis when flags are omitted):

/usr/local/bin/pgredis \
  -listen 127.0.0.1:6379 \
  -default-user pgredis_app \
  -pg "postgres://127.0.0.1:5432/postgres?sslmode=disable"

Run a post-installation check across both the Redis port and SQL:

redis-cli -h 127.0.0.1 -p 6379 --user pgredis_app --askpass PING
redis-cli -h 127.0.0.1 -p 6379 --user pgredis_app --askpass SET install:check ready
redis-cli -h 127.0.0.1 -p 6379 --user pgredis_app --askpass GET install:check
psql -h 127.0.0.1 -p 5432 -U postgres -d postgres \
  -c "SELECT convert_from(redis.command(ARRAY['GET', 'install:check']), 'UTF8');"

redis-cli returns ready and psql returns the RESP2 bulk string $5\r\nready\r\n. To configure least-privilege database roles or Redis ACL rules before exposing the listener to applications, see Authentication and permissions.

6.2 - Build from source

Toolchain, build targets and test targets.

Building pgredis from source compiles both the pg_redis PostgreSQL C extension and the pgredis Go gateway executable.

Toolchain

  • PostgreSQL 18 Server binaries (initdb, pg_ctl, postgres, psql), pg_config, and server development headers (postgresql-server-dev-18 on Debian/Ubuntu).
  • Go 1.27.4 Required to build the gateway and test harnesses. CGO_ENABLED=1 is mandatory because the gateway uses libc host resolution for MIGRATE.
  • C11 compiler clang or gcc compatible with the PostgreSQL PGXS build flags reported by pg_config.
  • Python 3 Used by scripts/prepare_pgx.py (which applies the local read-budget patch to the vendored pgx cache) and by the reference/application test runners.

The gateway and both Go test modules require Go 1.27.4. Current source uses pgx v5.12.0 with the project’s read-budget and password-preparation patch; the v0.1.0-rc1 packages use v5.11.0. The Go client tests use go-redis v9.23.0.

Build the gateway and extension

Run the gateway build from the repository root, then compile and install the C extension with PGXS:

make build
make -C extension PG_CONFIG=/path/to/pg_config
sudo make -C extension PG_CONFIG=/path/to/pg_config install

What each step produces:

  • make build runs python3 scripts/prepare_pgx.py, verifies CGO_ENABLED=1, executes go generate ./internal/gateway (which generates the command dispatch table from spec/commands.json), and writes the gateway binary to build/pgredis.
  • make -C extension compiles extension/pg_redis.c into extension/pg_redis.so against the target PostgreSQL 18 headers.
  • make -C extension install copies pg_redis.so, pg_redis.control, and pg_redis--*.sql (0.1 through 0.54) into the PostgreSQL installation directories reported by PG_CONFIG.

Test targets

TargetCommandScope
make testgo test ./cmd/... ./internal/... ./tests/integration/... ./tests/load/... ./tests/probes/...Fast Go unit tests (RESP parser/writer, command table generation, SQL error probes) without a running PostgreSQL cluster.
make test-integrationPGREDIS_INTEGRATION=1 go test -count=1 -v ...Initializes a temporary PostgreSQL 18 cluster, installs pg_redis, and runs end-to-end gateway, SQL rollback, Pub/Sub, Streams, Blocking, and Tracking tests.
make test-referencepython3 tests/reference/prepare.py && python3 tests/reference/run.py --mode external --variant prdBuilds the pinned Redis 7.2.4 reference binary (5221b82623c) and runs the upstream Tcl test harness against pgredis (requires tclsh).

Repository layout

  • pgredis/
    • cmd/pgredis/Gateway CLI entry point and flags
    • internal/
      • gateway/Session router, tx/watch state, blocking, Pub/Sub, MIGRATE
      • resp/Binary-safe RESP2 and RESP3 parser and serializer
    • extension/
      • pg_redis.cC dispatcher, SPI plans, shared ring, background worker
      • pg_redis.controlExtension metadata (default_version = '0.54')
      • pg_redis--*.sqlBase schema (0.1) and upgrade scripts through 0.54
    • patches/Local pgx v5.12.0 read-budget patch and earlier versions
    • spec/commands.jsonRedis 7.2.4 command specification (392 commands)
    • examples/outbox.sqlTransactional outbox SQL example
    • tests/Integration, reference, client, application, and load suites

6.3 - Authentication and permissions

PostgreSQL-role authentication, Redis ACL mode, TLS and the grants each role needs.

pgredis enforces permissions inside the pg_redis C dispatcher on every command. Even if a client bypasses the Go gateway and calls redis.command(...) directly over SQL, the C extension verifies the active PostgreSQL role capabilities or Redis ACL session before touching redis._keyspace or any typed value table.

Authentication modes

The gateway -auth-mode flag selects how Redis clients authenticate:

ModeFlagClient AUTH syntaxIdentity enforced by pg_redis
PostgreSQL role mode-auth-mode native (default)AUTH <pg_role> <password> or AUTH <password> (uses -default-user)PostgreSQL login role and SQL EXECUTE grants on capability functions
Redis ACL mode-auth-mode redis-aclAUTH <acl_user> <password> or AUTH <password> (for default)Redis ACL user row in redis._acl_user accessed via a bound PostgreSQL service role

Before authentication succeeds on a connection that requires AUTH, the gateway restricts incoming command headers to at most 10 arguments and 16,384 bytes per bulk argument so unauthenticated callers cannot allocate large buffers.

PostgreSQL role permissions

In native mode, CREATE EXTENSION pg_redis revokes public access from all internal redis._* tables and functions. Database administrators grant access by granting USAGE ON SCHEMA redis, EXECUTE on entry functions, and EXECUTE on three empty capability marker functions checked by the C dispatcher:

  • redis._read() — required for read-only commands (GET, HGETALL, LRANGE, XRANGE, SUBSCRIBE, WAIT)
  • redis._write() — required for data-modifying commands (SET, DEL, LPUSH, XADD, PUBLISH, EXEC with writes)
  • redis._admin() — required for administrative commands (FLUSHDB, FLUSHALL, CONFIG, SLOWLOG, ACL, DEBUG, MONITOR, MIGRATE)
-- Read/write application role (no admin commands)
CREATE ROLE app_rw LOGIN PASSWORD 'replace-with-strong-password';
GRANT USAGE ON SCHEMA redis TO app_rw;
GRANT EXECUTE ON FUNCTION
  redis._authorize(), redis._abi_version(), redis._read(), redis._write(),
  redis._dispatch(bytea[], integer),
  redis._dispatch(bytea[], integer, integer),
  redis._dispatch_single(bytea[], integer, integer),
  redis._pool_reset(),
  redis.command(text[], integer),
  redis.command_bin(bytea[], integer),
  redis.blocking_begin(bytea[], bytea, integer),
  redis.blocking_begin(bytea[], bytea, integer, integer),
  redis.blocking_poll(bytea, integer),
  redis.blocking_cancel(bytea, integer),
  redis.pubsub_open(bytea, integer),
  redis.pubsub_change(bytea, bytea[]),
  redis.pubsub_poll(bytea),
  redis.pubsub_cancel(bytea)
TO app_rw;

For a read-only role, omit redis._write() from the GRANT EXECUTE list. For an operational administrator role, add redis._admin().

Redis ACL mode

When -auth-mode redis-acl is enabled, the gateway connects to PostgreSQL using a single dedicated service role, and client sessions authenticate against rules stored in redis._acl_user.

  1. Create and bind the PostgreSQL service role

    Create a login role with read, write, and admin dispatch grants, then bind its regrole identity in redis._acl_service as an extension administrator:

    CREATE ROLE redis_service LOGIN PASSWORD 'replace-with-service-password';
    GRANT USAGE ON SCHEMA redis TO redis_service;
    GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA redis TO redis_service;
    
    SELECT redis._dispatch(ARRAY['ACLSERVICE', 'redis_service', 'ON']::bytea[], 0, 0);

    Once bound in redis._acl_service, redis_service cannot execute commands without an active redis._acl_session token.

  2. Configure ACL users and passwords

    Manage users over SQL or from an admin Redis connection:

    SELECT redis.command(ARRAY[
      'ACL', 'SETUSER', 'alice',
      'on', '>alice-secret',
      '~app:*', '&events:*',
      '+@read', '+@write', '-@admin'
    ]);

    Supported ACL subcommands include SETUSER, DELUSER, GETUSER, LIST, USERS, WHOAMI, CAT, GENPASS, DRYRUN, LOG, LOAD, and SAVE (LOAD and SAVE report that no external aclfile is configured because ACLs persist in PostgreSQL WAL).

  3. Start the gateway in redis-acl mode

    Do not place credentials in -pg; pass -acl-service-user and -acl-service-password-file (or PGREDIS_ACL_SERVICE_PASSWORD):

    pgredis \
      -listen 127.0.0.1:6379 \
      -auth-mode redis-acl \
      -acl-service-user redis_service \
      -acl-service-password-file /etc/pgredis/service.pass \
      -pg "postgres://127.0.0.1:5432/postgres?sslmode=disable"

CONFIG SET requirepass updates the password of the default ACL user in redis._acl_config (never a PostgreSQL LOGIN role). CONFIG SET acl-pubsub-default controls the default Pub/Sub channel policy (resetchannels by default, or allchannels) for newly created ACL users and RESET. redis._acl_user, redis._acl_config, and redis._acl_service are registered with pg_extension_config_dump, so pg_dump and pg_restore preserve ACL users and service role bindings across clusters.

Transport and tenant isolation

  • Remote TLS enforcement: Listening on any non-loopback address (0.0.0.0, ::, or a LAN IP) requires -tls-cert and -tls-key (minimum TLS 1.2). Starting without TLS on a non-loopback address fails immediately.
  • Database link security: Never embed a password in the -pg endpoint URL. When PostgreSQL runs on a separate host, configure sslmode=verify-full in the -pg connection string.
  • Tenant isolation: All 16 logical Redis databases (SELECT 0 through SELECT 15) share the same redis._keyspace table, Pub/Sub event queue, and MONITOR ring within one PostgreSQL database. Isolate untrusted tenants in separate PostgreSQL databases with separate pgredis gateway instances.

6.4 - Upgrade and recovery

Extension upgrades, backups and recovery with PostgreSQL tools.

pgredis stores its catalog schema and durable data inside PostgreSQL 18. Extension upgrades use ALTER EXTENSION, background cleanup runs inside a PostgreSQL background worker, and backup and recovery use standard PostgreSQL physical or logical tools.

Extension upgrades

The extension ships sequential SQL migration scripts from 0.1 through 0.54 (extension/pg_redis--*.sql). To upgrade an existing database to the current 0.54 schema (ABI 3):

  1. Install the updated binary and extension files

    Install the matching pgredis gateway binary, pg_redis.so library, pg_redis.control, and pg_redis--*.sql files on the PostgreSQL host. Stop the PostgreSQL instance before replacing a loaded pg_redis.so file, then start PostgreSQL and the new gateway.

  2. Run the catalog update in PostgreSQL

    Connect to each database where pg_redis is installed and update the extension as its administrator:

    ALTER EXTENSION pg_redis UPDATE TO '0.54';
    SELECT extversion FROM pg_extension WHERE extname = 'pg_redis';
    SELECT redis._abi_version();

    Verify that extversion is 0.54 and redis._abi_version() returns 3.

  3. Reconcile prerequisite checks if upgrading from older schemas

    Two migration steps refuse to overwrite ambiguous state automatically:

    • 0.49 → 0.50 (redis._acl_service): If a bound ACL service role was dropped or renamed in pg_roles so its legacy role_oid and role_name disagree, the migration raises SQLSTATE 55000 (ACL service bindings require explicit reconciliation before update to 0.50). Reconcile or unbind the stale entry before retrying.
    • 0.50 → 0.51 (stream_group_ready trigger): The migration verifies the SHA-256 hash of redis._stream_group_ready() before adding a WHEN (OLD.kind='x') filter, raising 55000 if the trigger or function was manually customized.

Background maintenance worker

While read paths filter out expired keys immediately (expires_at <= clock_timestamp()), background reclamation of expired keys and stale session leases runs in the pg_redis background worker. Enable it in postgresql.conf:

shared_preload_libraries = 'pg_redis'
pg_redis.maintenance_database = 'postgres'
pg_redis.maintenance_role = 'postgres'

Restart PostgreSQL after changing shared_preload_libraries. The worker periodically deletes expired rows from redis._keyspace, reclaims expired leases in _pubsub_session, _blocked, _transaction_session, and _acl_session, and compacts tracking and mutation-counter tables. DEBUG SET-ACTIVE-EXPIRE 0 and DEBUG PAUSE-CRON 1 pause periodic maintenance in the current database for deterministic testing; a new postmaster epoch resets both controls automatically.

Backup and recovery

  • Physical backup and PITR: pg_basebackup, WAL archiving, and point-in-time recovery preserve all keyspace tables, typed value tables, Streams metadata, and extension configuration tables together with ordinary SQL tables.
  • Logical backup (pg_dump / pg_restore): Use custom format (pg_dump -Fc) or plain SQL dumps. Keep PostgreSQL role DDL quiescent during dump and restore when migrating redis._acl_service bindings across clusters.

What a logical dump includes and excludes:

CategoryTablesLogical dump behavior
Keyspace and values_keyspace, _string, _hash, _list, _set, _zset, _stream_*, _hll, _bitmapRestored in full; expires_at retains its absolute timestamptz deadline.
Extension configuration_acl_user, _acl_config, _acl_service, _slowlog_config, _tracking_config, _output_configRegistered via pg_extension_config_dump and restored across clusters.
Derived caches_list_lengthExcluded from dumps; statement triggers on redis._list rebuild it automatically as rows are copied back during pg_restore.
Transient session state_pubsub_session, _pubsub_event, _blocked, _transaction_session, _watch, _acl_session, _tracking_*, _monitor_clientExcluded from dumps; reconnecting clients establish fresh sessions.

Failure handling and timeouts

  • Command and statement timeouts: Set -command-timeout on the gateway and statement_timeout / lock_timeout on the PostgreSQL role to bound worst-case query duration.
  • Inspecting active backends: Query pg_stat_activity for queries executing redis._dispatch or redis.command when diagnosing lock waits or slow commands.
  • Handling UNKNOWN write outcomes: If a network drop or gateway timeout interrupts a write after the SQL statement was sent to PostgreSQL, the transaction may have either committed or rolled back. Non-idempotent callers should inspect the target key or application outbox table before retrying.

7 - Status

Current candidate, what has been verified on it, known issues and the remaining roadmap.

Current candidate

pgredis is at Release candidate status. The current candidate is v0.1.0-rc1: product version 0.1.0, extension schema 0.54, ABI 3, for PostgreSQL 18.6 on Debian 13 (amd64 and arm64).

  • The packages were built on 2026-11-08 from commit 11411411d72ab45456904cc602cefbb13b68ff25.
  • The local tag v0.1.0-rc1 points to commit 2f8ee8d6a. Its product files are identical to 11411411d; it adds only the release regression record. The main branch is at 2d313bc7c.
  • The tag exists only in a local repository. There is no remote repository, no published tag and no public download.

The current goal and the release list are in MVP goal (v0.1.0).

Release regression on v0.1.0-rc1

All results are from the packages built from 11411411d and were recorded on 2026-11-08. Functional items ran in Debian 13 containers with PostgreSQL 18.6 (PGDG); G5 and B1 ran in a 4 CPU / 2 GiB container on an AMD Ryzen AI MAX+ 395 host with fdatasync about 0.19 ms.

ItemResult
Gateway make build and make test; extension buildPass
Integration tests without lab-container cases302 pass, 55 skip, 3 fail. The same 3 tests failed before this release
Seven-client smoke (native and Redis ACL × RESP2/RESP3; ioredis RESP2 only)338/338 checks pass
SQL/RESP core differential (Linux-built Redis 7.2.4 reference)5,187/5,187 in each of four RESP profiles; 5,151/5,151 in each of two SQL profiles
Transactional outbox example (native and Redis ACL × RESP2/RESP3)46/46 checks in each profile
New installation and upgrade from schema 0.52 to 0.54Pass on amd64 and arm64; every key’s DUMP and absolute expiry are unchanged after the upgrade
G5 (SET/GET, 50 clients, no pipeline)synchronous_commit=off: SET 20,056 req/s, p50 1.527 ms; GET 32,787 req/s, p50 0.775 ms. on: SET 8,423 req/s, p50 5.215 ms; GET 29,833 req/s, p50 0.807 ms
B1 (one hot key)on: INCR 2,469 req/s, LPUSH 2,057 req/s. off: INCR 6,207 req/s, LPUSH 4,902 req/s
Official Redis 7.2.4 subset (20 files, native RESP2, excluded tags for replication, Redis persistence, DEBUG, maxmemory, large memory and local process)1,090 pass, 6 fail, 4 files stop early, 79 excluded by tag

The stability run, sanitizer builds and Go race checks are not part of the MVP release list. Results on earlier checkpoints are in Compatibility.

Known issues

None of these issues blocks the release candidate.

  • Write commands other than plain GET/SET take a database-level exclusive lock and keep it until commit, including the WAL flush. Writes to different keys wait in line; see per-database serialization.
  • With synchronous_commit=on, the SET p50 is about 5.2 ms, above the original 2 ms target.
  • Lua scripting and Functions are not supported. Default Celery and Sidekiq configurations do not operate.
  • OBJECT IDLETIME/FREQ access tracking and exact List layout tracking are off by default; see object metadata and List encoding.
  • After a role is disabled with NOLOGIN and enabled again with a new password, an authenticated native session returns an unknown-outcome error when it next needs a new backend connection. The client must run AUTH again.
  • Official tests: a PUBLISH right after UNSUBSCRIBE/PUNSUBSCRIBE without arguments can still count the old subscriber (2 failures); INFO with several sections in one request differs from Redis (2 failures); CLIENT LIST and CLIENT INFO fields differ from Redis (2 failures). The multi, pubsub and introspection files stop at Lua cases, and introspection-2 stops at OBJECT IDLETIME.

Roadmap

Work deferred until after v0.1.0, in priority order:

  1. Per-key write concurrency: remove the per-database write lock after a full concurrency audit.
  2. Delivery stages P5 and P6.
  3. SET p50 ≤ 2 ms with synchronous_commit=on.
  4. Default Celery and Sidekiq paths; encoding, DEBUG and OBJECT fidelity; the MIGRATE contract; external ACL files; multiple gateways; EL and Ubuntu packages.

8 - Releases

The release candidate and the development checkpoints that led to it.

pgredis has no published release. The first release candidate is v0.1.0-rc1: product version 0.1.0, extension schema 0.54, ABI 3, for PostgreSQL 18.6. Earlier version numbers (0.1 to 0.53) identify extension schema migrations and source checkpoints, not releases.

Release candidate v0.1.0-rc1

  • Status: Release candidate. The local tag v0.1.0-rc1 points to commit 2f8ee8d6a (2026-11-08). It is not pushed and not published.
  • Package source: commit 11411411d72ab45456904cc602cefbb13b68ff25. The tagged commit has the same product files and adds the release regression record.
  • Product / schema / ABI: 0.1.0 / 0.54 / 3
  • Target database: PostgreSQL 18.6 from PGDG on Debian 13 (trixie)

Candidate packages

The archives exist only as local build output. There is no download location.

FilePlatformSize (bytes)SHA-256
pgredis-0.1.0-pg18.6-debian13-amd64.tar.gzDebian 13 x86_649,321,730d72fdcb4f40d429e5b650d0671105c923db7ceb4425b50f68d45eea0d61e2ba8
pgredis-0.1.0-pg18.6-debian13-arm64.tar.gzDebian 13 aarch648,574,4194dcc546ef4c0562eb0b69500c0bbb43f664c3b955259ccde92900ef52e269cd7

Key changes in schema 0.54

  • List length cache (redis._list_length): LLEN, the LPUSH/RPUSH replies and insertion-gap lookups read one cached length per list instead of counting every element. Statement triggers on redis._list maintain the cache from the rows actually inserted and deleted. The upgrade fills the cache for existing lists. The cache is not dumped: restoring the redis._list rows rebuilds it through the triggers, and a missing cache row falls back to counting.
  • Fidelity tracking off by default: pg_redis.object_heat_tracking and pg_redis.list_layout_tracking default to off. A plain GET writes no WAL, and List writes do not rewrite the full listpack/quicklist layout. See object metadata and List encoding.
  • One product version: the gateway log, HELLO, pgredis -version and INFO pgredis_version report 0.1.0. INFO adds pgredis_schema_version.

Performance baseline

Measured on 2026-11-08 with the amd64 package built from 11411411d: a container with 4 CPUs, 2 GiB of memory and no swap on an AMD Ryzen AI MAX+ 395 host; PostgreSQL 18.6; fdatasync about 0.19 ms. The load is redis-benchmark from Redis 7.2.4 with 50 clients, no pipeline, 10,000 random keys, 128-byte values and 50,000 requests per test; the gateway pool size is 4. Each test ran once. These numbers are a baseline, not an SLA.

TestCommandsynchronous_commit=onsynchronous_commit=off
G5SET8,423 req/s, p50 5.215 ms20,056 req/s, p50 1.527 ms
G5GET29,833 req/s, p50 0.807 ms32,787 req/s, p50 0.775 ms
B1 (one hot key)INCR2,469 req/s, p50 19.2 ms6,207 req/s, p50 7.0 ms
B1 (one hot key, list grows to 50,000)LPUSH2,057 req/s, p50 23.6 ms4,902 req/s, p50 9.4 ms

With off, G5 meets the original targets (GET ≥ 10,000 req/s, SET ≥ 5,000 req/s, p50 ≤ 2 ms). With on, GET meets them and SET does not. Before schema 0.54, single-hot-key LPUSH measured 64.6 req/s (on) in the same environment.

Regression and known issues

The release regression table is on the Status page. Known issues in v0.1.0-rc1, none of which blocks the candidate:

  • Write commands other than plain GET/SET serialize per database until commit and WAL flush; see per-database serialization.
  • With synchronous_commit=on, the SET p50 is about 5.2 ms.
  • No Lua or Functions; default Celery and Sidekiq configurations do not operate.
  • OBJECT IDLETIME/FREQ and exact List encoding need the tracking settings turned on.
  • After NOLOGIN and a password change, an authenticated native session must run AUTH again.
  • Official tests: 6 failures (PUBLISH after argument-less unsubscribe, multi-section INFO, CLIENT LIST/CLIENT INFO fields), and 4 files that stop at Lua or OBJECT IDLETIME cases.

Schema and checkpoint history

Each schema version has an upgrade script extension/pg_redis--<from>--<to>.sql. The table lists the tables and columns that each step adds.

SchemaAdds
0.1 – 0.5redis._keyspace, then redis._hash, redis._set, redis._list and redis._zset
0.6 – 0.11WATCH and EXEC state (_watch, _exec_context, _auth_ticket), _mutation_stats, blocking (_blocked, _block_keys, _ready), Pub/Sub (_pubsub_session, _pubsub_subscription, _pubsub_message), _notify_config
0.12 – 0.16Streams: _stream, _stream_entry, _stream_config, _stream_node, _stream_radix, _stream_group, _stream_consumer, _stream_pel
0.17 – 0.29_runtime_identity, object metadata (_object_heat, _object_config, _object_shared_heat, _object_reference, _object_encoding, _encoding_config), _transaction_session, _debug_control, _auth_key_ticket, _hll_config
0.30 – 0.39_client_pause_control, _slowlog_config, columns on existing tables
0.40 – 0.41Redis ACL: _acl_user, _acl_log, _acl_service, _acl_session
0.42 – 0.44Client tracking (_tracking_client, _tracking_key, _tracking_prefix, _tracking_pending, _tracking_config) and _monitor_client
0.45 – 0.49_acl_config, _output_config, latency percentiles, requirepass and acl-pubsub-default columns
0.50 – 0.51No new tables or columns
0.52redis._blocked.reply_before
0.53redis._debug_control.pause_cron (DEBUG PAUSE-CRON)
0.54redis._list_length and its two statement triggers (v0.1.0-rc1)

9 - Design

Design decisions behind pgredis.

These notes record the core architectural choices and scope boundaries of pgredis:

  • One semantic core — why all Redis command semantics execute inside the pg_redis PostgreSQL 18 C extension while the Go gateway handles protocol and session transport.
  • Persistence and replication scope — why PostgreSQL WAL, backup and replication replace Redis AOF, RDB and REPLICAOF, and how the 55 upstream test cases that depend on Redis-native persistence or replication are handled.
  • MIGRATE connections — how MIGRATE resolves target hosts via libc getaddrinfo, classifies connection versus write-stage errors, and interacts with database locks and SQL rollback.
  • MVP goal (v0.1.0) — the current goal approved on 2026-11-08: completion condition, scope, release list and deferred work; it replaces the P0–P6 completion condition.
  • Status review, 2026-11-08 — why the work did not reach a release before 2026-11-08, the decisions taken, and the v0.1.0-rc1 results.

For the results on the current candidate, see Status.

9.1 - One semantic core

Why RESP and SQL share one C implementation of Redis semantics.

Decision

Implement Redis 7.2.4 command semantics once in the pg_redis PostgreSQL 18 C extension, and use the pgredis Go gateway strictly for wire-protocol framing, TLS, authentication, session queues and connection pooling. Both RESP clients and SQL callers (redis.command, redis.command_bin) invoke the same C command core, with PostgreSQL tables and WAL as the only persistent store.

Rationale

Implementing Redis data semantics in the Go gateway would require duplicating PostgreSQL’s transaction isolation, savepoint rollback, MVCC visibility, expiry cleanup and role-permission enforcement across two processes. Putting the semantic core inside the PostgreSQL extension gives SQL table writes and Redis key mutations a single atomic commit boundary.

The Go gateway still performs essential transport work:

  • Negotiating TLS and parsing RESP2 / RESP3 frames under strict memory budgets.
  • Holding MULTI command queues before EXEC submits them in one transaction.
  • Driving long-lived blocking waits, Pub/Sub subscriptions, client-side caching pushes and MONITOR streams across pooled backend connections.
  • Verifying commit confirmation (ReadyForQuery) and running redis._pool_reset() before returning connections to the pool.

Trade-offs and invariants

  • Requires superuser and preload: Because pg_redis is a C extension that registers shared memory and a background expiry worker via shared_preload_libraries, it cannot be deployed as a gateway-only proxy in front of unprivileged managed PostgreSQL services.
  • Database-level write locking: Protecting cross-key and cross-database Redis invariants inside SQL transactions uses a per-database exclusive lock for writes other than plain GET/SET, trading single-database write concurrency for strict transactional consistency in 0.1.0.
  • Non-negotiable invariants: Every performance optimization must preserve byte-exact binary keys and values, lock ordering, PostgreSQL role permission checks, synchronous_commit = on by default, and the rule that an operation with an unknown commit outcome is never replayed.

9.2 - Persistence and replication scope

Why PostgreSQL WAL replaces AOF, RDB and Redis replication.

Decision

PostgreSQL WAL, checkpoints, physical/logical backups (pg_basebackup, pg_dump/pg_restore) and PostgreSQL streaming replication are the only durability and high-availability mechanisms in pgredis. Redis-native file persistence (AOF, RDB, SAVE, BGSAVE, BGREWRITEAOF, DEBUG RELOAD) and Redis replication (REPLICAOF, SLAVEOF, SYNC, PSYNC) are outside the product scope.

Upstream test conflicts

An audit of the 39 official Redis 7.2.4 test files (1,914 required test cases) identified 55 cases that invoke Redis-native persistence or replication mechanisms alongside ordinary data assertions:

Redis-native mechanismAffected upstream cases
SYNC, REPLICAOF or an external Redis replica17
AOF files, BGREWRITEAOF or AOF loader startup20
DEBUG RELOAD (save and reload RDB in place)12
BGSAVE child process or background-save rehash behavior1
RDB startup configuration1
Persisting a non-empty save schedule4

Because pgredis stores all keys in PostgreSQL tables rather than an in-memory heap backed by RDB/AOF files, it rejects these commands rather than faking a no-op success reply.

How mixed test cases are verified

  1. Unchanged official test counts: Official Redis 7.2.4 test files are run without editing their Tcl bodies or silently skipping assertions. When a file hits DEBUG RELOAD (for example in unit/type/list) or AOF/replica setup (in unit/type/stream and unit/type/stream-cgroups), the failure or abort remains visible in the official matrix counts.
  2. Retained ordinary obligations: For the 55 mixed cases, tests/differential/retained-scope-obligations.json maps the 24 groups that contain ordinary data, TTL, encoding, queue, Stream, DUMP/RESTORE or configuration assertions onto PostgreSQL recovery tests (normal restart, immediate shutdown WAL recovery and logical pg_dump/pg_restore).
  3. Clear separation of claims: Passing PostgreSQL restart and WAL recovery suites (such as the 246,784-assertion mixed-dataset recovery run on commit e8cb31f5) verifies durability of Redis data types in PostgreSQL storage; it does not claim compatibility with Redis AOF, RDB file loaders or Redis replication protocols.

9.3 - MIGRATE connections

How MIGRATE reaches another server, and its current limits.

MIGRATE moves or copies keys from a local pgredis database to a target Redis or pgredis server over TCP while holding a PostgreSQL transaction on the source.

Connection-stage versus write-stage errors

Redis 7.2.4 classifies MIGRATE socket failures according to the result of the initial non-blocking connect() syscall:

  • Once connect() succeeds immediately or returns EINPROGRESS, Redis stops traversing the remaining resolved addresses and waits on that socket. Any later connection refusal or timeout is reported as IOERR error or timeout writing to target instance.
  • Standard Go net.Dialer collapses address iteration and returns only the final errno or timeout, losing the boundary between connecting to the client and writing to target instance.

To match Redis 7.2.4 error classification, the pgredis MIGRATE connector walks resolved addresses in order and inspects the initial connect() result directly:

ObservationConnector action
Host resolution fails, setup fails, or context is canceled before connect()Return a connecting to the client error
Socket creation fails, or initial connect() fails immediatelyTry the next resolved address
Initial connect() succeeds or returns EINPROGRESSStop traversing addresses and wait on this socket
Accepted/in-progress socket later fails, times out or is canceledReturn a writing to target instance error without trying another address
SO_ERROR is 0 and getpeername() succeedsHand the connected socket to the MIGRATE protocol handler

Platform libc address resolution

In standard cgo builds on Linux and macOS, MIGRATE resolves target host names through the platform’s libc getaddrinfo() using a zeroed addrinfo hints structure with AF_UNSPEC and SOCK_STREAM:

  • Address order, socket family (AF_INET / AF_INET6), protocol, port and numeric IPv6 scope IDs are preserved as returned by libc.
  • Empty host strings follow the host libc (glibc on Linux returns EAI_NONAME, whereas macOS resolves to loopback). Host names containing NUL bytes or exceeding 1,023 bytes are rejected before calling libc.
  • Up to 8 concurrent resolver calls are permitted per gateway process; resolution and connection establishment share one overall deadline.

Acknowledgement and commit ordering

  1. The pg_redis extension checks permissions, locks the source keys and serializes DUMP payloads in a source PostgreSQL transaction.
  2. After the connector hands off an established socket, the gateway sends AUTH (when requested) and SELECT to the target and waits for each acknowledgement before sending RESTORE.
  3. Only keys whose target RESTORE returns an exact +OK are deleted from the source database (unless COPY is set). The gateway replies to the caller only after the source PostgreSQL transaction confirms commit.
  4. If an acknowledgement is lost or the source commit outcome is unknown, the target may already hold a copy while the source key remains. The gateway never replays MIGRATE or deletes target keys to compensate for a source rollback.

Current limits

  • Targets sharing the same PostgreSQL database: Because a MIGRATE transaction holds the per-database exclusive lock on the source database until commit, migrating to a gateway bound to the same PostgreSQL database (even with a different Redis logical database 0–15) blocks when the target attempts AUTH, SELECT or RESTORE, and times out. Migrating between gateways backed by separate PostgreSQL databases works as expected (verified across 96 cases in 8 auth/protocol profiles on commit 715827aa0).
  • SQL transactions and MULTI/EXEC: Calling MIGRATE inside MULTI/EXEC or via redis.command / redis.command_bin returns NOKEY when all named source keys are missing or expired, and returns an explicit scope error when any source key exists because remote network writes cannot be rolled back if the caller later rolls back its SQL transaction.

9.4 - Status review, 2026-11-08

Why pgredis did not reach a release before 2026-11-08, what was decided, and what the MVP candidate measured.

Scope

This review covers pgredis up to commit c25638e1b (2026-10-30, the last commit before the review) and the decisions made on 2026-11-08. It replaces no earlier record. The resulting goal is MVP goal (v0.1.0).

State before the review

  • Architecture: a Go gateway for RESP and sessions, and a PostgreSQL 18 C extension (pg_redis) that runs every command; PostgreSQL is the only persistent layer.
  • Commands: all classic Redis 7.2.4 data families had an implementation: String, Hash, List, Set, ZSet, Stream, Bitmap, HyperLogLog, Geo, Pub/Sub, transactions and keyspace commands. The 87 commands marked pending were all out of scope: Cluster, Sentinel, Lua/Functions, Redis replication, persistence files, modules and SHUTDOWN.
  • Size at c25638e1b: about 29,000 hand-written lines of C plus 54 SQL migration scripts (schema 0.1 to 0.53); about 11,500 lines of non-test Go. Test code was about five times the product code.
  • History: schema 0.1 to 0.50 was built from 2026-10-06 to 2026-10-15. From 2026-10-16 to 2026-10-30 only three schema versions were added. Of 906 commits, about 13% were feat, fix or perf; most of the rest recorded test evidence. No commit was made after 2026-10-30.
  • Gates: no delivery stage was formally closed. The fixed G5 benchmark met its throughput bounds but failed p50 with synchronous_commit=on (for example SET p50 6.743 ms and GET p50 3.559 ms on 2026-10-30). Seven 24-hour runs had started and none completed. The official Redis matrices still had failures and aborted files.

Why the work did not finish

  1. A goal with no intermediate stop. Completion required all stages P0–P6 at once, and the goal text stated that a runnable MVP does not count. The first installable stage (P4) was a waypoint, not a stopping point.
  2. Zero-tolerance gates. G5 was defined with synchronous_commit=off in the PRD; that definition passed on 2026-10-29, but the gate had been moved to on. A 24-hour run failed on one request slower than 3 s or 8 s. The official suites required zero failures, and the 55 cases excluded by the persistence decision were not subtracted.
  3. Change a little, retest everything. A dated pass did not count for newer source bytes, so each product change reopened earlier results. Each narrow check was reviewed twice offline, with process, session and volume retirement evidence. Late fixes addressed edge cases such as tracking order across shared redirects.
  4. Test fidelity on hot paths. Two features that exist mainly for OBJECT output made core commands slow:
    • every GET updated LRU/LFU metadata, so reads also waited for a WAL flush;
    • every LPUSH rewrote and compressed the full list layout, so single-key LPUSH measured 64.6 req/s with the list growing to 50,000 elements.

The goal text did not allow these features to be simplified.

Decisions

  • Make an MVP release candidate the only current goal, with a frozen scope and a release list that completes in one or two hours (MVP goal).
  • Remove defensive tests from the release list: stability and endurance runs, instrumentation matrices, repeated benchmarks and root-cause batches for rare problems. A twelve-hour stability run was started and then stopped by the user; it counts neither as a pass nor as a failure.
  • Turn the two fidelity features into settings that are off by default, and cache List lengths in schema 0.54.
  • Keep the per-database write lock for v0.1.0 and document it. Per-key concurrency is the first deferred item.

Outcome

v0.1.0-rc1: product version 0.1.0, schema 0.54, ABI 3; packages built from 11411411d, local tag on 2f8ee8d6a. Measured on 2026-11-08 in a 4 CPU / 2 GiB container with fdatasync about 0.19 ms:

MeasurementBefore (c25638e1b)After (11411411d)
G5 GET, synchronous_commit=onabout 13,500 req/s, p50 about 3.1 ms29,833 req/s, p50 0.807 ms
G5 SET, synchronous_commit=onabout 8,200 req/s, p50 about 5.3 ms8,423 req/s, p50 5.215 ms
B1 LPUSH, one key to 50,000 elements, on64.6 req/s2,057 req/s
WAL written by one B1 runabout 3.1 GBabout 67 MB
WAL for 2,000 GET requests after warm-up391,976 bytes0 bytes

The “before” G5 and B1 values were measured on the same host and container limits as the “after” values. The WAL-per-GET values come from local macOS builds of c25638e1b and c6e2eb9d2, the change that 11411411d includes. The full release regression and known issues are on the Status page.

9.5 - MVP goal (v0.1.0)

The current pgredis goal: completion condition, scope, release list and deferred work for v0.1.0.

Decision

On 2026-11-08 the user approved an MVP release candidate (v0.1.0-rcN) as the current pgredis goal. It replaces the earlier completion condition, which required all delivery stages P0–P6 and the PRD goals G1–G6 together. Those stages stay as the roadmap after the MVP. The first candidate under this goal is v0.1.0-rc1: local tag on commit 2f8ee8d6a, packages built from 11411411d.

The same rules apply to pgredis, pgetcd and pgsilo.

Rules

  • Completion condition: the goal is complete when a release candidate exists. Then work stops and the user decides the next step. No stage starts automatically.
  • Scope freeze: only the listed work items and fixes for problems that block the MVP. No new functions, test layers, evidence formats or infrastructure.
  • Proportionate verification: run only functional and smoke tests that complete in a few minutes; the full release list completes in one or two hours. Long stability or endurance runs, full instrumentation matrices, repeated benchmark rounds, conformance tests that need a large rebuilt environment, and diagnostic batches for rare intermittent problems are not run and are not post-MVP gates. The user asks for them separately if they become necessary.
  • One verification line: each list item is recorded as pass, fail or not applicable, with the command and the raw output location. A failure is fixed, or listed as a known issue marked blocking or not; the user decides. Dual independent review, full re-validation after each source change, retirement evidence and tests of the test infrastructure are cancelled.
  • Unchanged invariants: no hidden failures, no runtime branches for test names, no silent exemptions; synchronous commit by default; no replay of a commit with an unknown outcome; permission boundaries.
  • Numbers: the MVP publishes measured baselines with their environment and promises no SLA.

Scope of v0.1.0

LevelContents
SupportedString; keyspace, TTL, SCAN, SELECT; Hash; Set; ZSet; List including blocking pops; MULTI/EXEC/WATCH; Pub/Sub including sharded; subsets of INFO, CONFIG, CLIENT; SQL interface redis.command and redis.command_bin in the caller’s transaction; native authentication with PostgreSQL roles; TLS required on non-loopback listeners
BetaStreams and consumer groups; Bitmap, HyperLogLog, Geo; DUMP/RESTORE; client tracking; MONITOR; Redis ACL mode
Not supportedLua and Functions (so default Celery and Sidekiq configurations do not operate); Cluster, Sentinel, Redis replication; AOF, RDB, SAVE, BGSAVE, DEBUG RELOAD; maxmemory eviction; modules; multiple gateways; Redis 7.4+ commands; exactly-once semantics

Deployment: PostgreSQL 18 with pg_redis in shared_preload_libraries, one gateway process, Debian 13 amd64 and arm64 packages.

Work items

  1. No disk writes on the read path: OBJECT access tracking becomes a setting that is off by default, so a plain GET writes no WAL.
  2. List append without a full layout rewrite: push cost does not grow with the list length; OBJECT ENCODING for a List becomes an estimate.
  3. One public version: gateway, packages and documentation report 0.1.0; the schema version stays visible through the gateway.
  4. Packages and documentation: Debian 13 packages, quick start, supported/unsupported list, release notes, local tag v0.1.0-rc1.

A twelve-hour stability run was first listed as a work item. The user removed it on 2026-11-08; the partial run counts neither as a pass nor as a failure.

Release list

ItemRequirement
Build and unit testsGateway make build, make test; extension build; integration tests without lab-container cases
Clients and semanticsSeven-client smoke; SQL/RESP core differential; outbox example
InstallationNew installation; upgrade from 0.52 to the current schema
G5Once. With synchronous_commit=off, GET ≥ 10,000 req/s, SET ≥ 5,000 req/s, p50 ≤ 2 ms; with on, record only
B1Hot-key benchmark, once
Official testsRedis 7.2.4 files for the supported scope, once, native RESP2; failures become known issues

Results for v0.1.0-rc1 are on the Status page.

Deferred

  1. Per-key write concurrency: remove the per-database serialization of write commands other than GET/SET (details). A full concurrency audit comes first.
  2. Delivery stages P5 and P6.
  3. SET p50 ≤ 2 ms with synchronous_commit=on.
  4. Default Celery and Sidekiq paths; encoding, DEBUG and OBJECT fidelity; the MIGRATE contract; external ACL files; multiple gateways.
  5. EL and Ubuntu packages.

Earlier scope decisions stay in effect, for example persistence and replication scope.