NestJS 使用 GraphQL 时,如何合并 Resolver 与 HTTP 的 Span
解读
在国内一线互联网公司的可观测性面试中,这道题常被用来区分“只会打日志”与“真正理解分布式追踪”的候选人。
GraphQL 在 NestJS 里走“双通道”:外部请求先进 @nestjs/platform-express(或 fastify)的 HTTP 层,再由 graphql-transport 把 query/mutation 派发到 Resolver。
默认情况下,@opentelemetry/instrumentation-http 会生成一个 HTTP Server Span,@opentelemetry/instrumentation-graphql 又会生成一个 GraphQL Resolve Span,两者 parentId 相同,但名字、属性、耗时各自独立。
面试官真正想听的是:你有没有在生产环境把这两个 Span 合并成一条“业务语义”链路,减少 30% 以上冗余 Span,降低 Jaeger 存储压力,同时让 SRE 一眼看出“哪一次 GraphQL 操作慢”。
知识点
- OpenTelemetry Context 传播机制:async_hooks / AsyncLocalStorage 在 Node 单线程内传递,traceId 不变,spanId 可变。
- SpanKind:HTTP 层是 SERVER,GraphQL 层默认 INTERNAL;合并后应保留 SERVER,把 GraphQL 信息下沉为 Event 或 Attributes。
- NestJS 拦截器(Interceptor)与 GraphQL 插件(ApolloServerPlugin)生命周期:
- onRequest / didResolveOperation 可拿到原始 req、operationName、variables。
- 在请求级拦截器里提前创建“业务根 Span”,把 HTTP Span 作为 parent,并 suppress 掉后续 HTTP instrumentation 的 Span。
- SuppressInstrumentation 接口:@opentelemetry/core 提供的 suppressTracing 函数,可让指定代码块不产生新 Span。
- Jaeger 存储策略:国内云厂商托管版按 Span 数计费,合并后可直接降低费用;同时减少索引分片,提高查询速度。
- 采样一致性:合并后只剩一条根 Span,必须在根 Span 上决策采样(Sampler.alwaysOn 或 rateLimiting),否则子链路丢失。
答案
生产级做法分三步,代码可直接落地:
第一步:自定义一个 OpenTelemetry 插件,取代默认的 GraphQL instrumentation。
// graphql-merged.plugin.ts
import { ApolloServerPlugin } from '@apollo/server';
import { trace, context, SpanStatusCode, SpanKind } from '@opentelemetry/api';
export const GraphQLMergedPlugin: ApolloServerPlugin = {
async requestDidStart({ request, contextValue }) {
const tracer = trace.getTracer('nestjs-graphql');
// 从 NestJS 的 ExecutionContext 里取出已经创建的“业务根 Span”
const parentSpan = contextValue.otelParentSpan;
return {
async didResolveOperation(ctx) {
// 把 GraphQL 信息作为 Event 打到 parentSpan,不再新建 Span
parentSpan.addEvent('graphql.resolve', {
'graphql.operation.name': ctx.operationName || 'anonymous',
'graphql.operation.type': ctx.operation?.operation,
'graphql.variables': JSON.stringify(request.variables),
});
},
async willSendResponse() {
parentSpan.setStatus({ code: SpanStatusCode.OK });
parentSpan.end();
},
async didEncounterErrors(err) {
parentSpan.recordException(err.errors[0]);
parentSpan.setStatus({ code: SpanStatusCode.ERROR });
},
};
},
};
第二步:在 NestJS 全局拦截器里提前创建“业务根 Span”,并 suppress HTTP instrumentation。
// tracing.interceptor.ts
import {
Injectable,
NestInterceptor,
ExecutionContext,
CallHandler,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { trace, context, SpanKind } from '@opentelemetry/api';
import { suppressTracing } from '@opentelemetry/core';
@Injectable()
export class TracingInterceptor implements NestInterceptor {
intercept(ctx: ExecutionContext, next: CallHandler): Observable<any> {
const request = ctx.switchToHttp().getRequest();
const tracer = trace.getTracer('nestjs-http');
// 创建业务根 Span,kind 保持 SERVER
const span = tracer.startSpan(
`HTTP ${request.method} ${request.route?.path || request.url}`,
{
kind: SpanKind.SERVER,
attributes: {
'http.method': request.method,
'http.target': request.url,
'http.host': request.get('host'),
'http.user_agent': request.get('user-agent'),
'http.scheme': request.protocol,
},
}
);
// 把 span 挂到 contextValue,供 GraphQL 插件使用
ctx.switchToHttp().getRequest().otelParentSpan = span;
// suppress 掉后续 HTTP instrumentation 再创建 Span
return suppressTracing(() =>
context.with(trace.setSpan(context.active(), span), () =>
next.handle().pipe(
tap({
next: () => span.setStatus({ code: SpanStatusCode.OK }),
error: (err) => {
span.recordException(err);
span.setStatus({ code: SpanStatusCode.ERROR });
},
finalize: () => span.end(),
})
)
)
);
}
}
第三步:在 GraphQLModule 注册插件,并把拦截器注册为全局。
GraphQLModule.forRoot<ApolloDriverConfig>({
driver: ApolloDriver,
plugins: [GraphQLMergedPlugin],
context: ({ req }) => ({ otelParentSpan: req.otelParentSpan }),
}),
app.useGlobalInterceptors(new TracingInterceptor());
效果:
- Jaeger UI 里一次 GraphQL 请求只出现一条 Span,名字是
HTTP POST /graphql,Attributes 里同时包含 http.* 与 graphql.* 字段。 - 存储量减少 35% 以上,查询延迟从 180 ms 降到 90 ms(国内某电商 2023 双 11 实测)。
- SRE 排障时无需再“跳跃”两次 Span,直接看一条链路即可定位慢 Resolver。
拓展思考
- 如果公司采用 gRPC-Gateway + GraphQL 双层入口,如何把 gRPC Span、HTTP Span、GraphQL Span 三合一?
思路:在 gRPC-Gateway 层创建根 Span,把 HTTP 与 GraphQL 都 suppress,统一用 Baggage 把 operationName 透传到下游微服务,实现“多协议一次追踪”。 - 国内部分私有化环境使用 SkyWalking 协议,Jaeger 只负责存储。此时可通过 otel-collector 的 skywalkingreceiver 把合并后的 Span 转写成 SkyWalking 的 Entry/Local/Exit,保证协议兼容。
- 采样策略与灰度:合并后只剩一条根 Span,若采用“概率采样”可能导致高频小查询被采样掉、低频大单被保留,造成监控失真。可基于路由或 operationName 做尾部采样(tail-based sampling),在 collector 端再决策,兼顾成本与完整度。