Skip to content

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

Return to the regular view of this page

Architecture

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

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

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

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

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

Component responsibilities

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

Section contents

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

1 - Request path

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

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

Ordinary command sequence

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

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

Fast path for plain GET and SET

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

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

Wire pipelining and pooled-connection reset

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

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

2 - Storage

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

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

Keyspace and binary identity

Every Redis key has one row in redis._keyspace:

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

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

Table inventory (schema 0.54)

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

Encoding history and Streams

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

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

Runtime statistics versus durable rows

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

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

3 - Session lifecycle

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

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

Blocking commands and Pub/Sub

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

Key expiry and background maintenance

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

Pooled connection reuse and shutdown

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