@convex-dev/action-cache

中文文档
0.3.1发布于 2026/07/07Apache-2.0TypeScriptES Module零依赖近 30 天下载 42.8万

A Convex component for caching values that are expensive to compute.

原始使用文档
文档目录6 节
  1. Pre-requisite: Convex
  2. Installation
  3. Example
  4. Defining multiple caches
  5. Updating the cache before it expires
  6. Clearing values

Convex Action Cache Component

npm version

Sometimes your app needs to fetch information from a third-party API that is slow or costs money. Caching can help! This is a Convex component that can cache the results of expensive functions and set an optional TTL. Expired entries are cleaned up via a cron job once a day. The cache key is the ActionCache's name (defaults to function name) and the arguments to the action that generates the cache values.

import { action } from "./_generated/server";
import { components } from "./_generated/api";
import { ActionCache } from "@convex-dev/action-cache";

const cache = new ActionCache(components.actionCache, {
  action: internal.example.myExpensiveAction,
});

export const myFunction = action({
  // NOTE: If we're returning the result, we need explicitly type the return value.
  // Refer to https://docs.convex.dev/functions/actions#dealing-with-circular-type-inference for more info.
  handler: async (ctx, args): Promise<{ text: string }> => {
    // Call it with the parameters to `myExpensiveAction`
    const result = await cache.fetch(ctx, { foo: "bar" });

    // Do something with the result or just return it
    return result;
  },
});

export const myExpensiveAction = internalAction({
  args: { foo: v.string() },
  handler: async (ctx, args): Promise<{ text: string }> {
    const data = await generateLLMResponse(ctx, args);
    return data;
  }
})

To invalidate the cache, you can set a new name explicitly and/or clear cached values by name.

Pre-requisite: Convex

You'll need an existing Convex project to use the component. Convex is a hosted backend platform, including a database, serverless functions, and a ton more you can learn about here.

Run npm create convex or follow any of the quickstarts to set one up.

Installation

Install the component package:

npm install @convex-dev/action-cache

Create a convex.config.ts file in your app's convex/ folder and install the component by calling use:

// convex/convex.config.ts
import { defineApp } from "convex/server";
import cache from "@convex-dev/action-cache/convex.config.js";

const app = defineApp();
app.use(cache);

export default app;

Finally, create a new ActionCache with optional name and expiration within your Convex project, and point it to the installed component.

  • The name field can be used for identifying the function or version being used to create the values in the cache and can also be used for grouping entries to remove.
  • The ttl (Time-To-Live) field determines how long the cache entries are valid, in milliseconds.
    • If no ttl is provided, the cache entries are kept indefinitely.
    • If an ttl is provided, expired cache entries are deleted when they are retrieved and in a daily cron job.
import { ActionCache } from "@convex-dev/action-cache";
import { components } from "./_generated/api";

const cache = new ActionCache(components.actionCache, {
  action: internal.example.myExpensiveAction,
  name: "myExpensiveActionV1",
  ttl: 1000 * 60 * 60 * 24 * 7, // 7 days
});

Example

Suppose you're building an app that uses vector search. Calculating embeddings is often expensive - in our case, we are using OpenAI's API which adds latency to every search and costs money to use. We can reduce the number of API calls by caching the results!

Start by defining the Convex action that calls the API to create embeddings. Feel free to substitute your favorite embeddings API. You may need to adjust the vector dimensions in the schema in example/schema.ts accordingly.

Set your API key environment variable

npx convex env set OPENAI_API_KEY <your-api-key>
export const embed = internalAction({
  args: { text: v.string() },
  handler: async (_ctx, { text }) => {
    const apiKey = process.env.OPENAI_API_KEY;
    if (!apiKey) {
      throw new Error("OPENAI_API_KEY environment variable not set!");
    }
    const req = { input: text, model: "text-embedding-ada-002" };
    const resp = await fetch("https://api.openai.com/v1/embeddings", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${apiKey}`,
      },
      body: JSON.stringify(req),
    });
    if (!resp.ok) {
      const msg = await resp.text();
      throw new Error(`OpenAI API error: ${msg}`);
    }
    const json = await resp.json();
    const vector = json["data"][0]["embedding"];
    console.log(`Computed embedding of "${text}": ${vector.length} dimensions`);
    return vector as number[];
  },
});

Create the embeddings cache:

const embeddingsCache = new ActionCache(components.actionCache, {
  action: internal.example.embed,
  name: "embed-v1",
});

Use the cache when you run a vector search:

export const vectorSearch = action({
  args: { query: v.string(), cuisines: v.array(v.string()) },
  handler: async (ctx, args) => {
    const embedding = await embeddingsCache.fetch(ctx, {
      text: args.query,
    });
    const results = await ctx.vectorSearch("foods", "by_embedding", {
      vector: embedding,
      limit: 16,
      filter: (q) =>
        q.or(...args.cuisines.map((cuisine) => q.eq("cuisine", cuisine))),
    });
    const rows: SearchResult[] = await ctx.runQuery(
      internal.example.fetchResults,
      { results },
    );
    return rows;
  },
});

Defining multiple caches

You can use the same component for multiple actions, or multiple versions of the same action. You can specify a custom name argument to denote which cache you want to use, or change the name to start fresh, like embed-v2.

If the return value changes, it is important to change the name so you don't get unexpected values.

Updating the cache before it expires

It's convenient to lazily run the action when there is a cache miss. However, this means that some requests will be slow, and many competeing requests may race to all run the action and populate the cache.

You can avoid this by calling fetch with the force option. This will force the action to run and update the cache, even if there is a cache hit. In the meantime, other requests will get a cache hit.

If you call this from a cron job, the cache will always have an entry (unless the action fails).

Clearing values

To clear old values, you can:

  1. Remove one entry by arguments.

    await embeddingsCache.remove(ctx, { text: "target text" });
    
  2. Remove all entries for the current name (defaults to function name). This is useful if you updated the implementation and want to clear

    await embeddingsCache.removeAllForName(ctx);
    
  3. Remove all entries in the component, including all names.

    await embeddingsCache.removeAll(ctx);
    

See more example usage in example.ts.

版本与发布记录

@convex-dev/action-cache 共发布 22 个版本,首次发布于 2024/10/17;过去 12 个月发布了 2 个版本。

版本发布日期距今
0.3.1latest2026/07/074 个月前
0.3.02025/11/1311 个月前
0.2.112025/08/011.3 年前
0.2.102025/06/181.4 年前
0.2.92025/05/311.4 年前
0.2.82025/05/311.4 年前

其他发布通道:alpha → 0.2.2-alpha.0。

关于 @convex-dev/action-cache 的常见问题

@convex-dev/action-cache 是什么?

A Convex component for caching values that are expensive to compute.

如何安装 @convex-dev/action-cache?

在项目目录运行 npm install @convex-dev/action-cache,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:convex(^1.24.8)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@convex-dev/action-cache 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@convex-dev/action-cache 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@convex-dev/action-cache 可以商用吗?

@convex-dev/action-cache 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@convex-dev/action-cache 的下载量有多少?

根据 npm 官方下载统计,@convex-dev/action-cache 在 2026/10/11 – 2026/11/09 这 30 天内被下载 428,270 次,日均约 14,276 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@convex-dev/action-cache 还在维护吗?

最新版本 0.3.1 发布于 2026/07/07(4 个月前);至今共发布 22 个版本,其中过去 12 个月发布了 2 个;首次发布于 2024/10/17。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。