🪢 Langfuse 图解教程Langfuse Visual Guide 第四部分 · 查询链路Part 4 · The Read Path 21 / 55
第四部分 · 查询链路Part 4 · The Read Path

tRPC 骨架The tRPC backbone

🧭 读前Before you start
先读 第20课 的 web 架构,本课讲贯穿前后端的 tRPC 骨架。
Read Lesson 20 on the web architecture; this lesson covers the tRPC backbone spanning front and back.

上一课点出了三道门,这一课推开「员工通道」——tRPC,看它的骨架。tRPC 是 UI 与后端之间类型安全的契约:后端定义的类型,前端调用时一路贯穿, 改一处、全链路即时报错。它的结构出奇地简洁:一个根路由聚合约 62 个功能路由,加一小撮「procedure 构建器」用分层中间件统一把守鉴权与 RBAC。 看懂这套中间件栈,你就看懂了 Langfuse 整个 UI 后端的安检与脉络。

🛂 生活类比
把每个 tRPC 请求想成走一条安检走廊。走廊里一道道关卡就是中间件:先有摄像头记录你来过(OTel 追踪),再有应急员守着随时接住异常(错误处理), 然后是身份核验(你登录了吗),最后是门禁名单(你在这个房间的准入名单上吗——即「你是这个 project 的成员吗」)。 不同的门(procedure)配不同数量的关卡:公开的门只过前两关,受保护的门要全程走完。关卡定义一次,每道门按需挑选——这就是 procedure 构建器的精髓。

procedure = 可叠加的中间件栈

tRPC 的精髓在于:procedure(过程)是一摞中间件叠出来的。每个中间件干一件事,按 .use() 顺序串起来;不同的 procedure 构建器叠不同的关卡。 Langfuse 在 web/src/server/api/trpc.ts 里定义了一组:从只过基础关卡的 publicProcedure,到层层加码的 protectedProjectProcedure。

procedure 构建器:一层层叠中间件 publicProcedure ① OTel 追踪 ② 错误处理 谁都能调(如健康检查) authenticatedProcedure ① OTel ② 错误处理 ③ 你登录了吗enforceUserIsAuthed 需登录(账号级操作) protectedProjectProcedure ① OTel ② 错误处理 ③ 你是这个 project 成员吗从输入取 projectId + 校验 绝大多数业务路由(traces/scores/…) 越往右关卡越多:定义一次中间件,每道门按需 .use() 挑选——RBAC 不必每个路由重写
分层中间件,按需组合:publicProcedure(OTel+错误处理) → authenticatedProcedure(+登录校验) → protectedProjectProcedure(+项目成员 RBAC)。还有 protectedOrganizationProcedure、protectedGetTraceProcedure 等变体。源码:web/src/server/api/trpc.ts:238-583。
示例:一次类型安全的 tRPC 调用 React 组件 tRPC client/link protectedProjectProcedure procedure +仓储层 ClickHouse ① trace.list (typed input) ② 校验归属:属于此 project? ③ 执行 + 调仓储 ④ SELECT … WHERE project_id ⑤ rows → 同一类型原路返回
一条类型从头贯到尾(依据 web/src/server/api/trpc.ts):组件发的 query 与服务端 procedure 共享同一份 TypeScript 类型,所以前后端对不齐会在编译期报错。关键一步是 protectedProjectProcedure 中间件——任何 procedure 跑之前先校验你属不属于这个 project(第 10、48 课鉴权)。
web/src/server/api/trpc.tsprocedure 构建器
const withOtelTracingProcedure = t.procedure.use(withOtelInstrumentation);

// 公开:只过 OTel + 错误处理
export const publicProcedure = withOtelTracingProcedure.use(withErrorHandling);

// 需登录:再叠一层「你登录了吗」
export const authenticatedProcedure = withOtelTracingProcedure
  .use(withErrorHandling).use(enforceUserIsAuthed);

// 受保护(项目级):再叠一层「你是这个 project 的成员吗」——最常用
export const protectedProjectProcedure = withOtelTracingProcedure
  .use(withErrorHandling).use(enforceUserIsAuthedAndProjectMember);

注意每道门最先叠的两层——OTel 追踪与错误处理——是所有 procedure 的共同底座。错误处理这一层(withErrorHandling)尤其用心: 它把 resolver 抛出的异常统一翻译成对前端友好的形态——隐藏 5xx 的内部细节与堆栈(防泄露),还特别照顾 ClickHouse 的资源类错误(内存超限、查询超时), 把它们映射成 UNPROCESSABLE_CONTENT 并附上「换个更小的时间范围试试」之类的可操作建议。于是无论哪个路由、查崩了什么,用户看到的都是一致、可读、不暴露内幕的错误。

