如何根据 `CDN-Cache-Control` 头部控制 Apollo 缓存?
解读
面试官抛出这个问题,并不是想听你背诵“Apollo 有 InMemoryCache”这么简单,而是考察三件事:
- 你是否意识到 Apollo Client 的缓存与 HTTP 缓存分属两层,不能天然互通;
- 你是否能把 CDN 边缘节点的缓存策略(
CDN-Cache-Control)反向映射到 Apollo 的缓存策略,实现“服务端声明 → 客户端执行”的闭环; - 你是否能在国内“双域名 + 多 CDN”场景(阿里 CDN、腾讯云、又拍等)里落地,兼顾灰度、回退、合规与可观测。
一句话:让 Apollo 像浏览器尊重 Cache-Control 一样,尊重 CDN-Cache-Control,而且不重启、不硬编码。
知识点
-
CDN-Cache-Control与Cache-Control的区别
RFC 9213 新增,专为 CDN 设计,优先级高于Cache-Control,国内主流 CDN 已支持。
常见指令:max-age、s-maxage、stale-while-revalidate、must-revalidate、no-store等。 -
Apollo Client 缓存决策链
请求 → 命中 cache → policies(fetchPolicy、nextFetchPolicy)→ 网络 → 响应归一化 → 写 cache → 广播更新。
决策链里没有任何一步默认读取 HTTP 响应头。 -
扩展链路的关键钩子
ApolloLink:可读取response.headers;cache.policies:可运行时调整TypePolicy与FieldPolicy;cache.modify/writeQuery:可手动失效;client.setLink:支持热替换,用于灰度。
-
国内合规细节
- 对“个人信息”接口必须
no-store,需动态识别 GraphQL 路径与变量; - 灰度发布时,同一 CDN 节点可能同时服务新旧版本,需把版本号写入缓存 key,避免指令错位。
- 对“个人信息”接口必须
答案
生产级落地分四步,全部用 TypeScript 示范,可直接写进简历。
第一步:定义“指令 → 缓存时间”映射表,支持运行时热更新
// cdn-cache-policy.ts
export const CDN_POLICY = {
'max-age=30': { maxAge: 30_000, staleWhileRevalidate: 0 },
'max-age=60, stale-while-revalidate=300': { maxAge: 60_000, staleWhileRevalidate: 300_000 },
'no-store': { maxAge: 0 },
} as const;
第二步:编写 CDNCacheLink,把响应头转成 Apollo 可识别的上下文变量
import { ApolloLink, Observable } from '@apollo/client';
export const cdnCacheLink = new ApolloLink((operation, forward) =>
forward(operation).flatMap((response) => {
const context = operation.getContext();
const headers: Headers = context.response.headers;
const cdnHeader = headers.get('cdn-cache-control') || headers.get('cache-control');
if (cdnHeader) {
operation.setContext({ cdnCacheDirective: cdnHeader });
}
return Observable.of(response);
})
);
第三步:自定义 FetchPolicyLink,在真正发起请求前,根据上下文动态改写 fetchPolicy 与 nextFetchPolicy
import { ApolloLink } from '@apollo/client';
import { CDN_POLICY } from './cdn-cache-policy';
export const fetchPolicyLink = new ApolloLink((operation, forward) => {
const { cdnCacheDirective } = operation.getContext();
const policy = CDN_POLICY[cdnCacheDirective as keyof typeof CDN_POLICY];
if (policy) {
// 对查询生效,mutation 跳过
if (operation.query.definitions.some((d: any) => d.kind === 'OperationDefinition' && d.operation === 'query')) {
operation.setContext({
fetchPolicy: 'cache-first',
nextFetchPolicy: () => (policy.maxAge === 0 ? 'network-only' : 'cache-first'),
});
// 把 maxAge 写入 cache 配置
operation.setContext({ http: { ...operation.getContext().http, maxAge: policy.maxAge } });
}
}
return forward(operation);
});
第四步:把 Link 按序插入,并给 InMemoryCache 提供 typePolicies 读取上下文里的 maxAge
const cache = new InMemoryCache({
typePolicies: {
Query: {
fields: {
// 示例字段
article: {
read(_, { args, cache, toReference }) {
const maxAge = cache.policies.rootIds.ROOT_QUERY?.__context?.maxAge;
const ref = toReference({ __typename: 'Article', id: args?.id });
if (!ref) return undefined;
const data = cache.data.data.get(ref.__ref);
if (!data) return undefined;
// 手写 TTL 校验
const now = Date.now();
const cachedAt = cache.data.data.get(ref.__ref + ':ts');
if (cachedAt && now - Number(cachedAt) > maxAge) {
cache.evict({ id: ref.__ref });
return undefined;
}
return data;
},
merge(existing, incoming, { args, cache }) {
const ref = cache.writeFragment({
data: incoming,
fragment: gql`fragment _ on Article { id title }`,
});
cache.data.data.set(ref.__ref + ':ts', Date.now());
return ref;
},
},
},
},
},
});
const client = new ApolloClient({
link: ApolloLink.from([cdnCacheLink, fetchPolicyLink, httpLink]),
cache,
});
至此,服务端只要返回
CDN-Cache-Control: max-age=60, stale-while-revalidate=300
Apollo 会自动把对应查询缓存 60s,并在后台重新验证,实现“零配置、按头治理”。
如需立即失效,让服务端改发 no-store 或调用 client.refetchQueries({ include: 'active' }) 即可。
拓展思考
-
多 CDN 混用场景
国内常见“阿里云 + 腾讯云”双备份,边缘节点返回的CDN-Cache-Control可能不一致。
解决:在CDNCacheLink里把指令写入extensions.trace,再通过自研网关做“指令归一”,保证同一资源在任何节点拿到的策略相同。 -
与 SSR 同构
Next.js 中,服务端渲染时 Node 层没有window,需要把CDN-Cache-Control随getServerSideProps的pageProps注入到initialState,浏览器端复用同一套typePolicies,避免 hydration 错位。 -
可观测与灰度
把最终生效的指令和缓存命中率打到 SLS 或 ARMS:
logger.info({ directive, queryName, cacheHit, duration })
结合阿里云 MSE 灰度,可在控制台按用户百分比切换CDN_POLICY版本,实现“服务端改头 → 客户端实时生效”的闭环实验。 -
合规红线
对含手机号、身份证的 GraphQL 字段,即使 CDN 给了max-age=5,也必须强制降级为no-store。
可在fetchPolicyLink里做字段级静态分析,发现变量名包含phone/idCard直接覆写为network-only,并打审计日志,满足《个人信息保护法》要求。
掌握以上思路,你不仅回答了“如何根据 CDN-Cache-Control 控制 Apollo 缓存”,还展示了国内工程化、合规、灰度、可观测的完整闭环,面试官基本会给出“超出预期”的评价。