如何透過 Lambda 後端對 API Gateway REST API 的 HTTP 504 錯誤進行疑難排解?

2 分的閱讀內容
0

當我搭配使用 Amazon API Gateway 與 AWS Lambda 後端以叫用 REST API 時,收到 HTTP 504 錯誤狀態碼。如何對此錯誤進行疑難排解?

解決方案

當您的 REST API 請求傳回 HTTP 504 錯誤狀態碼時,必須執行各種檢查。

檢查 IntegrationLatency 尖峰

檢閱整合延遲持續時間,以檢查 API Gateway 是否存在 IntegrationLatency 尖峰。若要查看 IntegrationLatency 持續時間,請設定 HTTP API 日誌記錄的存取日誌記錄變數 $context.integration.latency

如需詳細資訊,請參閱使用 API Gateway 主控台設定 Amazon CloudWatch API 日誌記錄

API Gateway 中的 IntegrationLatency 尖峰表示,請求大部分時間花在 Lambda 上。檢查 Lambda 函數的持續時間效能指標,以確認這一點。

如需詳細資訊,請參閱使用 Lambda 函數指標

使用 CloudWatch Logs Insights 來檢閱請求

使用 Amazon CloudWatch Logs Insights 來檢閱導致 504 錯誤的請求。若要檢閱請求,請在 CloudWatch 主控台的導覽窗格中,選擇 Logs (日誌)、Log Insights (日誌洞察)。選取您的 API Gateway 日誌群組。然後,使用以下查詢之一來設定相對時間:

parse @message '(*) *' as reqId, message
| filter message like /Method completed with status: \d\d\d/
| parse message 'Method completed with status: *' as status
| filter status = 504
| sort @timestamp desc
| limit 20

-或-

fields @timestamp, @message
| filter message like /Method completed with status: 504/
| sort @timestamp desc
| limit 20

檢查 X 射線追蹤

如果 504 錯誤持續發生,請確定 Lambda 函數花費時間的位置。根據 Lambda 函數執行時間,對 Lambda 函數進行 AWS X-Ray 追蹤檢測。

針對 Python︰

from aws_xray_sdk.core import xray_recorder
from aws_xray_sdk.core import patch_all
patch_all()

針對 Node.js︰

const AWSXRay = require('aws-xray-sdk-core')
const AWS = AWSXRay.captureAWS(require('aws-sdk'))

**注意:**在 Lambda 函數上檢測 X-Ray 追蹤之後,需要建置新的部署套件。

實作 API 重試

當發生 504 錯誤且 Lambda 中找不到請求時,請在用戶端上實作 API 重試。該錯誤可能是由於 API Gateway 中的暫時網絡故障所致。

檢查 Lambda 函數組態

請確定 Lambda 函數僅包含 API Gateway 事件特定的處理邏輯。如此一來,Lambda 函數執行所需的時間減少,並且能跟上傳入的事件。

REST API 的預設整合逾時上限為 29 秒。因此,請確定 Lambda 函數的執行持續時間低於 29 秒。

如果您有應用程式對時間敏感的使用案例,請參閱設定後端 Lambda 函數的非同步調用


相關資訊

API Gateway 維度和指標

在 API Gateway 中設定 REST API 的 CloudWatch 日誌記錄

在 CloudWatch 主控台中檢視 API Gateway 日誌事件

使用 X-Ray 追蹤使用者的 REST API 請求

搭配使用 Lambda 與 X-Ray

AWS 官方
AWS 官方已更新 1 年前