跳至内容

如何对 API 网关 HTTP 504 状态代码超时错误进行故障排除?

2 分钟阅读
0

当我使用 Amazon API Gateway 调用 REST API、HTTP API 或 WebSocket API 时,我收到 HTTP 504 错误状态代码。

简短描述

如果集成请求所耗时间超出您配置的 API Gateway API 最大集成超时参数,则 API Gateway 返回 HTTP 504 状态代码。

要对 API Gateway 中的 504 超时错误进行故障排除,请首先在您的 Amazon CloudWatch 事件日志中确定并验证错误的来源。然后,使用以下方法之一来减少集成请求的运行时系统,直到它们不再超时。

您还可以将区域和私有 REST API 的集成超时限制提高到超过 29 秒的默认限制

解决方法

确定并验证 CloudWatch 日志中 504 错误的来源

完成以下步骤:

  1. 对于 Rest APIWebsocket API,为 504 错误设置 API Gateway 日志记录。对于 HTTP API,激活日志记录以将日志写入 CloudWatch 日志

  2. 手动尝试在 API 中重现 504 错误。

  3. 激活 API 的访问日志。然后,使用以下参数占位符来诊断错误来源:

    $context.integration.status: The status code returned from an integration. For AWS Lambda proxy integrations, this is the status code that your Lambda function code returns.$context.integrationStatus: For Lambda proxy integration, this parameter represents the status code returned from Lambda, not from the backend Lambda function.
    $context.integrationLatency: The integration latency in ms.

    有关详细信息,请参阅用于数据转换的上下文变量

  4. 要从访问日志中筛选“5##”状态代码,请使用以下 CloudWatch Log Insights 查询:

    fields @timestamp, @message, @logStream| filter status like '5'
    | sort @timestamp desc
    | display @timestamp,httpMethod,resourcePath,status,extendedRequestId,requestId
  5. CloudWatch 控制台中,查看 API Gateway 日志事件,以了解收到错误的集成。

  6. 在 CloudWatch 日志中追踪请求 ID。如果集成出现超时,则会在“转换后的端点请求正文:”行后出现“Execution failed due to a timeout”错误。有关详细信息,请参阅如何在我的 CloudWatch 日志中找到 API Gateway REST API 错误?

  7. 使用以下 CloudWatch Log Insights 查询,筛选错误并选择您的 API Gateway 执行日志组:

    fields @timestamp, @message|filter @message like "Execution failed due to a timeout error"
    |sort @timestamp desc
  8. 要确定错误的来源,请查看后端日志并验证关联的集成端点是否已调用。

  9. 确认集成花了多长时间才完成请求过程并响应 API Gateway。

  10. 如果未调用集成,则在客户端上实施 API 重试。该错误可能是由 API Gateway 服务中的临时网络故障引起的。
    注意:确保您的应用程序是幂等的,这样在重试 API 请求时可以避免数据冲突。

如果已调用集成但仍返回 504 错误消息,请缩短集成的运行时。

缩短集成的运行时

完成以下操作:

  • 确保您的后端集成仅包含 API Gateway 向客户端发送 HTTP 响应所需的逻辑。
  • 将任何非依赖逻辑或后处理逻辑移至其他服务,例如 AWS Lambda
  • 如果网络延迟导致 504 错误,则在客户端应用程序上实施重试逻辑
  • 遵循您的 AWS 产品和服务的最佳实践,以提高后端集成性能。
  • 设置后端 Lambda 函数的异步调用

提高区域和私有 API 的集成超时限制

您可以提交配额请求,将区域 API 和私有 API 的默认集成超时限制配额增加到 29 秒以上。但是,增加集成超时时间可能需要降低您的 AWS 账户的区域级节流配额。

**注意:**如果您增加集成超时限制,请确保将默认超时值 29 秒更改为新值。例如,在要应用增量的集成中更改默认超时值 29 秒。然后,重新部署 API 以使新的集成超时限制生效。

相关信息

API Gateway 中 REST API 的集成

在 API Gateway 中设置 WebSocket API 集成请求

在 API Gateway 中为 HTTP API 创建集成

如何排查带有 Lambda 后端的 API Gateway REST API 中的 HTTP 504 错误?