# Database caching with PostgreSQL (https://layerscache.com/docs/learn/database-caching-postgres)

> Database caching for PostgreSQL: what Postgres already caches, why apps still cache query results, and how to do it in Node.js with pg, Prisma and Redis.



**Database caching** means keeping the result of a database read in a faster place, usually memory or Redis, so the next identical read does not reach the database. PostgreSQL has no query result cache of its own, so apps add one in front of it to cut latency, save database CPU, and keep connection pool slots free.

**Level:** one to ten · &#x2A;*You need:** [What is caching?](/docs/learn/what-is-caching) and [The cache-aside pattern](/docs/learn/cache-aside-pattern)

```mermaid
flowchart LR
  R["Request"] --> C{"Cache"}
  C -->|"hit"| H["Return the copy"]
  C -->|"miss"| P["Pool<br/>borrow a connection"]
  P --> D[("PostgreSQL")]
  D --> S["Store with a TTL"]
  S --> H
```

On a hit the request never touches the pool. On a miss it borrows one connection, runs the query, and leaves a copy behind for the next reader.

## What does PostgreSQL cache by itself? [#what-does-postgresql-cache-by-itself]

PostgreSQL caches data, not answers. Table and index pages are stored in `shared_buffers`, a block of shared memory that is 128 MB by default. A page is 8 kB. When a query needs a page that is already in `shared_buffers`, PostgreSQL skips the disk read.

Behind that sits the operating system page cache, which keeps recently read files in free RAM. A page that falls out of `shared_buffers` often still sits there, so the read is cheap but not free.

Two things are not cached:

* **Query results.** If you run `select name from users where id = 42` twice, PostgreSQL runs it twice. The second run is fast because the pages are in memory, but it still plans the query, walks the index, and builds the row.
* **Prepared statements cache plans, not rows.** A prepared statement saves the parse and plan work, not the execution.

You can see how well the page cache works with a hit ratio from `pg_statio_user_tables`.

```sql
select sum(heap_blks_hit)::float / nullif(sum(heap_blks_hit) + sum(heap_blks_read), 0) as hit_ratio
from pg_statio_user_tables;
```

A ratio near 1.0 means almost every page read came from memory. That is good, and it still costs a network round trip and a query execution per request.

### Can PostgreSQL keep a table in memory? [#can-postgresql-keep-a-table-in-memory]

Not directly, but a table that fits in `shared_buffers` or the OS cache stays there while it is read often. The `pg_prewarm` extension can load a table into the buffer cache after a restart. This helps the database read pages faster. It does not remove the query, so it is not a replacement for caching results.

## Why cache query results in front of PostgreSQL? [#why-cache-query-results-in-front-of-postgresql]

Three costs remain even when every page is in memory.

| Cost        | What happens                                                                                                                                                | What a cache hit does                                          |
| ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------- |
| Latency     | A query costs a network round trip (about 0.5 ms inside a datacenter, per "Latency numbers every programmer should know") plus parse, plan and execute time | A memory hit takes nanoseconds, a Redis hit one round trip     |
| CPU         | The database repeats the same plan and index walk for every identical read                                                                                  | The database sees one query per TTL instead of one per request |
| Connections | Every query holds one pooled connection while it runs                                                                                                       | A hit never borrows a connection                               |

The third cost is the one that takes systems down. A connection pool holds a fixed number of open connections to the database. The `pg` pool defaults to 10, and PostgreSQL's own `max_connections` defaults to 100, so the pool cannot grow without limit.

### What is connection pool exhaustion? [#what-is-connection-pool-exhaustion]

Here is an example with made-up numbers. A pool has 10 connections and each query takes 50 ms. The pool can finish at most 10 / 0.05 = 200 queries per second. If 300 requests per second arrive, 100 per second have to wait, and the queue grows every second.

Now one slow query appears. A report query that takes 2 seconds holds a connection for 2 seconds. Ten of them in parallel hold every connection, and every other request, including a cheap `select` by primary key, waits for a free slot.

```mermaid
flowchart LR
  A["Many requests"] --> Q["Waiting for a connection"]
  Q --> P["Pool of 10<br/>all busy with slow queries"]
  P --> D[("PostgreSQL")]
  Q -.->|"wait too long"| T["Timeout errors"]
```

Caching helps in two ways. Cached reads leave the queue, so fewer requests compete for the pool. And the database sees fewer queries, so each one finishes faster. See [cache stampede](/docs/learn/cache-stampede) for the case where a popular key expires and every request misses at once.

## How do you cache PostgreSQL query results in Node.js? [#how-do-you-cache-postgresql-query-results-in-nodejs]

Use [cache-aside](/docs/learn/cache-aside-pattern): the application checks the cache, queries on a miss, stores the result, and invalidates after a write. Three decisions matter.

