如何为不同优先级订阅设置 `throttle` 与 `debounce`?
解读
在真实业务里,GraphQL 订阅(subscription)的推送频率往往由后端决定,前端只能被动接收。但国内网络环境复杂,4G/5G 切换、电梯、地铁等场景会造成瞬时风暴;同时不同业务对实时性要求差异巨大:
- 高优:股价、告警、竞价,延迟容忍 0~200 ms,不允许丢中间态。
- 中优:工单状态、物流轨迹,延迟容忍 500~1000 ms,可合并。
- 低优: unread 计数、运营横幅,延迟容忍 1 s 以上,可采样。
面试官想知道:
- 你是否理解 Apollo Client 订阅链路(WebSocket/link 层)没有内建 throttle/debounce;
- 能否用 Link 组合 + 自定义操作符,把“优先级”这一业务维度映射到“节流/防抖”这一技术维度;
- 是否能在不破坏缓存一致性的前提下,把合并后的数据写回缓存,同时让 UI 无感刷新;
- 是否考虑内存泄漏、热切换、调试、降级等工程化问题。
知识点
- Apollo Client 订阅架构:
- 网络层由
split+WebSocketLink承担; - 订阅返回
Observable<FetchResult>,可被 Link 链变换。
- 网络层由
- RxJS 操作符:
throttleTime、debounceTime、auditTime、sampleTime,以及priority调度器。 - Apollo Link 组合模式:
ApolloLink.from([throttleLink, retryLink, wsLink]);- 通过
operation.getContext().priority拿到业务优先级。
- 缓存写回策略:
- 合并后只能拿到“最新一次”payload,需保证该 payload 是“增量”或“全量”快照;
- 用
cache.writeFragment/writeQuery手动更新,避免直接修改proxy。
- 国内优化细节:
- 小程序/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'
});
缓存一致性保证:
- 后端订阅 payload 必须带
__typename与主键id,确保cache.writeFragment能正确归一化; - 若业务是“增量 delta”,则在
next里先读缓存再合并,再写回; - 若业务是“全量快照”,直接
writeQuery覆盖即可。
内存与异常:
unsubscribe时自动切断 RxJS 流,防止泄漏;- 若 WebSocket 断连,Apollo 会重新实例化
Observable,throttle 状态自动重置,不会残留旧窗口; - 给
medium/low加trailing: true,确保窗口最后一条数据不会被丢弃。
拓展思考
- 动态优先级:
页面可见时priority='high',切后台后自动降级为low,可结合document.visibilityChange在context里动态改写,无需重新订阅。 - 多字段差异化:
同一条订阅返回{ fieldA, fieldB },fieldA需要 throttle,fieldB需要 debounce,可在next里把 payload 拆成两个writeFragment,各自走不同策略。 - 网络自适应:
通过navigator.connection.effectiveType把ms系数动态化,例如4g保持默认,3g翻倍,2g直接采样 1/5。 - 服务端协同:
国内有些团队把节流逻辑下沉到网关(基于subscriptionId+ 用户标签),此时前端只需传priority头,网关返回throttleHint,前端根据 hint 决定是否本地再节流,避免双重合并。 - 调试与可观测:
在PriorityThrottleLink里打console.debug('[Throttle]', priority, Date.now()),并上报window.__APOLLO_THROTTLE_METRICS,方便线上复盘“丢中间态”是否影响业务。