# Redis cache in Node.js (https://layerscache.com/docs/learn/redis-cache-nodejs)

> A Redis cache keeps hot data in memory so Node.js skips the database. Set one up with ioredis, TTL, EXPIRE, MGET and pipelines, then see the getOrSet version.



A **Redis cache** is a Redis server that holds copies of data your application would otherwise fetch from a slower source such as PostgreSQL. Redis keeps its data in memory, so a read takes a fraction of a millisecond. Your app checks Redis first, loads from the database on a miss, and stores the result with a TTL.

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

```mermaid
flowchart LR
    A1["App server 1"] --> R["Redis"]
    A2["App server 2"] --> R
    A3["App server 3"] --> R
    R -->|"miss"| P["PostgreSQL"]
```

Every app server shares one Redis. The first server to miss loads the row from PostgreSQL and stores it, and the others read it from Redis.

## What is Redis used for? [#what-is-redis-used-for]

Redis is a general-purpose in-memory server, and caching is only one of its jobs. Teams also use it for:

* **Sessions.** Store a login session under a key with a TTL, so any server can read it.
* **Rate limiting.** Count requests per user per minute with `INCR` and `EXPIRE`.
* **Queues.** Lists and streams hold jobs for background workers.
* **Pub/Sub.** One server publishes a message and all subscribers receive it.
* **Leaderboards.** Sorted sets keep scores in order.

This lesson covers the first job: a cache in front of a database.

## Is Redis a cache or a database? [#is-redis-a-cache-or-a-database]

Redis is an **in-memory data store with optional persistence**. It is a cache when you treat its contents as disposable copies, and a database when you rely on it to keep data. Redis can write to disk in two ways:

| Mode                   | How it works                                          | Trade-off                                                                |
| ---------------------- | ----------------------------------------------------- | ------------------------------------------------------------------------ |
| RDB snapshots          | Saves the whole dataset to a file at intervals        | Compact and fast to restart, but you lose writes since the last snapshot |
| AOF (append-only file) | Logs every write command and replays the log on start | Loses less data, larger files                                            |

For a cache you can turn both off. If Redis restarts empty, the next reads miss and refill it from the database.

## How does Redis work, and why is it fast? [#how-does-redis-work-and-why-is-it-fast]

Redis keeps every value in RAM, which is about 100 ns to read according to the often-quoted "Latency numbers every programmer should know", against 10 ms for a disk seek. A client sends a command over TCP, Redis runs it, and sends the reply.

Redis runs commands **on a single thread**, one after another. That sounds slow, but it means no locks and no two commands interleave, so each command is atomic. Its data structures (strings, hashes, lists, sets, sorted sets) are simple and well suited to this. The cost to watch is the network round trip, about 0.5 ms inside a datacenter, which is why batching matters later in this lesson.

The single thread has one catch. A slow command blocks every other client. That is why `KEYS *` is dangerous in production, a topic covered in [delete Redis keys by pattern](/docs/learn/redis-delete-keys-by-pattern).

## Set up Redis and ioredis [#set-up-redis-and-ioredis]

