Keel by ChimpLabs
Jump to page or section Esc
Primitives

Cache

Read-through caching with singleflight stampede protection, TTL expiration, tag-based invalidation, and hit and miss metrics.

Cache wraps expensive computations and reads with schema-typed caching, TTL expiration, tag-based invalidation, and singleflight coalescing (getOrCompute).

Use Cache for derived values that are safe to recompute on a miss. For authoritative application state such as sessions or checkpoints, see KV.


Declaring a Cache

Plain TypeScript SDK (@chimp-labs/keel/sdk)

import { k } from "@chimp-labs/keel/sdk"

export const PriceCache = k.cache(
  "prices",
  k.object({
    cents: k.int(),
    currency: k.string(),
  }),
  { ttl: "5 minutes" }
)

Configuration options

Option Type Required Description
ttl Duration.Input Yes Default time-to-live for cached entries, for example "5 minutes".

Effect v4 (@chimp-labs/keel/cache)

import { Schema } from "effect"
import { Cache } from "@chimp-labs/keel/cache"

export class PriceCache extends Cache<
  "prices",
  `sku:${string}`,
  typeof Schema.Int
>("prices", {
  value: Schema.Int,
  ttl: "5 minutes",
}) {}

Attaching to a service

export const PricingService = k.service("pricing", {
  resources: [PriceCache],
  operations: { /* ... */ },
})

Operations reference

Singleflight getOrCompute

When 100 concurrent requests miss the same key at once, getOrCompute runs compute() once through an Effect Deferred and returns the result to all waiters. This prevents duplicate concurrent load on your database or upstream APIs:

const price = await keel.prices.getOrCompute(
  `sku:${sku}`,
  async () => {
    const row = await keel.products.getById(sku)
    return { cents: row.priceCents, currency: "USD" }
  },
  {
    ttl: "10 minutes",
    tags: [`category:${category}`, "catalog"],
  }
)

Manual get, set, and tag invalidation

// Direct read & write
const cached = await keel.prices.get(`sku:${sku}`) // Price | undefined
await keel.prices.set(`sku:${sku}`, { cents: 2900, currency: "USD" }, {
  ttl: "5 minutes",
  tags: ["catalog", `sku:${sku}`],
})

// Invalidate one key
await keel.prices.invalidate(`sku:${sku}`)

// Invalidate an entire group of entries by tag
await keel.prices.invalidateTag("catalog")

Built-in metrics

Every cache lookup increments KeelMetrics.cacheRequestsTotal (keel_cache_requests_total), tagged with the cache name and outcome: "hit" | "miss".

SDK and Effect API mapping

SDK method (keel.<cache>.*) Effect function (@chimp-labs/keel/cache) Description
get(key) cacheGet(cache, key) Looks up a cached entry (T | undefined or Option<T>).
set(key, value, { ttl?, tags? }) cacheSet(cache, key, value, opts) Writes an entry with an optional TTL override and tags.
getOrCompute(key, fn, { ttl?, tags? }) cacheGetOrCompute(cache, key, effect, opts) Performs a read-through lookup with singleflight coalescing.
invalidate(key) cacheInvalidate(cache, key) Evicts a single key.
invalidateTag(tag) cacheInvalidateTag(tag) Evicts all keys associated with tag.

Errors and failure modes

Error tag Category HTTP status Retryable When it occurs
CacheError internal 500 Yes Underlying cache store failure
SchemaError invalid 400 No Value fails schema encoding or decoding

Keel propagates errors from the getOrCompute compute function to callers without caching them.


Backends and infrastructure

  • Memory uses an in-process TTL cache with a tag index and Deferred-based singleflight coordination.
  • PostgreSQL 17 (KeelPostgresLive / backend: "postgres"), SQLite, and SurrealDB 4 use in-process CacheStoreMemory (TTL, tags, and Deferred singleflight) by default with createKeel. You can also supply a custom CacheStore layer, for example over PostgreSQL or Redis, for shared multi-replica caching.

Testing in Memory

await using keel = await createKeel({
  backend: "memory",
  resources: { prices: PriceCache },
})

let calls = 0
const [a, b] = await Promise.all([
  keel.prices.getOrCompute("sku:1", async () => {
    calls++
    return { cents: 1500, currency: "USD" }
  }, { tags: ["all"] }),
  keel.prices.getOrCompute("sku:1", async () => {
    calls++
    return { cents: 1500, currency: "USD" }
  }, { tags: ["all"] }),
])
// calls === 1 (coalesced), a.cents === 1500, b.cents === 1500

await keel.prices.invalidateTag("all")
// await keel.prices.get("sku:1") === undefined