如何为不同优先级订阅设置 `throttle` 与 `debounce`?

解读

在真实业务里,GraphQL 订阅(subscription)的推送频率往往由后端决定,前端只能被动接收。但国内网络环境复杂,4G/5G 切换、电梯、地铁等场景会造成瞬时风暴;同时不同业务对实时性要求差异巨大:

  • 高优:股价、告警、竞价,延迟容忍 0~200 ms,不允许丢中间态。
  • 中优:工单状态、物流轨迹,延迟容忍 500~1000 ms,可合并。
  • 低优: unread 计数、运营横幅,延迟容忍 1 s 以上,可采样。

面试官想知道:

  1. 你是否理解 Apollo Client 订阅链路(WebSocket/link 层)没有内建 throttle/debounce;
  2. 能否用 Link 组合 + 自定义操作符,把“优先级”这一业务维度映射到“节流/防抖”这一技术维度;
  3. 是否能在不破坏缓存一致性的前提下,把合并后的数据写回缓存,同时让 UI 无感刷新;
  4. 是否考虑内存泄漏、热切换、调试、降级等工程化问题。

知识点

  1. Apollo Client 订阅架构:
    • 网络层由 split + WebSocketLink 承担;
    • 订阅返回 Observable<FetchResult>,可被 Link 链变换。
  2. RxJS 操作符:throttleTime、debounceTime、auditTime、sampleTime,以及 priority 调度器。
  3. Apollo Link 组合模式:
    • ApolloLink.from([throttleLink, retryLink, wsLink]);
    • 通过 operation.getContext().priority 拿到业务优先级。
  4. 缓存写回策略:
    • 合并后只能拿到“最新一次”payload,需保证该 payload 是“增量”或“全量”快照;
    • 用 cache.writeFragment/writeQuery 手动更新,避免直接修改 proxy。
  5. 国内优化细节:
    • 小程序/WebView 里 WebSocket 断连重连成本高,throttle 还能减少重连次数;
    • 运营商 NAT 超时普遍 50~90 s,心跳间隔要小于 throttle 窗口;
    • 弱网降级:连续两次合并后仍无更新,则主动拉一次 query 兜底。

答案

整体思路:自定义一个 PriorityThrottleLink,插在 WebSocketLink 之前,根据 operation.context.priority 把同一订阅字段分流到不同 RxJS 策略,最后把合并后的结果 observer.next(result) 还给下游。

步骤代码(TypeScript):

import { ApolloLink, Observable, Operation, FetchResult } from '@apollo/client';
import { throttleTime, debounceTime, auditTime } from 'rxjs/operators';
import { from, Subscriber } from 'rxjs';

type Priority = 'high' | 'medium' | 'low';

export class PriorityThrottleLink extends ApolloLink {
  private config = {
    high:    { strategy: 'audit',   ms: 0 },      // 不节流,直接透传
    medium:  { strategy: 'throttle', ms: 500 },
    low:     { strategy: 'debounce', ms: 1500 }
  };

  public request(operation: Operation, forward: ApolloLink) {
    const priority: Priority = operation.getContext().priority || 'medium';
    const { strategy, ms } = this.config[priority];

    return new Observable<FetchResult>((observer: Subscriber<FetchResult>) => {
      const upstream = forward(operation);

      let stream = from(upstream);

      if (strategy === 'throttle') {
        stream = stream.pipe(throttleTime(ms, undefined, { leading: true, trailing: true }));
      } else if (strategy === 'debounce') {
        stream = stream.pipe(debounceTime(ms));
      } else if (strategy === 'audit') {
        stream = stream.pipe(auditTime(ms));
      }

      const sub = stream.subscribe({
        next: v => observer.next(v),
        error: e => observer.error(e),
        complete: () => observer.complete()
      });

      return () => sub.unsubscribe();
    });
  }
}

使用方式:

const wsLink = new GraphQLWsLink(createClient({ url: 'wss://api.xxx.com/graphql' }));

const splitLink = split(
  ({ query }) => {
    const def = getMainDefinition(query);
    return def.kind === 'OperationDefinition' && def.operation === 'subscription';
  },
  ApolloLink.from([
    new PriorityThrottleLink(),
    wsLink
  ]),
  httpLink
);

const client = new ApolloClient({
  link: splitLink,
  cache: new InMemoryCache()
});

组件侧声明优先级:

const { data, loading } = useSubscription(STOCK_SUB, {
  context: { priority: 'high' }   // 或 'medium' / 'low'
});

缓存一致性保证:

  1. 后端订阅 payload 必须带 __typename 与主键 id,确保 cache.writeFragment 能正确归一化;
  2. 若业务是“增量 delta”,则在 next 里先读缓存再合并,再写回;
  3. 若业务是“全量快照”,直接 writeQuery 覆盖即可。

内存与异常:

  • unsubscribe 时自动切断 RxJS 流,防止泄漏;
  • 若 WebSocket 断连,Apollo 会重新实例化 Observable,throttle 状态自动重置,不会残留旧窗口;
  • 给 medium/low 加 trailing: true,确保窗口最后一条数据不会被丢弃。

拓展思考

  1. 动态优先级:
    页面可见时 priority='high',切后台后自动降级为 low,可结合 document.visibilityChange 在 context 里动态改写,无需重新订阅。
  2. 多字段差异化:
    同一条订阅返回 { fieldA, fieldB },fieldA 需要 throttle,fieldB 需要 debounce,可在 next 里把 payload 拆成两个 writeFragment,各自走不同策略。
  3. 网络自适应:
    通过 navigator.connection.effectiveType 把 ms 系数动态化,例如 4g 保持默认,3g 翻倍,2g 直接采样 1/5。
  4. 服务端协同:
    国内有些团队把节流逻辑下沉到网关(基于 subscriptionId + 用户标签),此时前端只需传 priority 头,网关返回 throttleHint,前端根据 hint 决定是否本地再节流,避免双重合并。
  5. 调试与可观测:
    在 PriorityThrottleLink 里打 console.debug('[Throttle]', priority, Date.now()),并上报 window.__APOLLO_THROTTLE_METRICS,方便线上复盘“丢中间态”是否影响业务。