tl;dr

  • The cache server is the easy part of caching Postgres. The hard part is knowing when a cached result stops being true, and what happens when a popular entry misses. TTLs are enough for many reads, and when freshness matters, invalidation driven by Postgres’s logical replication is the most reliable option.
  • Memcached is the simplest key-value cache, and Redis (or Valkey, its BSD-licensed fork) adds data structures and persistence. For query results, both leave invalidation to your application code, and if you use row-level security, the tenant has to be part of every key.
  • Postgres can be its own cache. An UNLOGGED table with an expiry column needs no new infrastructure, but cache reads still land on the database.
  • A proxy cache (pgpool-II, Readyset, PgCache) sits between your app and Postgres, so there’s no cache code in the app. Some proxies, like PgCache, also read the replication stream to handle invalidation for you. The tradeoffs include another network hop and less control over what gets cached.
  • Not sure you need a cache at all? Our Fit Analyzer reads a pg_stat_statements export in your browser and shows which queries are worth caching.

A lot of our recent conversations have started the same way. Someone’s Postgres database is spending its day answering the same reads over and over, and they’re trying to decide how to cache them: Redis, Memcached, a table in Postgres, or something they build themselves.

This guide is meant for people facing that decision. It assumes you already know that repeated reads are your problem. If you’re not sure yet, our guide to PostgreSQL caching covers what Postgres already caches and how to figure out which problem you actually have.

Here the goal is to compare the options, with special attention to long-term tradeoffs that you might not think of when you’re solutioning for read optimization:

  1. deciding what to cache, and who’s allowed to see it,
  2. keeping cached results true when the data (or the schema) changes,
  3. surviving a burst of misses, and
  4. letting people see their own writes.

In case it’s not obvious, my company builds one of the options in this guide (a proxy cache). Our solution is not for everyone, and for a lot of teams Redis or a table in Postgres is the right answer. I do my best to provide a balanced view.

First, decide what you’re caching

Before you choose a cache, decide what goes in it. This determines how hard invalidation will be.

Query results are the rows a specific SELECT returned, keyed by the query and its parameters. When one of the underlying rows changes, the cached result is wrong. You know exactly which tables a query reads, which makes query results the easiest thing to invalidate.

Objects are things like a user profile, a product page model, or a set of permissions, assembled from several queries and maybe some application logic. The key is usually an ID (user:500). A change to any table that fed the object makes it stale.

Rendered output is an HTML fragment or a JSON response. It’s the cheapest thing to serve from cache and the hardest to keep correct, because one response can depend on dozens of rows across many tables.

The further a cached value is from the database, the more rows it depends on, and the harder it is to know when it went stale. Most teams caching Postgres reads end up with a mix: query results for hot lookups, and objects for the things the app assembles on every request.

Tenants, roles and row-level security

If your app serves more than one customer from the same tables, there’s one more thing to decide before you pick a cache: who’s allowed to see a cached result.

Postgres enforces permissions when a query runs. Grants decide which tables and columns a role can read, and row-level security (RLS) policies decide which rows, often by reading the current role or a setting the app sets for each request, like app.tenant_id. A cache hit doesn’t run the query, so none of that applies to it unless the cache does the checking itself.

For an application-side cache, this means the tenant (and the role, if it matters) has to be part of every key: tenant:42:product:7, not product:7. If the tenant information is missed anywhere in the cache, one customer’s cached rows might get served to another. The same goes for a cache table inside Postgres, because the policies on products don’t carry over to a JSON copy of a product sitting in query_cache.

Proxy caches each handle this differently, so check before you put one in front of a multi-tenant database.

1. Redis or Valkey with cache-aside

How it works

Redis is the default answer, and for good reason. It’s fast, every language has a client for it, and a lot of teams already run one. The usual pattern is called cache-aside (or lazy loading): the application checks the cache, and on a miss it queries Postgres and stores the result.

import json
import psycopg
import redis
from psycopg.rows import dict_row

r = redis.Redis()
conn = psycopg.connect(DATABASE_URL, autocommit=True, row_factory=dict_row)

def get_product(product_id):
    key = f"product:{product_id}"
    cached = r.get(key)
    if cached is not None:
        return json.loads(cached)

    product = conn.execute(
        "SELECT id, name, price_cents FROM products WHERE id = %s",
        (product_id,),
    ).fetchone()

    # cache misses too ("null"), so a missing id doesn't hit Postgres every time
    r.set(key, json.dumps(product), ex=300)
    return product

