如何使用 AsyncLocalStorage(Node.js 14+)实现异步上下文传播?

解读

国内一线/二线互联网公司在 NestJS 岗位面试中,这道题出现的频率极高。
面试官真正想验证的,并不是“能写几行代码”,而是:

  1. 你是否理解 Node.js 事件循环中“异步资源”与“执行上下文”的生命周期;
  2. 你是否能把 AsyncLocalStorage(ALS)与 NestJS 的 IoC、拦截器、守卫、管道、异常过滤器等机制无缝结合;
  3. 你是否能在高并发场景下(网关层→微服务→数据库)保证 traceId/tenantId/userId 的“零侵入”透传,同时避免内存泄漏;
  4. 你是否知道 ALS 与 cls-hooked、zone.js、AsyncHooks 的演进关系,以及 14.x/16.x/18.x 版本差异;
  5. 你是否能在 Serverless(阿里云 FC、腾讯云 SCF)冷启动场景下正确初始化与销毁 store。

一句话:这道题考察的是“企业级可观测性”与“框架级可扩展性”的综合设计能力。

知识点

  • AsyncLocalStorage 核心 API:run、enterWith、getStore、disable
  • AsyncResource、executionAsyncId、triggerAsyncId 的底层关联
  • NestJS 请求生命周期:Middleware → Guard → Interceptor → Pipe → Handler → Interceptor → ExceptionFilter → Response
  • 平台无关性:@nestjs/platform-express 与 @nestjs/platform-fastify 在 ALS 初始化顺序上的差异
  • 内存泄漏根因:未正确销毁 store、未关闭定时器、未解绑事件监听器
  • 性能陷阱:enterWith 与 run 的适用场景,避免在热路径反复创建闭包
  • 测试策略:Jest 中开启 --experimental-vm-modules 与 fakeTimers 时如何清理 ALS
  • 链路追踪规范:国内主流方案 SkyWalking、Jaeger、ARMS(阿里云)对 ALS 的埋点要求
  • 多租户隔离:tenantId 在 GraphQL 订阅、WebSocket 握手、gRPC metadata 中的透传方式
  • Serverless 冷启动:阿里云 FC 的 initializer 回调与 SCF 的 scf_init 中如何提前初始化 ALS

答案

(可直接在 IDE 跑通,符合国内大多数公司代码规范)

  1. 安装依赖
npm i async-local-storage   # 仅做类型提示,Node 14+ 已内置
  1. 创建 ALS 实例与类型定义
// src/common/als/alS.constants.ts
export const ALS_KEY = 'als:context';

// src/common/als/als.service.ts
import { AsyncLocalStorage } from 'async_hooks';
import { Injectable, OnModuleDestroy } from '@nestjs/common';

export interface AlsStore {
  traceId: string;
  tenantId: string;
  userId?: string;
  startTime: number;
}

@Injectable()
export class AlsService implements OnModuleDestroy {
  private readonly als = new AsyncLocalStorage<AlsStore>();

  getStore(): AlsStore | undefined {
    return this.als.getStore();
  }

  run<T>(store: AlsStore, fn: () => T): T {
    return this.als.run(store, fn);
  }

  /* 用于 Serverless 场景,提前注入全局上下文 */
  enterWith(store: AlsStore): void {
    this.als.enterWith(store);
  }

  OnModuleDestroy() {
    // Node 18+ 支持,防止热更新时泄漏
    this.als.disable();
  }
}
  1. 中间件层初始化(平台无关,优先于 Guard)
// src/common/als/als.middleware.ts
import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
import { randomUUID } from 'crypto';
import { AlsService } from './als.service';

@Injectable()
export class AlsMiddleware implements NestMiddleware {
  constructor(private readonly alsService: AlsService) {}

  use(req: Request, res: Response, next: NextFunction) {
    const traceId = req.headers['x-trace-id'] || randomUUID();
    const tenantId = req.headers['x-tenant-id'] || 'default';
    const store = {
      traceId,
      tenantId,
      userId: (req as any).user?.userId, // 若 JWT Guard 已解析
      startTime: Date.now(),
    };

    // 统一注入 ALS
    this.alsService.run(store, () => next());
  }
}
  1. 全局注册
// src/app.module.ts
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import { AlsMiddleware } from './common/als/als.middleware';
import { AlsService } from './common/als/als.service';

@Module({
  providers: [AlsService],
  exports: [AlsService],
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(AlsMiddleware).forRoutes('*');
  }
}
  1. 在任意地方零侵入获取上下文
// src/order/order.service.ts
import { Injectable } from '@nestjs/common';
import { AlsService } from '../common/als/als.service';

@Injectable()
export class OrderService {
  constructor(private readonly alsService: AlsService) {}

