Changelog
0.9.2 — 2026-11-18
Reliability
- Replication resumes after repeated drops — a second drop soon after a reconnect restarted the cache cold; it now resumes with the cache intact. See Operations.
Observability
/statusdisk fields renamed —cache.disk_used_bytesandcache.disk_limit_bytes;size_bytesandsize_limit_bytesremain as deprecated aliases.- Version in
/status— a root-levelversionfield.
Deployment
--versionfrom the image —docker run pgcache/pgcache --versionprints the version.- Stale publication note removed — the image no longer tells you to create the publication; PgCache manages it.
try.shasks before restarting a database —--yesno longer covers thewal_levelfix; pass--fix-wal-level.try.sh --no-telemetry— and the script now prints the PgCache version it ran.- Clean shutdown on SIGTERM — PgCache drops its slot and publication on SIGTERM, SIGHUP and SIGQUIT as well as SIGINT; previously
systemctl stopandkillleft the slot on the origin. - Failed startup leaves no slot — a startup that fails after provisioning drops the slot and publication it created.
pgcache cleanup— removes a stopped instance’s slot and publication from the origin;--purgealso removes the shared event triggers and schema. See Operations.- Stop signals logged — with the sending process; a second signal exits at once.
try.sh stopcleans up the origin — it stops PgCache gracefully instead of killing it;stop --purgeremoves everything.
0.9.1 — 2026-11-17
Release notes explain these changes and how to upgrade.
Upgrading from 0.9.0
- Schema-change event triggers required — PgCache refuses to start unless they are installed at its version. A superuser (on RDS and Aurora, the master user) installs them at startup; otherwise run the SQL
pgcache checkprints. See Getting Started → Schema-Change Signal. - 0.9.0’s partition truncate triggers no longer used — PgCache ignores them and warns at startup while they remain. Remove them with:
DROP FUNCTION IF EXISTS pgcache.partition_truncate() CASCADE; DROP FUNCTION IF EXISTS pgcache.partition_signal_install(regclass);
Partitions and Inheritance
- Partitions cached alongside their ancestors — previously a partition’s entries went stale once its root was cached.
- Partitions whose replica identity lacks the table’s key forwarded — previously the table was cached and evicted on every change from that partition.
- Inheritance parents and
ONLYforwarded — previouslyONLYwas ignored and a parent’s entry missed changes to its children.
Predicates
- Pattern and null-safe operators cached —
~,~*,!~,!~*,SIMILAR TOandIS [NOT] DISTINCT FROM. Row-level security policies usingLIKEorILIKEare now inlined. - JSON operators cached —
->,->>,#>,#>>,@>,<@,?,?|,?&,@?and#-;@@and||in the SELECT list only. - Literals compared by column type —
'10.50'and10.5match asnumeric, and date, timestamp and numeric ranges now subsume. Fixes a read-after-write miss when a write spelled the value differently from the read. - Text compared under the column’s collation — fixes CDC leaving out rows inserted into a cached text range under a linguistic collation.
Deployment
- Config file errors no longer print the file — previously a parse error echoed the whole TOML, passwords included.
- Docker image on Debian — moved from Alpine to
postgres:18-trixiewith glibc locales, so text ordering served from cache matches origin. The image grows to about 240 MB. - Cache database created under origin’s locale — PgCache refuses to start when the cache host lacks it.
- A second cache PostgreSQL for RDS and Aurora — built on Amazon Linux 2’s glibc to match their collation;
CACHE_PG_FLAVOURforces either build. - Text ordering checked at startup — PgCache refuses to start when origin and the cache database sort a sample of strings differently.
Session Terms
- Queries reading the session cached per value —
current_user,current_setting(…)and claims extracted from a JSON setting; previously forwarded. See Compatibility → Session Settings. - Session values the cast rejects forward at once — previously the query registered and failed population on every read.
- Row-level security policies keyed on the claim — every token of one user shares an entry.
set_configof a named setting is not a write — PostgREST-style requests are served from cache.
Row-Level Security
- Settings changed out of PgCache’s sight are read back — e.g.
set_configinside a function, orDO, before the next read over a secured table. SET LOCALof a setting the session never had — keyed on the empty string the session reads afterward, as on origin.- Owner exemption through role membership — members of a table’s owning role read the whole table from cache.
- PgCache’s own role checked at runtime — losing
SUPERUSERorBYPASSRLSforwards secured reads without a restart. - A new connection’s first read served — previously forwarded while the settings were probed.
Consistency
- Reads forward until the stream catches up at startup —
/statusreports the position ascdc.startup_lsn.
Functions
- SQL function bodies inlined — STABLE or IMMUTABLE
LANGUAGE sqlfunctions, such as Supabase’sauth.uid(), are cached. See Compatibility → Known Limitations. - Calls resolved through the function catalog — by schema, name and arity on the session’s
search_path; schema-qualified user functions are now cached. - User functions cached when the cache database has them — otherwise forwarded at registration; previously a SELECT-list call failed on every hit.
pgcache.queries.function_forwardscounts the forwards. - Function changes reach the cache —
CREATE OR REPLACE,ALTERandDROP FUNCTIONevict the queries calling the function. - Policy functions resolved where the policy was written — on PgCache’s own
search_path, not the reader’s. COALESCE,NULLIF,GREATESTandLEASTcached inWHERE— previously only in the SELECT list.- Volatile functions always forwarded — previously a SELECT-list call was cached and ran on the cache database.
- Stable functions recomputed on every hit —
now(),to_char()and similar builtins in the SELECT list; other stable calls forward.
0.9.0 — 2026-11-03
Access Control
- Privileges checked on every cache hit — a cached result is served only to a role origin would let run the read. Verdicts are read from origin once per role and object and dropped on DDL or a role catalog change; a role without a positive verdict has its read forwarded. See Compatibility → Known Limitations.
- Row-level security enforced — a table with RLS enabled is cached by inlining the policies that apply to the reading role. A policy that cannot be inlined forwards to origin, and PgCache’s role must be a superuser or have
BYPASSRLSto populate secured tables. See Compatibility → Known Limitations. - Role catalog poll — role membership,
SUPERUSER,INHERITand a role recreated under the same name fire no event trigger, so PgCache polls the origin’s role catalog (every 5 s by default) and forgets every privilege verdict on a change.
Consistency
- Anti-joins over rows other queries loaded — a
LEFT JOIN … WHERE x IS NULL,NOT EXISTSorNOT INnow loads every matching row of itsNULL-filled side for every preserved row its other conditions admit. - Row-level read-after-write for joins — a join read is checked against a pending write per table reference, on that reference’s own filters, so a pending
INSERToutside a joined table’s filter no longer forwards the read. A joined table without a filter, or on theNULL-filled side of an outer join, still forwards on any pending write to it. - Pending writes matched by schema — the table a pending write names is resolved the way origin resolves it, by its schema qualifier or along the connection’s search_path, before reads are checked against it. When the name could resolve to more than one cached table, reads of each forward.
Subsumption
- Readmission by subsumption — an invalidated query whose tables are covered by cached queries that are still current is stamped from their rows on readmission instead of repopulated from origin.
- Waiting on a populating parent — a query covered by a cached query still being populated waits and is stamped from that parent’s rows once they land, so a burst of narrower variants behind a broad query costs one origin population. Its reads forward until then; if the parent is invalidated, evicted or fails first, it populates itself.
- Set operations subsumed — a
UNION,INTERSECTorEXCEPTquery is served from cached parents that cover every arm. - Every reference is a parent — a query that reads a relation more than once offers each fully loaded reference as a subsumption parent on its own.
- IN lists covered value by value —
WHERE id IN (1, 2, 3)is served from cachedWHERE id = 1,WHERE id = 2andWHERE id = 3when no single parent holds the whole set. - Joins served from a cached join of the same shape — a join whose
FROMclause matches a cached join’s under a narrowerWHEREis served from the cached join’s rows instead of populated: cachedorders o JOIN customers c ON o.customer_id = c.id WHERE o.tenant_id = 7now covers the same join withAND o.status = 'open'.
Predicates
- Any predicate in a join’s
ON— comparisons,LIKE,IN,BETWEEN,ORand other predicates aWHEREaccepts are now accepted in anONclause and maintained in place. Previously such joins were forwarded as non-equi joins; a non-immutable function or a subquery inONstill forwards. - Null tests as constraints —
IS NULLandIS NOT NULLon a column are recognised constraints, so a cachedWHERE deleted_at IS NULLcan act as a subsumption parent, and a pending insert the test rejects is proven disjoint from the read.
Change Application
- Memoized and materialized results survive unread-column churn — an
UPDATEthat keeps a row’s primary key and changes only columns a query never reads no longer evicts the query’s memo entry or dirties its materialized result. - Capped queries survive unrelated deletes — a
DELETEinvalidates anORDER BY … LIMITquery only when the deleted row could have met its filters; previously every delete on the relation invalidated every capped query over it.
Serving
- Large results memoized — the in-process memo no longer refuses a result above a fixed 128 KiB per-entry cap; when the budget is full, a result displaces entries that save less cache-database time per byte held.
- Index-only scans on the cache tables — every secondary index on a cache table carries the primary key as
INCLUDEcolumns and the generation tracker stamps a row from the index tuple, so the cache database plans index-only scans again. - Read facts built once — the relations, columns and ranges a cached query’s read-after-write and privilege checks need are derived once when the entry is published, not per read.
Admission
- Cheaper admission-threshold misses — a query below the admission threshold is bound and checked for subsumption before the rest of its resolution is built, so a miss costs the check alone.
- Pending set bounded — with
admission_thresholdabove 1, a flood of first-sight queries that never repeat could grow the pending set without bound. - Box CPU pressure feeds the registration gate — PgCache reads the box’s CPU pressure (Linux PSI) and run-queue wait, and the registration gate backs off its admit rate while pressure stands on both the 10 s and 60 s windows with the run queue growing. Readmissions now take an admission token like fresh registrations.
Population and Merges
- LIMIT-capped population for joins — a plain join under
ORDER BY … LIMITis populated from the join’s top N rows instead of every row the join admits; outer joins, derived tables and shapes that compute their result still load whole. - Merges stamp without rewriting rows — a population merge lifts the rows the cache table already holds to the new generation by stamping inside the extension instead of updating each row.
- Readmission deferred behind a congested merge queue — an invalidated query read again while the oldest staged population has waited longer than the query’s last cached period is forwarded and stays invalidated, since its new copy would be invalidated before it landed.
- Staging released the moment a population is superseded — a population whose query is invalidated, readmitted or evicted while it waits for its merge releases its staging copy at once.
Fixes
- TLS connections under bursts — ciphertext the TLS engine cannot take yet is kept for the next poll instead of closing the connection, so a TLS client or origin connection no longer drops when records arrive faster than the decrypted bytes are drained.
- Right-nested joins rendered in parentheses — a join nested on the right side of another join keeps its parentheses in the SQL PgCache runs on the cache database and at population; the bare form read as the wrong nesting in statement logs.
Configuration
- New
role_poll_intervalsetting (default5;0disables) — seconds between role catalog polls. Also--role_poll_intervalandPGCACHE_ROLE_POLL_INTERVAL.
Observability
pgcache.queries.privilege_forwards(counter, labeledreason=pending|denied) — cache hits forwarded on the role’s privileges.pgcache.queries.rls_skipped(counter) — reads over a row-level-secured table forwarded because a policy cannot be inlined;pgcache.queries.rls_forwards(counter, labeledreason=setting_unknown|default_deny|row_security_off|unsupported) — reads over a secured table forwarded for another reason.pgcache.cache.role_changes(counter) — role catalog changes seen by the poll, each forgetting every verdict.pgcache.cache.readmission_subsumptions(counter) — readmissions served by a current parent instead of a population.pgcache.cache.subsumptions_split(counter) — subsumptions that covered anINlist value by value.pgcache.cache.subsumptions_join(counter) — subsumptions served by a cached join of the same shape.pgcache.cache.subsumption_waitsandpgcache.cache.subsumption_wait_fallbacks(counters) — registrations parked on a populating parent that covers them, and those released to a population of their own after all.pgcache.raw.writes_unresolved(counter) — table-scoped writes naming no cached relation, recorded by name alone.pgcache.cache.memo_evictions_skippedandpgcache.cache.mv_dirty_skipped(counters) — memo evictions and materialized-result dirties skipped because theUPDATEchanged no column the query reads.pgcache.cache.memo_replacementsandpgcache.cache.memo_refused(counters) — memo entries displaced for a result worth more per byte, and captures refused for lack of room;pgcache.cache.memo_evictionsnow counts only entries dropped as stale after a CDC change.pgcache.cache.writer.register.bind_seconds(histogram) — the bind phase ofquery_register, recorded for every registration including a check-only miss.cmd=privilege_resolve— new label value onpgcache.cache.writer.command_handle_seconds.pgcache --checkon row-level security — previously a failure on any secured table; the check passes when PgCache’s role can bypass the policies and otherwise warns, naming the tables and theALTER ROLEto run.- Merge queue congestion —
pgcache.cache.merge.head_age_seconds(wait of the oldest pending merge),pgcache.cache.merge.superseded_total(staged populations dropped while they waited) andpgcache.cache.readmissions_deferred(readmissions forwarded behind a congested queue). - Staging held —
pgcache.cache.staging.held(populations holding a staging copy),pgcache.cache.merge.discards_totalandpgcache.cache.merge.discards_pending(staging handed to the population workers to empty, and how much is still on its way back). - Box CPU pressure —
pgcache.cache.cpu_pressure_avg10/avg60,pgcache.cache.cpu_waiting_tasksandpgcache.cache.population.expected_wait_seconds(the PSI readings and run-queue magnitude the gate acts on, and the queue-wait term of the readmission horizon).
0.8.0 — 2026-10-22
Consistency
- Schema changes observed on the replication stream — PgCache installs two event triggers on the origin database that report every DDL command and dropped object as a logical message inside its transaction. See Getting Started → Schema-Change Signal.
- Read-after-write through views and partitions — a write into a partition child while the parent is cached, a write to the root of a partition cached on its own, and a write through an auto-updatable view are now matched to reads of the table the rows land in. Views with
INSTEAD OFtriggers orDO INSTEADrules, and rows written by triggers or cascades, remain unmatched. - Outer joins serve single-table queries — a cached
users LEFT JOIN ordersnow acts as a subsumption parent for a query overusersalone, since the preserved side holds every row itsWHEREadmits. - Fewer join invalidations — a change to a join partner invalidates a cached join only when the partner’s cached rows may be incomplete. A row whose join column moves to another cached preserved row is now patched in place.
Origin Objects
- Event triggers and a
pgcacheschema on the origin — when its role is a superuser, PgCache creates thepgcache_ddl_command_endandpgcache_sql_dropevent triggers, apgcacheschema holding their functions, and a statement-levelpgcache_truncatetrigger on every partition. They are shared by every PgCache instance on the database and are left in place at shutdown; the shutdown log prints the SQL that removes them.
Performance
- Population through COPY — population rows stream from origin into the cache’s staging tables through a
COPYpipe instead of escapedINSERTbatches. - Repeated reads skipped within a population — a CTE referenced twice in one query loads its rows once.
- Self-joins batch CDC evaluation — a multi-row transaction into a self-joined relation is evaluated once per table reference instead of once per row.
- Metrics upkeep off the proxy threads — metric upkeep and telemetry run on a dedicated background thread.
Bug Fixes
LIMITqueries could cache the wrong rows — the capped population read dropped the query’sORDER BY, so it could load an arbitrary n rows, and the cap also applied to subquery reads, soIN (SELECT …)was evaluated over part of its set.- Self-joins and repeated tables in subsumption — a query that references one table twice (a self-join, or the same table in the outer query and a subquery or CTE) was served from a cached parent covering only one of the occurrences. Every reference must now be covered.
- Same-table column equality — a cached
WHERE a = bholds only rows where the two columns agree, and was used as a subsumption parent for narrower queries on other columns. - Literals in outer-join
ONclauses — a literal on the preserved side of aLEFT JOIN … ONfilters no rows, but was read as aWHEREconstraint: it could subsume a query needing every preserved row, and anUPDATEto such a column was patched in place when it could attach an unloaded row. BETWEEN,INandNOT INwith non-literal operands — these were read as literal constraints; the analysis is now marked incomplete, so such a query is neither subsumed nor used as a parent on that column.DELETErelevance underREPLICA IDENTITY DEFAULT— aDELETE’s relevance to a filteredIN/NOT INsubquery or to the optional side of an anti-join was judged on the key-onlyDELETEtuple, which read every filter column asNULL. It is now judged on the row’s recovered old image, so such deletes invalidate as they should.- Non-default replica identities — a table with
REPLICA IDENTITY FULL,USING INDEXorNOTHINGwas re-registered on theRelationmessage that precedes its first change, because the message flags the replica identity columns and PgCache read them as the primary key. The key now comes from the origin catalog and queries are kept. - Date-time and float old images — date, timestamptz and float filter columns are now recovered with origin’s exact text when origin’s role settings render them unlike the cache’s defaults. Previously an unrelated row’s update could evict a memo entry, and a matching row’s update could keep one.
- Stale-read holes on joins — a
WHEREconjunct PgCache cannot read, and a table sharing theNULL-filled side of an outer join with another table, were applied as terminal changes. Such anUPDATEorINSERTcan attach partner rows that were never loaded, so it now invalidates.
Observability
pgcache.cdc.messages(counter) — logical decoding messages delivered on the stream; PgCache’s own carry the schema-change signal.cmd=cdc_schema_change— new label value onpgcache.cache.writer.command_handle_seconds.pgcache --checkreports the schema-change signal — passes when the event triggers are installed or the role can install them, and warns with the install SQL otherwise.
0.7.1 — 2026-10-15
Consistency
- Session settings tracked per connection —
search_path, role, date-time, output and locale settings are now tracked on every connection, and reads forward while a setting they depend on is unknown. Previously a session on a non-defaultTimeZoneorDateStylecould be served results computed under other settings. - Results rendered with the client’s settings — cache hits apply the client’s output settings, so timestamps, intervals, floats,
byteaandmoneyrender as origin would. Memo entries and coalesced waits are keyed by them. - Date-time literals canonicalised — date and timestamp literals are normalised at registration, so sessions share a cache entry only when their literals select the same rows.
- Literal comparisons by column type — CDC evaluation compares literals by column type, not text, so
'2024-01-15 10:00'matches2024-01-15 10:00:00. - Parse-changing settings forward the session — e.g.
standard_conforming_strings = offor a non-UTF-8client_encoding. $userinsearch_path— a quoted"$user"now expands to the current role, as in PostgreSQL.- Shadowed builtins — sessions whose
search_pathlistspg_catalogafter another schema are forwarded. - Schema-qualified function calls — only
pg_catalog-qualified calls are cached;myschema.f(x)was previously cached as the builtin. - Concurrent deletes during population — a delete still waiting on a synchronous standby could be undone by an in-flight population.
- Stale memo entries — fixed two cases where a memo entry outlived the change that should have evicted it.
Performance
- Reads served despite an unrelated pending
UPDATE— read-your-own-writes serves a read when the pending update assigns only columns the read doesn’t reference. - Fewer repopulations under CDC lag — an unrepairable TOAST update no longer invalidates a query that is still loading unless its snapshot missed the update.
- Lower per-query overhead — fewer allocations in parsing, registration and CDC evaluation.
Bug Fixes
- First statement on a new connection answered with “read committed” — on PostgreSQL 17 and earlier, a connect-time probe’s reply could be returned in place of the client’s first statement’s result.
- Probes no longer wait for an idle origin socket — busy pipelining connections no longer have reads forwarded while a probe waits for a gap.
- Plain
EXPLAINno longer blocks cache hits — it was treated as a write, forwarding the connection’s reads until cleared. - Failed CDC messages are no longer skipped — the stream now reconnects or the cache restarts, instead of dropping the change.
- TOAST repair on tables with quoted identifiers — repairs on such tables always fell back to invalidation.
- Memo bookkeeping growth — the memo no longer keeps a slot for every query it has ever seen.
- Fewer panic paths — several panics now return errors or restart the cache.
Observability
pgcache.conn.settings_probes(counter) — session-settings probes sent to origin.pgcache.cache.serve_settings_applied(counter) — serves that applied the client’s output settings on the serve connection.pgcache.cache.reference_only_forward_total(counter) — hits forwarded because the entry’s literals are only valid under origin’s default settings.pgcache.cache.memo_slots(gauge) — memo version slots.
Breaking Changes
pgcache.txn.isolation_probesremoved — usepgcache.conn.settings_probes.- Cache host must support origin’s locales — pgcache refuses to start if the cache database lacks origin’s default
lc_monetary,lc_numericorlc_time.
0.7.0 — 2026-09-25
Consistency
- Read-your-own-writes — each connection now tracks the writes it forwards to origin. Until CDC has applied a write, a cacheable read on the same connection is served from cache only if pgcache can prove the read is disjoint from it; otherwise it is forwarded to origin.
- Writes through an auto-updatable view, or directly into a partition child while the parent is cached, are not matched to reads of the underlying table.
- Cache hits inside transactions — cacheable reads inside a
READ COMMITTEDtransaction block are now served from cache when they are disjoint from the block’s own uncommitted writes. Previously every statement inside a block was forwarded. Blocks atREPEATABLE READorSERIALIZABLE, and failed blocks, are still forwarded.
Performance
- Elastic population worker pool — population work goes through one shared queue served by whichever worker is idle, replacing per-worker round-robin queues where one slow item could strand its lane. The pool grows and shrinks dynamically. Bounds are the new
population_workers_min/population_workers_maxsettings. - Elastic serve pool — the cache-database serve pool, previously fixed at
num_workers × 2(min 4), now sizes itself betweennum_workers × 2andnum_workers × 8. It grows under cache-hit load that queues on the pool and releases idle connections when load falls. - Narrower TOAST fallback during population — an unrepairable unchanged-TOAST update on a relation with an in-flight population now aborts only the populations that staged the affected row, instead of invalidating every cached query over the relation.
Bug Fixes
- Text range subsumption under non-C collations — subsumption compared string range bounds by byte order, which differs from collation order (
'a' > 'B'in bytes,'a' < 'B'underen_US). A cached query such asWHERE name > 'B'could be used to serveWHERE name > 'a'and miss rows. Range bounds on quoted literals (text, and dates or timestamps written as strings) are no longer used for subsumption; equality andIN-set coverage are unaffected. - Dead population cache connection — a population worker whose cache-side connection died (backend killed, cache reset) now reconnects it, as it already did for its origin connection. Previously that worker failed every population it received from then on.
- Client hang during cache restart — a cache serve waiting for a pool connection while every serve connection was lost at restart now closes the client connection instead of waiting forever.
Configuration
- New
population_workers_minsetting (defaultmax(num_workers, 2)) — floor and starting size of the population worker pool. Each worker holds one origin and one cache connection. - New
population_workers_maxsetting (defaultnum_workers × 8) — ceiling on concurrent population queries against origin. An explicitpopulation_workers_maxbelow the default floor lowers the floor with it.
Observability
- Read-after-write metrics —
pgcache.raw.writes_recorded,pgcache.raw.probes(commit-LSN probes sent to origin),pgcache.raw.forwards(labeledscope=table|connection),pgcache.raw.forward_blocked(labeledcause=unstamped|delivery_lag|apply_lag),pgcache.raw.clearance_seconds(histogram: time from a write’s commit probe to its clearance),pgcache.raw.serve_disjoint_insert/_update/_delete(reads served because they were proven disjoint from a pending write),pgcache.raw.cap_degraded_insert/_update_delete, andpgcache.raw.tier_merges. - In-transaction serving metrics —
pgcache.txn.served,pgcache.txn.forwards(labeledreason=failed|isolation_unknown|isolation_strict|pending_write), andpgcache.txn.isolation_probes. - Elastic pool metrics —
pgcache.cache.population_workersandpgcache.cache.serve_pool_size(gauges: live pool size),pgcache.cache.population_scale_up/_scale_down/_backstop_growsandpgcache.cache.serve_pool_scale_up/_scale_down/_backstop_grows(counters), andpgcache.cache.population_queue(gauge: shared population queue depth). pgcache.cache.cdc_toast_stale_aborts— population merges aborted and re-run because their staging held a row an unrepairable TOAST update left stale.cdc.settled_lsnin/status— every origin transaction committing at or below this LSN is either applied to the cache or produced no change pgcache consumes. Unlikelast_applied_lsn, it also advances across WAL with nothing to apply (DDL, unpublished tables, idle origin).
Breaking Changes
/statuscdc.apply_idleremoved — replaced bycdc.settled_lsn. To wait until pgcache has applied everything up to an origin LSN, poll untilsettled_lsnreaches it.pgcache.cache.population_worker_queueremoved — the per-worker gauge (labeledworker) is replaced by the singlepgcache.cache.population_queuegauge.
0.6.4 — 2026-09-18
Bug Fixes
- Memory growth with many connections — every connection kept its own parsed copy of the cacheability analysis for each distinct SQL text it had seen. Analyses are now interned once per process and shared across connections.
- Unbounded histogram samples when
/metricsis never scraped — latency histogram samples were only drained on a/metricsrender, so a process that was never scraped retained every sample it had recorded. Samples are now drained once a second regardless of scraping. - CDC apply no longer waits behind a population merge — a population’s staging→cache merge ran as one statement per relation on the writer thread, so no CDC change applied until it finished. The merge now drains staging in bounded chunks with CDC applied between them.
- Abandoned population staging is emptied in chunks — when a population is superseded, invalidated, evicted, aborted, or fails, its staging tables used to be emptied with one
DELETEon the writer, stalling CDC apply for seconds on large populations. They are now drained in the same bounded chunks as a merge, with CDC applied between them. - Eviction no longer strands a query mid-population — under a query-count cap, a pinned or CLOCK-referenced query whose population was still in flight could have its generation bumped by the eviction tick, abandoning the population with nothing to finish or readmit it, so it stayed Loading forever. Such candidates are now skipped for the round and bumped once Ready.
- Dual-stack admin listener — the admin HTTP server bound to
0.0.0.0is now reachable over IPv6 loopback too, so a container healthcheck againstlocalhost:9090works on images whose/etc/hostsresolveslocalhostto::1first. The bound admin address is logged at startup. - Docker image healthcheck — the image now declares a
HEALTHCHECKon/healthz; the documented compose examples usedcurl, which the image does not ship.
Observability
pgcache.connections.cacheability_entries(gauge) — interned cacheability analyses currently referenced by live connections; bounded by distinct SQL texts in use, not by connection count.pgcache.cache.merge.chunks_total(counter) andpgcache.cache.merge.chunk_seconds(histogram) — merge chunks applied and their wall time, the longest a CDC frame waits behind an in-progress merge.pgcache.cdc.keepalive_marks_coalesced(counter) — a run of consecutive replication keepalives queued for the writer is now handled as one at its highest LSN, so a keepalive burst from a busy origin cluster costs the writer one iteration instead of one each.
0.6.3 — 2026-09-11
Performance
- Materialized-view rebuild backoff — a query whose MV keeps getting dirtied right after a rebuild now backs off exponentially (1 s → 300 s) after two consecutive wasted builds instead of rebuilding on every hit.
- Broader subsumption matching — a new query mixing equality and range predicates (
tenant_id = 7 AND created_at > 150) can now be served from a cached equality-only parent (tenant_id = 7).
Reliability
- Cgroup memory budget — the memory monitor now honors the tightest limit on the cgroup ancestor chain (e.g. systemd
MemoryMax=) and measures usage as the working set (excluding reclaimable page cache), so the cache database’s page cache no longer trips the registration throttle. - Serve-pool replenishment on task death — a serve task that panics or is cancelled while holding a connection now triggers a replenish. Protocol desyncs poison the connection at detection instead of waiting out the stall deadline.
- Non-blocking log writes — log lines go through a queue and a dedicated writer thread; a stalled stdout reader can no longer block a worker thread. On overflow lines are dropped and counted.
Bug Fixes
- Self-joins — CDC membership is evaluated against every occurrence of a self-joined relation; a row needed only by one arm could previously be evicted from the cached result.
- Enum and other origin-only column types — tables with such columns no longer have their cache table recreated on every CDC relation message. Order-dependent enum usage (
ORDER BY, range comparisons,min/max) is now forwarded, since enums are stored astextin the cache. - Identifiers that require quoting — mixed-case names, reserved keywords, and embedded quotes now survive cache DDL, population, CDC apply, and deparse.
- Quantified
ANYcomparisons —x > ANY (SELECT …)and other non-equalityANYsublinks are now forwarded instead of being cached withINsemantics. *over derived tables —USINGandNATURALjoins over subqueries no longer drop columns from the cached result.
Configuration
- New
--config_createflag — a missing config file is no longer a startup error; it is created by the firstPUT /config, so dynamic configuration changes persist.
Observability
- CDC watermarks in
/status—cdc.last_applied_lsnnow advances only on applied cache commits; the receive/liveness watermark is the newcdc.last_received_lsn. A newcdc.apply_idleflag reports whether the apply pipeline has nothing in flight. - MV backoff —
pgcache.cache.mv_builds_suppressed(counter) and per-querymv_wasted_builds/mv_backoff_remaining_msin/status. pgcache.cache.serve_desync_total— unexpected backend frames caught in the serve relay.pgcache.log.dropped_lines— log lines dropped because the stdout consumer is not keeping up.- Cacheability errors name the offending construct — the
uncacheable SELECTdebug log now says e.g.Unsupported FROM clause: FULL JOINrather than a generic category.
Breaking Changes
/statuscdc.last_applied_lsnsemantics changed — consumers that compared it against the origin LSN for liveness should switch tocdc.last_received_lsn.
Internals
- The proxy runtime is behind a default
proxyCargo feature;cargo buildis unchanged,--no-default-featuresyields the query-analysis library only.
0.6.2 — 2026-07-03
Reliability
- Slow populations no longer hold coalesced waiters hostage — when concurrent requests coalesce onto a single in-flight population, a waiter whose population runs past a forward deadline is now degraded to origin while the population completes in the background. This decouples serve latency from population latency, so a large cold first-population or a re-population running past its estimate no longer stalls the requests waiting on it.
Performance
- More precise CDC invalidation under
REPLICA IDENTITY FULL— UPDATE and DELETE events are now probed against the recovered old-row values rather than a primary-key-only wildcard, so changes to joined tables invalidate fewer cached queries. - Candidate-narrowed CDC invalidation and memo eviction — the invalidation and in-process memo-eviction passes now run against the per-operation candidate sets produced by the shared constraint-containment probe, replacing full-set scans.
- Lower CDC apply overhead — the per-event CDC hot path was reworked to avoid unnecessary work and allocations.
- Lower population and escaping overhead — population row tuples and string literals are escaped directly into the output buffer without per-column or temporary strings.
- More precise
LIMIT-window maintenance — changes to a column used in a cached query’s sort key is now analyzed to see if the query can be maintained in place instead of invalidating.
Observability
- Population merge-stage metrics —
pgcache.cache.merge.pending_depth(gauge: staged populations awaiting the merge drain gate),pgcache.cache.merge.wait_seconds(histogram: time from merge-enqueue to merge-apply), andpgcache.cache.merge.applied_total(counter: merges applied). Together with the existingpopulation.wait/population.taskhistograms these localize a population stall to the queue, fetch, or merge stage. pgcache.cache.coalesce_deadline_forward_total— counts coalesced waiters forwarded to origin because their population exceeded the forward deadline.- Accurate CDC invalidation counts — the CDC invalidation counter now increments once per Ready → Invalidated transition, so the metric no longer over-counts.
Bug Fixes
- MV rebuild uses
DELETEinstead ofTRUNCATE— rebuilding a materialized-view table now clears it withDELETE, avoiding theTRUNCATE-related locking/visibility issue.
0.6.1 — 2026-06-22
Query Language Support
- Window frame clauses — explicit
ROWS/RANGE/GROUPS BETWEEN ...frames are now preserved through parsing, resolution, and deparse, so windowed queries with a custom frame are cached. - Named windows —
WINDOW w AS (...)definitions and theirOVER wreferences are now resolved and cached. PreviouslyOVER wcould not be resolved and the query was forwarded.
Performance
- Shape-keyed prepared statements on cache hits — cache serves now reuse one prepared statement per query shape (literals bound as parameters) instead of re-parsing per distinct literal.
- Replicated partial and expression indexes — partial (
WHERE-qualified) and expression indexes on origin tables are now recreated on the corresponding cache tables. - Indexed CDC evaluation — a shared per-relation constraint-containment index narrows which cached queries a CDC change must be checked against, replacing per-relation full scans.
- Lower-overhead population — population now reuses pooled per-relation staging tables instead of issuing per-population DDL, and each population worker uses its own dedicated origin connection.
Reliability
- Adaptive registration pacing — new-query registration is paced to the cache writer’s measured drain rate. Registration bursts are shed to origin instead of saturating the writer and degrading already-cached query latency.
- TOAST-safe CDC updates — UPDATE events that omit unchanged TOASTed columns (Postgres’s
unchanged-toastmarker) are now repaired from the cached row via a single batched lookup per relation, rather than being mis-applied. Cases that cannot be repaired conservatively invalidate the affected query. - Protocol desync fix on serve failure — a cache-serve error that occurs after bytes have already been sent to the client now terminates the response with a synthetic
ErrorResponseinstead of emitting a duplicateBindComplete. - Correct alias quoting — resolved-
SELECTdeparse now quotes column aliases that require it, fixing result column names for aliases containing special characters or matching keywords. - Faster shutdown during an origin outage — CDC reconnect-probe awaits are cancel-guarded so teardown is no longer blocked behind an origin connect timeout.
Configuration
- Disk-pressure eviction;
cache_sizedeprecated — pgcache now measures real cache-volume usage (viastatvfs) and evicts under disk pressure.cache_sizeis now deprecated and ignored (setting it logs a warning). The optional newdisk_limitcaps cache-volume bytes; when unset it auto-derives from the volume’s live free space, keeping a reserve free (5% of capacity, clamped 1–10 GiB); a configured value will only lower the auto-derived ceiling. - New
mv_compute_min_rowssetting (default1000) — adds a compute-avoidance path to the materialized-view first-build gate: a shape-eligible query is now materialized if either its result is sufficiently smaller than its input (the existingmv_size_ratiorow-reduction test) or its population source-row count reachesmv_compute_min_rows, so large inputs aren’t recomputed from source rows on every serve. Settable via TOML (mv_compute_min_rows), CLI (--mv_compute_min_rows), env (PGCACHE_MV_COMPUTE_MIN_ROWS), and at runtime viaPUT /config. - Native environment variables —
mv_size_ratio,mv_compute_min_rows,memo_cache_size,memory_limit, anddisk_limitcan now be set directly viaPGCACHE_*environment variables (in addition to TOML and CLI).
Observability
- Cache-volume disk metrics —
pgcache.cache.disk_total_bytes,pgcache.cache.disk_available_bytes,pgcache.cache.disk_used_bytes, andpgcache.cache.disk_limit_bytes(the effective disk-usage ceiling above which reclaim engages). - Materialized-view build metrics —
pgcache.cache.mv_build_queue(gauge: build tasks waiting for a build-pool connection) andpgcache.cache.mv_gate(counter, labeledoutcome=admit|reject: first-build gate decisions). - CDC TOAST-repair metrics —
pgcache.cache.cdc_toast_repairsandpgcache.cache.cdc_toast_fallbacks(unchanged-TOAST images repaired from cache vs. routed to conservative invalidation). - Serve-pool metrics —
pgcache.cache.serves_in_flight,pgcache.cache.pool_available,pgcache.cache.serve_stall_total(serves that exceeded the stall deadline and were forwarded to origin), andpgcache.cache.serve_dirty_return_total(serves that finished with unconsumed bytes — a response-desync guard). - Registration-gate metrics —
pgcache.cache.reg_gate_rate,pgcache.cache.reg_gate_btlbw,pgcache.cache.reg_gate_queue_min,pgcache.cache.reg_gate_drain_rate, andpgcache.cache.reg_gate_loadingexpose the adaptive registration pacer’s internal state. /statusadditions — a rootfault_injectionflag (whether the binary was built with thefault-injectionfeature) and a per-querymv_statefield (materialized-view state-machine position).
Breaking Changes
- Removed the Prometheus gauges
pgcache.cache.size_bytesandpgcache.cache.size_limit_bytes, superseded by thepgcache.cache.disk_*gauges. The/statusJSONsize_bytes/size_limit_bytesfields remain, now reporting cache-volume used bytes and the effective disk limit respectively.
0.6.0 — 2026-06-10
Reliability
- Population/CDC merge consistency — query population and the live CDC stream are two independent writers to the same cache tables, observing origin at different points on the replication timeline. pgcache now coordinates them so the data in the cache is always consistent.
- Bounded memory under high query cardinality — pgcache no longer grows its in-process state without limit. A memory monitor throttles registration of new distinct queries as whole-system used memory approaches a budget (80% of detected RAM by default, cgroup-aware in containers). Already-cached queries keep serving.
- Serve-pool connection recycling under memory pressure — cache-database serve-pool connections are now periodically recycled to reclaim the per-connection plan-cache memory Postgres accumulates, keeping the cache backend’s footprint bounded over long runs.
Performance
- Prepared, pipelined CDC evaluation — per-query CDC membership and row-change checks are now prepared once and pipelined rather than re-parsed per event. Membership is evaluated in batch, lowering CDC apply cost.
Configuration
- New optional
memory_limitsetting — an absolute ceiling (bytes) on pgcache’s total memory footprint. Unset → 80% of detected RAM; a configured value can only lower the effective ceiling. Settable via TOML (memory_limit), CLI (--memory_limit), env (PGCACHE_MEMORY_LIMIT), Docker (MEMORY_LIMIT), and at runtime viaPUT /config. - Automatic disk-size limit;
cache_sizedeprecated — whencache_sizeis unset, pgcache now derives the cache’s disk-size limit from the cache volume’s live free space, evicting to keep a reserve free (5% of total capacity, clamped between 1 GiB and 10 GiB). A configuredcache_sizeremains a hard override but is deprecated, a newdisk_limitsetting will be added analogous to thememory_limitsetting.
Observability
- Memory and registration-throttle metrics —
pgcache.cache.memory_used_bytes,pgcache.cache.rss_bytes,pgcache.cache.memory_budget_bytes,pgcache.cache.query_count_cap,pgcache.cache.marginal_bytes_per_query,pgcache.cache.registration_throttled, andpgcache.cache.registration_throttled_total. - CDC prepared-eval metrics —
pgcache.cache.cdc_prepared_hitsandpgcache.cache.cdc_prepared_missestrack the prepared-statement cache for CDC evaluation (a high miss rate signals the live query working set exceeds the cache capacity). pgcache.cache.pool_recycled— counts serve-pool connections recycled to reclaim plan-cache memory.
0.5.0 — 2026-06-07
Performance
- Unified serving runtime — connections, the request coordinator, and the cache worker now run as tasks on a single shared multi-threaded runtime instead of separate per-thread executors.
- In-process result memo — a new in-memory tier caches full result snapshots for the hottest queries and serves them inline skipping the cache-database round-trip entirely. Controlled by the new
memo_cache_sizesetting (default 64 MiB;0disables); adjustable at runtime via the admin API.
Reliability
- Cache restart supervisor — backend failures (writer, CDC, or connection-pool death) self-heal. A supervisor rebuilds the cache subsystem with exponential backoff (500 ms → 30 s) while the proxy keeps serving by forwarding to origin.
- Serve-pool connection replenishment — a poisoned cache-database connection is now discarded and transparently replaced rather than degrading the serve pool.
Configuration
- New
memo_cache_sizesetting (default64 MiB) — total byte budget for the in-process result memo;0disables it. Settable via TOML (memo_cache_size), CLI (--memo_cache_size), thePGCACHE_MEMO_CACHE_SIZEenvironment variable, and at runtime viaPUT /config.
Observability
- In-process result memo metrics —
pgcache.cache.memo_hits,pgcache.cache.memo_captures,pgcache.cache.memo_evictions,pgcache.cache.memo_entries, andpgcache.cache.memo_bytes. - Restart and pool metrics —
pgcache.cache.restarts_total(successful cache-subsystem restarts) andpgcache.cache.pool_replenished(replaced serve-pool connections). pgcache.protocol.close_local— countsClose(statement)messages handled locally without forwarding to origin.
Breaking Changes
- Removed the internal queue-depth metrics
pgcache.cache.proxy_message_queueandpgcache.proxy.worker_queue— the per-connection and coordinator message queues they measured no longer exist under the new runtime.
Internals
num_workersnow sizes the shared runtime’s worker-thread pool; it remains the multiplier for the connection-pool, command-channel, and population-pool sizes.
0.4.12 — 2026-06-01
Query Language Support
USING,NATURAL, andCROSS JOIN— these join forms are now parsed, resolved, and cached.USINGandNATURALresolve to the equivalent equi-join;CROSS JOIN(and aNATURALjoin with no common columns) is treated as a cartesian product.FULL JOINis still forwarded.- Typecasts on
WHERE-clause values —WHERE col = '2026-01-01'::dateand similar casts on literals are now parsed and usable both on the CDC fast path and for subsumption. (0.4.11 added typecasts in the select list.) - Parameters in the
SELECTlist — extended-protocol parameters in the target list (e.g.SELECT $1, col FROM t) are now handled. NULLS FIRST/NULLS LAST— explicit null ordering inORDER BYis now supported.
Performance
- Subsumption index covers non-equality predicates — the subsumption index now indexes inequalities and two-sided ranges, not just equality literals, so more cached queries serve narrower requests via the indexed path instead of a linear scan.
- Direct pg_query parse-tree reads — query analysis reads libpg_query’s parse tree directly instead of round-tripping through protobuf.
- Combined EXISTS evaluation — per-query EXISTS predicates are evaluated in a single
pg_evalquery rather than one query per predicate. - Lower CDC and forward-path overhead — CDC frame writes are buffered and flushed in a single round-trip; the
query_row_changesSELECT is skipped for relations a change cannot affect; metric handles are resolved once into a grouped struct, eliminating per-emit key hashing. - Extended-protocol Parse/Describe caching — synthesized Parse+Describe messages are cached and Parse is sent to the origin lazily, only when needed on the forward path. Handling of multiple Parse/Bind/Describe/Execute sequences before a Sync was improved.
LIMIT-aware materialization — materialized-view analysis now handlesLIMITqueries.
Reliability
- Transaction-aligned replication apply — pgcache now respects the BEGIN/COMMIT markers in the logical replication stream, applying each source transaction atomically.
- Deadlock recovery — CDC stream processing recovers from deadlock errors and the population worker retries on deadlock. Population batches are sorted by primary key to prevent
ON CONFLICTdeadlocks. - In-order client responses — an explicit ordering queue enforces the order of responses sent back to the client.
- Clean thread shutdown — the CDC and worker threads now exit when the writer thread exits.
Bug Fixes
LIMITinvalidation on window-column updates — updating a column that defines a window now invalidatesLIMIT-cached rows.- Scalar context for aggregate
FILTERsubqueries — subqueries inside aggregateFILTERclauses are correctly treated as scalar context.
Observability
- More precise
mv_fallthrough—pgcache.cache.mv_fallthroughnow reflects the actual materialized-view fast-path-vs-fallthrough decision, and join queries are routed through the measured MV get path. - New protocol metrics —
pgcache.protocol.describe_cache.{hits,misses,evictions,invalidations}andpgcache.protocol.lazy_parse_forwardedsurface the extended-protocol Parse/Describe cache and lazy-parse behavior.
Breaking Changes
- Removed the
pgcache.cache.freshness_hitscounter.
0.4.11 — 2026-05-14
Query Language Support
- Arithmetic constant folding —
WHERE x = 1 + 2now fingerprints identically toWHERE x = 3 - Modulo operator —
%is now supported in expressions. ::<type>typecast in select lists —SELECT col::int FROM tand similar typecast expressions in the target list are now parsed and cached.
Performance
- Subsumption index — replaces the previous O(N) per-relation scan with an indexed lookup keyed on column-set + equality literals.
- Forward-path latency — reduced the work done on the cache-miss / forward path.
- Incremental
active_relations— the publication-managed relation set is now maintained via refcounts on register/evict instead of being rebuilt by scanning the cached-query table. - Stale-entries cleanup off the Ready hot path — periodic Pending/Invalidated cleanup no longer runs inline with cache-Ready notifications.
Observability
- Per-stage forward and coalesce timings — new histograms
pgcache.query.stage.forward_decision_seconds,pgcache.query.stage.coalesce_intake_seconds, andpgcache.query.stage.coalesce_wait_secondssurface latency on the cache-miss and request-coalesce paths that priorlookup_secondsdid not capture. - Writer command instrumentation —
pgcache.cache.writer.command_handle_secondsreports per-command handler latency, labeled by command variant. - Query registration phase timings —
pgcache.cache.writer.register.{resolve,subsumption_check,subsume,insert,publication_update,populate_dispatch}_secondsandpgcache.cache.writer.resolve.{update_queries_register,deparse}_secondsbreak downquery_registerinto its constituent phases. - Population pipeline timings —
pgcache.cache.population.{task,stream,wait,worker_idle}_secondsmeasure per-task duration, streaming time, channel wait, and per-worker idle time. - Scaling signals —
pgcache.cache.writer.update_queries_totalandpgcache.cache.writer.update_queries_max_per_relationcorrelate per-Register cost against state size.
0.4.10 — 2026-05-08
Query Language Support
FILTERclause on aggregates —agg(...) FILTER (WHERE ...)is now parsed, resolved, and cached, including when used inside window function calls (agg(...) FILTER (WHERE ...) OVER (...)).- Additional binary parameter types — extended query protocol parameters in binary format are now decoded for
BYTEA,NUMERIC,DATE,TIME,TIMETZ,TIMESTAMP,TIMESTAMPTZ,INTERVAL,INET,CIDR,MACADDR, andMACADDR8.
Performance
- Subsumption across binary array parameters —
WHERE col = ANY($1)queries with binary array parameters now extractIN-set constraints and subsume each other (a cached... = ANY(ARRAY[1,2,3])serves a request for... = ANY(ARRAY[1,2])).
Bug Fixes
- WHERE-clause provenance in constraints — the constraint analyzer now distinguishes a query with no
WHEREclause from one whoseWHEREclause has terms the analyzer doesn’t support. - CDC invalidation walks
FILTER/ORDER BY/OVER— subquery node collection for invalidation now traverses aggregate-filter, aggregate-order, and window-OVER expressions. Previously, subqueries inside these clauses could miss invalidation.
Observability
- Applied LSN tracking —
/statusnow reportscdc.last_applied_lsn, the highest LSN whose effects (cache mutations and invalidations) have been fully applied by the writer thread. It advances on transaction-commit and keep-alive markers and is transaction-aligned. - New Prometheus gauges —
pgcache.cdc.received_lsn,pgcache.cdc.flushed_lsn, andpgcache.cdc.applied_lsn. - Improved diagnostic logs — CDC connection failures and database errors now log full error chains.
Breaking Changes
/statuscdcobject no longer includeslast_received_lsn,last_flushed_lsn, orlag_bytes. These remain available as Prometheus gauges (pgcache.cdc.received_lsn,pgcache.cdc.flushed_lsn,pgcache.cdc.lag_bytes).
Internals
- Refactored CDC LSN handling so applied LSN flows from the writer thread as its source of truth, decoupled from CDC-processor-local received/flushed LSNs.
numeric_to_textwrites into a single pre-sized buffer.LiteralValuecast fields useEcoString.query/transform/parameters.rssplit into focused submodules.- Integration tests now use LSN- and status-based settling instead of fixed sleeps.
0.4.9 — 2026-04-24
Features
- Materialized query results — for queries that reduce a large input to a small output (aggregates, window functions, GROUP BY, DISTINCT), pgcache now maintains a second tier of cache that stores the result rather than recomputing it from source rows. When stale, the serve path falls back to evaluating over source rows.
- Request coalescing — multiple concurrent requests for a query that’s currently loading now share a single backend execution. Subsequent requests wait for the in-flight load instead of triggering parallel populations.
Compatibility
- Pre-PG18
search_pathchange tracking — PostgreSQL 16 and 17 now support session-levelsearch_pathchanges. pgcache piggybacksSHOW search_pathonto detected mutations (SET/RESET search_path, DISCARD ALL, transaction boundaries) to track the current value. PG 18+ continues to use the nativeParameterStatusnotifications.
Configuration
- Default
admission_thresholdchanged from2to1— queries are now cached on first occurrence by default. - New
mv_size_ratiosetting (default10) — controls the materialization size gate for shape-eligible queries. Adjustable at runtime via the HTTP admin API.
Internals
- Local CDC update evaluation — simple update queries are now evaluated directly in Rust against cached rows for in-place updates, avoiding a round-trip to the cache database.
0.4.8 — 2026-04-10
Features
- Range-based predicate subsumption — subsumption now handles inequality and BETWEEN constraints. A cached
WHERE value > 50serves narrower queries likeWHERE value > 100,WHERE value BETWEEN 60 AND 80, orWHERE value = 100. - IN-set constraint support —
WHERE col IN (v1, v2, ...)is extracted as a first-class constraint used for subsumption (subset, point, and range checks) and CDC row filtering.NOT INis handled as individual inequality constraints. - Dynamic runtime configuration —
cache_size,cache_policy,admission_threshold,allowed_tables, andlog_levelcan be adjusted at runtime via new HTTP admin endpoints (GET /config,PUT /config,POST /config/reload). The TOML file remains the source of truth and is updated in place with comments preserved. - Anonymous telemetry — PgCache reports coarse usage statistics (version, OS, Postgres version, cache hit rate, approximate query volume) to help guide development. Telemetry is enabled by default and can be disabled with
PGCACHE_TELEMETRY=off,telemetry = falsein TOML, or--telemetry_offon the CLI. See Telemetry for details.
Internals
- Constraint propagation through join equivalences now handles IN-sets (e.g.,
a.id IN (1,2) AND a.id = b.idpropagates tob.id IN (1,2))
0.4.7 — 2026-03-27
Reliability
- CDC connection resilience — when the replication connection is lost, pgcache now preserves the cache and transparently forwards all queries to the origin database. On reconnect, it verifies the replication slot’s LSN hasn’t advanced past its last acknowledged position; if safe, cache dispatch resumes without a full restart. If the slot was dropped or the LSN diverged, pgcache performs a clean restart. Reconnection uses exponential backoff (500ms–30s).
Internals
- Improved LSN tracking in keep-alive handling — the CDC processor now advances its position to the logical decoder’s read cursor on keep-alive messages, enabling more accurate reconnect decisions
- Set TCP_NODELAY on sockets
0.4.6 — 2026-03-23
Features
- Per-query operational metrics — the
/statusendpoint now reports detailed metrics for each cached query:hit_count,miss_count,invalidation_count,eviction_count,readmission_count,subsumption_count,population_count,total_bytes_served,population_row_count, andcache_hit_latencyhistogram (p50/p95/p99/min/max/mean) - Duration tracking — per-query
idle_duration_ms(time since last hit),registered_duration_ms(time since first seen),cached_duration_ms(time since last population), andlast_population_duration_ms - Global cache status metrics —
/statuscache object now includesqueries_registered,uptime_ms,cache_hits, andcache_misses
Internals
- Updated for latest hotpath profiling API changes
- Updated and cleaned up dependencies
0.4.5 — 2026-03-16
Features
- Admin HTTP endpoints — the metrics HTTP server now also serves
/healthz(liveness),/readyz(readiness), and/status(JSON cache, CDC, and query status). - Database mismatch detection — when a client connects requesting a different database than the cache is configured for, pgcache logs a warning and proxyies all queries to origin for that connection.
Performance
- Pool sizing from num_workers — cache connection pool and population worker pool sizes now scale automatically based on
num_workers
Bug Fixes
- SELECT * column order — fixed
SELECT *returning columns in non-deterministic order from cache.
Observability
- New per-stage timing metrics:
pgcache.query.stage.queue_wait_seconds,pgcache.query.stage.conn_wait_seconds,pgcache.query.stage.spawn_wait_seconds— measure time waiting in worker queue, waiting for a cache database connection, and waiting for worker task spawn
Internals
- Replaced hand-rolled HTTP server with hyper
- Refactored
TableMetadatacolumn storage fromBiHashMaptoColumnStore(orderedVec+ name index) - Refactored test utilities into separate submodules (
context,assertions,http,metrics,process,pgproto) - Updated and cleaned up dependencies
0.4.4 — 2026-03-07
Reliability
- Graceful shutdown — SIGINT now triggers coordinated shutdown via cancellation tokens propagated to all threads. The publication and replication slot are removed during the shutdown.
Breaking Changes
- CLI argument
--cache_tablesrenamed to--allowed_tablesto match the TOML configuration field name
0.4.3 — 2026-03-06
Features
- Table allowlist — restrict caching to specific tables via
allowed_tablesconfiguration. Queries referencing non-allowlisted tables are forwarded to the origin. - Pinned queries — pre-populate and permanently cache specific queries at startup via
pinned_queriesconfiguration. Pinned queries are protected from eviction and automatically re-populated after CDC invalidation - Pinned tables — convenience configuration (
pinned_tables) that expands table names intoSELECT * FROM {table}pinned queries - Predicate subsumption — skip cache population when a new query’s data is already covered by existing cached results (e.g.,
SELECT * FROM users WHERE id = 1served immediately from a cachedSELECT * FROM users) - Config file support in Docker — mount a TOML config file into the container via
CONFIG_FILEenv var or--configCLI arg
Observability
- New
pgcache.queries.allowlist_skippedmetric counts queries rejected by the table allowlist - New
pgcache.cache.subsumptionsmetric counts queries served via predicate subsumption - New
pgcache.cache.subsumption_latency_secondshistogram tracks subsumption detection latency - CORS headers added to the metrics HTTP endpoint
Docker
- New environment variables:
CONFIG_FILE,ALLOWED_TABLES,PINNED_QUERIES,PINNED_TABLES - New CLI arguments:
--config,--allowed-tables,--pinned-queries,--pinned-tables UPSTREAM_URLis no longer required when a config file is provided
Internals
- Dynamic publication management reduces CDC bandwidth by only subscribing to tables with active cached queries
- EcoString used in table constraints for memory efficiency
0.4.2 — 2026-02-28
Bug Fixes
- Fixed TLS reads losing unconsumed ciphertext across poll calls
- Fixed TLS partial writes dropping data
Observability
- New
pgcache.cache.freshness_hitsmetric counts cached queries confirmed fresh (not invalidated) by each CDC event
0.4.1 — 2026-02-27
Security & Connectivity
ssl_mode = "require"now matches PostgreSQL semantics: encrypts the connection without verifying the server certificate, allowing connections to servers with self-signed or private CA certificates- New
ssl_mode = "verify-full"option: encrypts the connection and verifies the server certificate against trusted public CAs (the previous behavior ofrequire)
0.4.0 — 2026-02-27
Query Language Support
- Correlated scalar subqueries
- Correlated IN/ANY subqueries
- Correlated NOT IN/ALL subqueries
- IS TRUE, IS NOT TRUE, IS FALSE, IS NOT FALSE, IS UNKNOWN, IS NOT UNKNOWN expressions
- Locking clauses (
FOR UPDATE,FOR SHARE, etc.) are now properly forwarded to the origin as uncacheable
Performance
- More precise CDC invalidation for DELETE events on inner join tables
Internals
- Split
ast.rsandresolved.rsinto separate submodule files for maintainability - Refactored query dispatch, connection handling, query registration, and population streaming
- Replaced boxed
CacheableQuerywithArc-based sharing
0.3.8 — 2026-02-23
Query Language Support
- EXISTS and NOT EXISTS subqueries
Bug Fixes
- Fixed count(*) handling in cached function expressions
Internals
- Refactored update query generation to work exclusively with the resolved AST
- Reorganized transform and query update logic into a clearer file layout
- Replaced
expect()calls with proper error handling - Grouped related fields in
ConnectionStatefor better organization
0.3.7 — 2026-02-22
Query Language Support
- Predicate pushdown for subqueries and CTEs
- Mixed wildcards and explicit columns in SELECT lists (
SELECT *, id, name FROM ...)
Internals
- Overhauled extended query protocol handling for improved Parse/Bind/Describe/Execute support
0.3.6 — 2026-02-18
Query Language Support
- Immutable function calls in WHERE and JOIN clauses (
WHERE lower(name) = 'foo') — function volatility loaded frompg_procat startup
Performance
- Cache admission policy — queries must be seen multiple times before being cached (configurable via
admission_threshold, default 2) - CLOCK eviction — second-chance algorithm replaces FIFO (configurable via
cache_policy) - Fast readmission of CDC-invalidated queries — metadata retained so re-seen queries skip the admission threshold
Observability
- New metrics:
pgcache.cache.queries_pending,pgcache.cache.queries_invalidated,pgcache.cache.readmissions - Improved error reporting when the metrics server fails to start
0.3.5 — 2026-02-16
Query Language Support
- LIMIT and OFFSET clause caching — queries differing only in LIMIT/OFFSET share a cache entry, with automatic re-population when a larger limit is requested
- BETWEEN, NOT BETWEEN, BETWEEN SYMMETRIC, and NOT BETWEEN SYMMETRIC expressions
- ANY and ALL expressions (
= ANY(ARRAY[...]),op ALL(...)) with array literals and parameters - LIKE, NOT LIKE, ILIKE, and NOT ILIKE pattern matching expressions
Performance
- Inequality constraint checking for CDC invalidation — UPDATE and DELETE events on joined tables are filtered using
<,<=,>,>=, and!=constraints, reducing unnecessary cache invalidation - CDC worker sends commands directly to the writer thread, eliminating an intermediate message hop through the runtime event loop
Bug Fixes
- NULL values in CDC update queries now carry type casts (
NULL::typename) for correct PostgreSQL type inference in VALUES clauses
0.3.4 — 2026-02-12
Query Language Support
- LEFT JOIN and RIGHT JOIN queries with equality join conditions
Performance
- Streaming cache population (rows streamed directly instead of buffered)
- Multi-value upserts for cache population (batched inserts instead of one per row)
Bug Fixes
- Fixed cache table not populated properly for self-joins
- Fixed parentheses missing when deparsing logical expressions
- Preserved error context when bubbling errors up
Internals
- Local connection handling for cache worker
- Refactored integration tests to use more precise cache hit/miss detection
0.3.3 — 2026-02-09
Query Language Support
- Uncorrelated subqueries in
SELECT,FROM(derived tables), andWHERE(IN,NOT IN, scalar) - Nested subqueries (multi-level)
- Non-recursive CTEs (
WITH ... AS), includingMATERIALIZED/NOT MATERIALIZED - CDC invalidation for subqueries and CTEs with directional semantics (inclusion vs exclusion vs scalar)
Observability
- Queue depth metrics for all unbounded channels
- Wait time metrics in worker for incoming work and database connection waits
Internals
- Subquery nesting depth factors into query complexity scoring
- Cache population ordering ensures inner/simpler queries are populated before outer queries that depend on them
- Moved constraint handling from cached query into update queries
- Improved LSN confirmation handling
- Respect column ordering when registering a table
0.3.2 — 2026-02-05
Query Language Support
- Set operations (UNION, INTERSECT, EXCEPT) in select statements
Internals
- Refactored CacheQuery to use QueryExpr and ResolvedQueryExpr for set operation support
0.3.1 — 2026-02-04
Query Language Support
- Arithmetic expressions
- ORDER BY in aggregate functions
- IS [NOT] NULL expressions
- IN expressions
- Window functions
- CASE expressions
- Functions in select target list
- Subqueries in select statements
- GROUP BY, HAVING, and LIMIT clauses
Performance
- Split writer command queue into separate queues for query registrations and CDC handling
- Refactored query registration to avoid blocking writer processing
- Concurrent processing of queries when handling INSERT and UPDATE CDC messages
- Multi-table join support with optimized invalidation
2026-01-30
Observability
- Prometheus metrics endpoint
- Metrics for writer receive queue sizes
- CDC operation metrics
- Query processing timing instrumentation
Performance
- Cache database connection pool for worker threads
- Pre-computed join column equivalences for invalidation (replaces AST traversal)
- More precise invalidation for joins (skips when UPDATE doesn’t modify join columns or query constraints)
Reliability
- Refined behavior during cache failures
2026-01-24
Features
- Separate replication connection settings
- Domain and enum type support in query registration
- Log level configuration setting
- Partitioned table support
- Duplicate query registration prevention
Performance
- Fixed pool of tasks for query registration
- Generation tracking bundled with simple query
Error Handling
- Switched to
rootcausecrate for location-tracking error reports attach_loc()context throughout codebase
2026-01-12
Security & Connectivity
- TLS support for client and origin connections
- Origin database password support
- Automatic replication slot and publication creation on startup
Bug Fixes
- Fixed TLS session ticket handling causing connection hangs
- Fixed
select!panic on stream closure - PostgreSQL identifier quoting where necessary
- Stripped SCRAM-SHA-256-PLUS from SASL options (unsupported)
2026-01-03
Cache Management
- Cache size limit enforcement
- Clean cache database on start/restart
- Generation-based cache purging with row removal
- Generation tracking for inserts and updates
- Unlogged cache tables for performance
- Initial cache size tracking
Reliability
- Cache thread restart on failure detection
- Proper CDC/cache thread failure detection
2025-12-20
Schema Support
- Full search path support
- Explicit schema qualification for all cache tables
- Schema-aware table metadata lookup
- Resolved AST with aliases and deparse
2025-12-04
Protocol Support
- Binary parameters in extended query protocol
- Correct column types returned from cache
Code Quality
- Refactored integration tests
- Split proxy.rs into modules
2025-11-12
Observability
- Initial metrics implementation
Bug Fixes
- Switched to sequential CDC event handling
- Fixed CDC insert message handling
2025-10-17
Protocol Support
- Extended query protocol support
- Order By in queries
- Parameter references in queries
Performance
- Optimized cache query handling
- DataRow message grouping
- SIGINT handling with graceful shutdown
Query Analysis
- Constraint propagation for cache invalidation
- Multiple join support
2025-09-30
Query Support
- Chained AND/OR expressions
- Table aliases
- VALUES clause
- Subqueries (select target list and table position)
Internals
- Generic
nodes()iterator for AST traversal - Reworked CDC message support for joins
2025-08-08 — Initial Release
Core Architecture
- Transparent PostgreSQL caching proxy
- Simple query protocol support
- Worker thread architecture for cache handling
- MD5 and SCRAM authentication passthrough
Query Support
- Query cacheability analysis
- Initial join support
- Comparison operators
- Custom AST with fingerprinting and deparse
Cache Invalidation
- CDC-based invalidation via logical replication
- TRUNCATE message handling
- Relation message handling (invalidates on schema change)
Configuration
- TOML configuration file support
- Transaction handling (queries bypass cache during transactions)