Rails (Rails.cache.fetch), Django (cache.get_or_set) and Laravel (Cache::remember) all wrap this same pattern with a TTL.

Invalidation

The TTL caps how stale an entry can get. If five minutes of staleness is fine for a given read, you can stop here, and plenty of teams do.

If it isn’t fine, you need to delete the key whenever the row changes. Deleting is safer than updating the cached value, because an update built from a stale read can write a wrong value into the cache, while a delete just sends the next read back to Postgres.

The delete has to happen after the transaction commits:

def update_price(product_id, price_cents):
    with conn.transaction():
        conn.execute(
            "UPDATE products SET price_cents = %s WHERE id = %s",
            (price_cents, product_id),
        )
    # the transaction has committed here, so it's safe to delete
    r.delete(f"product:{product_id}")

If you delete before the commit, another request can slip in, read the old row from Postgres (the new one isn’t visible yet), and put it right back in the cache. Most frameworks give you a hook for this: Django has transaction.on_commit(), and Rails has after_commit.

Even with the delete after the commit, there’s a well-known race:

  1. Request A misses the cache and reads the product from Postgres. It sees a price of $10.
  2. Request B updates the price to $12, commits, and deletes the key.
  3. Request A, which was slow, writes $10 into the cache.

The cache now says $10 until the TTL runs out. Facebook described this exact problem (they called it a “stale set”) in their 2013 paper on scaling memcache. Their fix was leases: on a miss, the cache gives the reader a token, a delete cancels outstanding tokens, and a write with a cancelled token is rejected.

Redis doesn’t do that for you, but a couple of patterns get close. One is to set a short TTL as a backstop, so a stale set can’t last long. A more involved approach is to use versioned keys: keep a version counter per product, increment it after every committed write, and put it in the cache key (product:42:v8). A slow reader that started on version 7 writes to a key that is no longer requested. The cost is an extra round trip to read the version.

The biggest headache with invalidation is that every code path that writes to a table has to remember to delete the affected entries. Depending on your setup that can include an admin panel, background jobs, migrations, bulk imports, additional services that share the database, and whoever opens psql to fix a row by hand. If you forget one of those as you configure the cache, it will serve stale data until the TTL saves you. It gets harder for derived keys, like the cached list of products in a category or a user’s order count, which also go stale when one product or one order changes.

Running Redis or Valkey

  • Memory and eviction. Self-hosted Redis has no memory limit and no eviction by default (maxmemory 0, maxmemory-policy noeviction). For a cache, set a maxmemory and an eviction policy like allkeys-lru, or it grows until the machine runs out of memory.
  • It’s another service. Monitoring, patching, failover and capacity planning all come with it. A managed service takes care of most of that, for a price.
  • Cold starts. After a restart, or a failover to an empty node, every request misses at once (see stampedes below).
  • The license. Redis moved from BSD to a source-available license (RSALv2/SSPLv1) in March 2024. The Linux Foundation forked the last BSD release as Valkey, and Redis 8 added AGPLv3 as an option in May 2025. For a cache behind your app this rarely matters, but it’s why the managed services now offer Valkey alongside Redis.

When Redis is the right call

  • If you already run Redis for sessions, rate limits, queues or counters, then a cache comes with minimal added operational burden.
  • You have a small number of hot keys, and writes to those tables go through one or two code paths you control.
  • Most of what you cache can be a few minutes stale.
  • You want to cache things that aren’t query results, like rendered fragments or API responses.

For how each one compares with PgCache, see PgCache vs Redis, PgCache vs Valkey and PgCache vs Amazon ElastiCache.

2. Memcached

Memcached does one thing, which is hold keys and values in memory. It’s multithreaded, with no persistence, no replication and no data types beyond strings (values up to 1MB by default). Clients spread keys across servers with consistent hashing, and when memory fills up, Memcached evicts the least recently used items. It’s a short feature list, which is appealing for a lot of teams.

For caching Postgres query results, Memcached and Redis behave almost the same. Cache-aside looks identical and invalidation is the biggest problem (the stale-set race described above was first documented on Memcached). The difference is that Redis does lots of other things, too. If you want those extras, use Redis. If you want the simplest thing that can hold a lot of cached results across many cores, Memcached is very good at that, and the big clouds run it for you (ElastiCache on AWS, Memorystore on Google Cloud).

3. Postgres as its own cache

A cache table

You can also cache inside Postgres itself, with a plain table, like this:

CREATE UNLOGGED TABLE query_cache (
    key        text PRIMARY KEY,
    value      jsonb NOT NULL,
    expires_at timestamptz NOT NULL
);

-- read
SELECT value FROM query_cache
WHERE key = $1 AND expires_at > now();

-- write or refresh
INSERT INTO query_cache (key, value, expires_at)
VALUES ($1, $2, now() + interval '5 minutes')
ON CONFLICT (key) DO UPDATE
SET value = EXCLUDED.value, expires_at = EXCLUDED.expires_at;

-- clean up expired rows every minute (with pg_cron)
SELECT cron.schedule('query-cache-cleanup', '* * * * *',
  $$DELETE FROM query_cache WHERE expires_at < now()$$);

UNLOGGED skips the write-ahead log, which makes writes much cheaper. The price is that an unlogged table is truncated after a crash or an unclean shutdown, and it isn’t replicated to standbys. For a cache, both are usually fine.

The big advantage is that the cache lives next to your data, so a trigger can clear cache rows in the same transaction as the write that made them stale:

CREATE FUNCTION invalidate_product_cache() RETURNS trigger AS $$
BEGIN
  DELETE FROM query_cache
  WHERE key = 'product:' || COALESCE(NEW.id, OLD.id);
  RETURN NULL;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER products_cache_invalidate
AFTER INSERT OR UPDATE OR DELETE ON products
FOR EACH ROW EXECUTE FUNCTION invalidate_product_cache();

Including INSERT matters if you cache misses, the way the Redis example does: a new row clears the cached “not found” for its id.

This approach avoids the complexity inherent in cache-aside patterns, because the database enforces the invalidation instead of the application. Writes from the admin tool, the migration, and the person in psql all clear the cache by default.

It isn’t a perfect fix. The stale-set race from the Redis section can still happen: a reader that started before the write committed can insert the old value after the trigger has already run. So you might want to keep the expiry column as a backstop.

The catch

Cache reads still run on Postgres, and each one is a round trip, a parse, a plan and an index lookup. That’s a great trade when the cached query is expensive (a reporting aggregate, a five-table join) and the cache lookup is cheap.

But it’s less helpful if the problem you’re trying to solve is a flood of cheap queries that run millions of times a day. Swapping one cheap query for another cheap query doesn’t take any load off the database.

A cache table that’s rewritten constantly also produces a lot of dead rows, so autovacuum has to keep up with it.

Materialized views

For expensive aggregates where some lag is fine, a materialized view is the same idea with less code: precompute the result, index it, and run REFRESH MATERIALIZED VIEW CONCURRENTLY on a schedule (which needs a unique index on the view). Core Postgres recomputes the whole view on every refresh, and the pg_ivm extension can maintain some views incrementally. Our caching guide goes into more detail.

4. Building invalidation from Postgres

If you want Redis-speed reads but don’t trust every code path to remember its deletes, you can have Postgres tell your cache what changed. There are two common ways to do that.

Triggers and LISTEN/NOTIFY

A trigger sends a notification on every change, and a small listener process deletes the matching keys in Redis:

CREATE FUNCTION notify_product_change() RETURNS trigger AS $$
BEGIN
  PERFORM pg_notify('cache_invalidate',
                    'product:' || COALESCE(NEW.id, OLD.id));
  RETURN NULL;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER products_notify
AFTER INSERT OR UPDATE OR DELETE ON products
FOR EACH ROW EXECUTE FUNCTION notify_product_change();
listener = psycopg.connect(DATABASE_URL, autocommit=True)
listener.execute("LISTEN cache_invalidate")
for note in listener.notifies():
    r.delete(note.payload)

This is appealing because it’s all built into Postgres, and notifications are only delivered when the transaction commits. A few things to know before you rely on it:

  • Nothing is replayed. If the listener is disconnected, the notifications sent in the meantime are gone. You need a fallback, like a TTL, or flushing the affected keys when the listener reconnects.
  • The listener needs its own session. LISTEN doesn’t survive PgBouncer’s transaction pooling, so connect the listener directly or through a session-mode pool.
  • Payloads are small. The default limit is just under 8,000 bytes, so send keys, not data.
  • Heavy write traffic can feel it. A transaction that issued NOTIFY takes a database-wide lock at commit to keep notifications in order. Recall.ai wrote up the outages this caused them under heavy concurrent writes. Their post now points to a change in Postgres core, committed in January 2026, that they credit with removing the bottleneck. That change landed in PostgreSQL 19 (released November 2026), so if you’re still on 18 or earlier, it’s worth a load test before you depend on it.