一次 UI 查询的旅程,与 RBAC 的关键一招

把这套骨架放进真实数据流里看。UI 里一个 React Query 钩子(如 api.traces.all.useQuery)发起调用,经过统一入口 pages/api/trpc/[trpc].ts, 先由 createTRPCContext 注入上下文——把 { session, headers, prisma } 挂上每个请求(session 来自 NextAuth);再走中间件栈,最后到路由的 resolver, 调 @langfuse/shared 的仓储/服务读 ClickHouse/Postgres:

一次 tRPC 查询从前端到数据库 UI 钩子api.traces.all.useQuery tRPC 入口[trpc].ts + context注入 session/prisma 中间件栈OTel→错误→鉴权RBAC 在此把守 路由 resolvertraceRouter.all(62 个路由之一) shared 仓储/服务@langfuse/shared→ ClickHouse / Postgres 类型贯穿全链路:resolver 的返回类型,前端 useQuery 拿到时即已知 改后端字段 → 前端编译即报错,这是 tRPC 相对 REST 的最大不同 仓储层、过滤、读模型的细节 → 第 22–25 课
从钩子到数据库:createTRPCContext(trpc.ts:57)把 {session, headers, prisma} 注入每个请求;中间件栈把守鉴权/RBAC;resolver 调 @langfuse/shared 仓储读库。返回类型一路贯穿到前端。源码:root.ts:70(appRouter 聚合 ~62 路由)。

那个被注入每个请求的 context 看似不起眼,却是整套机制的地基——它把「这次请求是谁、带了什么、能用哪些工具」一次性备齐:

session你是谁(NextAuth)
当前登录用户及其「组织 → 项目」成员树。RBAC 中间件正是查这棵树,判断你能否访问某个 project——身份信息随 session 一起到,不必每次查库。
headers这次请求带了什么
原始请求头,供限流、追踪、特性标志等横切关注点使用——比如根据来源限速、或把请求关联到一条 OTel trace。
prisma能用哪些工具
Postgres 客户端(第 9 课),让 resolver 与中间件能读控制面数据(如 admin 兜底查 project 的归属组织)。ClickHouse 则由仓储层按需取(第 22 课)。

RBAC 最关键的一招,藏在 enforceUserIsAuthedAndProjectMember 里:它不等 resolver 跑,而是在中间件阶段就从请求输入里把 projectId 抠出来, 再去 session 里查「你是不是这个 project 的成员」。这样一来,每个受保护路由都自动获得统一的租户校验,无需各写一遍,也不会因为某个路由作者一时疏忽而留下后门(呼应第 10 课「project_id 是隔离键」):

请求输入 { projectId, … } RBAC 中间件(resolver 之前) ① 抠出 projectId(parse 原始输入) ② 查 session 的 组织→项目 成员树 ③ 是成员 或 admin? 每个受保护路由自动统一校验 session.user.organizations .flatMap(projects).find(id) ✓ 放行 → resolver 读库 ✗ throw 403 FORBIDDEN
web/src/server/api/trpc.tsenforceUserIsAuthedAndProjectMember :288
const enforceUserIsAuthedAndProjectMember = t.middleware(async (opts) => {
  if (!ctx.session?.user) throw new TRPCError({ code: "UNAUTHORIZED" });

  // 关键:在 resolver 之前,就从原始输入里取出 projectId
  const input = inputProjectSchema.parse(await opts.getRawInput());

  // 在 session 的「组织 → 项目」树里找:你是这个 project 的成员吗?
  const member = ctx.session.user.organizations
    .flatMap((org) => org.projects)
    .find((p) => p.id === input.projectId);
  if (!member && !ctx.session.user.admin) throw new TRPCError({ code: "FORBIDDEN" });
  return next({ /* 把校验过的 scope 挂进 ctx */ });
});
procedure叠了哪些关卡用在哪
publicProcedureOTel + 错误处理无需登录(健康检查、公开分享)
authenticatedProcedure+ 登录校验账号级、跨项目操作
protectedProjectProcedure+ 项目成员 RBAC绝大多数业务路由(traces/scores/…)
protectedOrganizationProcedure+ 组织成员校验组织级管理
protectedGetTraceProcedure+ trace 访问校验(含公开 trace)单条 trace 读取(允许公开分享)

