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

公共 REST APIThe public REST API

🧭 读前Before you start
先读 第21课 的 tRPC 与 第12课 的摄取,本课讲对外的公共 REST API。
Read Lesson 21 (tRPC) and Lesson 12 (ingestion); this lesson covers the outward-facing public REST API.

第 21 课开的是给自家 UI 的「员工通道」(tRPC)。这一课开第三道门也是最后一道——给外部 SDK 的公共 REST API。它的优先级和 tRPC 截然不同:对内求类型安全、改得快, 对外求契约稳定、扛得住量。这一课看四件事:一个路由工厂怎么统一所有端点的鉴权/限流/校验,鉴权怎么用 Redis 缓存扛住海量请求, 版本怎么靠文件夹管理,以及一份 Fern 契约怎么生成多语言 SDK。看完这一课,第 20 课「三道门」就全开齐了。

🏛️ 生活类比
把公共 REST API 想成一座政府大楼的对外服务大厅。不管你来办哪种业务(查 trace、提交 score、拉 dataset),都先走同一道安检与叫号流程(路由工厂:验证件、限流、查表格填得对不对)—— 没人能绕开。常来的人,证件信息被前台缓存下来,下次不必每回都回档案室核查(Redis 缓存鉴权)。大厅的办事规程印成了手册,还翻译成各种语言发给你(Fern 生成多语言 SDK); 规程更新时,旧版手册仍然有效,新规程发布成「v2」,老用户不受影响(按文件夹版本化)。统一、稳定、可缓存、带版本——这就是一个对外 API 该有的样子。

一个路由工厂,统一所有端点

就像 tRPC 用 procedure 构建器把鉴权收敛到一处(第 21 课),公共 REST 用一个路由工厂 createAuthedProjectAPIRoute 把所有端点的「规定动作」收敛到一处。 每个端点只需声明自己的 query/body/response schema 和限流资源,工厂就统一把这几关跑完:

createAuthedProjectAPIRoute:每个端点的统一流水线 SDK 请求Basic/Bearer ① 鉴权key→project (缓存) ② 访问级别project / scores ③ 限流按资源/计划 ④ Zod 校验query/body ⑤ 你的 handlerOTel surface=publicapi 这五关由工厂统一跑——端点只声明 schema,不重复写鉴权/限流/校验 超大请求体→ PayloadTooLargeError 响应也校验(开发期)防契约漂移
对外端点的统一流水线:createAuthedProjectAPIRoute 依次跑鉴权(key→project,含访问级别)→ 限流 → Zod 校验 query/body → 在 OTel 上下文(surface=publicapi)里跑你的 handler → 校验响应(开发期防契约漂移);请求体过大 → PayloadTooLargeError。源码:web/src/features/public-api/server/createAuthedProjectAPIRoute.ts。
示例:一次公共 REST 调用与响应 curl -u pk:sk GET https://cloud.langfuse.com/api/public/traces/chat_a1b2 200 OK { "id":"chat_a1b2", "name":"chat-support", "userId":"u_42", "timestamp":"2025-…Z", "totalCost":0.0042, "latency":1.93, "observations":[ {"id":"obs_7f","type":"GENERATION","model":"gpt-4o", …}, … ], "scores":[ {"name":"helpfulness","value":0.9} ] } 同一套领域对象,REST/SDK/Fern 多语言客户端共用
对外的同一套领域对象(端点对齐 web/src/pages/api/public/traces;值为示例):用 pk:sk 做 Basic 认证 GET /api/public/traces/{{id}},拿回一个 JSON——里面是你在 UI 里看到的同一个 trace:observations[]、scores[]、totalCost、latency。Fern 据 API 定义生成多语言 SDK,所以 REST 和各语言客户端拿到的形状一致。
web/src/features/public-api/server/createAuthedProjectAPIRoute.ts路由工厂
// 每个端点只声明 schema 与限流资源,工厂统一跑鉴权/限流/校验/OTel
export const handler = createAuthedProjectAPIRoute({
  name: "Get Traces",
  querySchema: GetTracesV1Query,   bodySchema: z.never(),
  responseSchema: GetTracesV1Response,
  rateLimitResource: "public-api",
  allowedAccessLevels: ["project"],  // 这个端点要 project 级 key
  fn: async ({ query, auth }) => { /* 只写业务:此时已鉴权+校验完毕 */ },
});

