This is the multi-page printable view of this section.
Architecture
- 1: Request path
- 2: Storage
- 3: Session lifecycle
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.
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.
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.
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.