😖 假如每个路由各写鉴权

62 个路由各自手写「检查登录、检查项目成员」。只要有一个人忘了写、或写得不一致,那一处就成了租户隔离的破口——别的项目的数据可能被读走。安全代码最怕这种「一处疏漏」。

😀 收敛成中间件 + procedure

校验写一次、测一次,路由作者只需选对那道门(protectedProjectProcedure),RBAC 就自动统一生效。新增路由几乎不可能漏掉租户校验——安全靠结构兜底。

🎯 设计取舍
为什么把鉴权做成「中间件 + procedure 构建器」,而不是在每个路由里各写一遍 if 判断? 因为安全代码最怕「漏写」和「写歪」。 如果 62 个路由各自手写「检查登录、检查项目成员」,迟早有人会忘掉一处、或写得不一致——而那一处就是租户隔离的破口。把校验收敛成几个中间件、 再用 procedure 构建器声明式地组合,路由作者只需选对「门」(protectedProjectProcedure),RBAC 就自动、统一地生效。 更妙的是「从输入里取 projectId」这一招:它让校验先于业务逻辑发生,任何受保护路由都不可能在没核验租户的情况下碰到数据。 这正是第 6 课「把复杂度收敛到一处能严格测试的地方」、第 10 课「project_id 是隔离键」在 API 层的落地——安全靠结构保证,而非靠每个人自觉。
🎯 本课要点
  • tRPC 是 UI↔后端的类型安全契约:一个根路由 appRouter(root.ts:70)聚合约 62 个功能路由,返回类型一路贯穿到前端。
  • context(createTRPCContext)给每个请求注入 { session, headers, prisma };session 来自 NextAuth。
  • procedure = 可叠加的中间件栈:publicProcedure(OTel+错误处理) → authenticatedProcedure(+登录) → protectedProjectProcedure(+项目 RBAC)。
  • RBAC 关键招:enforceUserIsAuthedAndProjectMember 在中间件阶段从输入取 projectId、校验 session 成员资格——统一、先于 resolver(呼应第 10 课)。
  • 取舍:把鉴权收敛成中间件 + 声明式 procedure,避免 62 个路由各写各错;安全靠结构保证、而非靠人人自觉(第 6 课)。错误处理还会把 ClickHouse 资源错误翻成友好提示。

🧪 自测 · 想一想为什么这么设计

1. Langfuse 用 procedure 构建器(publicProcedure / authenticatedProcedure / protectedProjectProcedure)来定义 tRPC 接口。这种「分层中间件栈」的本质是什么?
  1. procedure 是一摞中间件按 .use() 叠出来的;公开门只过 OTel+错误处理,受保护门再叠登录、项目成员校验。中间件定义一次,每个路由按需挑选——RBAC 不必各写一遍
  2. 中间件只能用一个,不能叠加
  3. procedure 只是给接口起个名字,无实际作用
  4. 每个路由都必须手写完整的鉴权逻辑
看答案与解析 点击展开
答案:A。tRPC 的精髓是 procedure = 可叠加的中间件栈。withOtelTracingProcedure 叠 OTel,再 .use(withErrorHandling) 得 publicProcedure,再 .use(enforceUserIsAuthed) 得 authenticatedProcedure,再换成 enforceUserIsAuthedAndProjectMember 得 protectedProjectProcedure。声明式组合让安全检查写一次、处处复用。
2. protectedProjectProcedure 的 RBAC 中间件做了一件关键的事:它在 resolver 跑之前就从请求输入里取出 projectId。为什么这一招重要?
  1. 为了让请求更快返回
  2. projectId 只是用来打日志
  3. 校验先于业务逻辑发生:任何受保护路由都不可能在没核验「你是这个 project 成员」之前碰到数据,租户隔离由结构保证,而非靠每个路由作者自觉
  4. 为了节省数据库连接
看答案与解析 点击展开
答案:C。enforceUserIsAuthedAndProjectMember 用 getRawInput() 取出 projectId,再去 session 的「组织→项目」树里查成员资格,不通过就抛 FORBIDDEN。这让每个受保护路由自动获得统一、前置的租户校验——正是第 10 课「project_id 是隔离键」在 API 层的落地,安全靠结构而非靠人。
3. 所有 procedure 最底层都叠了 withErrorHandling 这一中间件。它对 ClickHouse 的资源类错误(内存超限、超时)做了什么特殊处理?
  1. 自动重试一百次
  2. 忽略错误,返回空结果
  3. 直接把原始堆栈和 SQL 返回给前端
  4. 把它们映射成 UNPROCESSABLE_CONTENT 并附上「换个更小的时间范围」之类可操作建议;同时隐藏 5xx 内部细节与堆栈,防止泄露