  createOrder() {
    const store = this.alsService.getStore();
    console.log(`[${store?.traceId}] 创建订单,租户=${store?.tenantId}`);
    // 后续数据库、RPC、MQ 调用均可透传 traceId
  }
}
  1. 日志切面(Interceptor)
// src/common/logger/logging.interceptor.ts
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { AlsService } from '../als/als.service';
import { Logger } from '@nestjs/common';

@Injectable()
export class LoggingInterceptor implements NestInterceptor {
  private readonly logger = new Logger(LoggingInterceptor.name);
  constructor(private readonly alsService: AlsService) {}

  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const store = this.alsService.getStore();
    const now = Date.now();
    return next.handle().pipe(
      tap(() => {
        const cost = Date.now() - now;
        this.logger.log(`[${store?.traceId}] ${context.getClass().name}.${
          context.getHandler().name
        } 耗时=${cost}ms`);
      }),
    );
  }
}
  1. 异常过滤器中同样可获取
// src/common/filter/http-ex.filter.ts
import { Catch, ArgumentsHost, HttpException, ExceptionFilter } from '@nestjs/common';
import { AlsService } from '../als/als.service';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  constructor(private readonly alsService: AlsService) {}
  catch(exception: HttpException, host: ArgumentsHost) {
    const store = this.alsService.getStore();
    console.error(`[${store?.traceId}] 业务异常`, exception.getResponse());
    // 可上报 SLS、ARMS、Sentry
  }
}
  1. 测试用例(Jest 27+)
// src/common/als/als.service.spec.ts
import { Test } from '@nestjs/testing';
import { AlsService } from './als.service';

describe('AlsService', () => {
  let service: AlsService;

  beforeAll(async () => {
    const module = await Test.createTestingModule({
      providers: [AlsService],
    }).compile();
    service = module.get<AlsService>(AlsService);
  });

  afterAll(() => {
    service.OnModuleDestroy();
  });

  it('should propagate context across async boundary', async () => {
    const store = { traceId: 't123', tenantId: 'taobao', startTime: Date.now() };
    await new Promise<void>((resolve) =>
      service.run(store, () => {
        setImmediate(() => {
          expect(service.getStore()?.traceId).toBe('t123');
          resolve();
        });
      }),
    );
  });
});
  1. 部署与运维要点
  • 容器镜像:基于 node:18-alpine,启动参数加 --enable-source-maps,方便 ARMS 链路对齐;
  • 环境变量:NODE_OPTIONS="--max-old-space-size=4096 --experimental-loader=./tracing-hook.mjs";
  • 灰度策略:按租户百分比灰度,ALS 中 tenantId 与配置中心联动;
  • 监控指标:通过 Prometheus 暴露 als_active_stores 与 als_memory_bytes,告警阈值 500 MB;
  • 冷启动优化:Serverless 场景下,在 initializer 函数中调用 alsService.enterWith 占位,避免首次请求创建开销。

拓展思考

  1. 如果公司强制使用 Node 12,如何降级到 cls-hooked 并保持 NestJS 代码零改动?
    提示:封装同名的 AlsService,内部用 cls-hooked 的 namespace.run/get 实现,上线后择机升级到 Node 18。

  2. GraphQL 订阅(WebSocket)握手阶段拿不到 HTTP headers,如何把 tenantId 注入 ALS?
    提示:在 GraphQL 的 onConnect 回调里解析 connectionParams,手动调用 alsService.run。

  3. 微服务间使用 gRPC,如何确保 traceId 在 metadata 中透传且不破坏 ALS 上下文?
    提示:实现一个 ClientInterceptor,在发送前把 alsService.getStore()?.traceId 写入 metadata;服务端在 Middleware 中解析并再次 ALS.run。

  4. 高并发压测时发现 CPU 暴涨,perf 火焰图显示 AsyncHooks 占比 30%,如何优化?
    提示:

    • 用 run 替代 enterWith,减少闭包数量;
    • 避免在 for 循环内部频繁调用 getStore(),可缓存到局部变量;
    • 升级 Node 18,启用 --perf-basic-prof-only-functions,对比启用/关闭 ALS 的 QPS 差异。
  5. 国内金融公司要求“线程级”隔离,但 Node 单线程,如何用 Worker Threads + ALS 实现“准线程级”上下文?
    提示:在 Worker 入口文件再次初始化 AsyncLocalStorage,父线程通过 transferList 把 traceId 序列化给子线程,子线程用 enterWith 恢复上下文,实现“跨 Worker”链路对齐。

掌握以上深度,面试中无论面试官如何追问“性能、内存、多租户、Serverless、降级、测试、运维”,都能给出符合国内大厂落地标准的答案。