Change data capture

The heavier and sturdier version of Postgres-driven cache invalidation involves reading the logical replication stream, which is the same ordered feed of row changes that Postgres uses for logical replicas. A typical setup is to use Debezium to read the stream into Kafka, plus a consumer that deletes or updates cache keys. Facebook built the MySQL version of this at enormous scale: a daemon called mcsqueal reads the database’s commit log and broadcasts deletes to their memcache servers.

The upside is that nothing gets lost. A replication slot holds changes until the consumer confirms them, so a consumer that restarts picks up where it left off, and every write is caught no matter which code path made it.

The downsides are real, though. With several new moving parts, you still have to map row changes to cache keys yourself (including the derived ones), and a stuck consumer means the slot just holds on to WAL on your primary … until someone notices (set max_slot_wal_keep_size so that a stuck slot can’t fill the disk!). Another gotcha is that the logical replication stream doesn’t carry schema changes, which can be significant, especially on the day you run a migration (more on that below).

5. A cache in front of Postgres: proxies

The last option moves the cache out of your application entirely. A proxy speaks the Postgres wire protocol, so the app connects to it as if it were the database. Cacheable reads come back from the cache, and everything else passes through to origin. There’s no cache-aside code and no keys to manage.

The tradeoffs are that you can only cache SQL results (no rendered fragments or computed objects), you add a network hop, and you rely on the proxy to know which queries are safe to cache.

A caching proxy isn’t a connection pooler, but it can run alongside one if you already have it: see our explainers about PgCache and PgBouncer and PgCache and PgDog.

A few common caching proxies include:

pgpool-II

pgpool-II’s query cache stores SELECT results in shared memory or in memcached. Invalidation takes place at the table level: a single UPDATE to one row drops every cached result that touches that table. Writes that don’t go through pgpool are invisible to it, so you lean on a TTL for those. It’s simple, and it works well for read-mostly tables.

Readyset

Readyset works with both Postgres and MySQL and has two kinds of cache. Shallow caches, the default kind, keep results in memory and refresh them on a timer (10 seconds by default), and Readyset’s automatic caching mode creates them. Deep caches, which you create with CREATE DEEP CACHE, copy the tables they replicate and then update each cached result incrementally as changes arrive through the replication stream. For both shallow and deep caches, anything that isn’t cached is proxied to the database. We compare Readyset with our own product in more detail here: PgCache vs Readyset.

PgCache

PgCache is ours. It’s a drop-in proxy, so there’s nothing to declare: it decides from live traffic which queries are cacheable, caches them as they’re used, and stores the data for those queries in its own Postgres instance. PgCache subscribes to the logical replication stream and updates cached rows in place when it can, or invalidates them when it can’t, within typical logical replication lag. If several requests miss on the same query at once, PgCache runs it once against origin and shares the result.

Recent releases cover several of the things that usually rule a cache out:

  • Transactions and your own writes (0.7.0). Cached reads are served inside READ COMMITTED transactions (Postgres’s default isolation level), and each connection reads its own writes (more on that below).
  • Migrations (0.8.0). Event triggers on origin report each schema change inside its own transaction, so an ALTER TABLE or a DROP TABLE evicts the affected results at the right point in the stream. PgCache installs them at startup when it connects as a superuser or as your managed database’s admin user (the master user on RDS and Aurora, postgres on Supabase).
  • Multi-tenant apps (0.9.0 and 0.9.1). Tables with row-level security are cached by inlining the policies that apply to the reading role. If your policies read the current role, a setting like app.tenant_id, or a JWT claim the way Supabase does with auth.uid(), each tenant, role and user gets its own cache entry, with no tenant-aware keys to write.
  • Permissions (0.9.0). Every cache hit is checked against what the reading role is allowed to read on origin: tables, columns, schemas and functions.

PgCache is source-available under the Elastic License v2. We’re working with a limited number of design partners to prove it in production, so if that sounds like you, give us a shout!

A few limits to know before you try it:

  • It needs Postgres 16 or newer, with wal_level = logical.
  • Reads inside REPEATABLE READ or SERIALIZABLE transactions are forwarded to origin, because a cache can’t reproduce a pinned snapshot.
  • Some queries pass through uncached: views, FOR UPDATE, FULL JOIN, LATERAL, recursive CTEs, functions like now() in a WHERE clause, and tables with extension-type columns (pgvector’s vector, PostGIS geometry). Tables need a primary key. The compatibility page has the full list.
  • Like every cache fed by replication, PgCache is eventually consistent across connections.
  • The cache starts empty after a restart, unless you pin tables and queries so they’re loaded at startup.