这正是第 21 课「安全靠结构」在 REST 侧的翻版:鉴权、限流、Zod 校验不靠每个端点作者自觉,而是工厂强制跑完。 区别在优先级——tRPC 那套是给内部的,REST 这套多了限流(防外部滥用)、响应校验(防对外契约漂移)、访问级别(如 Bearer 只读 score)这些面向公众才需要的关卡。

tRPC(第 21 课 · 对内)公共 REST(本课 · 对外)
给谁自家 UI(同仓库、同团队)外部 SDK / 用户脚本(海量、长期)
首要价值类型安全、改得快契约稳定、扛得住量
收敛方式procedure 构建器(叠中间件)路由工厂 createAuthedProjectAPIRoute
额外关卡—限流、响应校验、访问级别
稳定手段编译期类型检查(改了即报错)文件夹版本 + Fern 契约 + 多语言 SDK

鉴权要扛量:Redis 缓存 + 负缓存

对外 API 每一个请求都要先验 key——而 SDK 可能每秒打来成千上万条。要是每条都回 Postgres 查 key,数据库会被鉴权本身压垮。 于是 ApiAuthService 给 key 验证套了一层 Redis 缓存:

缓存鉴权:让数据库别为「验 key」累垮 收到 API key先查 Redis ✅ 命中 → 直接返回 scope ❌ 未命中 → 回 Postgres 查 按 fastHashedSecretKey 查 + 回填 Redis 负缓存:key 不存在也记一笔(API_KEY_NON_EXISTENT)→ 用假 key 暴力打库时,第二次起直接被 Redis 挡回,不碰 Postgres 缓存命中 → 验 key 几乎零成本;负缓存 → 攻击者用不存在的 key 刷不动数据库 删除 key 时主动失效缓存——没有「更新」路径,只有「失效」
缓存正例、也缓存反例:鉴权先查 Redis,命中即返回;未命中回 Postgres 按 fastHashedSecretKey 查再回填。关键是负缓存:连「这个 key 不存在」也记下(API_KEY_NON_EXISTENT),让攻击者拿假 key 暴力打库时打不动数据库。源码:web/src/features/public-api/server/apiAuth.ts:75。

😖 不缓存:每请求都查库

SDK 每秒上万条请求,每条都回 Postgres 验一次 key——数据库的负载里很大一块是鉴权本身,业务还没开始就先被拖慢;攻击者拿一堆假 key 来刷,更是直接打在库上。

😀 缓存 + 负缓存:库几乎不碰

常用 key 命中 Redis,验 key 几乎零成本;连「不存在的 key」也被负缓存挡在 Redis 这一层。无论正常流量还是恶意刷量,Postgres 都被保护在后面,只在缓存未命中时才被惊动。

版本靠文件夹,契约靠 Fern

对外 API 一旦发布就不能随意改——可需求总在变,怎么办?Langfuse 的两招:用文件夹做版本、用 Fern 生成 SDK。

① 版本 = 文件夹(老路径永不改) public/ (v1) · 默认在根 public/v2/ public/v3/ · 可做减法 如 v3/scores 改用游标分页 ② 契约 = Fern(一处定义) Fern YAML fern/apis/{server,client} Python SDK TypeScript SDK OpenAPI 导出 版本化保证「旧的不破」,Fern 生成保证「多语言一致、契约即文档」
版本=文件夹v1 在根,v2/、v3/…
默认 v1 在 public/ 根,新版放进 v2/、v3/ 子文件夹。老路径永不改,你两年前的集成今天照跑;想要新能力就显式切到新版本。
新版可做减法去掉昂贵特性
新版本不只是加功能,也能砍掉代价大的旧设计:比如 v3/scores 去掉了需要 JOIN trace 的 userId/traceTags 过滤、改用游标分页——把「该用 v2」的话直接写进文档。
Fern 契约一份 YAML → 多语言 SDK
API 契约是手写的 Fern YAML(fern/apis/{server,client}/…),由它生成 Python 与 TypeScript SDK(generated/),还导出 OpenAPI。一处定义、处处一致。

这两招合起来,正是第 20 课说的「对外求契约稳定」的落地:版本化保证「旧的不破」,Fern 生成保证「多语言一致、契约即文档」。 配合开发期的响应 schema 校验(防手写实现和 Fern 契约悄悄漂移),整条对外通道既稳又不会偷偷变样。