<Steps>
  <Step title="Design the key from the query and its parameters">
    A key must be the same for the same question and different for any other. Use a name for the query and its parameters: `users:byId:42` or `orders:byUser:42:page:3`. Do not use the raw SQL text as a key (it is long, and two spellings of one query would not match). If the parameters are long or unordered, hash them.
  </Step>

  <Step title="Set a TTL">
    The TTL is your safety net. Even if you forget an invalidation, the copy dies when the TTL ends. Pick it from how stale the data may be: a product description can wait minutes, an account balance cannot.
  </Step>

  <Step title="Invalidate after the UPDATE commits">
    Delete the key after `commit`, never inside the transaction before it. Before the commit, other connections still see the old row. A reader that misses the deleted key loads that old row and puts it back in the cache, and it stays there until the TTL ends.
  </Step>
</Steps>

A helper for keys with several parameters:

```ts title="query-key.ts"
import { createHash } from 'node:crypto'

// A stable key for a named query and its parameters.
export function queryKey(name: string, params: unknown[]): string {
  const digest = createHash('sha256').update(JSON.stringify(params)).digest('hex').slice(0, 16)
  return `q:${name}:${digest}`
}
```

Here is the whole read and write path with `pg` and ioredis.

```ts title="users.ts"
import { Redis } from 'ioredis'
import pg from 'pg'

type User = { id: number; name: string; plan: string }

const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL, max: 10 })
const redis = new Redis(process.env.REDIS_URL ?? 'redis://localhost:6379')
const TTL_SECONDS = 60

export async function getUser(id: number): Promise<User | null> {
  const key = `users:byId:${id}`

  const cached = await redis.get(key)
  if (cached !== null) return JSON.parse(cached) as User // hit: no pool connection

  const { rows } = await pool.query<User>('select id, name, plan from users where id = $1', [id])
  const user = rows[0] ?? null // miss: one pool connection
  if (user) await redis.set(key, JSON.stringify(user), 'EX', TTL_SECONDS)
  return user
}

export async function changePlan(id: number, plan: string): Promise<void> {
  const client = await pool.connect()
  try {
    await client.query('begin')
    await client.query('update users set plan = $1 where id = $2', [plan, id])
    await client.query('commit')
  } catch (error) {
    await client.query('rollback')
    throw error
  } finally {
    client.release()
  }

  // The transaction has committed, so the next read loads the new row.
  await redis.del(`users:byId:${id}`)
}
```

Notice that `redis.del` is the last line, after `client.release()`. If it ran before `commit`, a concurrent `getUser` could read the old row and cache it again.

### How do you cache a Prisma query? [#how-do-you-cache-a-prisma-query]

The same pattern works with any client. With Prisma, the loader is the Prisma call. Prisma returns `null` for a missing row, and `getOrSet` treats `undefined` as "not found" and remembers it, so convert `null` to `undefined`.

```ts title="prisma-users.ts"
import { PrismaClient, type User } from '@prisma/client'
import { setupCache } from 'lazy-layers-cache'

const prisma = new PrismaClient()
const cache = await setupCache<string, User>({
  namespace: 'users-api',
  redis: { required: true }, // reads REDIS_URL
  ttlMs: 60_000,
})

export function getUser(id: number): Promise<User | undefined> {
  return cache.getOrSet(`user:${id}`, async () => {
    const user = await prisma.user.findUnique({ where: { id } })
    return user ?? undefined
  })
}
```

<Note>
  If you cache by hand with `JSON.stringify`, a Prisma `Date` field comes back from `JSON.parse` as a string, so convert it on read. For what survives encoding in lazy-layers-cache, see [serialization](/docs/concepts/serialization).
</Note>

## Redis or PostgreSQL as a cache? [#redis-or-postgresql-as-a-cache]

You can cache inside PostgreSQL too. An `UNLOGGED` table skips the write-ahead log, so writes are faster, but its contents are lost after a crash and are not replicated. That fits a cache, whose rows can be rebuilt.

|                      | Redis                        | PostgreSQL (UNLOGGED table)                   |
| -------------------- | ---------------------------- | --------------------------------------------- |
| Read latency         | About one network round trip | A query on the database you wanted to protect |
| Expiry               | Built-in TTL per key         | You delete old rows yourself                  |
| Load on the database | None                         | Adds reads and writes to it                   |
| Extra service to run | Yes                          | No                                            |

PostgreSQL alone is enough when traffic is low, the queries are indexed lookups that finish in a few milliseconds, and you run one server. Add a cache when you see slow queries repeated many times, a pool that fills during traffic spikes, or database CPU spent on reads that return the same rows. For the Redis side, see [Redis cache in Node.js](/docs/learn/redis-cache-nodejs).

## Where the hand-written version breaks [#where-the-hand-written-version-breaks]

The code above is correct for one server and moderate traffic. Four things go wrong at the next level.

* **A miss storm.** When a popular key expires, 500 requests miss together and send 500 identical queries to a pool of 10. That is the thundering herd, and it exhausts the pool exactly when the key is hottest.
* **Unbounded misses.** Even with different keys, a burst of cold reads sends as many queries as there are requests. Nothing limits how many reach the pool.
* **One tenant starves the rest.** In a multi-tenant app, one customer's traffic spike fills the wait queue and every other customer waits behind it.
* **Redis down.** If `redis.get` throws, every request fails even though PostgreSQL is healthy.

## The same idea with getOrSet [#the-same-idea-with-getorset]

