---
title: "Cache expensive actions"
description: "Keep an action's results for a while with Convex's action cache component, so the same call is paid for once, with expiry and invalidation."
canonical_url: "https://nuxt-backend.dev/docs/build/data/jobs/action-cache"
---
# Cache expensive actions

> Keep an action's results for a while with Convex's action cache component, so the same call is paid for once, with expiry and invalidation.

Version: nuxt-backend 0.6.x · Tab: Build · Kind: recipe · Status: stable

Every page: [llms.txt](https://nuxt-backend.dev/llms.txt) · Skill for coding agents: [nuxt-backend](https://nuxt-backend.dev/.well-known/skills/nuxt-backend/SKILL.md)

Commands use npm; use your project's package manager.

Fetch a city's forecast once a day, not on every page view. An action that calls a model, geocodes an address or fetches exchange rates costs time and often money, and is often called again with the same arguments. The official [`@convex-dev/action-cache`](https://www.convex.dev/components/action-cache) component keeps its results: the first call runs the action and stores what it returns, and every call with the same arguments gets the stored result until it expires.

## Cache a forecast

```bash
npm install @convex-dev/action-cache
```

<code-tree default-value="backend/weather.ts">

```ts [backend/convex.config.ts]
import actionCache from '@convex-dev/action-cache/convex.config'

// …after the package's components
app.use(actionCache)
```

```ts [backend/weather.ts]
import { ActionCache } from '@convex-dev/action-cache'
import { v } from 'convex/values'
import { components, internal } from './_generated/api'
import { internalAction } from './_generated/server'
import { authed } from './functions'

type Forecast = { high: number, low: number }

export const forecastFor = internalAction({
  args: { city: v.string() },
  handler: async (_ctx, { city }): Promise<Forecast> => {
    const response = await fetch(`https://api.example.com/forecast?city=${encodeURIComponent(city)}`)
    return await response.json() as Forecast
  },
})

const forecasts = new ActionCache(components.actionCache, {
  action: internal.weather.forecastFor,
  name: 'forecast:v1',
  ttl: 86_400_000,
})

export const forecast = authed.action({
  args: { city: v.string() },
  handler: (ctx, { city }): Promise<Forecast> => forecasts.fetch(ctx, { city }),
})
```

</code-tree>

<table>
<thead>
  <tr>
    <th>
      Option
    </th>
    
    <th>
      This recipe
    </th>
    
    <th>
      Effect
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        action
      </code>
    </td>
    
    <td>
      <code>
        internal.weather.forecastFor
      </code>
    </td>
    
    <td>
      The action whose results are kept. It runs on a miss, with the arguments <code>
        fetch
      </code>
      
       got
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        name
      </code>
    </td>
    
    <td>
      <code>
        'forecast:v1'
      </code>
    </td>
    
    <td>
      Part of every key; the action's name when you leave it out. Change it when the action starts returning something else, so no old result is served
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        ttl
      </code>
    </td>
    
    <td>
      <code>
        86_400_000
      </code>
      
      , a day
    </td>
    
    <td>
      How long a result is served, in milliseconds. Without it, results stay until you remove them
    </td>
  </tr>
</tbody>
</table>

One mount holds every cache your app defines, each told apart by its `name`.

## How a fetch answers

`fetch(ctx, args)` runs in an action, since a miss runs one. On a hit it returns the stored result without calling the action. On a miss, or once the stored result has expired, it runs the action, stores what it returns and returns that. Two callers that miss at the same moment both run the action, and one result is kept. A failed action stores nothing.

The arguments are the key, whole. Every caller who passes the same ones gets the same result, so a result that belongs to one person needs that person among the arguments: pass their id to the cached action, even when it only reads it to find their data.

## Expiry and invalidation

An expired result is never served. The component deletes expired results when it reads them and in a purge it runs once a day.

<table>
<thead>
  <tr>
    <th>
      Call
    </th>
    
    <th>
      Effect
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        fetch(ctx, args, { force: true })
      </code>
    </td>
    
    <td>
      Runs the action now and replaces the stored result. Call it from a cron to refresh a result before anyone misses
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        remove(ctx, args)
      </code>
    </td>
    
    <td>
      Forgets the result for these arguments. Call it from the mutation that changes what the action reads
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        removeAllForName(ctx)
      </code>
    </td>
    
    <td>
      Forgets every result of this cache, a batch at a time
    </td>
  </tr>
</tbody>
</table>

A result keyed by a person's id is that person's data. Where you erase their data, `remove` each result cached under their id, or give a cache of personal results a `ttl` short enough that the daily purge erases them in time.

## Related

- [Background work](https://nuxt-backend.dev/docs/build/data/jobs): when to reach for the cache, a workpool or a cron.
- [Queue work with a workpool](https://nuxt-backend.dev/docs/build/data/jobs/workpool): run many expensive actions a few at a time.
- [Metered actions](https://nuxt-backend.dev/docs/build/ai/metered-actions): charge credits for a model call; a cached result costs nothing to serve again.
- The [action cache component](https://www.convex.dev/components/action-cache): every method.


## Sitemap

See the full [sitemap](https://nuxt-backend.dev/sitemap.md) for all pages.