🎯 设计取舍
同样是「把数据查出来」,为什么 UI 走 tRPC、SDK 却要这一整套 REST 工厂 + 缓存 + 版本 + Fern? 因为受众不同,约束就不同(呼应第 20 课)。 UI 是自家的、同仓库的,所以 tRPC 用类型贯穿换迭代速度,接口天天改也无妨。而 SDK 面向外部、海量、长期的用户:海量,所以鉴权必须能缓存(Redis + 负缓存),否则数据库被验 key 拖垮; 长期,所以接口必须带版本(文件夹 + Fern),否则一改就破坏别人两年前写的集成。同一个「把横切关注收敛到一处」的工厂模式(第 21、22 课), 在这里被赋予了面向公众的新内涵:限流防滥用、响应校验防契约漂移、缓存扛流量、版本保稳定。对内优化「改得快」,对外优化「不破坏」——这是同一套数据,两种工程价值观的分野。 至此,第 20 课的「三道门」全部走完:tRPC 给 UI、REST 给 SDK、App-Router 给流式/webhook,各按受众分而治之。
🎯 本课要点 · 第四部分收官
  • 一个路由工厂 createAuthedProjectAPIRoute 统一所有公共端点的鉴权 → 访问级别 → 限流 → Zod 校验 query/body → OTel(surface=publicapi) → 响应校验 → 超大体拒绝。
  • 鉴权用 Redis 缓存扛海量请求:命中即返回、未命中回 Postgres 按 fastHashedSecretKey 查再回填;负缓存(API_KEY_NON_EXISTENT)挡住假 key 暴力打库。
  • 版本靠文件夹:v1 在根、v2/v3 子文件夹;老路径永不改,新版可做减法(如 v3 scores 去掉需 JOIN 的过滤、改游标分页)。
  • 契约靠 Fern:手写 Fern YAML → 生成 Python/TS SDK + OpenAPI;开发期响应校验防手写实现与契约漂移。
  • 取舍:对内(tRPC)优化类型安全与速度,对外(REST)优化稳定与扛量——同一份数据、两种价值观。至此第 20 课「三道门」全开齐。

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

1. 公共 REST API 用一个路由工厂 createAuthedProjectAPIRoute 统一所有端点。和第 21 课 tRPC 的 procedure 构建器相比,它额外多了哪些「面向公众」的关卡?
  1. 更快的数据库连接
  2. 去掉了鉴权
  3. 限流(防外部滥用)、响应校验(防对外契约漂移)、访问级别(如 Bearer 只读 score)——都是对内 tRPC 不需要、对外才必须的关卡
  4. 更复杂的类型检查
看答案与解析 点击展开
答案:C。两套都用「工厂/构建器把横切关注收敛到一处」的同一模式,但优先级不同:tRPC 对内求速度,REST 对外求稳定与扛量,故多了限流、响应校验、访问级别。鉴权、Zod 校验则是两者共有——都不靠端点作者自觉,由工厂强制跑。
2. 对外 API 每个请求都要验 key,SDK 可能每秒上万条。Langfuse 的鉴权除了用 Redis 缓存命中的 key,还特意「负缓存」不存在的 key。负缓存防的是什么?
  1. 防止版本不一致
  2. 暴力打库:攻击者拿大量假 key 来刷,若不缓存「不存在」,每个假 key 都会回 Postgres 查一遍;负缓存(API_KEY_NON_EXISTENT)让第二次起就被 Redis 挡回,保护数据库
  3. 防止响应太大
  4. 防止 key 泄露
看答案与解析 点击展开
答案:B。只缓存有效 key 时,攻击者用海量不存在的 key 仍能让每次都穿透到 Postgres。负缓存把「这个 key 不存在」也记进 Redis,于是无论正常流量还是恶意刷量,数据库都被保护在缓存后面,只在真正缓存未命中时才被惊动。这是「缓存正例也缓存反例」的安全考量。
3. Langfuse 用「文件夹做版本」(v1 在根、v2/、v3/)+「Fern 契约生成 SDK」来管理对外 API。这套组合解决的核心矛盾是?
  1. 「需求要演进」与「发布后不能破坏老用户」的矛盾:文件夹版本让老路径永不改(旧集成照跑)、新版可显式切换甚至做减法;Fern 一份契约生成多语言 SDK、保证一致,开发期响应校验防实现与契约漂移
  2. 让 API 响应更快
  3. 减少端点数量
  4. 让前端不用写代码