看答案与解析 点击展开
答案:D。withErrorHandling 统一翻译异常:5xx 隐藏内部细节防泄露;ClickHouse 资源错误(如内存/超时)被特判为 UNPROCESSABLE_CONTENT,并给出「缩小时间范围」等用户能照做的建议。于是无论哪个路由查崩了什么,用户看到的都是一致、可读、不暴露内幕的错误。
💭 发散思考(没有标准答案,动手或动脑想想)
  • 「把安全检查收敛成中间件、用声明式 procedure 组合,而不是每个接口各写一遍」——这条原则你能用到自己的系统吗?如果你的 API 有几十个端点都要做同一种权限校验,你会怎么设计,才能让「新增端点几乎不可能漏掉校验」?

Last lesson named the three doors; this one pushes open the "staff entrance" — tRPC — and shows its skeleton. tRPC is the type-safe contract between UI and server: types the backend defines flow end to end to the frontend caller, so a change in one place errors the whole chain instantly. Its structure is surprisingly lean: one root router aggregates ~62 feature routers, plus a handful of "procedure builders" that guard auth and RBAC uniformly via layered middleware. Grasp this middleware stack and you grasp the security and the flow of Langfuse's entire UI backend.

🛂 Analogy
Think of each tRPC request as walking a security corridor. The checkpoints along it are the middleware: first a camera logs that you came (OTel tracing), then a responder stands ready to catch exceptions (error handling), then an ID check (are you logged in), and finally the guest list (are you on the access list for this room — i.e. "are you a member of this project"). Different doors (procedures) carry different numbers of checkpoints: a public door passes only the first two, a protected door walks them all. Define a checkpoint once, each door picks what it needs — that's the essence of procedure builders.

A procedure = a stackable middleware chain

The essence of tRPC: a procedure is built by stacking middleware. Each middleware does one thing, chained in .use() order; different procedure builders stack different checkpoints. Langfuse defines a set in web/src/server/api/trpc.ts: from the bare-bones publicProcedure to the layered protectedProjectProcedure.

Procedure builders: stacking middleware, layer by layer publicProcedure ① OTel tracing ② error handling anyone can call(e.g. health check) authenticatedProcedure ① OTel ② error handling ③ are you logged inenforceUserIsAuthed login required(account-level ops) protectedProjectProcedure ① OTel ② error handling ③ member of this project?pull projectId from input + check most business routers(traces/scores/…) more checkpoints to the right: define middleware once, each door .use()s what it needs — no per-router RBAC rewrite
Layered middleware, composed on demand: publicProcedure(OTel+error) → authenticatedProcedure(+login) → protectedProjectProcedure(+project-member RBAC). Plus variants protectedOrganizationProcedure, protectedGetTraceProcedure. Source: web/src/server/api/trpc.ts:238-583.
Example: one type-safe tRPC call React component tRPC client/link protectedProjectProcedure procedure +repository ClickHouse ① trace.list (typed input) ② check membership in project? ③ run + call repository ④ SELECT … WHERE project_id ⑤ rows → typed result back
One type runs end to end (per web/src/server/api/trpc.ts): the component's query and the server procedure share the same TypeScript types, so a front/back mismatch fails at compile time. The key step is the protectedProjectProcedure middleware — before any procedure runs it checks project membership first (Lessons 10, 48).
web/src/server/api/trpc.tsprocedure builders
const withOtelTracingProcedure = t.procedure.use(withOtelInstrumentation);

// public: only OTel + error handling
export const publicProcedure = withOtelTracingProcedure.use(withErrorHandling);

// authenticated: add a "are you logged in" layer
export const authenticatedProcedure = withOtelTracingProcedure
  .use(withErrorHandling).use(enforceUserIsAuthed);

// protected (project-level): add "are you a member of this project" — the most used
export const protectedProjectProcedure = withOtelTracingProcedure
  .use(withErrorHandling).use(enforceUserIsAuthedAndProjectMember);