Some common caching woes and how to avoid them

Stampedes

A cache stampede happens when a popular entry disappears all at once. A TTL expires, a node restarts, or someone flushes the cache, and thousands of requests miss at the same moment and run the same query against Postgres. The database slows down, requests time out, clients retry, and the retries make it worse.

OpenAI’s write-up on scaling Postgres for ChatGPT (January 2026) describes this loop, with a caching layer serving most reads in front of one primary and nearly 50 read replicas. Their fix: when many requests miss the same key, one of them takes a lock and fetches from Postgres, and the rest wait for the cache to be refilled.

Here are the usual defenses against stampedes, roughly from cheapest to most involved:

  • Jitter your TTLs, so entries written together don’t expire together.
  • Coalesce requests inside each app process, so only one miss per key goes to the database. Go’s singleflight package is the classic example.
  • Lock or lease per key across processes, the way OpenAI and Facebook do. A Redis SET lock:key 1 NX EX 10 makes a serviceable lock.
  • Refresh early. The XFetch approach from this 2015 VLDB paper has each request recompute with a small probability that rises as the TTL approaches, so one request usually refreshes the entry before it expires. Most appealing for D&D fans.
  • Serve stale while you revalidate. Keep the old value a little past its expiry, return it, and refresh it in the background.

Caches fed by the replication stream don’t use TTLs, so they don’t get synchronized expiries. They still miss after a restart, an eviction, or the invalidation of a hot result, which is why coalescing matters there too.

PgCache handles this risk in a few ways. It updates cached rows in place from the replication stream when it can, so a write often refreshes a hot entry instead of emptying it. When a popular query does miss, the first request goes to origin while PgCache loads the result once, and requests that arrive in the meantime wait for that one load instead of each going to origin (if a load runs long, they’re sent on to origin rather than held up). And for tables and queries you know will be hot, you can pin them, so they’re loaded at startup and reloaded right after an invalidation.

Read-your-own-writes

This is the bug that comes with every cache sooner or later: a user changes their name, the page reloads, and the old name comes back. The write went to Postgres, but the read came from a cache (or a replica) that hadn’t caught up yet.

Common fixes:

  • Read from the primary after a write. Pin a user’s reads to Postgres for a few seconds after they write anything. It’s simple and blunt.
  • Write-through. Put the new value in the cache in the same request. It’s fast, but you still run the risk of the races mentioned earlier (and it only covers the keys you remember to update).
  • Wait for the replication position. With replicas, record the WAL position after the write (pg_current_wal_lsn() on the primary), and then read from a replica only after pg_last_wal_replay_lsn() has passed it. If every read has to be fresh, synchronous replication with synchronous_commit = remote_apply makes each commit wait for the replica to apply it, at the cost of slower commits.
  • Track pending writes in the proxy. This is what PgCache does. Each connection records the writes it forwards, and until those writes arrive over the replication stream, a read on that connection is served from cache only if PgCache can prove it doesn’t overlap them. If the proxy can’t be sure, the query goes to origin.

Schema changes and migrations

Caches have to survive your migrations. A cached object built before an ALTER TABLE can have the old shape: a renamed column, a missing field, a value computed the old way.

A common fix with cache-aside is to put a version in every key prefix (v12:product:7) and bump it on deploys that change what’s cached. Flushing the cache on deploy works too, but it turns every deploy into a cold start (which can lead to stampedes).

Invalidation built on the replication stream has a gap here, because logical replication carries row changes, not DDL. A pipeline that only reads the stream doesn’t hear about an ALTER TABLE or a DROP TABLE when it happens. We wrote about how schema information does show up in the stream, just later than you’d think, and what that means for anything built on it.

PgCache fills this gap with the event triggers that I described above. The triggers put each schema change into the stream inside its own transaction.

How to choose your read cache