看答案与解析 点击展开
答案:A。对外契约一旦发布就不能随意改,但需求总在变。文件夹版本让 v1 永不破、新能力进 v2/v3(甚至砍掉昂贵旧设计,如 v3 scores 去掉需 JOIN 的过滤、改游标分页);Fern 用一份手写 YAML 生成 Python/TS SDK + OpenAPI,一处定义处处一致。这正是第 20 课「对外求契约稳定」的落地。
💭 发散思考(没有标准答案,动手或动脑想想)
  • 「对内优化『改得快』、对外优化『不破坏』」——同一份数据,UI 用 tRPC、SDK 用版本化 REST。你做过或用过的系统里,内部接口和对外 API 是怎么处理这对矛盾的?如果让你给一个对外 API 设计「演进而不破坏」的机制,你会怎么做版本、怎么防契约漂移?

Lesson 21 opened the "staff entrance" for the in-house UI (tRPC). This lesson opens the third and last door — the public REST API for external SDKs. Its priorities differ sharply from tRPC's: internally seek type-safety, fast to change; externally seek contract stability, holding up at scale. Four things to see: how a route factory unifies auth/rate-limit/validation across all endpoints, how auth uses a Redis cache to withstand massive traffic, how versions are managed by folder, and how a Fern contract generates multi-language SDKs. Finish this and Lesson 20's "three doors" are all open.

🏛️ Analogy
Think of the public REST API as a government building's public service hall. Whatever business you come for (query a trace, submit a score, pull a dataset), you first go through the same security and queue process (the route factory: check ID, rate-limit, verify your form is filled right) — no one skips it. Frequent visitors get their ID info cached at the front desk, no trip to the archives each time (Redis-cached auth). The hall's procedures are printed into a manual and translated into your language (Fern generates multi-language SDKs); when procedures update, the old manual still works, the new procedure ships as "v2", existing users unaffected (versioning by folder). Unified, stable, cacheable, versioned — that's what an external API should look like.

One route factory, unifying every endpoint

Just as tRPC converges auth into procedure builders (Lesson 21), the public REST converges every endpoint's "mandatory moves" into one route factory createAuthedProjectAPIRoute. Each endpoint just declares its query/body/response schema and rate-limit resource, and the factory uniformly runs these gates:

createAuthedProjectAPIRoute: every endpoint's unified pipeline SDK requestBasic/Bearer ① authkey→project (cached) ② access levelproject / scores ③ rate limitby resource/plan ④ Zod validatequery/body ⑤ your handlerOTel surface=publicapi the factory runs these five — endpoints just declare schema, never re-write auth/rate-limit/validation oversized body→ PayloadTooLargeError response validated (dev)prevents contract drift
The unified pipeline for external endpoints: createAuthedProjectAPIRoute runs auth (key→project, incl. access level) → rate limit → Zod-validate query/body → the handler in an OTel context (surface=publicapi) → validate the response (dev, anti contract-drift); oversized body → PayloadTooLargeError. Source: web/src/features/public-api/server/createAuthedProjectAPIRoute.ts.
Example: one public REST call and response curl -u pk:sk GET https://cloud.langfuse.com/api/public/traces/chat_a1b2 200 OK { "id":"chat_a1b2", "name":"chat-support", "userId":"u_42", "timestamp":"2025-…Z", "totalCost":0.0042, "latency":1.93, "observations":[ {"id":"obs_7f","type":"GENERATION","model":"gpt-4o", …}, … ], "scores":[ {"name":"helpfulness","value":0.9} ] } one set of domain objects, shared by REST / SDK / Fern multi-language clients
The same domain objects, exposed (endpoint per web/src/pages/api/public/traces; values illustrative): Basic-auth with pk:sk and GET /api/public/traces/{{id}} returns a JSON — the same trace you see in the UI: observations[], scores[], totalCost, latency. Fern generates multi-language SDKs from the API definition, so REST and every client get the same shape.
web/src/features/public-api/server/createAuthedProjectAPIRoute.tsroute factory
// each endpoint only declares schema & rate-limit resource; the factory runs auth/limit/validate/OTel
export const handler = createAuthedProjectAPIRoute({
  name: "Get Traces",
  querySchema: GetTracesV1Query,   bodySchema: z.never(),
  responseSchema: GetTracesV1Response,
  rateLimitResource: "public-api",
  allowedAccessLevels: ["project"],  // this endpoint needs a project-level key
  fn: async ({ query, auth }) => { /* business only: already authed + validated */ },
});

