Caching

Memoize expensive operations with Thunder's built-in cache utility.

Thunder provides a lightweight cache utility that memoizes the result of an async function for a configurable time-to-live (TTL). It's ideal for expensive operations such as database lookups or external API calls that don't need to run on every request.

Basic Usage

Wrap any async function with cache, passing a TTL in milliseconds:

import { cache } from "@/core/utils/cache.ts";

// Cache function results with a 1 minute TTL
const getUser = cache(async (id: string) => {
  return await userModel.findOne({ _id: new ObjectId(id) });
}, 60_000);

// First call hits the database; subsequent calls within 60s return the cached value.
const user = await getUser("123");

Permanent Cache

Use Infinity as the TTL to cache a value permanently for the lifetime of the process - useful for configuration that never changes at runtime:

import { cache } from "@/core/utils/cache.ts";

const getConfig = cache(async () => {
  return await loadConfig();
}, Infinity);

Because Thunder is serverless-first, caches live only for the duration of a single execution context. For cross-request caching across instances, use an external store such as Redis.


On this page