使用 Apollo Cache Control 如何设置 maxAge 与 scope

解读

在国内一线/二线互联网公司的 GraphQL 面试中,“缓存命中率”与“数据一致性” 是区分初中高级的重要指标。面试官抛出本题的潜台词是:

  1. 你是否真的在生产环境用过 Apollo Cache Control,而不是只看过文档;
  2. 你是否理解 maxAge 与 scope 对 CDN、边缘节点、网关缓存的三层影响;
  3. 你是否能权衡 业务实时性 与 缓存收益,给出可落地的代码片段与回滚方案。

因此,回答时必须给出 服务端 + 客户端 的完整写法,并说明在 微服务灰度发布 场景下如何动态调整这两个参数。

知识点

  1. @cacheControl 指令:只能出现在 Object、Field、Interface 三种语法节点上;
  2. maxAge 单位是秒,0 代表“不缓存”,-1 代表“永久缓存”(慎用,必须配合 scope: PRIVATE);
  3. scope 枚举值:
    • PUBLIC:可被 CDN、边缘、浏览器共享;
    • PRIVATE:仅用户维度缓存,必须携带 sessionId 或 userId 作为缓存 key 的一部分;
  4. 动态计算:通过 apollo-server-plugin-cache-control 的 willSendResponse 钩子 可基于 ctx.auth.role 或 请求头 x-cache-strategy 在运行时改写 maxAge;
  5. 合并规则:子字段的 maxAge 取 最小值,scope 只要出现一次 PRIVATE 则整体降级为 PRIVATE;
  6. 与 CDN 联动:国内阿里云全站加速、腾讯云 ECDN 均支持 Cache-Control: s-maxage={maxAge} 与 Vary: Authorization,需保证网关层 转发 response 头 不被吞掉。

答案

服务端代码(Node.js + apollo-server v4)

import { ApolloServer } from '@apollo/server';
import { startStandaloneServer } from '@apollo/server/standalone';
import { cacheControlDirective } from '@apollo/cache-control-types';

const typeDefs = `#graphql
  directive @cacheControl(maxAge: Int, scope: CacheControlScope) on OBJECT | FIELD | INTERFACE

  enum CacheControlScope { PUBLIC PRIVATE }

  type Query {
    user(id: ID!): User @cacheControl(maxAge: 30, scope: PRIVATE)
    hotArticles: [Article!]! @cacheControl(maxAge: 300, scope: PUBLIC)
  }

  type User {
    id: ID!
    vipLevel: Int @cacheControl(maxAge: 0)  # 实时校验,不缓存
    profile: UserProfile
  }

  type UserProfile {
    nickName: String
    avatar: String @cacheControl(maxAge: 86400)  # 头像可缓存 1 天
  }
`;

const resolvers = { /* 略 */ };

const server = new ApolloServer({
  typeDefs,
  resolvers,
  cacheControl: {
    defaultMaxAge: 5,          // 兜底 5 秒
    calculateHttpHeaders: true, // 自动写入 Cache-Control 响应头
  },
  plugins: [
    {
      requestDidStart() {
        return {
          willSendResponse(requestContext) {
            const { response, context } = requestContext;
            // 灰度场景:内部员工请求实时数据
            if (context.headers['x-employee'] === 'true') {
              response.http.headers.set('Cache-Control', 'no-cache');
            }
          },
        };
      },
    },
  ],
});

await startStandaloneServer(server, { listen: { port: 4000 } });

客户端代码(React + @apollo/client 3.8)

import { ApolloClient, InMemoryCache } from '@apollo/client';

const client = new ApolloClient({
  uri: 'https://api.xxx.com/graphql',
  cache: new InMemoryCache({
    typePolicies: {
      Query: {
        fields: {
          hotArticles: {
            keyArgs: false,
            merge(existing = [], incoming) {
              return incoming; // 列表不做增量合并,直接替换
            },
          },
        },
      },
    },
  }),
  defaultOptions: {
    watchQuery: {
      fetchPolicy: 'cache-first', // 优先读缓存,命中失败再发请求
      nextFetchPolicy: 'cache-first',
    },
  },
});

验证方式

  1. 抓包查看响应头:cache-control: max-age=30, private;
  2. 在阿里云 CDN 控制台观察 缓存命中率 是否提升;
  3. 压测时通过 artillery 或 jmeter 对比 QPS 与 P99 延迟,验证 maxAge 调整效果。

拓展思考

  1. 多级缓存一致性:当 数据库 binlog 延迟 500ms 时,maxAge 设置为 1s 仍可能读到脏数据;可引入 Redis 发布订阅 主动失效 Apollo 内存缓存,实现 毫秒级一致性。
  2. 用户维度的动态 scope:在 SaaS 多租户 场景下,scope 需要细化到 tenantId + userId;可自定义 CacheKeyGenerator,把 scope 值拼成 PRIVATE:${tenantId}:${userId},避免跨租户缓存穿透。
  3. 版本灰度:利用 x-cache-version 请求头,在 willSendResponse 钩子中根据 feature flag 返回不同的 maxAge,实现 “缓存灰度”,降低全量变更风险。