This is Lesson 21's "security by structure" on the REST side: auth, rate-limit, Zod validation don't rely on each endpoint author's diligence — the factory forces them all. The difference is priority — tRPC's set is internal; REST's adds rate limiting (against external abuse), response validation (against external contract drift), access levels (e.g. Bearer read-only scores) — gates only the public-facing side needs.

tRPC (Lesson 21 · internal)public REST (this lesson · external)
for whomown UI (same repo, same team)external SDK / user scripts (massive, long-lived)
top valuetype-safety, fast to changecontract stability, holds up at scale
convergenceprocedure builders (stacked middleware)route factory createAuthedProjectAPIRoute
extra gates—rate limit, response validation, access level
stability meanscompile-time type checks (change → error)folder versions + Fern contract + multi-language SDKs

Auth must scale: Redis cache + negative caching

An external API verifies a key on every request — and an SDK may send thousands per second. Hit Postgres for every key check and the database gets crushed by auth itself. So ApiAuthService wraps key verification in a Redis cache:

Cached auth: keep the DB from being crushed by "verify key" API key arrivescheck Redis first ✅ hit → return scope directly ❌ miss → fall back to Postgres look up by fastHashedSecretKey + re-cache negative caching: even "key doesn't exist" is recorded (API_KEY_NON_EXISTENT)→ brute-forcing with fake keys is blocked by Redis from the 2nd hit, never touching Postgres cache hit → near-zero-cost key check; negative cache → attackers with fake keys can't pound the DB on key deletion the cache is actively invalidated — no "update" path, only "invalidate"
Cache the positives, and the negatives too: auth checks Redis first, returns on hit; on miss falls back to Postgres by fastHashedSecretKey and re-caches. The key is negative caching: even "this key doesn't exist" is recorded (API_KEY_NON_EXISTENT), so attackers brute-forcing with fake keys can't pound the database. Source: web/src/features/public-api/server/apiAuth.ts:75.

😖 no cache: every request hits the DB

The SDK sends tens of thousands of requests a second, each verifying a key against Postgres — a big chunk of the DB's load is auth itself, slowing things before business even starts; attackers flooding with fake keys hit the DB directly.

😀 cache + negative cache: the DB is barely touched

Common keys hit Redis, key checks near-zero-cost; even "nonexistent keys" are stopped at the Redis layer by negative caching. Whether normal traffic or malicious flooding, Postgres is shielded behind, disturbed only on a cache miss.

Versions by folder, contracts by Fern

An external API, once published, can't change freely — but needs keep evolving, so what? Langfuse's two moves: version by folder, generate SDKs with Fern.

(1) version = folder (old paths never change) public/ (v1) · default at root public/v2/ public/v3/ · can subtract e.g. v3/scores uses cursor paging (2) contract = Fern (define once) Fern YAML fern/apis/{server,client} Python SDK TypeScript SDK OpenAPI export versioning keeps "the old unbroken"; Fern generation keeps "multi-language consistent, contract is the doc"
version = folderv1 at root, v2/, v3/…
v1 sits at the public/ root by default, new versions in v2/, v3/ subfolders. Old paths never change, so your two-year-old integration still runs today; opt into new capability by explicitly switching version.
new versions can subtractdrop expensive features
A new version isn't only additive; it can cut costly old designs: e.g. v3/scores drops the userId/traceTags filters that need a trace JOIN and uses cursor pagination — writing "use v2 for that" straight into the docs.
Fern contractone YAML → multi-language SDKs
The API contract is hand-written Fern YAML (fern/apis/{server,client}/…), which generates the Python and TypeScript SDKs (generated/) and exports OpenAPI. Define once, consistent everywhere.

Together these are Lesson 20's "externally seek contract stability" made real: versioning ensures "the old doesn't break", Fern generation ensures "multi-language consistency, contract-as-docs". Paired with dev-time response-schema validation (against the hand-written implementation silently drifting from the Fern contract), the whole external channel stays stable and never quietly changes shape.

