This is the multi-page printable view of this section.
Redis
- 1: Quick start
- 2: Tutorials
- 3: Compatibility
- 4: Architecture
- 4.1: Request path
- 4.2: Storage
- 4.3: Session lifecycle
- 5: Reference
- 5.1: Commands
- 5.2: Data types
- 5.3: SQL API
- 5.4: Transactions and retries
- 5.5: Pub/Sub and keyspace events
- 5.6: Streams and consumer groups
- 5.7: Configuration
- 5.8: Limits
- 6: Operations
- 6.1: Install
- 6.2: Build from source
- 6.3: Authentication and permissions
- 6.4: Upgrade and recovery
- 7: Status
- 8: Releases
- 9: Design
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 on2f8ee8d6a, packages from11411411d. Not published. Extension schema 0.54, ABI 3. Port- 6379 in the Mimus plan; the gateway defaults to
127.0.0.1:56379 Gatewaypgredis, Go: RESP2/RESP3, TLS, authentication, sessions,MULTIqueues, poolsExtensionpg_redis, C, schemaredis; needs superuser andshared_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._keyspaceholds the binary key, type, value and expiry;_hash,_list,_set,_zsetand the_stream*tables hold the rest. - Each command is one PostgreSQL transaction. The reply leaves only after commit.
EXECruns the whole queue in one transaction. A reply whose outcome is unknown is never replayed. - SQL:
redis.command(text[], db)andredis.command_bin(bytea[], db)call the same core and join the caller’s transaction (READ COMMITTEDonly). - Pub/Sub and blocking commands use tables plus
NOTIFYwake-ups and leases. - Write commands other than plain
GET/SETrun one at a time per database; WAL flush latency limits their throughput.
Try it
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
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.
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 (
amd64orarm64) for development archives, or a Linux / macOS build host for source builds. - PostgreSQL 18 (tested on 18.6) with
pg_config(postgresql-server-dev-18on Debian). - Superuser access to a dedicated PostgreSQL instance that you can configure and restart (
pg_redisrequiressuperuser = trueandshared_preload_libraries). - Python 3 (when running
install.pyfrom a development archive) andredis-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):
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:
Add SCRAM authentication for the application role to pg_hba.conf before broader rules:
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:
Verify the installed extension schema version and ABI:
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:
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:
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:
Deployment notes
- Non-loopback listeners require TLS. When
-listenbinds to a non-loopback address, you must pass-tls-certand-tls-keyor the gateway refuses to start. - One gateway per database. Run one
pgredisgateway process per PostgreSQL database; multiple gateways sharing one database are not verified. - Write serialization. Write commands other than plain
GETandSETtake a per-database exclusive lock until commit; see Per-database serialization. - Schema upgrades. When upgrading from extension schema
0.52or0.53, replace the binaries and runALTER EXTENSION pg_redis UPDATE TO '0.54';in each database.
2 - Tutorials
These tutorials use the pgredis_demo database and pgredis_app role created in Quick start, with PostgreSQL listening on 127.0.0.1:5432 and the pgredis gateway listening on 127.0.0.1:6379.
Work through the examples in order:
- Connect a Redis client — authenticate over RESP2 and RESP3, switch logical databases with
SELECT, and write and read keys. - Roll back SQL and Redis together — modify a SQL table row and a Redis key in one PostgreSQL transaction and roll both back.
- Binary keys and values — store and read raw byte sequences containing
NUL(\x00) bytes throughredis.command_bin. - Transactional outbox — commit business rows and Redis Stream events in one transaction, then consume and acknowledge them idempotently with
XREADGROUPandXACK.
2.1 - Connect a Redis client
Complete Quick start first. This tutorial uses redis-cli, the pgredis_app role and the pgredis_demo database with the gateway listening on 127.0.0.1:6379 (or 56379 if started with the default -listen flag).
Open a RESP2 session
Connect with redis-cli and authenticate as pgredis_app:
Enter the password for the pgredis_app PostgreSQL role, then run the following commands at the prompt:
SELECT 1 switches the current connection to logical database 1. Because pgredis:demo:client was created in logical database 0, EXISTS in database 1 returns 0. Switching back to SELECT 0 finds and deletes the key.
Use RESP3
The gateway supports both RESP2 and RESP3 on the same listener. Pass -3 to redis-cli (or send HELLO 3) to negotiate RESP3:
Both protocol versions read and write the same PostgreSQL tables.
Handle lost responses
Each standalone command commits in PostgreSQL before the gateway writes the reply to the client socket. If the network drops after PostgreSQL commits but before the client reads the reply, the write has already taken effect. Do not blindly retry non-idempotent commands such as INCR or LPUSH; see Disconnects and unknown outcomes.
2.2 - Roll back SQL and Redis together
Use the pgredis_demo database and pgredis_app role from Quick start. Connect with psql as the application role:
Run and roll back a transaction
Create a temporary SQL table, then start a transaction that inserts a business row and sets a Redis key before rolling back:
After ROLLBACK, SELECT count(*) FROM pgredis_demo_row; returns 0 and the decoded EXISTS reply is :0\r\n (the key does not exist). The temporary table remains because it was created before BEGIN, while both the SQL row insert and the Redis SET were rolled back together.
How it works
redis.command and redis.command_bin execute inside the caller’s PostgreSQL transaction (READ COMMITTED isolation level) and write directly to the extension’s WAL-logged tables. Separate requests sent over a RESP gateway connection run in their own transactions and do not join an open psql transaction.
Clean up the temporary table when finished:
Next, see Transactional outbox to commit business rows and Redis Stream events together.
2.3 - Binary keys and values
PostgreSQL text values cannot contain NUL (\x00) bytes or invalid UTF-8 sequences, whereas Redis keys and values are arbitrary byte strings. Use redis.command_bin(bytea[], integer) from SQL (or raw binary arguments over RESP) to store and read arbitrary bytes without text conversion.
Send and read raw bytes
Connect to pgredis_demo as pgredis_app (psql -h 127.0.0.1 -p 5432 -U pgredis_app -d pgredis_demo) and pass bytea[] arguments containing \x00 and \xff bytes:
The GET query returns 24320d0a00ff0d0a:
24320d0ais the RESP bulk string header$2\r\n(2 bytes).00ffis the exact two-byte payload.0d0ais the trailing\r\n.
Keep the interface binary
Always use redis.command_bin(bytea[], integer) when keys, values, hash fields, set members, sorted-set members or Pub/Sub channel names can contain NUL bytes or non-UTF-8 payloads. Parse the outer RESP frame in bytea before interpreting the payload bytes, and do not pass binary payloads through PostgreSQL text or JSON string conversions.
2.4 - Transactional outbox
This tutorial implements a transactional outbox using examples/outbox.sql from the pgredis source repository (Apache-2.0). A producer inserts an order row and appends a Redis Stream entry with XADD in one PostgreSQL transaction; a consumer reads from a Stream consumer group over RESP, then writes its shipment row and runs XACK in one PostgreSQL transaction.
On commit 715827aa0 (Linux arm64, PostgreSQL 18.6, 2026-10-21), the examples/outbox.sql integration suite passed all 46/46 checks across each of the 4 authentication and protocol profiles (native and redis-acl × RESP2 and RESP3), covering rollback, savepoints, binary payloads, concurrent deduplication, consumer takeover and lost COMMIT replies.
1. Install the outbox schema and consumer group
Use the pgredis_demo database and pgredis_app role from Quick start. Make sure logical database 0 does not already contain the key pgredis:outbox:orders and that schema pgredis_outbox_demo does not exist.
Connect as a superuser (postgres) and run examples/outbox.sql:
The script creates three tables (orders, events, shipments), two SECURITY INVOKER functions (place_order, apply_order), and the Stream consumer group shipping on pgredis:outbox:orders:
Grant access on the outbox schema to pgredis_app:
2. Produce an order and Stream event in one transaction
Connect with psql as pgredis_app:
Assign a stable request_id UUID to the business operation and call place_order inside a READ COMMITTED transaction:
place_order inserts into orders, calls redis.command(ARRAY['XADD', 'pgredis:outbox:orders', '*', 'request_id', p_request::text]), and stores the returned Stream entry ID in events:
- Calling
place_orderagain with the samerequest_idand identicalpayloadbytes returns the originalevent_idwithout appending a duplicate Stream entry. - A concurrent duplicate waits on the
ordersprimary key until the first transaction finishes. - Passing a different payload for the same
request_idraises SQLSTATE22023. - Rolling back the SQL transaction removes the
ordersrow, theeventsmapping and the Stream entry together.
3. Consume and acknowledge the event
In a separate terminal, connect with redis-cli and read the next unread entry for consumer group shipping:
Record the returned Stream entry ID (for example 1761955200000-0) and the request_id field. Complete the XREADGROUP call before starting the consumer’s SQL transaction. Until acknowledged, the entry stays in the group’s Pending Entries List (PEL).
In your psql session, apply the order and acknowledge the Stream entry in one SQL transaction:
apply_order checks that event_id matches events, copies the order payload into shipments (ON CONFLICT DO NOTHING), and calls XACK inside the same transaction:
- On the first execution,
apply_orderreturnstrueand requiresXACKto acknowledge1pending entry (ifXACKreturns:0,apply_orderraises an exception and rolls backshipments). - On a repeated call after commit,
apply_orderreturnsfalsewithout inserting a second shipment.
Verify the committed shipment row:
4. Recover after worker failures or lost commit replies
- Worker crash before
COMMIT: Ifworker-1stops beforeapply_ordercommits, inspect its pending entries withXREADGROUP GROUP shipping worker-1 COUNT 10 STREAMS pgredis:outbox:orders 0, or let another worker reclaim idle entries withXAUTOCLAIM/XCLAIM, then callapply_orderwith the reclaimedrequest_idandevent_id. KeepXREADGROUPandXAUTOCLAIMoutside the SQL transaction, and never send a standaloneXACKbeforeapply_order. - Lost
COMMITreply: If the network drops duringCOMMIT, the client can safely re-runplace_order(request_id, payload)orapply_order(request_id, event_id)on a new connection. The primary-key lock waits for any still-running transaction and resolves the duplicate deterministically.
3 - Compatibility
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:
| Category | Scope |
|---|---|
| Data types | String, Hash, Set, ZSet and List, including blocking pops (BLPOP, BRPOP, BLMOVE, BRPOPLPUSH, BLMPOP, BZPOPMIN, BZPOPMAX, BZMPOP) |
| Keyspace | TTL and expiry, SCAN, SELECT (logical databases 0–15), DEL, EXISTS, TYPE, RENAME, COPY |
| Transactions | MULTI, EXEC, DISCARD, WATCH |
| Publish/Subscribe | Channels, pattern subscriptions and sharded Pub/Sub (SSUBSCRIBE, SPUBLISH) |
| Administration | Subsets of INFO, CONFIG and CLIENT |
| SQL API | redis.command(text[], integer) and redis.command_bin(bytea[], integer) in the same transaction as SQL tables |
| Authentication | Native PostgreSQL role mode (AUTH maps to a LOGIN role; permissions enforced by extension entry points) |
| Transport | RESP2 and RESP3; mandatory TLS on non-loopback listen addresses |
| Durability | synchronous_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,RESTOREandMIGRATE.- Client-side caching (
CLIENT TRACKING,CLIENT CACHING,CLIENT GETREDIR,CLIENT TRACKINGINFO). MONITOR.- Redis ACL compatibility mode (
-auth-mode redis-acl).
Unsupported
| Area | Behavior and impact |
|---|---|
| Lua scripting and Functions | EVAL, 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 Sentinel | CLUSTER and SENTINEL commands are not implemented |
| Redis replication | REPLICAOF, 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 files | AOF and RDB files, SAVE, BGSAVE, BGREWRITEAOF, WAITAOF (numlocal=1) and DEBUG RELOAD are not supported; use PostgreSQL backup and recovery tools |
| Memory eviction | maxmemory eviction policies are not implemented |
| Modules | MODULE load/unload commands and Redis modules are not supported (MODULE LIST returns an empty list) |
| Multi-gateway | Running multiple gateway processes against one PostgreSQL database is not verified |
| Redis 7.4+ commands | Commands introduced after Redis 7.2.4 (such as Hash field expiry HEXPIRE) are not implemented |
| Exactly-once delivery | When 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
WRONGTYPEor syntax errors) is recorded as an error element in theEXECreply 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
EXECtransaction.
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):
| Workload | synchronous_commit=on | synchronous_commit=off |
|---|---|---|
SET (random keys) | 8,423 req/s, p50 5.215 ms | 20,056 req/s, p50 1.527 ms |
GET (random keys) | 29,833 req/s, p50 0.807 ms | 32,787 req/s, p50 0.775 ms |
INCR (one hot key) | 2,469 req/s, p50 19.2 ms | 6,207 req/s, p50 7.0 ms |
LPUSH (one hot key, growing to 50,000 items) | 2,057 req/s, p50 23.6 ms | 4,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 = offby default):- Reading a key does not update LRU/LFU metadata. A plain
GETwrites no WAL and does not wait for a WAL flush undersynchronous_commit = on. OBJECT IDLETIMEreturns an explicit error stating that object access tracking is disabled.OBJECT FREQreturns the same error when an LFU policy is selected, or the standard Redis error when a non-LFU policy is active.DEBUG OBJECTreports only thelrutimestamp recorded when the key was created, replaced or restored.
- Reading a key does not update LRU/LFU metadata. A plain
- List layout tracking (
pg_redis.list_layout_tracking = offby default):LPUSH,RPUSHandLLENuse theredis._list_lengthcache added in schema0.54; append cost stays flat as the list grows (in0.53, single-hot-keyLPUSHwas 64.6 req/s in the same benchmark environment).OBJECT ENCODINGandDEBUG OBJECTestimatelistpackversusquicklistfrom current elements usinglist-max-listpack-size, without modeling hysteresis after a list shrinks.MEMORY USAGEomits 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_trackinglater causesOBJECT ENCODINGon 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__:invalidatethrough a redirected connection subscribed to that channel. - Default tracking sends one single-element key array per invalidated key (even when
MSETmodifies multiple keys);BCASTgroups 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-keysbounds distinct tracked keys across logical databases (default1,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,SELECTandRESTOREreplies before deleting migrated source keys. - If a network failure or timeout occurs after the target accepts
RESTOREor while the source commit is in flight, the target may already hold a copy while the source key remains. The gateway never replaysMIGRATEor deletes target keys to compensate for a source rollback. - Calling
MIGRATEinsideMULTI/EXECor through direct SQL returnsNOKEYwhen 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),MIGRATEbetween 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
MONITORrecords. - Complete binary arguments are preserved with control bytes escaped, while passwords in
AUTH,HELLO ... AUTHandMIGRATE ... AUTH/AUTH2are redacted. - Each database maintains a volatile ring buffer capped at
4 MiBand4,096entries. If an observer falls behind and unread entries are overwritten, or if permissions are revoked orPREPARE TRANSACTIONruns on a monitored session, the gateway closes theMONITORconnection so the caller detects the gap.MONITORis 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:
| Suite | Build and platform | Date | Result |
|---|---|---|---|
| Official Redis 7.2.4 server matrix (39 files × RESP2/RESP3 = 78 profiles, Redis ACL) | 715827aa0, Linux arm64, PG 18.6 | 2026-10-21 | 2,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.6 | 2026-10-21 | 3,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.6 | 2026-10-21 | 5,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.6 | 2026-10-21 | 169 core checks per auth mode (338/338 pass; ioredis RESP2 only) |
Official unit/tracking file | 0.53 package, Linux amd64, PG 18.6 | 2026-10-29 | 54/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.6 | 2026-10-30 | 246,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.6 | 2026-10-30 | 1,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.6 | 2026-10-21 | 46/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.6 | 2026-10-21 | Django/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:
| Stage | Scope |
|---|---|
| P0 | Reference sources, command inventory, test ledger and acceptance contract |
| P1 | Native PostgreSQL role identity and secure vertical slice |
| P2 | Core data types and transactions |
| P3 | Blocking commands, Pub/Sub and keyspace events |
| P4 | First installable version and operational verification |
| P5 | Extended data types, Redis ACL and application framework coverage |
| P6 | Management commands, object encoding, serialization, server behavior and seven-client matrix |
4 - Architecture
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, maintainsMULTIqueues and session state, and manages per-identity PostgreSQL connection pools. Current source usespgxv5.12.0 with a local read-budget patch; thev0.1.0-rc1packages use v5.11.0.pg_redis(PostgreSQL 18 C extension): implements Redis 7.2.4 standalone command semantics in schemaredis, enforces privileges and lock order, runs a background expiry worker viashared_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
| Component | Responsibilities |
|---|---|
pgredis Go gateway | RESP2/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 extension | Command execution, capability checks, database and key locking, binary key/member lookup, lazy and background expiry, tracking invalidation and MONITOR staging |
| PostgreSQL 18 | ACID 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
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
- The gateway parses the incoming RESP2 or RESP3 frame and enforces request-header and argument-size budgets.
- The gateway acquires a pooled PostgreSQL connection bound to the authenticated identity.
- The
pg_redisextension verifies function ownership and role capabilities (redis._read(),redis._write(),redis._admin()) and acquires the required database and key locks. - The extension takes a current snapshot and runs the C command handler against the
redis.*tables. - PostgreSQL commits the transaction (including a WAL flush when
synchronous_commit = on). - Once the commit
ReadyForQueryframe 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.commandandredis.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/SETdispatch andredis._pool_reset()use PostgreSQLFunctionCallmessages, each followed by its ownReadyForQueryresponse. - The first
ReadyForQuerymust 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
ReadyForQueryconfirms thatredis._pool_reset()cleared all session-local state (temporary settings, advisory locks, notification listeners and execution context) and returned binarytrue. - 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
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:
- Digest-indexed lookup: Unbounded binary keys (
bytea, up to 512 MiB) never enter a PostgreSQL B-tree index directly. Instead,pg_redisindexes(db, digest)using a 32-byte SHA-256 digest, locks the digest bucket, and compares the fullkeybytes 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-bytedigest+ fullbyteacomparison rule, referencingredis._keyspace(id)withON DELETE CASCADE. - Sorted sets:
redis._zsetstoresscore double precision(rejectingNaN) and breaks ties by comparing full member bytes. - Lists and length cache:
redis._listorders elements by(kid, pos, id)without putting elementvaluebytes in a B-tree. Schema0.54addsredis._list_length(kid, length), maintained by statement-level transition-table triggers onredis._listsoLLEN,LPUSHandRPUSHread one row instead of counting every element.
Table inventory (schema 0.54)
| Category | Tables | Purpose |
|---|---|---|
| Keyspace and Strings | redis._keyspace | Logical 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) |
| Hashes | redis._hash | (kid, digest, field, value) rows per hash field |
| Lists | redis._list, redis._list_length | (kid, pos, value) element rows and statement-trigger-maintained per-list length cache |
| Sets | redis._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 |
| Streams | redis._stream, redis._stream_entry, redis._stream_node, redis._stream_radix, redis._stream_group, redis._stream_consumer, redis._stream_pel, redis._stream_config | Stream metadata (last_id, max_deleted_id, entries_added), live entries, listpack nodes, radix tree prefixes, consumer groups, consumers and Pending Entries List (PEL) |
| Object metadata | redis._object_encoding, redis._object_heat, redis._object_shared_heat, redis._object_reference, redis._object_config | Encoding state, optional listpack/quicklist layout (pg_redis.list_layout_tracking), optional LRU/LFU heat (pg_redis.object_heat_tracking) and shared-integer tracking |
| Transactions | redis._transaction_session, redis._watch, redis._exec_context, redis._mutation_stats | WATCH key versions, EXEC context and per-key mutation counters |
| Blocking commands | redis._blocked, redis._block_keys, redis._ready | Blocked waiter registrations, watched keys per waiter and committed handoff replies |
| Pub/Sub | redis._pubsub_session, redis._pubsub_subscription, redis._pubsub_message, redis._notify_config | Subscriber sessions, channel/pattern/shard bindings, message ring pages and keyspace-event configuration |
| Client tracking | redis._tracking_client, redis._tracking_key, redis._tracking_prefix, redis._tracking_pending, redis._tracking_config | Client-side caching sessions, tracked key digests, BCAST prefixes and queued invalidations |
| Auth and Redis ACL | redis._acl_user, redis._acl_session, redis._acl_log, redis._acl_config, redis._acl_service, redis._auth_ticket, redis._auth_key_ticket | Redis ACL users, rules, security log and session tickets |
| Diagnostics and control | redis._monitor_client, redis._client_pause_control, redis._debug_control, redis._output_config, redis._slowlog_config, redis._encoding_config, redis._hll_config, redis._runtime_identity | MONITOR 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_pollcalls do not increment completion counts again.
4.3 - Session lifecycle
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):- When a blocking command (
BLPOP,BLMOVE,BZPOPMIN,XREAD BLOCK,XREADGROUP BLOCK,WAIT) cannot be satisfied immediately,redis.blocking_beginrecords the waiter, logical database, opaque token, command arguments and reply protocol. - 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 PostgreSQLNOTIFYwakeup. - Inside
MULTI/EXEC, waiters only see the final state after the entireEXECbatch completes; an item pushed and deleted within the sameEXECnever escapes to a blocked reader. - The gateway polls
redis.blocking_pollto retrieve the stored reply without re-executing the pop, or callsredis.blocking_cancelon disconnect.
- When a blocking command (
- Pub/Sub and tracking routes (
redis._pubsub_*,redis._tracking_*):redis.pubsub_openandredis.pubsub_changeregister subscriptions in PostgreSQL tables with a lease deadline.- Publishers write message pages to
redis._pubsub_message(and tracking invalidations toredis._tracking_pending) inside their transaction and emitNOTIFY. - 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_redisis loaded viashared_preload_libraries, a background coordinator discovers databases containing the extension and runs periodic workers that delete expired rows fromredis._keyspacein batches, clean up expired blocking/Pub/Sub leases, trim tracking tables and compact mutation counters. PostgreSQLVACUUMlater 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 inredis._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 = Iand binarytruereceipt). - 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
WATCHstate, blocking waits and Pub/Sub or tracking subscriptions.
5 - Reference
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 fromspec/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 handlingUNKNOWNoutcomes 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
pgredisgateway CLI flags, connection pools,pg_redisextension GUCs, and supportedCONFIG GET/SETparameters.Limits
Request, reply, shared buffer, and backend workspace budgets, mutation-counter compaction, and tested 512 MiB capacity.
5.1 - Commands
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: falsein the specification file:partial-slicerecords 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
| Family | Total | partial-slice | pending | Execution owner |
|---|---|---|---|---|
| String | 22 | 22 | 0 | extension |
| Hash | 16 | 16 | 0 | extension |
| List | 22 | 22 | 0 | extension |
| Set | 17 | 17 | 0 | extension |
| Sorted set | 35 | 35 | 0 | extension |
| Stream | 25 | 25 | 0 | extension |
| Bitmap | 7 | 7 | 0 | extension |
| GEO | 10 | 10 | 0 | extension |
| HyperLogLog | 5 | 5 | 0 | extension |
| Keyspace | 34 | 34 | 0 | extension |
| Transactions | 5 | 5 | 0 | gateway+extension |
| Pub/Sub | 15 | 15 | 0 | extension |
| Connection | 26 | 26 | 0 | extension, gateway, gateway+extension |
| Server | 76 | 62 | 14 | extension |
| Cluster | 32 | 0 | 32 | extension |
| Sentinel | 22 | 0 | 22 | extension |
| Scripting | 23 | 4 | 19 | extension |
String
| Command | Arity | Owner | Implementation |
|---|---|---|---|
APPEND | 3 | extension | partial-slice |
DECR | 2 | extension | partial-slice |
DECRBY | 3 | extension | partial-slice |
GET | 2 | extension | partial-slice |
GETDEL | 2 | extension | partial-slice |
GETEX | -2 | extension | partial-slice |
GETRANGE | 4 | extension | partial-slice |
GETSET | 3 | extension | partial-slice |
INCR | 2 | extension | partial-slice |
INCRBY | 3 | extension | partial-slice |
INCRBYFLOAT | 3 | extension | partial-slice |
LCS | -3 | extension | partial-slice |
MGET | -2 | extension | partial-slice |
MSET | -3 | extension | partial-slice |
MSETNX | -3 | extension | partial-slice |
PSETEX | 4 | extension | partial-slice |
SET | -3 | extension | partial-slice |
SETEX | 4 | extension | partial-slice |
SETNX | 3 | extension | partial-slice |
SETRANGE | 4 | extension | partial-slice |
STRLEN | 2 | extension | partial-slice |
SUBSTR | 4 | extension | partial-slice |
Hash
| Command | Arity | Owner | Implementation |
|---|---|---|---|
HDEL | -3 | extension | partial-slice |
HEXISTS | 3 | extension | partial-slice |
HGET | 3 | extension | partial-slice |
HGETALL | 2 | extension | partial-slice |
HINCRBY | 4 | extension | partial-slice |
HINCRBYFLOAT | 4 | extension | partial-slice |
HKEYS | 2 | extension | partial-slice |
HLEN | 2 | extension | partial-slice |
HMGET | -3 | extension | partial-slice |
HMSET | -4 | extension | partial-slice |
HRANDFIELD | -2 | extension | partial-slice |
HSCAN | -3 | extension | partial-slice |
HSET | -4 | extension | partial-slice |
HSETNX | 4 | extension | partial-slice |
HSTRLEN | 3 | extension | partial-slice |
HVALS | 2 | extension | partial-slice |
List
| Command | Arity | Owner | Implementation |
|---|---|---|---|
BLMOVE | 6 | extension | partial-slice |
BLMPOP | -5 | extension | partial-slice |
BLPOP | -3 | extension | partial-slice |
BRPOP | -3 | extension | partial-slice |
BRPOPLPUSH | 4 | extension | partial-slice |
LINDEX | 3 | extension | partial-slice |
LINSERT | 5 | extension | partial-slice |
LLEN | 2 | extension | partial-slice |
LMOVE | 5 | extension | partial-slice |
LMPOP | -4 | extension | partial-slice |
LPOP | -2 | extension | partial-slice |
LPOS | -3 | extension | partial-slice |
LPUSH | -3 | extension | partial-slice |
LPUSHX | -3 | extension | partial-slice |
LRANGE | 4 | extension | partial-slice |
LREM | 4 | extension | partial-slice |
LSET | 4 | extension | partial-slice |
LTRIM | 4 | extension | partial-slice |
RPOP | -2 | extension | partial-slice |
RPOPLPUSH | 3 | extension | partial-slice |
RPUSH | -3 | extension | partial-slice |
RPUSHX | -3 | extension | partial-slice |
Set
| Command | Arity | Owner | Implementation |
|---|---|---|---|
SADD | -3 | extension | partial-slice |
SCARD | 2 | extension | partial-slice |
SDIFF | -2 | extension | partial-slice |
SDIFFSTORE | -3 | extension | partial-slice |
SINTER | -2 | extension | partial-slice |
SINTERCARD | -3 | extension | partial-slice |
SINTERSTORE | -3 | extension | partial-slice |
SISMEMBER | 3 | extension | partial-slice |
SMEMBERS | 2 | extension | partial-slice |
SMISMEMBER | -3 | extension | partial-slice |
SMOVE | 4 | extension | partial-slice |
SPOP | -2 | extension | partial-slice |
SRANDMEMBER | -2 | extension | partial-slice |
SREM | -3 | extension | partial-slice |
SSCAN | -3 | extension | partial-slice |
SUNION | -2 | extension | partial-slice |
SUNIONSTORE | -3 | extension | partial-slice |
Sorted set
| Command | Arity | Owner | Implementation |
|---|---|---|---|
BZMPOP | -5 | extension | partial-slice |
BZPOPMAX | -3 | extension | partial-slice |
BZPOPMIN | -3 | extension | partial-slice |
ZADD | -4 | extension | partial-slice |
ZCARD | 2 | extension | partial-slice |
ZCOUNT | 4 | extension | partial-slice |
ZDIFF | -3 | extension | partial-slice |
ZDIFFSTORE | -4 | extension | partial-slice |
ZINCRBY | 4 | extension | partial-slice |
ZINTER | -3 | extension | partial-slice |
ZINTERCARD | -3 | extension | partial-slice |
ZINTERSTORE | -4 | extension | partial-slice |
ZLEXCOUNT | 4 | extension | partial-slice |
ZMPOP | -4 | extension | partial-slice |
ZMSCORE | -3 | extension | partial-slice |
ZPOPMAX | -2 | extension | partial-slice |
ZPOPMIN | -2 | extension | partial-slice |
ZRANDMEMBER | -2 | extension | partial-slice |
ZRANGE | -4 | extension | partial-slice |
ZRANGEBYLEX | -4 | extension | partial-slice |
ZRANGEBYSCORE | -4 | extension | partial-slice |
ZRANGESTORE | -5 | extension | partial-slice |
ZRANK | -3 | extension | partial-slice |
ZREM | -3 | extension | partial-slice |
ZREMRANGEBYLEX | 4 | extension | partial-slice |
ZREMRANGEBYRANK | 4 | extension | partial-slice |
ZREMRANGEBYSCORE | 4 | extension | partial-slice |
ZREVRANGE | -4 | extension | partial-slice |
ZREVRANGEBYLEX | -4 | extension | partial-slice |
ZREVRANGEBYSCORE | -4 | extension | partial-slice |
ZREVRANK | -3 | extension | partial-slice |
ZSCAN | -3 | extension | partial-slice |
ZSCORE | 3 | extension | partial-slice |
ZUNION | -3 | extension | partial-slice |
ZUNIONSTORE | -4 | extension | partial-slice |
Stream
| Command | Arity | Owner | Implementation |
|---|---|---|---|
XACK | -4 | extension | partial-slice |
XADD | -5 | extension | partial-slice |
XAUTOCLAIM | -6 | extension | partial-slice |
XCLAIM | -6 | extension | partial-slice |
XDEL | -3 | extension | partial-slice |
XGROUP | -2 | extension | partial-slice |
XGROUP CREATE | -5 | extension | partial-slice |
XGROUP CREATECONSUMER | 5 | extension | partial-slice |
XGROUP DELCONSUMER | 5 | extension | partial-slice |
XGROUP DESTROY | 4 | extension | partial-slice |
XGROUP HELP | 2 | extension | partial-slice |
XGROUP SETID | -5 | extension | partial-slice |
XINFO | -2 | extension | partial-slice |
XINFO CONSUMERS | 4 | extension | partial-slice |
XINFO GROUPS | 3 | extension | partial-slice |
XINFO HELP | 2 | extension | partial-slice |
XINFO STREAM | -3 | extension | partial-slice |
XLEN | 2 | extension | partial-slice |
XPENDING | -3 | extension | partial-slice |
XRANGE | -4 | extension | partial-slice |
XREAD | -4 | extension | partial-slice |
XREADGROUP | -7 | extension | partial-slice |
XREVRANGE | -4 | extension | partial-slice |
XSETID | -3 | extension | partial-slice |
XTRIM | -4 | extension | partial-slice |
Bitmap
| Command | Arity | Owner | Implementation |
|---|---|---|---|
BITCOUNT | -2 | extension | partial-slice |
BITFIELD | -2 | extension | partial-slice |
BITFIELD_RO | -2 | extension | partial-slice |
BITOP | -4 | extension | partial-slice |
BITPOS | -3 | extension | partial-slice |
GETBIT | 3 | extension | partial-slice |
SETBIT | 4 | extension | partial-slice |
GEO
| Command | Arity | Owner | Implementation |
|---|---|---|---|
GEOADD | -5 | extension | partial-slice |
GEODIST | -4 | extension | partial-slice |
GEOHASH | -2 | extension | partial-slice |
GEOPOS | -2 | extension | partial-slice |
GEORADIUS | -6 | extension | partial-slice |
GEORADIUSBYMEMBER | -5 | extension | partial-slice |
GEORADIUSBYMEMBER_RO | -5 | extension | partial-slice |
GEORADIUS_RO | -6 | extension | partial-slice |
GEOSEARCH | -7 | extension | partial-slice |
GEOSEARCHSTORE | -8 | extension | partial-slice |
HyperLogLog
| Command | Arity | Owner | Implementation |
|---|---|---|---|
PFADD | -2 | extension | partial-slice |
PFCOUNT | -2 | extension | partial-slice |
PFDEBUG | 3 | extension | partial-slice |
PFMERGE | -2 | extension | partial-slice |
PFSELFTEST | 1 | extension | partial-slice |
Keyspace
| Command | Arity | Owner | Implementation |
|---|---|---|---|
COPY | -3 | extension | partial-slice |
DEL | -2 | extension | partial-slice |
DUMP | 2 | extension | partial-slice |
EXISTS | -2 | extension | partial-slice |
EXPIRE | -3 | extension | partial-slice |
EXPIREAT | -3 | extension | partial-slice |
EXPIRETIME | 2 | extension | partial-slice |
KEYS | 2 | extension | partial-slice |
MIGRATE | -6 | extension | partial-slice |
MOVE | 3 | extension | partial-slice |
OBJECT | -2 | extension | partial-slice |
OBJECT ENCODING | 3 | extension | partial-slice |
OBJECT FREQ | 3 | extension | partial-slice |
OBJECT HELP | 2 | extension | partial-slice |
OBJECT IDLETIME | 3 | extension | partial-slice |
OBJECT REFCOUNT | 3 | extension | partial-slice |
PERSIST | 2 | extension | partial-slice |
PEXPIRE | -3 | extension | partial-slice |
PEXPIREAT | -3 | extension | partial-slice |
PEXPIRETIME | 2 | extension | partial-slice |
PTTL | 2 | extension | partial-slice |
RANDOMKEY | 1 | extension | partial-slice |
RENAME | 3 | extension | partial-slice |
RENAMENX | 3 | extension | partial-slice |
RESTORE | -4 | extension | partial-slice |
SCAN | -2 | extension | partial-slice |
SORT | -2 | extension | partial-slice |
SORT_RO | -2 | extension | partial-slice |
TOUCH | -2 | extension | partial-slice |
TTL | 2 | extension | partial-slice |
TYPE | 2 | extension | partial-slice |
UNLINK | -2 | extension | partial-slice |
WAIT | 3 | extension | partial-slice |
WAITAOF | 4 | extension | partial-slice |
Transactions
| Command | Arity | Owner | Implementation |
|---|---|---|---|
DISCARD | 1 | gateway+extension | partial-slice |
EXEC | 1 | gateway+extension | partial-slice |
MULTI | 1 | gateway+extension | partial-slice |
UNWATCH | 1 | gateway+extension | partial-slice |
WATCH | -2 | gateway+extension | partial-slice |
Pub/Sub
| Command | Arity | Owner | Implementation |
|---|---|---|---|
PSUBSCRIBE | -2 | extension | partial-slice |
PUBLISH | 3 | extension | partial-slice |
PUBSUB | -2 | extension | partial-slice |
PUBSUB CHANNELS | -2 | extension | partial-slice |
PUBSUB HELP | 2 | extension | partial-slice |
PUBSUB NUMPAT | 2 | extension | partial-slice |
PUBSUB NUMSUB | -2 | extension | partial-slice |
PUBSUB SHARDCHANNELS | -2 | extension | partial-slice |
PUBSUB SHARDNUMSUB | -2 | extension | partial-slice |
PUNSUBSCRIBE | -1 | extension | partial-slice |
SPUBLISH | 3 | extension | partial-slice |
SSUBSCRIBE | -2 | extension | partial-slice |
SUBSCRIBE | -2 | extension | partial-slice |
SUNSUBSCRIBE | -1 | extension | partial-slice |
UNSUBSCRIBE | -1 | extension | partial-slice |
Connection
| Command | Arity | Owner | Implementation |
|---|---|---|---|
AUTH | -2 | gateway | partial-slice |
CLIENT | -2 | extension | partial-slice |
CLIENT CACHING | 3 | extension | partial-slice |
CLIENT GETNAME | 2 | gateway | partial-slice |
CLIENT GETREDIR | 2 | extension | partial-slice |
CLIENT HELP | 2 | extension | partial-slice |
CLIENT ID | 2 | extension | partial-slice |
CLIENT INFO | 2 | extension | partial-slice |
CLIENT KILL | -3 | extension | partial-slice |
CLIENT LIST | -2 | extension | partial-slice |
CLIENT NO-EVICT | 3 | extension | partial-slice |
CLIENT NO-TOUCH | 3 | gateway+extension | partial-slice |
CLIENT PAUSE | -3 | extension | partial-slice |
CLIENT REPLY | 3 | extension | partial-slice |
CLIENT SETINFO | 4 | gateway | partial-slice |
CLIENT SETNAME | 3 | gateway | partial-slice |
CLIENT TRACKING | -3 | extension | partial-slice |
CLIENT TRACKINGINFO | 2 | extension | partial-slice |
CLIENT UNBLOCK | -3 | extension | partial-slice |
CLIENT UNPAUSE | 2 | extension | partial-slice |
ECHO | 2 | gateway | partial-slice |
HELLO | -1 | gateway | partial-slice |
PING | -1 | gateway | partial-slice |
QUIT | -1 | gateway | partial-slice |
RESET | 1 | gateway | partial-slice |
SELECT | 2 | gateway | partial-slice |
Server
| Command | Arity | Owner | Implementation |
|---|---|---|---|
ACL | -2 | extension | partial-slice |
ACL CAT | -2 | extension | partial-slice |
ACL DELUSER | -3 | extension | partial-slice |
ACL DRYRUN | -4 | extension | partial-slice |
ACL GENPASS | -2 | extension | partial-slice |
ACL GETUSER | 3 | extension | partial-slice |
ACL HELP | 2 | extension | partial-slice |
ACL LIST | 2 | extension | partial-slice |
ACL LOAD | 2 | extension | partial-slice |
ACL LOG | -2 | extension | partial-slice |
ACL SAVE | 2 | extension | partial-slice |
ACL SETUSER | -3 | extension | partial-slice |
ACL USERS | 2 | extension | partial-slice |
ACL WHOAMI | 2 | extension | partial-slice |
BGREWRITEAOF | 1 | extension | pending |
BGSAVE | -1 | extension | pending |
COMMAND | -1 | extension | partial-slice |
COMMAND COUNT | 2 | extension | partial-slice |
COMMAND DOCS | -2 | extension | partial-slice |
COMMAND GETKEYS | -3 | extension | partial-slice |
COMMAND GETKEYSANDFLAGS | -3 | extension | partial-slice |
COMMAND HELP | 2 | extension | partial-slice |
COMMAND INFO | -2 | extension | partial-slice |
COMMAND LIST | -2 | extension | partial-slice |
CONFIG | -2 | extension | partial-slice |
CONFIG GET | -3 | extension | partial-slice |
CONFIG HELP | 2 | extension | partial-slice |
CONFIG RESETSTAT | 2 | extension | partial-slice |
CONFIG REWRITE | 2 | extension | partial-slice |
CONFIG SET | -4 | extension | partial-slice |
DBSIZE | 1 | extension | partial-slice |
DEBUG | -2 | extension | partial-slice |
FAILOVER | -1 | extension | pending |
FLUSHALL | -1 | extension | partial-slice |
FLUSHDB | -1 | extension | partial-slice |
INFO | -1 | extension | partial-slice |
LASTSAVE | 1 | extension | partial-slice |
LATENCY | -2 | extension | partial-slice |
LATENCY DOCTOR | 2 | extension | partial-slice |
LATENCY GRAPH | 3 | extension | partial-slice |
LATENCY HELP | 2 | extension | partial-slice |
LATENCY HISTOGRAM | -2 | extension | partial-slice |
LATENCY HISTORY | 3 | extension | partial-slice |
LATENCY LATEST | 2 | extension | partial-slice |
LATENCY RESET | -2 | extension | partial-slice |
LOLWUT | -1 | extension | partial-slice |
MEMORY | -2 | extension | partial-slice |
MEMORY DOCTOR | 2 | extension | partial-slice |
MEMORY HELP | 2 | extension | partial-slice |
MEMORY MALLOC-STATS | 2 | extension | partial-slice |
MEMORY PURGE | 2 | extension | partial-slice |
MEMORY STATS | 2 | extension | partial-slice |
MEMORY USAGE | -3 | extension | partial-slice |
MODULE | -2 | extension | partial-slice |
MODULE HELP | 2 | extension | partial-slice |
MODULE LIST | 2 | extension | partial-slice |
MODULE LOAD | -3 | extension | pending |
MODULE LOADEX | -3 | extension | pending |
MODULE UNLOAD | 3 | extension | pending |
MONITOR | 1 | extension | partial-slice |
PSYNC | -3 | extension | pending |
REPLCONF | -1 | extension | pending |
REPLICAOF | 3 | extension | pending |
RESTORE-ASKING | -4 | extension | pending |
ROLE | 1 | extension | partial-slice |
SAVE | 1 | extension | pending |
SHUTDOWN | -1 | extension | pending |
SLAVEOF | 3 | extension | pending |
SLOWLOG | -2 | extension | partial-slice |
SLOWLOG GET | -2 | extension | partial-slice |
SLOWLOG HELP | 2 | extension | partial-slice |
SLOWLOG LEN | 2 | extension | partial-slice |
SLOWLOG RESET | 2 | extension | partial-slice |
SWAPDB | 3 | extension | partial-slice |
SYNC | 1 | extension | pending |
TIME | 1 | extension | partial-slice |
Cluster
| Command | Arity | Owner | Implementation |
|---|---|---|---|
ASKING | 1 | extension | pending |
CLUSTER | -2 | extension | pending |
CLUSTER ADDSLOTS | -3 | extension | pending |
CLUSTER ADDSLOTSRANGE | -4 | extension | pending |
CLUSTER BUMPEPOCH | 2 | extension | pending |
CLUSTER COUNT-FAILURE-REPORTS | 3 | extension | pending |
CLUSTER COUNTKEYSINSLOT | 3 | extension | pending |
CLUSTER DELSLOTS | -3 | extension | pending |
CLUSTER DELSLOTSRANGE | -4 | extension | pending |
CLUSTER FAILOVER | -2 | extension | pending |
CLUSTER FLUSHSLOTS | 2 | extension | pending |
CLUSTER FORGET | 3 | extension | pending |
CLUSTER GETKEYSINSLOT | 4 | extension | pending |
CLUSTER HELP | 2 | extension | pending |
CLUSTER INFO | 2 | extension | pending |
CLUSTER KEYSLOT | 3 | extension | pending |
CLUSTER LINKS | 2 | extension | pending |
CLUSTER MEET | -4 | extension | pending |
CLUSTER MYID | 2 | extension | pending |
CLUSTER MYSHARDID | 2 | extension | pending |
CLUSTER NODES | 2 | extension | pending |
CLUSTER REPLICAS | 3 | extension | pending |
CLUSTER REPLICATE | 3 | extension | pending |
CLUSTER RESET | -2 | extension | pending |
CLUSTER SAVECONFIG | 2 | extension | pending |
CLUSTER SET-CONFIG-EPOCH | 3 | extension | pending |
CLUSTER SETSLOT | -4 | extension | pending |
CLUSTER SHARDS | 2 | extension | pending |
CLUSTER SLAVES | 3 | extension | pending |
CLUSTER SLOTS | 2 | extension | pending |
READONLY | 1 | extension | pending |
READWRITE | 1 | extension | pending |
Sentinel
| Command | Arity | Owner | Implementation |
|---|---|---|---|
SENTINEL | -2 | extension | pending |
SENTINEL CKQUORUM | 3 | extension | pending |
SENTINEL CONFIG | -4 | extension | pending |
SENTINEL DEBUG | -2 | extension | pending |
SENTINEL FAILOVER | 3 | extension | pending |
SENTINEL FLUSHCONFIG | 2 | extension | pending |
SENTINEL GET-MASTER-ADDR-BY-NAME | 3 | extension | pending |
SENTINEL HELP | 2 | extension | pending |
SENTINEL INFO-CACHE | -3 | extension | pending |
SENTINEL IS-MASTER-DOWN-BY-ADDR | 6 | extension | pending |
SENTINEL MASTER | 3 | extension | pending |
SENTINEL MASTERS | 2 | extension | pending |
SENTINEL MONITOR | 6 | extension | pending |
SENTINEL MYID | 2 | extension | pending |
SENTINEL PENDING-SCRIPTS | 2 | extension | pending |
SENTINEL REMOVE | 3 | extension | pending |
SENTINEL REPLICAS | 3 | extension | pending |
SENTINEL RESET | 3 | extension | pending |
SENTINEL SENTINELS | 3 | extension | pending |
SENTINEL SET | -5 | extension | pending |
SENTINEL SIMULATE-FAILURE | -3 | extension | pending |
SENTINEL SLAVES | 3 | extension | pending |
Scripting
| Command | Arity | Owner | Implementation |
|---|---|---|---|
EVAL | -3 | extension | pending |
EVALSHA | -3 | extension | pending |
EVALSHA_RO | -3 | extension | pending |
EVAL_RO | -3 | extension | pending |
FCALL | -3 | extension | pending |
FCALL_RO | -3 | extension | pending |
FUNCTION | -2 | extension | partial-slice |
FUNCTION DELETE | 3 | extension | pending |
FUNCTION DUMP | 2 | extension | pending |
FUNCTION FLUSH | -2 | extension | partial-slice |
FUNCTION HELP | 2 | extension | pending |
FUNCTION KILL | 2 | extension | pending |
FUNCTION LIST | -2 | extension | pending |
FUNCTION LOAD | -3 | extension | pending |
FUNCTION RESTORE | -3 | extension | pending |
FUNCTION STATS | 2 | extension | pending |
SCRIPT | -2 | extension | partial-slice |
SCRIPT DEBUG | 3 | extension | pending |
SCRIPT EXISTS | -3 | extension | pending |
SCRIPT FLUSH | -2 | extension | partial-slice |
SCRIPT HELP | 2 | extension | pending |
SCRIPT KILL | 2 | extension | pending |
SCRIPT LOAD | 3 | extension | pending |
5.2 - Data types
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
| Type | Backing table | Primary use | Representative commands |
|---|---|---|---|
| String | redis._string | Byte sequences, integers, floats, or bitmaps | SET, GET, MSET, MGET, INCR, INCRBYFLOAT, LCS |
| Hash | redis._hash | Field/value maps under one key | HSET, HGET, HMGET, HGETALL, HINCRBY, HRANDFIELD, HSCAN |
| List | redis._list, redis._list_length | Ordered sequences of elements (duplicates allowed) | LPUSH, RPUSH, LPOP, LRANGE, LINDEX, LINSERT, BLMOVE, BLPOP |
| Set | redis._set | Unordered collections of unique members | SADD, SREM, SMEMBERS, SISMEMBER, SUNION, SINTER, SSCAN |
| Sorted set | redis._zset | Unique members ordered by float8 score, then raw member bytes | ZADD, ZRANGE, ZREM, ZSCORE, ZRANK, ZUNIONSTORE, BZPOPMIN |
| Stream | redis._stream, redis._stream_group, redis._stream_pel | Append-only entries ordered by (ms, seq) ID with consumer groups | XADD, 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, andBITFIELD/BITFIELD_ROoperate on the underlying String value inredis._string(redis._bitmaphelpers), preserving byte-exact compatibility withGETandSET. - GEO:
GEOADD,GEODIST,GEOHASH,GEOPOS,GEORADIUS,GEORADIUSBYMEMBER,GEOSEARCH, andGEOSEARCHSTOREstore 52-bit geohash integers as scores insideredis._zset. Radius and box queries, result limits,ASC/DESCordering, 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, andPFMERGEstore the Redis 7.2.4 sparse and dense HLL representations inside String values (HYLLheader), soGETandSETcan read or restore raw HyperLogLog state directly.
Object operations
DUMPandRESTORE:DUMPserializes a single key in Redis RDB v11 payload format with a 64-bit CRC64 checksum, andRESTOREreconstructs the key (REPLACE,ABSTTL,IDLETIME,FREQ). They operate on individual keys and do not read or write whole-instance.rdbor AOF files; use PostgreSQL backup tools for database backups.OBJECTandDEBUG OBJECT:OBJECT ENCODINGreports the Redis-compatible encoding name (int,embstr,raw,listpack,hashtable,skiplist,stream).OBJECT IDLETIMEandOBJECT FREQrequirepg_redis.object_heat_tracking = on, and exact listpack/quicklist transition tracking requirespg_redis.list_layout_tracking = on(both default tooffso ordinary reads and list writes avoid extra metadata updates; see Compatibility).
5.3 - SQL API
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
| Function | Arguments | Description |
|---|---|---|
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. |
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 COMMITTEDPostgreSQL transaction (REPEATABLE READandSERIALIZABLEare rejected). Even when invoked from a SQLSELECT, a mutating command such asSETwrites rows and requiresredis._write(). - SQLSTATE codes: Redis command errors (such as
WRONGTYPEor syntax errors) raise SQLSTATERD001. Commands blocked byCLIENT PAUSEraise SQLSTATERD002. PostgreSQL engine errors (such as deadlocks or constraint failures) retain their native PostgreSQL SQLSTATE codes. - Savepoint recovery: Because an unhandled
RD001aborts the current SQL transaction block, wrap fallible Redis calls in aSAVEPOINT(or a PL/pgSQLBEGIN ... EXCEPTION WHEN SQLSTATE 'RD001' THEN ... ENDblock) to recover without losing earlier SQL work. - Per-call database index: The
dbparameter applies only to that function call. ExecutingSELECTinsideredis.commanddoes 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:
| Function | Positional parameters | Return value (bytea) |
|---|---|---|
redis.blocking_begin(bytea[], bytea, integer DEFAULT 0) | args, token, db=0 | Registers 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, protocol | Registers a blocking command with explicit reply protocol (2 or 3); returns [flag, result]. |
redis.blocking_poll(bytea, integer DEFAULT 0) | token, db=0 | Polls for completion and renews the lease; returns [flag, result]. |
redis.blocking_cancel(bytea, integer DEFAULT 0) | token, db=0 | Deletes the registration and returns +OK\r\n. |
redis.pubsub_open(bytea, integer DEFAULT 2) | token, protocol=2 | Opens a Pub/Sub session with protocol 2 or 3; returns +OK\r\n. |
redis.pubsub_change(bytea, bytea[]) | token, args | Applies a subscription command (SUBSCRIBE, UNSUBSCRIBE, PSUBSCRIBE, SSUBSCRIBE, etc.); returns [count, frames]. |
redis.pubsub_poll(bytea) | token | Dequeues pending messages in the current transaction; returns [count, frames]. |
redis.pubsub_cancel(bytea) | token | Closes the Pub/Sub session and deletes queued messages; returns +OK\r\n. |
Parameter and lifecycle rules:
tokenis a unique 32-bytebyteagenerated by the caller for each blocking wait or Pub/Sub session. All subsequentpoll,change, andcancelcalls must use the sameLOGINand active role.- For blocking operations,
[flag, result]hasflag = 0(with a null bulk string) while waiting, andflag = 1once fulfilled. Register withblocking_beginand commit first, then callblocking_pollin subsequent transactions. Repeated polls after completion return the fixed result without popping a second element. - For Pub/Sub,
pubsub_polldeletes delivered rows fromredis._pubsub_eventinside the caller’s transaction; rolling back that transaction restores the messages to the queue.
5.4 - Transactions and retries
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.
| Condition | Behavior on EXEC |
|---|---|
| Unknown command or wrong arity while queuing | Queuing 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 EXEC | EXEC 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. |
WATCHon existing and missing keys:WATCHregisters key digests inredis._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 andEXECdetects the conflict.- Deterministic command time and wakeups: All commands inside one
EXECbatch share a single timestamp for key expiry checks. Blocked clients waiting on keys touched byEXECobserve 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 COMMITTEDtransaction isolation is supported. Callingredis.commandunderREPEATABLE READorSERIALIZABLEraises 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 defaultredis-py6.4.0 client (which defaults to 3 retries) repeated anINCRafter a dropped reply and incremented the counter to2. SettingRetry(NoBackoff(), 0)sent the command once and raised a connection error, leaving the caller responsible for resolving theUNKNOWNstate. Even with zero connection retries,redis-py’sRedis.transaction()helper catchesWatchErrorand re-runs its callback when anEXECreply 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
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, orSSUBSCRIBEonly after PostgreSQL commits the subscription registration inredis._pubsub_session. AnyPUBLISHorSPUBLISHcommitted afterwards reaches the subscriber. - Transactional publishing: Because
PUBLISHinserts intoredis._pubsub_eventinside the publisher’s PostgreSQL transaction, rolling back a SQL transaction or abortingEXECdiscards any messages published inside that transaction. Publishing the same payload twice in committed transactions delivers two distinct messages. - Sharded Pub/Sub scope:
SSUBSCRIBE,SUNSUBSCRIBE, andSPUBLISHoperate 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, andredis.pubsub_cancel. Commit the subscription transaction before publishing from another connection.pubsub_polldeletes 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-eventsand emitted notifications participate in SQL transactions andMULTI/EXECcommit 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 theexpiredkeyspace 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:
| Resource | Default limit |
|---|---|
| Session lease TTL | 120 seconds |
| Queued message payload per client | 1 MiB |
| Queued message frames per client | 1,024 |
| Total retained Pub/Sub payload across sessions | 64 MiB |
| Active Pub/Sub sessions | 4,096 |
| Total subscription registrations | 16,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
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).pgredispreserves the fulluint64range for both components insideredis._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
XADDto append entries (NOMKSTREAM,MAXLEN,MINID),XRANGEandXREVRANGEto query ID intervals (-,+, exclusive(bounds,COUNT),XLENto read the entry count, andXDELorXTRIMto remove entries. - Approximate trimming and
XSETID: Approximate trimming (MAXLEN ~orMINID ~) follows internal stream node boundaries configured bystream-node-max-entriesandstream-node-max-bytes, so it may retain more entries than the requested threshold.XSETIDupdates 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, andXGROUP DELCONSUMERmanage consumer group state inredis._stream_group. - Reading and acknowledging:
XREADGROUP GROUP <group> <consumer> ... STREAMS <key> >delivers new entries and records them inredis._stream_pelunlessNOACKis specified.XACKremoves acknowledged entries from the PEL. - Inspecting and claiming stalled work:
XPENDINGinspects unacknowledged entries by ID range, idle time (IDLE), and consumer.XCLAIMandXAUTOCLAIMtransfer ownership of pending entries to another consumer and increment delivery counters. - Deleted entries in the PEL: If an entry is deleted with
XDELwhile still referenced inredis._stream_pel, historicalXREADGROUP(0) orXCLAIMcalls return a nil/empty payload for that ID, matching Redis 7.2.4. Known gaps inv0.1.0-rc1:XINFO GROUPScomputeslagfrom stream length rather than adjusting forXDEL, andXAUTOCLAIMhas one cursor formatting difference when draining an empty queue (99/101inunit/type/stream-cgroups; see Status).
Blocking reads
- RESP connections:
XREAD BLOCK <ms>andXREADGROUP BLOCK <ms>wait for matchingXADDcommits. InsideMULTI/EXEC,BLOCKoptions run non-blockingly as immediate reads; external clients blocked on a stream wake only after anEXECbatch or SQL transaction commits. - SQL transactions: Ordinary
redis.commandcalls cannot block and commit a caller’s transaction while waiting. SQL callers useredis.blocking_begin,redis.blocking_poll, andredis.blocking_cancelacross transactions. - Restart behavior: Stream entries, consumer group offsets (
last_delivered_id), and PEL records persist in PostgreSQL WAL and survive restarts andpg_dump/pg_restore, whereas activeBLOCKnetwork waits are transient and require clients to reconnect.
5.7 - Configuration
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
| Flag | Default | Description |
|---|---|---|
-listen | 127.0.0.1:56379 | RESP listener address (Mimus assigns 6379 in standard deployments). |
-pg | postgres://127.0.0.1:55432/pgredis?sslmode=disable | PostgreSQL connection URL without credentials. |
-auth-mode | native | Authentication 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-user | app | PostgreSQL LOGIN role used for single-argument AUTH <password> in native mode. |
-client-default-resp | 2 | Initial wire protocol for new connections and RESET (2 or 3). |
-max-clients | 1024 | Maximum concurrent RESP client connections. |
-max-pools | 8 | Maximum cached PostgreSQL identity connection pools. |
-pool-size | 4 | Maximum 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-bytes | 536870912 (512 MiB) | Maximum bytes for a single request bulk argument. |
-max-frame-bytes | 1074790400 (1 GiB + 1 MiB) | Maximum sum of argument bytes in a single request frame. |
-max-reply-bytes | 1074790400 (1 GiB + 1 MiB) | Maximum wire bytes for a complete reply, including EXEC child replies. |
-max-input-bytes | 2147483648 (2 GiB) | Shared budget across connections for live input payloads and bookkeeping. |
-max-output-bytes | 2147483648 (2 GiB) | Shared budget across connections for live replies, workspace, and bookkeeping. |
-max-pg-read-bytes | 2147483648 (2 GiB) | Shared budget for PostgreSQL receive buffers and DataRow metadata. |
-max-pg-message-bytes | 1073741822 (1 GiB - 2 B) | Maximum bytes in a single PostgreSQL wire message body. |
-frame-read-timeout | 30s | Deadline to finish reading a frame after its first byte arrives. |
-command-timeout | 30s | Per-command execution timeout against PostgreSQL. |
-write-timeout | 10s | Deadline for writing a reply frame to the client socket. |
-tls-handshake-timeout | 5s | Deadline for completing a client TLS handshake. |
-version | false | Print 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 3starts new connections in RESP3 mode instead of RESP2.HELLO 2orHELLO 3switches the active connection protocol,AUTHpreserves it, andRESETrestores the gateway’s-client-default-respdefault.
PostgreSQL extension GUCs
Configure these PostgreSQL GUCs in postgresql.conf (or with ALTER DATABASE ... SET as a superuser):
| GUC | Default | Context | Description |
|---|---|---|---|
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_tracking | off | superuser | When 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_tracking | off | superuser | When 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:
| Parameter | Default | Backing table | Effect |
|---|---|---|---|
notify-keyspace-events | "" (disabled) | redis._config | Enables keyspace (K) and keyevent (E) Pub/Sub notifications. |
slowlog-log-slower-than | 10000 (10 ms) | redis._slowlog_config | Microsecond threshold for recording entries in redis._slowlog (negative disables). |
slowlog-max-len | 128 | redis._slowlog_config | Maximum retained slowlog entries. |
latency-tracking-info-percentiles | "50 99 99.9" | redis._slowlog_config | Space-separated percentile list formatted in INFO latencystats. |
acllog-max-len | 128 | redis._acl_config | Maximum entries retained in redis._acl_log for ACL LOG. |
requirepass | "" | redis._acl_config | Password for the Redis default ACL user (does not alter PostgreSQL LOGIN roles). |
acl-pubsub-default | "resetchannels" | redis._acl_config | Default Pub/Sub channel policy (resetchannels or allchannels) for new ACL users and RESET. |
tracking-table-max-keys | 1000000 | redis._tracking_config | Maximum 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_config | Per-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-entries | Redis 7.2.4 defaults | redis._config | Thresholds used for OBJECT ENCODING reporting and approximate XTRIM node boundaries. |
Client output buffer limits and route logs
client-output-buffer-limitaccounting:normallimits apply to ordinary,MONITOR, and tracking-only connections (0 0 0disabled by default);pubsublimits apply to subscribed connections (32 MiBhard,8 MiBsoft for60seconds by default). Accounting sums retained Go reply bytes plus unread rows inredis._pubsub_eventor theMONITORring. 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_rediswrites apg_redis Pub/Sub route failure decisionmessage 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
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
| Resource | Flag | Default limit |
|---|---|---|
| Single bulk argument | -max-bulk-bytes | 512 MiB (536,870,912 bytes) |
| Total argument bytes in one request frame | -max-frame-bytes | 1 GiB + 1 MiB (1,074,790,400 bytes) |
Unauthenticated request header (AUTH pending) | Built-in | 10 arguments, 16,384 bytes per bulk argument |
Complete wire reply (including EXEC array) | -max-reply-bytes | 1 GiB + 1 MiB (1,074,790,400 bytes) |
| Shared live input payload and bookkeeping | -max-input-bytes | 2 GiB (2,147,483,648 bytes) |
| Shared live output payload and workspace | -max-output-bytes | 2 GiB (2,147,483,648 bytes) |
| Shared PostgreSQL receive buffer budget | -max-pg-read-bytes | 2 GiB (2,147,483,648 bytes) |
| Single PostgreSQL wire message body | -max-pg-message-bytes | 1 GiB - 2 B (1,073,741,822 bytes) |
- Local
pgxread-budget patch: Duringmake build,scripts/prepare_pgx.pyappliespatches/pgx-v5.11.0-read-budget.patchto the Go driver so oversized PostgreSQL wire messages and shared-max-pg-read-bytesbudgets 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-bytesor-max-output-bytes. Callers that lose a connection or receive an output-budget error must treat the write outcome asUNKNOWN.
Extension workspace and session limits
| Component | Default limit | Behavior when exceeded |
|---|---|---|
| Per-backend C workspace and reply budget | 2 GiB | Raises a PostgreSQL error and rolls back the statement or savepoint. |
Shared preload memory budget (shared_preload_libraries) | 2 GiB | Bounds shared allocations across backends. |
MONITOR shared-memory ring | 4 MiB / 4,096 entries | Drops stalled MONITOR cursors that fall behind the ring head. |
| Pub/Sub queue per client | 1 MiB / 1,024 frames | Marks the session failed and closes the subscriber connection. |
| Total retained Pub/Sub payload | 64 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 overflowbigintis 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
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
Installpgredisandpg_redisfrom a Linux development archive, enable the extension, and verify the deployment.Build from source
Required compilers, headers, Makefile targets, and test suites for buildingpgredisandpg_redisfrom source.Authentication and permissions
Configure native PostgreSQL role authentication, Redis ACL mode, SQL capability grants, and TLS listeners.Upgrade and recovery
RunALTER EXTENSION pg_redis UPDATE, configure the background maintenance worker, and back up or restore data.
6.1 - Install
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:
| Archive | Platform | Size (bytes) | SHA-256 |
|---|---|---|---|
pgredis-0.1.0-pg18.6-debian13-amd64.tar.gz | Linux x86_64, glibc 2.41 | 9,321,730 | d72fdcb4f40d429e5b650d0671105c923db7ceb4425b50f68d45eea0d61e2ba8 |
pgredis-0.1.0-pg18.6-debian13-arm64.tar.gz | Linux aarch64, glibc 2.41 | 8,574,419 | 4dcc546ef4c0562eb0b69500c0bbb43f664c3b955259ccde92900ef52e269cd7 |
Each archive contains these members at its top level:
bin/pgredis— the Redis wire gateway executablelib/pg_redis.so— the PostgreSQL 18 C extension library (ABI3)share/extension/pg_redis.controlandshare/extension/pg_redis--*.sql— the base script (0.1) and upgrade scripts through0.54licenses/— project, Redis and dependency licence filesinstall.pyandmanifest.json— the installer and the file list with SHA-256, size and mode of every member
Install files
Verify the archive checksum
Check the archive hash before unpacking:
Run the installer
install.pychecks that the host is Debian 13 onx86_64oraarch64, thatpg_config --versionreports PostgreSQL 18.6, and that every member matchesmanifest.json. Then it installs the binary and extension files:The installer copies
pgredisinto/usr/local/bin/pgredis,pg_redis.sointopg_config --pkglibdir, and the control and SQL files intopg_config --sharedir/extension.Create the extension in PostgreSQL
Connect to the target PostgreSQL 18 database as a superuser and create the extension:
Confirm that
extversionreturns0.54andredis._abi_version()returns3.
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):
Run a post-installation check across both the Redis port and SQL:
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
Building pgredis from source compiles both the pg_redis PostgreSQL C extension and the pgredis Go gateway executable.
Toolchain
PostgreSQL 18Server binaries (initdb,pg_ctl,postgres,psql),pg_config, and server development headers (postgresql-server-dev-18on Debian/Ubuntu).Go 1.27.4Required to build the gateway and test harnesses.CGO_ENABLED=1is mandatory because the gateway uses libc host resolution forMIGRATE.C11 compilerclangorgcccompatible with the PostgreSQL PGXS build flags reported bypg_config.Python 3Used byscripts/prepare_pgx.py(which applies the local read-budget patch to the vendoredpgxcache) 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:
What each step produces:
make buildrunspython3 scripts/prepare_pgx.py, verifiesCGO_ENABLED=1, executesgo generate ./internal/gateway(which generates the command dispatch table fromspec/commands.json), and writes the gateway binary tobuild/pgredis.make -C extensioncompilesextension/pg_redis.cintoextension/pg_redis.soagainst the target PostgreSQL 18 headers.make -C extension installcopiespg_redis.so,pg_redis.control, andpg_redis--*.sql(0.1through0.54) into the PostgreSQL installation directories reported byPG_CONFIG.
Test targets
| Target | Command | Scope |
|---|---|---|
make test | go 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-integration | PGREDIS_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-reference | python3 tests/reference/prepare.py && python3 tests/reference/run.py --mode external --variant prd | Builds 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
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:
| Mode | Flag | Client AUTH syntax | Identity 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-acl | AUTH <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,EXECwith writes)redis._admin()— required for administrative commands (FLUSHDB,FLUSHALL,CONFIG,SLOWLOG,ACL,DEBUG,MONITOR,MIGRATE)
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.
Create and bind the PostgreSQL service role
Create a login role with read, write, and admin dispatch grants, then bind its
regroleidentity inredis._acl_serviceas an extension administrator:Once bound in
redis._acl_service,redis_servicecannot execute commands without an activeredis._acl_sessiontoken.Configure ACL users and passwords
Manage users over SQL or from an admin Redis connection:
Supported
ACLsubcommands includeSETUSER,DELUSER,GETUSER,LIST,USERS,WHOAMI,CAT,GENPASS,DRYRUN,LOG,LOAD, andSAVE(LOADandSAVEreport that no externalaclfileis configured because ACLs persist in PostgreSQL WAL).Start the gateway in
redis-aclmodeDo not place credentials in
-pg; pass-acl-service-userand-acl-service-password-file(orPGREDIS_ACL_SERVICE_PASSWORD):
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-certand-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
-pgendpoint URL. When PostgreSQL runs on a separate host, configuresslmode=verify-fullin the-pgconnection string. - Tenant isolation: All 16 logical Redis databases (
SELECT 0throughSELECT 15) share the sameredis._keyspacetable, Pub/Sub event queue, andMONITORring within one PostgreSQL database. Isolate untrusted tenants in separate PostgreSQL databases with separatepgredisgateway instances.
6.4 - Upgrade and recovery
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):
Install the updated binary and extension files
Install the matching
pgredisgateway binary,pg_redis.solibrary,pg_redis.control, andpg_redis--*.sqlfiles on the PostgreSQL host. Stop the PostgreSQL instance before replacing a loadedpg_redis.sofile, then start PostgreSQL and the new gateway.Run the catalog update in PostgreSQL
Connect to each database where
pg_redisis installed and update the extension as its administrator:Verify that
extversionis0.54andredis._abi_version()returns3.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 inpg_rolesso its legacyrole_oidandrole_namedisagree, the migration raises SQLSTATE55000(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_readytrigger): The migration verifies the SHA-256 hash ofredis._stream_group_ready()before adding aWHEN (OLD.kind='x')filter, raising55000if 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:
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 migratingredis._acl_servicebindings across clusters.
What a logical dump includes and excludes:
| Category | Tables | Logical dump behavior |
|---|---|---|
| Keyspace and values | _keyspace, _string, _hash, _list, _set, _zset, _stream_*, _hll, _bitmap | Restored in full; expires_at retains its absolute timestamptz deadline. |
| Extension configuration | _acl_user, _acl_config, _acl_service, _slowlog_config, _tracking_config, _output_config | Registered via pg_extension_config_dump and restored across clusters. |
| Derived caches | _list_length | Excluded 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_client | Excluded from dumps; reconnecting clients establish fresh sessions. |
Failure handling and timeouts
- Command and statement timeouts: Set
-command-timeouton the gateway andstatement_timeout/lock_timeouton the PostgreSQL role to bound worst-case query duration. - Inspecting active backends: Query
pg_stat_activityfor queries executingredis._dispatchorredis.commandwhen diagnosing lock waits or slow commands. - Handling
UNKNOWNwrite 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
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-rc1points to commit2f8ee8d6a. Its product files are identical to11411411d; it adds only the release regression record. Themainbranch is at2d313bc7c. - 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.
| Item | Result |
|---|---|
Gateway make build and make test; extension build | Pass |
| Integration tests without lab-container cases | 302 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.54 | Pass 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/SETtake 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, theSETp50 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/FREQaccess tracking and exact List layout tracking are off by default; see object metadata and List encoding.- After a role is disabled with
NOLOGINand 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 runAUTHagain. - Official tests: a
PUBLISHright afterUNSUBSCRIBE/PUNSUBSCRIBEwithout arguments can still count the old subscriber (2 failures);INFOwith several sections in one request differs from Redis (2 failures);CLIENT LISTandCLIENT INFOfields differ from Redis (2 failures). Themulti,pubsubandintrospectionfiles stop at Lua cases, andintrospection-2stops atOBJECT IDLETIME.
Roadmap
Work deferred until after v0.1.0, in priority order:
- Per-key write concurrency: remove the per-database write lock after a full concurrency audit.
- Delivery stages P5 and P6.
SETp50 ≤ 2 ms withsynchronous_commit=on.- Default Celery and Sidekiq paths; encoding,
DEBUGandOBJECTfidelity; theMIGRATEcontract; external ACL files; multiple gateways; EL and Ubuntu packages.
8 - Releases
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-rc1points to commit2f8ee8d6a(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.
| File | Platform | Size (bytes) | SHA-256 |
|---|---|---|---|
pgredis-0.1.0-pg18.6-debian13-amd64.tar.gz | Debian 13 x86_64 | 9,321,730 | d72fdcb4f40d429e5b650d0671105c923db7ceb4425b50f68d45eea0d61e2ba8 |
pgredis-0.1.0-pg18.6-debian13-arm64.tar.gz | Debian 13 aarch64 | 8,574,419 | 4dcc546ef4c0562eb0b69500c0bbb43f664c3b955259ccde92900ef52e269cd7 |
Key changes in schema 0.54
- List length cache (
redis._list_length):LLEN, theLPUSH/RPUSHreplies and insertion-gap lookups read one cached length per list instead of counting every element. Statement triggers onredis._listmaintain the cache from the rows actually inserted and deleted. The upgrade fills the cache for existing lists. The cache is not dumped: restoring theredis._listrows rebuilds it through the triggers, and a missing cache row falls back to counting. - Fidelity tracking off by default:
pg_redis.object_heat_trackingandpg_redis.list_layout_trackingdefault tooff. A plainGETwrites 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 -versionand INFOpgredis_versionreport0.1.0. INFO addspgredis_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.
| Test | Command | synchronous_commit=on | synchronous_commit=off |
|---|---|---|---|
| G5 | SET | 8,423 req/s, p50 5.215 ms | 20,056 req/s, p50 1.527 ms |
| G5 | GET | 29,833 req/s, p50 0.807 ms | 32,787 req/s, p50 0.775 ms |
| B1 (one hot key) | INCR | 2,469 req/s, p50 19.2 ms | 6,207 req/s, p50 7.0 ms |
| B1 (one hot key, list grows to 50,000) | LPUSH | 2,057 req/s, p50 23.6 ms | 4,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/SETserialize per database until commit and WAL flush; see per-database serialization. - With
synchronous_commit=on, theSETp50 is about 5.2 ms. - No Lua or Functions; default Celery and Sidekiq configurations do not operate.
OBJECT IDLETIME/FREQand exact List encoding need the tracking settings turned on.- After
NOLOGINand a password change, an authenticated native session must runAUTHagain. - Official tests: 6 failures (
PUBLISHafter argument-less unsubscribe, multi-sectionINFO,CLIENT LIST/CLIENT INFOfields), and 4 files that stop at Lua orOBJECT IDLETIMEcases.
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.
| Schema | Adds |
|---|---|
0.1 – 0.5 | redis._keyspace, then redis._hash, redis._set, redis._list and redis._zset |
0.6 – 0.11 | WATCH 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.16 | Streams: _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.41 | Redis ACL: _acl_user, _acl_log, _acl_service, _acl_session |
0.42 – 0.44 | Client 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.51 | No new tables or columns |
0.52 | redis._blocked.reply_before |
0.53 | redis._debug_control.pause_cron (DEBUG PAUSE-CRON) |
0.54 | redis._list_length and its two statement triggers (v0.1.0-rc1) |
9 - Design
These notes record the core architectural choices and scope boundaries of pgredis:
- One semantic core — why all Redis command semantics execute inside the
pg_redisPostgreSQL 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
MIGRATEresolves target hosts via libcgetaddrinfo, 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-rc1results.
For the results on the current candidate, see Status.
9.1 - One semantic core
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
MULTIcommand queues beforeEXECsubmits them in one transaction. - Driving long-lived blocking waits, Pub/Sub subscriptions, client-side caching pushes and
MONITORstreams across pooled backend connections. - Verifying commit confirmation (
ReadyForQuery) and runningredis._pool_reset()before returning connections to the pool.
Trade-offs and invariants
- Requires superuser and preload: Because
pg_redisis a C extension that registers shared memory and a background expiry worker viashared_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 in0.1.0. - Non-negotiable invariants: Every performance optimization must preserve byte-exact binary keys and values, lock ordering, PostgreSQL role permission checks,
synchronous_commit = onby default, and the rule that an operation with an unknown commit outcome is never replayed.
9.2 - Persistence and replication scope
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 mechanism | Affected upstream cases |
|---|---|
SYNC, REPLICAOF or an external Redis replica | 17 |
AOF files, BGREWRITEAOF or AOF loader startup | 20 |
DEBUG RELOAD (save and reload RDB in place) | 12 |
BGSAVE child process or background-save rehash behavior | 1 |
| RDB startup configuration | 1 |
Persisting a non-empty save schedule | 4 |
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
- 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 inunit/type/list) or AOF/replica setup (inunit/type/streamandunit/type/stream-cgroups), the failure or abort remains visible in the official matrix counts. - Retained ordinary obligations: For the 55 mixed cases,
tests/differential/retained-scope-obligations.jsonmaps the 24 groups that contain ordinary data, TTL, encoding, queue, Stream,DUMP/RESTOREor configuration assertions onto PostgreSQL recovery tests (normal restart, immediate shutdown WAL recovery and logicalpg_dump/pg_restore). - Clear separation of claims: Passing PostgreSQL restart and WAL recovery suites (such as the
246,784-assertion mixed-dataset recovery run on commite8cb31f5) 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
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 returnsEINPROGRESS, Redis stops traversing the remaining resolved addresses and waits on that socket. Any later connection refusal or timeout is reported asIOERR error or timeout writing to target instance. - Standard Go
net.Dialercollapses address iteration and returns only the finalerrnoor timeout, losing the boundary betweenconnecting to the clientandwriting 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:
| Observation | Connector 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 immediately | Try the next resolved address |
Initial connect() succeeds or returns EINPROGRESS | Stop traversing addresses and wait on this socket |
| Accepted/in-progress socket later fails, times out or is canceled | Return a writing to target instance error without trying another address |
SO_ERROR is 0 and getpeername() succeeds | Hand 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 (
glibcon Linux returnsEAI_NONAME, whereas macOS resolves to loopback). Host names containingNULbytes or exceeding1,023bytes are rejected before calling libc. - Up to
8concurrent resolver calls are permitted per gateway process; resolution and connection establishment share one overall deadline.
Acknowledgement and commit ordering
- The
pg_redisextension checks permissions, locks the source keys and serializesDUMPpayloads in a source PostgreSQL transaction. - After the connector hands off an established socket, the gateway sends
AUTH(when requested) andSELECTto the target and waits for each acknowledgement before sendingRESTORE. - Only keys whose target
RESTOREreturns an exact+OKare deleted from the source database (unlessCOPYis set). The gateway replies to the caller only after the source PostgreSQL transaction confirms commit. - 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
MIGRATEor deletes target keys to compensate for a source rollback.
Current limits
- Targets sharing the same PostgreSQL database: Because a
MIGRATEtransaction 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 database0–15) blocks when the target attemptsAUTH,SELECTorRESTORE, and times out. Migrating between gateways backed by separate PostgreSQL databases works as expected (verified across 96 cases in 8 auth/protocol profiles on commit715827aa0). - SQL transactions and
MULTI/EXEC: CallingMIGRATEinsideMULTI/EXECor viaredis.command/redis.command_binreturnsNOKEYwhen 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
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 (schema0.1to0.53); about 11,500 lines of non-test Go. Test code was about five times the product code. - History: schema
0.1to0.50was 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% werefeat,fixorperf; 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 exampleSETp50 6.743 ms andGETp50 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
- 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.
- Zero-tolerance gates. G5 was defined with
synchronous_commit=offin the PRD; that definition passed on 2026-10-29, but the gate had been moved toon. 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. - 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.
- Test fidelity on hot paths. Two features that exist mainly for
OBJECToutput made core commands slow:- every
GETupdated LRU/LFU metadata, so reads also waited for a WAL flush; - every
LPUSHrewrote and compressed the full list layout, so single-keyLPUSHmeasured 64.6 req/s with the list growing to 50,000 elements.
- every
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.0and 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:
| Measurement | Before (c25638e1b) | After (11411411d) |
|---|---|---|
G5 GET, synchronous_commit=on | about 13,500 req/s, p50 about 3.1 ms | 29,833 req/s, p50 0.807 ms |
G5 SET, synchronous_commit=on | about 8,200 req/s, p50 about 5.3 ms | 8,423 req/s, p50 5.215 ms |
B1 LPUSH, one key to 50,000 elements, on | 64.6 req/s | 2,057 req/s |
| WAL written by one B1 run | about 3.1 GB | about 67 MB |
WAL for 2,000 GET requests after warm-up | 391,976 bytes | 0 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)
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
| Level | Contents |
|---|---|
| Supported | String; 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 |
| Beta | Streams and consumer groups; Bitmap, HyperLogLog, Geo; DUMP/RESTORE; client tracking; MONITOR; Redis ACL mode |
| Not supported | Lua 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
- No disk writes on the read path:
OBJECTaccess tracking becomes a setting that is off by default, so a plainGETwrites no WAL. - List append without a full layout rewrite: push cost does not grow with the list length;
OBJECT ENCODINGfor a List becomes an estimate. - One public version: gateway, packages and documentation report
0.1.0; the schema version stays visible through the gateway. - 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
| Item | Requirement |
|---|---|
| Build and unit tests | Gateway make build, make test; extension build; integration tests without lab-container cases |
| Clients and semantics | Seven-client smoke; SQL/RESP core differential; outbox example |
| Installation | New installation; upgrade from 0.52 to the current schema |
| G5 | Once. With synchronous_commit=off, GET ≥ 10,000 req/s, SET ≥ 5,000 req/s, p50 ≤ 2 ms; with on, record only |
| B1 | Hot-key benchmark, once |
| Official tests | Redis 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
- Per-key write concurrency: remove the per-database serialization of write commands other than
GET/SET(details). A full concurrency audit comes first. - Delivery stages P5 and P6.
SETp50 ≤ 2 ms withsynchronous_commit=on.- Default Celery and Sidekiq paths; encoding,
DEBUGandOBJECTfidelity; theMIGRATEcontract; external ACL files; multiple gateways. - EL and Ubuntu packages.
Earlier scope decisions stay in effect, for example persistence and replication scope.