我在使用 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 錯誤的來源
請完成下列步驟:
-
對於 Rest API 和 WebSocket API,設定 API Gateway 日誌以記錄 504 錯誤。如果是 HTTP API,請啟用日誌,並將日誌寫入 CloudWatch 日誌。
-
手動嘗試在 API 中重現 504 錯誤。
-
為 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.
如需詳細資訊,請參閱資料轉換的內容變數。
-
若要從存取日誌篩選出「5##」狀態碼,請使用下列 CloudWatch Log Insights 查詢:
fields @timestamp, @message, @logStream| filter status like '5'
| sort @timestamp desc
| display @timestamp,httpMethod,resourcePath,status,extendedRequestId,requestId
-
在 CloudWatch 主控台中,檢視接收到錯誤的整合項目的 API Gateway 日誌事件。
-
在 CloudWatch 日誌中追蹤請求 ID。如果整合發生逾時,則會在**轉換後的端點請求主體:**行之後出現「Execution failed due to a timeout」錯誤。如需詳細資訊,請參閱如何在我的 CloudWatch 日誌中尋找 API Gateway REST API 錯誤?
-
使用下列 CloudWatch 日誌洞察查詢來篩選錯誤,並選取您的 API Gateway 執行日誌群組:
fields @timestamp, @message|filter @message like "Execution failed due to a timeout error"
|sort @timestamp desc
-
若要判斷錯誤的來源,請檢視後端日誌,並確認是否已調用相關的整合端點。
-
確認整合完成處理請求並回應 API Gateway 所花費的時間。
-
如果未調用整合,請在用戶端上實作 API 重試。此錯誤可能是因為 API Gateway 服務中的暫時性網路失敗所導致。
注意:請確定您的應用程式為冪等的,以便在重試 API 請求時避免資料衝突。
如果已調用整合,但仍然傳回 504 錯誤訊息,請縮短整合的執行時間。
縮短整合的執行期
請執行下列動作:
提高區域和私有 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 錯誤進行疑難排解?