Skip to content

Caching

Use a JSON key-value schema for cached responses.

import { json, kv } from "benni/schema";
type ProductSummary = {
id: string;
name: string;
priceCents: number;
};
export const productCache = kv(
"cache:product",
json<ProductSummary>()
);

Read-through caching:

async function getProduct(id: string) {
const cached = await redis.kv(productCache).get(id);
if (cached) return cached;
const product = await fetchProductFromDatabase(id);
await redis.kv(productCache).set(id, product, {
ttlSeconds: 60 * 5
});
return product;
}

Invalidate when the source of truth changes:

await redis.kv(productCache).del(id);

Raw Redis equivalent:

await nodeRedis.set(
`cache:product:${id}`,
JSON.stringify(product),
{ EX: 60 * 5 }
);