在 BFF 层将 3 个 REST 响应聚合成 1 个 GraphQL,并处理部分失败

解读

国内大厂面试常把“BFF + 聚合 + 容错”放在同一题里,考察候选人是否真正落地过高并发场景。
题眼有三:

  1. 网络 I/O 必须并行,不能串行 await;
  2. 下游服务随时 502/超时,不能一个接口挂掉就整体 500;
  3. GraphQL 返回结构要符合规范,data 与 errors 并存,且前端可感知部分失败。
    面试官会追问:
  • 如何做熔断/降级?
  • 错误怎样打标,方便监控告警?
  • 聚合逻辑是否可配置化,避免硬编码?
  • 高并发下内存与句柄会不会爆炸?
    答不到这些,会被认为“只写过 Demo”。

知识点

  1. Node.js 事件循环 + Promise.allSettled 并行调度
  2. GraphQL 错误规范({ errors: [{message,path,extensions}] })
  3. 领域错误分类:可降级 / 不可降级,决定下游失败是否影响整体
  4. 超时与重试:p-retry + AbortController,避免句柄泄漏
  5. 熔断:opossum / self-made 计数滑动窗口,半开探活
  6. 缓存:基于数据新鲜度的短期内存缓存(LRU),降低扇出
  7. 监控:在 extensions 中透出耗时、返回码、是否降级,方便 SLS 索引
  8. 日志:使用 pino 结构化日志,带上 traceId,方便全链路排查
  9. 安全:GraphQL 深度限制、查询白名单,防止恶意放大攻击
  10. 性能:stream 化大字段、使用 DataLoader 批量去重,降低 N+1

答案

以下示例用 NestJS + GraphQL + Axios 编写,可脱离框架直接跑通,重点体现“并行 + 部分失败 + 可观测”。
场景:查询商品详情页,需要聚合

  • 商品基础服务 /api/item/:id
  • 价格服务 /api/price/:id
  • 库存服务 /api/stock/:id
// item.resolver.ts
@Resolver(() => ItemDTO)
export class ItemResolver {
  constructor(private readonly itemService: ItemService) {}

  @Query(() => ItemDTO, { nullable: true })
  async item(
    @Args('id') id: string,
    @Context() ctx: any,
  ): Promise<ItemDTO> {
    // 统一入口,返回 data + errors
    return this.itemService.aggregate(id, ctx.traceId);
  }
}
// item.service.ts
import { Injectable } from '@nestjs/common';
import axios, { AxiosError } from 'axios';
import * as pRetry from 'p-retry';

const HTTP_TIMEOUT = 800;          // 比下游 SLA 略小
const MAX_RETRIES  = 2;

@Injectable()
export class ItemService {
  private readonly client = axios.create({ timeout: HTTP_TIMEOUT });

  async aggregate(
    id: string,
    traceId: string,
  ): Promise<ItemDTO & { errors?: any[] }> {
    const errors: any[] = [];
    const log = (msg: string, meta?: any) =>
      console.log(JSON.stringify({ traceId, msg, ...meta }));

    // 1. 并行调用,使用 allSettled 保证全部结束
    const [itemRaw, priceRaw, stockRaw] = await Promise.allSettled([
      this.fetchItem(id),
      this.fetchPrice(id),
      this.fetchStock(id),
    ]);

    // 2. 处理 item 基础数据(不可降级)
    if (itemRaw.status === 'rejected') {
      log('item service fail', { err: itemRaw.reason });
      // 直接抛 GraphQL 错误,前端可感知整体不可用
      throw this.toGraphQLError('ITEM_SERVICE_ERROR', 'item');
    }
    const item = itemRaw.value;

    // 3. 处理价格(可降级,返回 null 并记录)
    let price: number | null = null;
    if (priceRaw.status === 'fulfilled') {
      price = priceRaw.value;
    } else {
      log('price service fail, downgrade to null');
      errors.push(this.formatError('PRICE_SERVICE_ERROR', 'price'));
    }

    // 4. 处理库存(可降级)
    let stock: number | null = null;
    if (stockRaw.status === 'fulfilled') {
      stock = stockRaw.value;
    } else {
      log('stock service fail, downgrade to null');
      errors.push(this.formatError('STOCK_SERVICE_ERROR', 'stock'));
    }

    // 5. 组装最终 DTO
    return {
      id: item.id,
      title: item.title,
      price,
      stock,
      errors: errors.length ? errors : undefined,
    };
  }

  private async fetchItem(id: string) {
    return pRetry(
      async () => (await this.client.get(`/api/item/${id}`)).data,
      { retries: MAX_RETRIES },
    );
  }

  private async fetchPrice(id: string) {
    return pRetry(
      async () => (await this.client.get(`/api/price/${id}`)).data.amount,
      { retries: MAX_RETRIES },
    );
  }

  private async fetchStock(id: string) {
    return pRetry(
      async () => (await this.client.get(`/api/stock/${id}`)).data.count,
      { retries: MAX_RETRIES },
    );
  }

  private toGraphQLError(code: string, path: string) {
    return new GraphQLError(code, { extensions: { code, path } });
  }

  private formatError(code: string, path: string) {
    return { message: code, path, extensions: { code, timestamp: new Date().toISOString() } };
  }
}

关键解读

  • Promise.allSettled 保证三个请求都结束,再统一决策;
  • 基础数据失败直接抛 GraphQLError,整体进入 errors 数组;可降级字段返回 null 并在同一级透出 errors,前端可弹窗提示“价格/库存暂不可用”;
  • 使用 p-retry 做指数退避,避免瞬时抖动;
  • 日志带 traceId,方便在阿里云 SLS 或腾讯云 CLS 里检索;
  • 若需要熔断,可在 fetchXXX 内再包一层 opossum,半开探活失败率超过 50% 直接短路,返回 fallback 值。

拓展思考

  1. 配置化聚合:把“依赖服务、字段映射、是否可降级”写进 YAML,BFF 启动时动态生成 GraphQL schema,做到新接口零代码发布。
  2. 数据Loader:如果一次查询 100 个商品,使用 DataLoader 批量拆 3 个服务,将 300 次调用合并成 3 次,降低连接数。
  3. 缓存一致性:价格、库存变化频繁,用短 TTL(1~3 秒)+ 事件推送(MQ)做主动失效,避免用户看到脏数据。
  4. 多区域容灾:国内一般做双可用区,BFF 层在 ingress 做流量镜像,聚合逻辑里优先读同机房服务,失败再跨区重试。
  5. Serverless 场景:函数实例冷启动高,可把“聚合结果”缓存到 Redis,设置 500 ms 粒度,防止函数并发暴涨导致费用失控。