Note the first two layers every door stacks — OTel tracing and error handling — are the common base of all procedures. The error-handling layer (withErrorHandling) is especially careful: it uniformly translates resolver exceptions into a frontend-friendly form — hiding 5xx internal detail and stacks (no leaks), and specially caring for ClickHouse resource errors (out-of-memory, query timeout), mapping them to UNPROCESSABLE_CONTENT with actionable advice like "try a smaller time range". So whatever router, whatever blew up, the user sees a consistent, readable error that doesn't expose the internals.

A UI query's journey, and RBAC's key move

Put this skeleton into a real data flow. A React Query hook in the UI (e.g. api.traces.all.useQuery) fires a call, through the unified entry pages/api/trpc/[trpc].ts; first createTRPCContext injects the context — attaching { session, headers, prisma } to every request (session from NextAuth); then the middleware stack runs, finally reaching the router's resolver, which calls a @langfuse/shared repository/service to read ClickHouse/Postgres:

One tRPC query from frontend to database UI hookapi.traces.all.useQuery tRPC entry[trpc].ts + contextinject session/prisma middleware stackOTel→error→authRBAC guards here router resolvertraceRouter.all(one of ~62 routers) shared repo/service@langfuse/shared→ ClickHouse / Postgres Types thread the whole chain: the resolver's return type is known when useQuery receives it change a backend field → the frontend errors at compile time — tRPC's biggest difference from REST repository, filtering, read-model details → Lessons 22–25
From hook to database: createTRPCContext (trpc.ts:57) injects {session, headers, prisma} into every request; the middleware stack guards auth/RBAC; the resolver calls a @langfuse/shared repository. The return type threads all the way to the frontend. Source: root.ts:70 (appRouter aggregates ~62 routers).

That context injected into every request looks unremarkable but is the bedrock — it gathers, in one shot, "who is this request, what did it carry, what tools may it use":

