Skip to Content
Athanor

The entity cache

One use cache function for the whole graph, keyed by typename and id, with a bucketed clock so a cached read is deterministic.

One function for the whole graph. Not one per node.

// server/athanor/cached.ts
export const cachedLoad = async (
  typename: string,
  id: string,
): Promise<CachedEntity> => {
  "use cache";
  const node = Athanor.types.get(typename);
  if (node?.cacheLife === undefined || node.cacheTag === undefined) return null;
  cacheLife(node.cacheLife);
  cacheTag(node.cacheTag(id));
  return graphRuntime.runPromise(
    node.load([id]).pipe(
      Effect.map((rows) => rows.get(id) ?? null),
      Effect.provide(BucketedClock.make(bucket[node.cacheLife])),
    ),
  );
};

Why this works, and why there is no per-node shell:

  • Only "use cache" is lexical. cacheLife and cacheTag read an async-local store and can be called from anywhere inside the boundary.
  • A cached function keys on its arguments. (typename, id) is both serializable and exactly the key an entity cache wants — so the node is looked up from inside the boundary.
  • BucketedClock is not optional. Effect reads the Clock service, and a wall-clock read inside use cache throws a prerender error or silently freezes to build time. Flooring "now" to the cacheLife window makes it deterministic and honestly "as of this window". Because the profile and the bucket both come from node.cacheLife, they cannot disagree.

readNode prefers this whenever a node declares a cacheLife; otherwise it uses the batched loader. They are alternatives, not layers — a cached read is per id and cannot batch, while the loader is one query of N that shares nothing across requests.