If this sounds like youStart with
A few hot keys, writes to them go through code you control, a few minutes of staleness is fineRedis or Valkey, cache-aside with a TTL
You only need a big, simple key-value cache across many coresMemcached
A handful of expensive queries, CPU headroom on Postgres, no appetite for new infrastructureAn UNLOGGED cache table, or a materialized view
You want Redis speed, but writes come from many places (jobs, admin tools, other services)Redis, with invalidation driven by Postgres (triggers or CDC)
Lots of distinct hot queries, and nobody wants to own invalidation codeA proxy cache: PgCache, Readyset, or pgpool-II for read-mostly tables
A multi-tenant app with RLS policies on the current role, a setting like app.tenant_id, or a JWT claim (as on Supabase)PgCache, which applies the policies on every hit
You need more read capacity for every kind of query, and a little replication lag is fineA read replica
Writes are the bottleneckNone of these. Caching doesn’t help writes

For side-by-sides of PgCache with read replicas, Redis, Valkey, ElastiCache, Readyset, PgBouncer and PgDog, see How PgCache compares.

A few questions to answer before you pick:

  • How stale can each read be? Answer per endpoint, not for the whole app. A product description can be a few minutes old, and an account balance can’t.
  • How many code paths write to the tables you want to cache? Count the jobs, admin tools, migrations and other services, not just the main app.
  • Are your hot reads a few expensive queries, or many cheap ones? Sort pg_stat_statements by total_exec_time and by calls, and for the top statements compare shared_blks_hit with shared_blks_read. Mostly reads points to memory or an index first. Mostly hits and still expensive (or cheap but called constantly) is where caching pays off.
  • Does anything decide who sees which rows? If you use RLS or per-role grants, check how the cache handles them before anything else.
  • Who gets paged when the cache misbehaves?

When not to cache

If you can avoid adding a cache, you should. Rule out the cheaper fixes: a missing index, a bad plan (EXPLAIN (ANALYZE, BUFFERS) will show it), an N+1 query hiding in the ORM, a connection pool that’s the wrong size, or simply a bigger instance.

A cache adds a moving part and new risks to your stack, so make sure the tradeoffs are worth it.

Common questions

Should I use Redis or Memcached to cache Postgres queries?

Either works for caching query results, and the hard parts are the same in both (invalidation, stampedes, read-your-own-writes). Memcached is a simple, multithreaded key-value cache. Redis, or its BSD-licensed fork Valkey, adds data structures, persistence and replication, which helps if you also need sessions, counters, rate limits or queues.

Can Postgres be its own read cache?

Yes. An UNLOGGED table with a key, a value and an expiry column works as a cache with no new infrastructure, and a trigger can clear cache rows in the same transaction as the write that made them stale. Cache reads still run on Postgres, so it helps with expensive queries, not with a flood of cheap ones.

How do I invalidate a Redis cache when Postgres data changes?

Delete the affected keys after the write commits, keep a TTL as a backstop, and watch for the race where a slow reader writes an old value back into the cache. For writes that bypass your application code, drive invalidation from the database: triggers with LISTEN/NOTIFY, or a CDC pipeline that reads the logical replication stream.

Does caching work with row-level security?

An application-side cache doesn’t see your RLS policies, so the tenant (and the role, if it matters) has to be part of every cache key. Proxy caches differ in how well they handle this. PgCache, since version 0.9.0, caches RLS tables by inlining the policies that apply to the reading role, so each tenant and role gets its own entry. Since 0.9.1 that includes policies built on JWT claims, the way Supabase does it with auth.uid().

What is a cache stampede?

When a popular cache entry expires or is evicted, many concurrent requests miss at the same moment and all run the same query against Postgres. Commonly used defenses against cache stampedes include jittered TTLs, request coalescing, per-key locks or leases, early probabilistic refresh, and simply serving stale data while one request refreshes.

Where PgCache fits

Our conviction is that most teams shouldn’t have to write cache invalidation code at all. Postgres already knows exactly when data changes, and since Postgres 10 and the release of logical replication, that information is available to anyone who subscribes to the stream. James built PgCache on that idea.

PgCache exists so that caching Postgres reads can be as easy as changing a connection string. Our philosophy of doing the hard part for you is why PgCache also applies RLS policies and grants, instead of asking you to rebuild them in cache keys.

If you only have 5 minutes, the easiest way to see whether PgCache would help your workload is to use our in-browser Fit Analyzer tool. Drop in a pg_stat_statements export and it shows what can be cached, in terms of queries and database time (it runs locally as WebAssembly, so nothing leaves your machine). If you’d rather run it yourself, you can try it in one command against a local Postgres.

This guide comes out of a lot of conversations with developers, DBAs and SREs who were making exactly this decision. If you have questions, or think I got something wrong, please write me at [email protected].