sessionwho you are (NextAuth)
The current logged-in user and their "organization → project" membership tree. The RBAC middleware reads exactly this tree to decide whether you can access a project — identity arrives with the session, no per-request DB lookup.
headerswhat the request carried
Raw request headers, used by cross-cutting concerns like rate limiting, tracing, feature flags — e.g. rate-limit by source, or tie the request to an OTel trace.
prismawhat tools you may use
The Postgres client (Lesson 9), letting resolvers and middleware read control-plane data (e.g. the admin fallback looking up a project's owning org). ClickHouse is fetched on demand by the repository layer (Lesson 22).

RBAC's key move hides in enforceUserIsAuthedAndProjectMember: rather than waiting for the resolver, it pulls projectId out of the request input at the middleware stage, then checks the session for "are you a member of this project". This way every protected router gets uniform tenant checking automatically, never re-written per router, and no backdoor left by one router author's lapse (echoing Lesson 10's "project_id is the isolation key"):

request input { projectId, … } RBAC middleware (before resolver) 1 pull projectId (parse raw input) 2 look up in session org→project tree 3 member or admin? every protected router, checked uniformly session.user.organizations .flatMap(projects).find(id) ✓ proceed → resolver reads DB ✗ throw 403 FORBIDDEN
web/src/server/api/trpc.tsenforceUserIsAuthedAndProjectMember :288
const enforceUserIsAuthedAndProjectMember = t.middleware(async (opts) => {
  if (!ctx.session?.user) throw new TRPCError({ code: "UNAUTHORIZED" });

  // key: pull projectId out of the raw input, before the resolver
  const input = inputProjectSchema.parse(await opts.getRawInput());

  // search the session's "org → project" tree: are you a member of this project?
  const member = ctx.session.user.organizations
    .flatMap((org) => org.projects)
    .find((p) => p.id === input.projectId);
  if (!member && !ctx.session.user.admin) throw new TRPCError({ code: "FORBIDDEN" });
  return next({ /* attach the verified scope to ctx */ });
});
procedurecheckpoints stackedused where
publicProcedureOTel + error handlingno login (health check, public share)
authenticatedProcedure+ login checkaccount-level, cross-project ops
protectedProjectProcedure+ project-member RBACmost business routers (traces/scores/…)
protectedOrganizationProcedure+ org-member checkorg-level admin
protectedGetTraceProcedure+ trace-access check (incl. public traces)single-trace reads (allows public share)

😖 if each router wrote its own auth

62 routers each hand-write "check login, check project membership". One person forgetting it, or writing it inconsistently, and that spot becomes a tenant-isolation breach — another project's data could be read. Security code dreads exactly this "single omission".

😀 converged into middleware + procedure

The check is written once, tested once; a router author just picks the right door (protectedProjectProcedure) and RBAC applies automatically and uniformly. A new router can hardly miss tenant checking — security backstopped by structure.

🎯 Design trade-off
Why make auth a "middleware + procedure builder" rather than an if-check hand-written in each router? Because security code most fears "omission" and "drift". If 62 routers each hand-write "check login, check project membership", sooner or later someone forgets one, or writes it inconsistently — and that one spot is a hole in tenant isolation. Converging the checks into a few middleware, then composing them declaratively via procedure builders, means a router author only picks the right "door" (protectedProjectProcedure) and RBAC takes effect automatically and uniformly. Even better is the "pull projectId from the input" move: it makes the check happen before business logic, so no protected router can ever touch data without verifying the tenant first. This is Lesson 6's "converge complexity into one strictly testable place" and Lesson 10's "project_id is the isolation key" landing at the API layer — security guaranteed by structure, not by everyone's diligence.
🎯 Key points
  • tRPC is the type-safe contract between UI and backend: one root router appRouter (root.ts:70) aggregates ~62 feature routers, the return type threading to the frontend.
  • context (createTRPCContext) injects { session, headers, prisma } into every request; session from NextAuth.
  • A procedure = a stackable middleware chain: publicProcedure(OTel+error) → authenticatedProcedure(+login) → protectedProjectProcedure(+project RBAC).
  • RBAC's key move: enforceUserIsAuthedAndProjectMember pulls projectId from the input at the middleware stage and checks session membership — uniform, before the resolver (echoing Lesson 10).
  • Tradeoff: converging auth into middleware + declarative procedures avoids 62 routers each writing (and mis-writing) it; security guaranteed by structure (Lesson 6). The error layer also turns ClickHouse resource errors into friendly advice.

🧪 Self-test - think about the design

1. Langfuse defines tRPC endpoints with procedure builders (publicProcedure / authenticatedProcedure / protectedProjectProcedure). What's the essence of this 'layered middleware stack'?
  1. a procedure is a stack of middleware chained by .use(); a public door passes only OTel+error handling, a protected door adds login and project-member checks. Middleware is defined once and each router picks what it needs — RBAC isn't rewritten per router
  2. only one middleware is allowed, no stacking
  3. procedures just name endpoints, with no real effect
  4. every router must hand-write full auth logic
Show answer & explanation click to expand
Answer: A. tRPC's essence is procedure = stackable middleware. withOtelTracingProcedure adds OTel, then .use(withErrorHandling) gives publicProcedure, then .use(enforceUserIsAuthed) gives authenticatedProcedure, then swapping in enforceUserIsAuthedAndProjectMember gives protectedProjectProcedure. Declarative composition lets a security check be written once and reused everywhere.
2. protectedProjectProcedure's RBAC middleware does one key thing: it pulls projectId from the request input before the resolver runs. Why does this matter?
  1. to make requests return faster
  2. projectId is only used for logging
  3. the check happens before business logic: no protected router can ever touch data before verifying 'you're a member of this project', so tenant isolation is guaranteed by structure, not by each router author's diligence
  4. to save database connections
Show answer & explanation click to expand
Answer: C. enforceUserIsAuthedAndProjectMember pulls projectId via getRawInput(), then checks membership in the session's 'org→project' tree, throwing FORBIDDEN otherwise. This gives every protected router uniform, up-front tenant checking — Lesson 10's 'project_id is the isolation key' landing at the API layer, security by structure not by people.
3. All procedures stack withErrorHandling at the base. What special handling does it give ClickHouse resource errors (out-of-memory, timeout)?
  1. automatically retries a hundred times
  2. ignores the error and returns empty results
  3. returns the raw stack and SQL straight to the frontend
  4. maps them to UNPROCESSABLE_CONTENT with actionable advice like 'try a smaller time range'; and hides 5xx internal detail and stacks to prevent leaks
Show answer & explanation click to expand
Answer: D. withErrorHandling uniformly translates exceptions: 5xx hides internal detail to prevent leaks; ClickHouse resource errors (memory/timeout) are special-cased to UNPROCESSABLE_CONTENT with actionable advice like 'narrow the time range'. So whatever router blew up, the user sees a consistent, readable error that doesn't expose internals.
💭 Open questions (no single right answer - just think or try)
  • 'Converge security checks into middleware and compose via declarative procedures, rather than hand-writing per endpoint' — can you apply this to your systems? If your API has dozens of endpoints all needing the same permission check, how would you design it so 'a new endpoint can hardly miss the check'?