<Steps>
  <Step title="Start Redis">
    Run `docker run -p 6379:6379 redis`. Redis now listens on `localhost:6379`.
  </Step>

  <Step title="Install a client">
    Run `npm install ioredis`. ioredis is the client lazy-layers-cache uses. The other common choice, [node-redis](https://github.com/redis/node-redis) (the `redis` package), has a similar API.
  </Step>

  <Step title="Check the connection">
    Run `redis-cli ping`, or call `await redis.ping()` from Node.js. Both answer `PONG`.
  </Step>
</Steps>

## Cache-aside with ioredis [#cache-aside-with-ioredis]

This is the [cache-aside pattern](/docs/learn/cache-aside-pattern) with Redis as the store. Values are saved as JSON, and `set` with `'EX'` gives each key a five-minute life.

```ts title="users.ts"
import { Redis } from 'ioredis'
import { db, type User } from './db.ts'

const redis = new Redis(process.env.REDIS_URL ?? 'redis://localhost:6379')
const TTL_SECONDS = 300

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

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

  const user = await db.users.find(id) // cache miss
  if (user) await redis.set(key, JSON.stringify(user), 'EX', TTL_SECONDS)
  return user
}
```

Redis stores strings, so you serialize on the way in and parse on the way out.

## Redis TTL and EXPIRE [#redis-ttl-and-expire]

A **TTL** (time to live) is how long a key stays in Redis before Redis deletes it. Without one, a key lives until you delete it or Redis runs out of memory, so set one on every cached value.

```text
SET user:42 '{"id":"42","name":"Ada"}' EX 300
TTL user:42        # 297 (seconds left)
EXPIRE user:42 600 # sets the TTL to 600 seconds, returns 1
TTL user:42        # 600
TTL missing:key    # -2 (the key does not exist)
```

`TTL` returns `-1` for a key that exists with no expiry and `-2` for a key that does not exist. `PEXPIRE` and `PTTL` work in milliseconds. Setting the value and the TTL in one `SET ... EX` call is safer than `SET` followed by `EXPIRE`, because a crash between the two would leave a key that never expires.

## Read many keys with MGET and pipelines [#read-many-keys-with-mget-and-pipelines]

Each Redis command costs a network round trip. A loop of 100 `get` calls waits for 100 round trips. Two tools reduce that:

* **`MGET`** reads many keys in one command and returns an array, with `null` for each miss.
* **A pipeline** sends many commands in one write and reads all the replies together. The commands can be different kinds, such as a batch of `SET` calls.

```ts title="users-many.ts"
import { Redis } from 'ioredis'
import { db, type User } from './db.ts'

const redis = new Redis(process.env.REDIS_URL ?? 'redis://localhost:6379')
const TTL_SECONDS = 300

export async function getUsers(ids: string[]): Promise<User[]> {
  if (ids.length === 0) return []

  const cached = await redis.mget(...ids.map((id) => `user:${id}`)) // 1 round trip
  const users = new Map<string, User>()
  const missing: string[] = []

  ids.forEach((id, i) => {
    const hit = cached[i]
    if (hit === null || hit === undefined) missing.push(id)
    else users.set(id, JSON.parse(hit) as User)
  })

  if (missing.length > 0) {
    const loaded = await db.users.findMany(missing) // 1 query for every miss
    const pipeline = redis.pipeline()
    for (const user of loaded) {
      users.set(user.id, user)
      pipeline.set(`user:${user.id}`, JSON.stringify(user), 'EX', TTL_SECONDS)
    }
    await pipeline.exec() // 1 round trip for every write
  }

  return ids.flatMap((id) => users.get(id) ?? [])
}
```

A pipeline is not a transaction. Other clients can run commands between yours, and one failed command does not undo the rest.

## Redis vs Memcached [#redis-vs-memcached]

Memcached is the older, simpler cache. Both are in-memory key-value servers, and for plain string caching either works.

|             | Redis                                              | Memcached                    |
| ----------- | -------------------------------------------------- | ---------------------------- |
| Data types  | Strings, hashes, lists, sets, sorted sets, streams | Strings                      |
| Persistence | Optional (RDB, AOF)                                | None                         |
| Replication | Built in, with Sentinel and Cluster                | Not built in                 |
| Threading   | Commands on one thread                             | Multi-threaded               |
| Extras      | Pub/Sub, Lua scripts, transactions                 | Counters and compare-and-set |

Pick Memcached when you only need a simple, multi-threaded string cache. Pick Redis when you also want data types, persistence, Pub/Sub or scripts, which is most teams.

## Redis vs an in-memory cache [#redis-vs-an-in-memory-cache]

A Redis read crosses the network, about 0.5 ms in a datacenter. A read from a `Map` in your own process takes nanoseconds, but each server has its own copy and none can see another's. In a recorded run, a warm hit from lazy-layers-cache's memory layer cost 180 ns in reference mode on an Apple M5.

|                        | In-process memory | Redis                     |
| ---------------------- | ----------------- | ------------------------- |
| Latency                | Nanoseconds       | About 0.5 ms              |
| Shared between servers | No                | Yes                       |
| Survives a restart     | No                | Yes, if persistence is on |
| Size limit             | Your process heap | The Redis server's memory |

You do not have to choose. Keep a small memory layer in front of Redis. The memory layer is **L1** and Redis is **L2**.

```mermaid
flowchart TB
    Q["getUser(42)"] --> L1{"In memory?"}
    L1 -->|"hit"| R["Return value"]
    L1 -->|"miss"| L2{"In Redis?"}
    L2 -->|"hit"| F1["Fill memory"] --> R
    L2 -->|"miss"| DB["Load from PostgreSQL"] --> F2["Fill Redis and memory"] --> R
```

## Where this breaks [#where-this-breaks]

The hand-written version works for one server. Four things go wrong as it grows:

1. **Redis is down.** If `redis.get` throws, the request fails even though PostgreSQL is fine. Cache reads should fail open and fall back to the database.
2. **Many misses at once.** When a hot key expires, every request misses and queries the database. See [cache stampede](/docs/learn/cache-stampede).
3. **Stale memory copies.** With an L1 in front, `redis.del` clears Redis but not the other servers' memory. Each server must be told.
4. **Round trips.** Reading 500 keys one at a time costs 500 round trips, and hand-written `MGET` and pipeline code gets long.

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

lazy-layers-cache is the L1 plus L2 setup above in one call. `setupCache` connects to Redis through `REDIS_URL`, and `required: true` makes it throw at startup if neither a client nor `REDIS_URL` is provided.

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

const cache = await setupCache<string, User>({
  namespace: 'users-api',
  redis: { required: true },
  ttlMs: 300_000,
})

export function getUser(id: string): Promise<User | undefined> {
  return cache.getOrSet(`user:${id}`, () => db.users.find(id))
}

export function getUsers(ids: string[]) {
  return cache.getOrSetMany(ids.map((id) => `user:${id}`), async (missing) => {
    const rows = await db.users.findMany(missing.map((key) => key.slice('user:'.length)))
    return new Map(rows.map((row) => [`user:${row.id}`, row] as const))
  })
}
```

What this adds over the hand-written code:

* **Memory in front of Redis.** `getOrSet` reads L1, then Redis, then your loader, and fills each layer on the way back. `invalidate` clears every server's memory over an event bus.
* **Batched Redis calls.** Redis calls made in the same tick run as one [Lua script](/docs/guides/redis-lua-scripts) per 64 keys. Redis runs a Lua script as one step, so a read and its TTL cannot be split by another client. In a recorded run, reading 500 keys made 8 script calls instead of 500.
* **Fail-open reads.** If Redis is slow or down, the read falls back to memory and the loader. In a recorded run, a 4 s Redis freeze caused 0 errors.
* **One load per miss.** Concurrent misses for a key share a single loader call.

See [multi-tier caching](/docs/concepts/multi-tier), the [Redis setup](/docs/setups/serverful) and the [configuration reference](/docs/reference/configuration) for every option.

Next lesson: [delete Redis keys by pattern](/docs/learn/redis-delete-keys-by-pattern).

## Further reading [#further-reading]

* [Redis, client-side caching reference](https://redis.io/docs/latest/develop/reference/client-side-caching/): how an application can keep replies in its own memory and receive invalidation messages from Redis.
* [Hello Interview, Caching for System Design Interviews](https://www.hellointerview.com/learn/system-design/core-concepts/caching): places an external cache such as Redis among the options and notes it supports LRU eviction and TTL.
* [Nishtala et al., Scaling Memcache at Facebook, NSDI 2013](https://www.usenix.org/conference/nsdi13/technical-sessions/presentation/nishtala): a large production use of memcached, the other widely used cache server, as a look-aside cache.
* [AWS Builders' Library, Caching challenges and strategies](https://aws.amazon.com/builders-library/caching-challenges-and-strategies/): compares local caches with external caches such as Redis and what to do when the external cache is unavailable.


## Questions

### What is a Redis cache?

A Redis cache is a Redis server used to store copies of data that is slow to fetch or compute, such as database rows or API responses. Each entry is a key with a value and usually a TTL. The application checks Redis first and goes to the database only on a miss.

### Is Redis a cache or a database?

Both. Redis is an in-memory data store. Used as a cache, it holds disposable copies with TTLs. Used as a database, it can save data to disk with RDB snapshots or an append-only file (AOF). Most teams run it as a cache next to a primary database such as PostgreSQL.

### Why is Redis so fast?

Redis keeps its data in RAM, so a read does not touch a disk. It runs commands on one thread, so it takes no locks, and its data structures are simple. Most of the time per call is the network round trip, not Redis itself.

### What is the difference between Redis and Memcached?

Memcached stores strings, uses several threads and has no persistence. Redis has strings, hashes, lists, sets, sorted sets and streams, can persist to disk, and supports replication, Lua scripts and Pub/Sub. For plain caching both work. Redis is the usual pick when you need more than string keys.

### What is the difference between Redis TTL and EXPIRE?

EXPIRE sets a time to live on a key, in seconds. TTL reads how many seconds a key has left, and returns -1 if the key has no expiry and -2 if the key does not exist. SET with the EX option stores a value and sets its expiry in one command.

### Do I need an in-memory cache if I have Redis?

Not to be correct, but it saves time. Redis answers in about half a millisecond over a network, and a Map in your own process answers in nanoseconds. Putting a small in-memory layer in front of Redis is called an L1 and L2 setup, and it needs a way to clear every server's copy.