# Node.js cache quickstart (https://lazy-layers-cache.vercel.app/docs/quickstart)

> Install a TypeScript cache npm package, start with in-memory L1, then add Redis L2, read-through loading, and invalidation.



To cache with Redis and an in-memory L1 in Node.js, install `lazy-layers-cache`, create one cache per process with `setupCache({ namespace, redis: { required: true } })`, read through it with `getOrSet(key, loader)`, and call `invalidate(key)` after each committed database write. This page builds that up in five steps, starting from an in-memory example that needs no database or Redis. You need Node.js 22 or later.

<Steps>
  <Step title="Install the package">
    ```bash
    npm install lazy-layers-cache
    ```
  </Step>

  <Step title="Run your first cached read">
    Save this file and run `node cache-demo.mjs`.

    ```js title="cache-demo.mjs"
    import { setupCache } from 'lazy-layers-cache'

    const cache = await setupCache({ namespace: 'demo', redis: false })
    let loaderCalls = 0

    try {
      const loadUser = async () => {
        loaderCalls++
        return { id: '42', name: 'Ada' }
      }

      await cache.getOrSet('user:42', loadUser)
      const user = await cache.getOrSet('user:42', loadUser)
      console.log(user.name, loaderCalls) // Ada 1

      await cache.invalidate('user:42')
      await cache.getOrSet('user:42', loadUser)
      console.log(loaderCalls) // 2
    } finally {
      await cache.close()
    }
    ```

    The first read runs the loader. The second reuses the value. Invalidating the key makes the next read load it again.
  </Step>

  <Step title="Share values across instances">
    Install the Redis client, an optional peer dependency:

    ```bash
    npm install ioredis
    ```

    Set `REDIS_URL` to your Redis 6+ service. Create one cache per application process:

    <CodeGroup>
      ```js title="src/cache/index.js"
      import { setupCache } from 'lazy-layers-cache'

      export const cache = await setupCache({
        namespace: 'users-api',
        redis: { required: true },
      })
      ```

      ```ts title="src/cache/index.ts"
      import { setupCache } from 'lazy-layers-cache'
      import type { User } from '../types/user.js'

      export const cache = await setupCache<string, User>({
        namespace: 'users-api',
        redis: { required: true },
      })
      ```
    </CodeGroup>

    For the TypeScript example, define the value your application reads:

    ```ts title="src/types/user.ts"
    export interface User {
      id: string
      name: string
    }
    ```

    Use the same namespace and Redis service for instances that share values. Setup waits for Redis and the event subscription to be ready. `required: true` prevents a missing URL from silently starting isolated L1 caches.
  </Step>

  <Step title="Connect your database reads and writes">
    The following repository assumes you provide `src/db.js`. Adapt the database calls to your client. Return `undefined` for a missing record, and pass the abort signal when your client supports cancellation.

    <CodeGroup>
      ```js title="src/users/repository.js"
      import { cache } from '../cache/index.js'
      import { db } from '../db.js'

      export function getUser(id) {
        return cache.getOrSet(`user:${id}`, async ({ signal } = {}) => {
          const user = await db.users.findById(id, { signal })
          return user ?? undefined
        })
      }

      export async function updateUser(id, patch) {
        const user = await db.users.update(id, patch)
        await cache.invalidate(`user:${id}`)
        return user
      }
      ```

      ```ts title="src/users/repository.ts"
      import { cache } from '../cache/index.js'
      import { db } from '../db.js'
      import type { User } from '../types/user.js'

      export function getUser(id: string): Promise<User | undefined> {
        return cache.getOrSet(`user:${id}`, async ({ signal } = {}) => {
          const user = await db.users.findById(id, { signal })
          return user ?? undefined
        })
      }

      export async function updateUser(id: string, patch: Partial<User>): Promise<User> {
        const user = await db.users.update(id, patch)
        await cache.invalidate(`user:${id}`)
        return user
      }
      ```
    </CodeGroup>

    Commit the database write before invalidating. Invalidation clears cached state and publishes a delete event to peers. Event delivery is asynchronous, so it does not make the database write and every cached read atomic.
  </Step>

  <Step title="Close the cache on shutdown">
    After your server stops accepting requests and drains active work, call:

    ```js title="Application shutdown"
    await cache.close()
    ```

    `close()` is idempotent. It disconnects the event bus, stops observability, and closes a Redis client created by `setupCache`. Your application closes any client it supplied itself.
  </Step>
</Steps>

## What is already configured [#what-is-already-configured]

In-flight dedupe shares concurrent same-key loads in one process. Redis per-key leases coordinate loads between instances. Loader timeouts, bounded origin work, stale fallback, negative caching, and circuit breakers are already active.

A successful loader can also prime peer L1 caches. `setupCache` limits the encoded broadcast to 32 KiB. Larger events skip priming, and memory pressure can prevent L1 admission. The [configuration reference](/docs/reference/configuration) documents every default and override.

Redis or bus failures can degrade to origin reads. Your application must still handle loader errors, overload, and lock deadlines. See [failure handling](/docs/guides/failure-handling).

## Add only what your application needs [#add-only-what-your-application-needs]

| Need                                          | Next step                                                                |
| --------------------------------------------- | ------------------------------------------------------------------------ |
| Warm a known key before traffic               | [`prewarm`](/docs/reference/api#prewarm), using the same loader          |
| Invalidate a key family                       | [`invalidateByPattern`](/docs/reference/api#invalidatebypattern)         |
| Tune memory, TTLs, and concurrency            | [Production setup](/docs/setups/production)                              |
| Coordinate a durable payment or order attempt | [Transaction coordination](/docs/reference/transactions), a separate API |

## Where to next [#where-to-next]

* [Walkthrough](/docs/walkthrough) follows one key through reads, writes, and failures.
* [Production setup](/docs/setups/production) covers deployment and capacity choices.
* [API reference](/docs/reference/api) gives the complete method list.


## Questions

### Which packages do I install to use Redis?

`lazy-layers-cache` and `ioredis`. Since 8.0, `ioredis` is an optional peer dependency: install it when you use Redis L2 or Redis Pub/Sub. Without it, `setupCache({ redis })` raises `MissingPeerDependencyError` with the install command.

### Can I start without Redis and add it later?

Yes. `setupCache({ namespace, redis: false })` runs an in-memory L1 only. Switching to `redis: { required: true }` adds Redis L2 and Redis Pub/Sub without changing the code that calls `getOrSet` and `invalidate`.