DEBUG.WIKI
阿里云;从建站到云上业务;云服务器 · 数据库 · 对象存储;查看产品 →
PanstarCloud:部署应用,接入 AI,云服务器与 AI 网关
IPPeak:从目标地区访问网页,住宅代理、SEO 监测、广告验证

解决 Apollo Server 报错 Query complexity limit exceeded 查询深度超限修复

排查 客户端向 GraphQL 发送深层嵌套关联查询时,Apollo Server 拦截并报错 Query has depth of 12, which exceeds max depth of 8 或 complexity limit exceeded,分析 GraphQL 攻击防范与复杂度验证器。

问题现象

前端向 Apollo Server 发起包含循环关联字段的复杂查询时,服务端返回 400 校验异常:

{
  "errors": [
    {
      "message": "Query has depth of 11, which exceeds max depth of 7",
      "extensions": { "code": "GRAPHQL_VALIDATION_FAILED" }
    }
  ]
}

触发根因

  1. GraphQL 容易受到恶意构造的递归嵌套查询(如 user -> posts -> author -> posts -> author)引发拒绝服务攻击(DoS);
  2. 服务端安全插件(graphql-depth-limit 或 graphql-query-complexity)对 AST 语法树深度或加权分值进行了严格防御;
  3. 业务合规深度确实需要穿透但默认阈值未对受信任客户端放开。

解决步骤

针对合法深层业务请求合理放宽深度限制并排除内省字段

在 Apollo Server 插件中微调:

import depthLimit from 'graphql-depth-limit';

const server = new ApolloServer({
  schema,
  validationRules: [depthLimit(10, { ignore: [ /_nonce/ ] })],
});

引入基于字段权重的复杂度计分器替代死板的层级计算

在字段级别分配耗时权重(如标量字段 1 分,列表分页字段 10 分):

import { createComplexityRule } from 'graphql-query-complexity';
// 允许最大综合分值 1000

在生产环境建议全面使用“持久化查询”(Persisted Queries)

客户端只发送查询 Hash,彻底免疫任意复杂查询攻击。

验证确认

重新发送前端请求:

正常业务查询在安全深度内顺利通过验证并返回数据,深度恶意遍历被坚决阻断在网关层。