Batching and caching

Backend request batching and caching#

A pipeline can turn one client request into many related server reads. Use Effect's Request, RequestResolver, and Cache APIs to prevent those reads from becoming N+1 downstream queries.

Define a bulk resolver#

RequestBatching.cache supplies a resolver identity and cache for each pipeline request:

ts
import * as Cache from "effect/Cache"
import * as Effect from "effect/Effect"
import * as Exit from "effect/Exit"
import * as Request from "effect/Request"
import * as RequestResolver from "effect/RequestResolver"

class GetUser extends Request.TaggedClass("GetUser")<
  { readonly id: string },
  User,
  UserNotFound
> {}

const UserResolver = RequestResolver.make<GetUser>((entries) =>
  Effect.gen(function*() {
    const ids = Array.from(new Set(entries.map((entry) => entry.request.id)))
    const users = yield* Users.findMany(ids)
    const byId = new Map(users.map((user) => [user.id, user]))

    for (const entry of entries) {
      const user = byId.get(entry.request.id)
      entry.completeUnsafe(user
        ? Exit.succeed(user)
        : Exit.fail(new UserNotFound({ id: entry.request.id })))
    }
  })
)

const UserCache = RequestBatching.cache(UserResolver, {
  capacity: 1_024,
  timeToLive: (exit) => Exit.isSuccess(exit) ? "30 seconds" : 0
})

Wire the handlers#

Use the cache in handlers. The supplied middleware also makes it available to standalone RPC calls:

ts
const UserRpcs = RpcGroup.make(
  Rpc.make("getUser", {
    payload: { id: Schema.String },
    success: User,
    error: UserNotFound
  })
).middleware(RequestBatching.Middleware)

const UserHandlers = UserRpcs.toLayer({
  getUser: ({ id }) => Effect.flatMap(
    UserCache,
    Cache.get(new GetUser({ id }))
  )
})

const Routes = PipelineServer.layerHttp({
  group: UserRpcs,
  path: "/rpc"
}).pipe(
  Layer.provide(UserHandlers),
  Layer.provide(RequestBatching.layer)
)

Concurrent reads for the same key share a cache miss. Different missing keys reach the resolver as a batch. The cache and resolver identity are discarded after the pipeline.

Unrelated requests and transactions therefore do not reuse those cached values.

Partition and invalidate the cache#

When one graph can use several tenants or users, include that identity in the Request key or partition the cache:

ts
const UserCache = RequestBatching.cache(UserResolver, {
  capacity: 1_024,
  partition: Effect.map(CurrentUser, (user) => user.tenantId)
})

Mutations should invalidate affected entries before a later query phase. Batching is not automatic for arbitrary repository effects: handlers must use the request-scoped cache, and the resolver must perform a real bulk operation.