🎯 Design trade-off
It's all "query the data out", so why does the UI use tRPC while the SDK needs this whole REST factory + cache + versions + Fern? Because different audiences, different constraints (echoing Lesson 20). The UI is in-house, same repo, so tRPC trades type threading for iteration speed, where daily changes are fine. The SDK faces external, massive, long-lived users: massive, so auth must be cacheable (Redis + negative cache), or the DB gets crushed by key checks; long-lived, so the API must be versioned (folders + Fern), or one change breaks someone's two-year-old integration. The same "converge cross-cutting concerns into one factory" pattern (Lessons 21, 22) takes on a public-facing new meaning here: rate-limit against abuse, response-validate against drift, cache to take traffic, version to stay stable. Internally optimize "fast to change", externally optimize "don't break" — the same data, two engineering value systems parting ways. With that, Lesson 20's "three doors" are all walked through: tRPC for the UI, REST for the SDK, App-Router for streaming/webhooks — each divided and conquered by audience.
🎯 Key points · Part 4 wrap-up
  • One route factory createAuthedProjectAPIRoute unifies every public endpoint's auth → access level → rate limit → Zod-validate query/body → OTel(surface=publicapi) → response validation → oversized-body rejection.
  • Auth uses a Redis cache to scale: hit returns directly, miss falls back to Postgres by fastHashedSecretKey and re-caches; negative caching (API_KEY_NON_EXISTENT) blocks fake-key brute force.
  • Versioning by folder: v1 at root, v2/v3 subfolders; old paths never change, new versions can subtract (e.g. v3 scores drops JOIN-needing filters, uses cursor pagination).
  • Contract by Fern: hand-written Fern YAML → generated Python/TS SDKs + OpenAPI; dev-time response validation guards against the implementation drifting from the contract.
  • Tradeoff: internal (tRPC) optimizes type-safety and speed, external (REST) optimizes stability and scale — same data, two value systems. With this, Lesson 20's "three doors" are all open.

🧪 Self-test - think about the design

1. The public REST API unifies all endpoints with one route factory createAuthedProjectAPIRoute. Compared to Lesson 21's tRPC procedure builders, what 'public-facing' gates does it add?
  1. faster database connections
  2. it removes auth
  3. rate limiting (against external abuse), response validation (against external contract drift), access levels (e.g. Bearer read-only scores) — gates the internal tRPC doesn't need but the external API must have
  4. more complex type checking
Show answer & explanation click to expand
Answer: C. Both use the same 'factory/builder converges cross-cutting concerns' pattern, but with different priorities: tRPC seeks internal speed, REST external stability and scale, hence the added rate-limit, response validation, access levels. Auth and Zod validation are common to both — neither relies on endpoint-author diligence; the factory forces them.
2. An external API verifies a key per request, and SDKs may send tens of thousands per second. Besides caching valid keys in Redis, Langfuse deliberately 'negatively caches' nonexistent keys. What does negative caching prevent?
  1. prevents version mismatch
  2. brute-forcing the DB: attackers flood with many fake keys; without caching 'nonexistent', each fake key would hit Postgres; negative caching (API_KEY_NON_EXISTENT) blocks them at Redis from the 2nd hit, shielding the database
  3. prevents oversized responses
  4. prevents key leakage
Show answer & explanation click to expand
Answer: B. Caching only valid keys still lets attackers with floods of nonexistent keys punch through to Postgres each time. Negative caching records 'this key doesn't exist' in Redis too, so whether normal traffic or malicious flooding, the DB stays shielded behind the cache, disturbed only on a true miss. A 'cache the positives and the negatives' security consideration.
3. Langfuse manages the external API with 'versioning by folder' (v1 at root, v2/, v3/) + 'Fern contract generates SDKs'. What core tension does this combo resolve?
  1. the tension between 'needs evolve' and 'can't break existing users after release': folder versions keep old paths unchanged (old integrations run) while new versions opt-in and can even subtract; Fern's one contract generates multi-language SDKs ensuring consistency, with dev-time response validation against drift
  2. makes API responses faster
  3. reduces the number of endpoints
  4. lets the frontend skip code
Show answer & explanation click to expand
Answer: A. An external contract can't change freely once published, yet needs keep evolving. Folder versions keep v1 unbroken and put new capability in v2/v3 (even cutting costly old designs, e.g. v3 scores dropping JOIN-needing filters for cursor pagination); Fern generates Python/TS SDKs + OpenAPI from one hand-written YAML, define-once consistent everywhere. This realizes Lesson 20's 'externally seek contract stability'.
💭 Open questions (no single right answer - just think or try)
  • 'Internally optimize fast-to-change, externally optimize don't-break' — same data, UI via tRPC, SDK via versioned REST. In systems you've built or used, how were internal interfaces and external APIs handled against this tension? Designing an 'evolve without breaking' mechanism for an external API, how would you do versioning and prevent contract drift?