`getOrSet(key, loader)` wraps the check, the query and the store. The loader is your `pool.query`, so the cache decides when it runs.

```ts title="users.ts"
import pg from 'pg'
import { setupCache } from 'lazy-layers-cache'

type User = { id: number; name: string; plan: string }

const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL, max: 10 })

const cache = await setupCache<string, User>({
  namespace: 'users-api',
  redis: { required: true },
  ttlMs: 60_000,
  originLoad: {
    // 'acme:users:42' belongs to the tenant 'acme'
    tenant: (key) => String(key).split(':', 1)[0],
  },
})

export function getUser(tenant: string, id: number): Promise<User | undefined> {
  return cache.getOrSet(`${tenant}:users:${id}`, async () => {
    const { rows } = await pool.query<User>('select id, name, plan from users where id = $1', [id])
    return rows[0]
  })
}

export async function changePlan(tenant: string, id: number, plan: string): Promise<void> {
  await pool.query('update users set plan = $1 where id = $2', [plan, id]) // commits on its own
  await cache.invalidate(`${tenant}:users:${id}`) // after the commit
}
```

Here is what the cache does for the pool:

| Situation                      | What `getOrSet` does                                                                                                                                                                                                           |
| ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Cache hit                      | Returns from memory or Redis. The loader does not run, so no pool connection is borrowed.                                                                                                                                      |
| 500 requests miss the same key | One loader call runs in the process. With Redis, a lease lets one server load while the others wait. In a recorded run, 1,200 callers on 6 servers caused 20 origin loads.                                                     |
| A burst of misses on many keys | At most `maxConcurrent` loaders run at once per process (32 by default), and `maxQueued` more wait (1,024 by default). A call that waits past the queue limit or the 1 s queue deadline fails instead of piling onto the pool. |
| One tenant floods the queue    | With `originLoad: { tenant }`, waiting loads are served round-robin across tenants, so one tenant cannot take every slot.                                                                                                      |
| Redis is slow or down          | The read fails open to the loader, so users still get an answer from PostgreSQL. In a recorded run, a 4 s Redis freeze caused 0 errors.                                                                                        |
| A row does not exist           | `undefined` is remembered for 10 s by default, so a missing ID does not query the database on every request.                                                                                                                   |

<Warning>
  The defaults allow 32 loaders per process, and a `pg` pool holds 10 connections by default. Loaders 11 to 32 would wait inside the pool. Set `originLoad: { maxConcurrent: 10 }` to match the pool, and remember the limit is per process, not per fleet: 10 servers with a pool of 10 each can still open 100 connections, which is PostgreSQL's default `max_connections`. See [stampede protection](/docs/guides/stampede-protection) for the full set of options and [failure handling](/docs/guides/failure-handling) for what callers see when the queue is full.
</Warning>

Next lesson: [Caching in Node.js](/docs/learn/nodejs-caching).

## Further reading [#further-reading]

* [PostgreSQL, resource consumption](https://www.postgresql.org/docs/current/runtime-config-resource.html): the `shared_buffers` setting, its 128 MB default and the advice to also rely on the operating system cache.
* [Uber, CacheFront](https://www.uber.com/blog/how-uber-serves-over-40-million-reads-per-second-using-an-integrated-cache/): Redis in front of a MySQL-based database, with the reported effect on hit rate and latency.
* [Shopify IdentityCache](https://github.com/Shopify/identity_cache): caches ActiveRecord models in Memcached, and the database is only hit when a copy cannot be found.
* [Nishtala et al., Scaling Memcache at Facebook, NSDI 2013](https://www.usenix.org/conference/nsdi13/technical-sessions/presentation/nishtala): uses memcache to lighten the read load on its databases.


## Questions

### What is database caching?

Database caching is keeping the result of a database read in a faster place, usually memory, so the next identical read skips the query. It lowers latency, saves database CPU, and keeps connection pool slots free. The copy can be stale, so it needs a TTL or an invalidation after writes.

### Does PostgreSQL have a query cache?

No. PostgreSQL does not cache query results, so the same SELECT runs again every time. It caches data pages in `shared_buffers` (128 MB by default) and relies on the operating system page cache. Prepared statements cache the query plan, not the rows.

### How do I cache PostgreSQL query results in Node.js?

Use the cache-aside pattern. Build a key from the query name and parameters, check Redis or memory first, run the query through the `pg` pool on a miss, store the rows with a TTL, and delete the key after an UPDATE commits.

### Should I use Redis or PostgreSQL as a cache?

Use Redis when you need sub-millisecond reads, high request rates, or TTL expiry handled for you. PostgreSQL alone is enough for low traffic and cheap indexed queries. An UNLOGGED table can act as a simple cache, but it adds load to the database you wanted to protect.

### What is connection pool exhaustion?

A connection pool holds a fixed number of database connections. When slow queries keep every connection busy, new requests wait for a free one, and a request that waits too long times out. The wait spreads to requests that never needed a slow query.

### When should I invalidate the cache after a database write?

After the transaction commits. If you delete the key before the commit, another request can read the old row, cache it, and keep serving it until the TTL ends. Delete after the commit and the next read loads the new row.