Skip to content

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

Return to the regular view of this page

Design

Design decisions behind pgredis.

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

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

For the results on the current candidate, see Status.

1 - One semantic core

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

Decision

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

Rationale

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

The Go gateway still performs essential transport work:

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

Trade-offs and invariants

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

2 - Persistence and replication scope

Why PostgreSQL WAL replaces AOF, RDB and Redis replication.

Decision

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

Upstream test conflicts

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

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

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

How mixed test cases are verified

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

3 - MIGRATE connections

How MIGRATE reaches another server, and its current limits.

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

Connection-stage versus write-stage errors

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

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

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

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

Platform libc address resolution

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

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

Acknowledgement and commit ordering

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

Current limits

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

4 - Status review, 2026-11-08

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

Scope

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

State before the review

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

Why the work did not finish

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

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

Decisions

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

Outcome

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

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

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

5 - MVP goal (v0.1.0)

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

Decision

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

The same rules apply to pgredis, pgetcd and pgsilo.

Rules

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

Scope of v0.1.0

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

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

Work items

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

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

Release list

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

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

Deferred

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

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