
How I traced an API Gateway 500 to Lambda
A 500 from API Gateway gave me little to go on. I followed one request ID into Lambda, found the exception, fixed it, and verified the same route returned 200.
A client reports HTTP 500 from an API Gateway route backed by Lambda. The response body says only
{"message":"Internal Server Error"} . At that point, changing the function is a guess. I want to know whether the request reached Lambda, what Lambda did with it, and whether the same client request works after a fix.I worked through that investigation with a failing request of my own. The gateway access log gave me a request ID and an integration error. I carried that ID into the Lambda log, where a traceback pointed to a missing-key read. After changing that line, I repeated the same URL and checked the new request in both log groups. The full chain went from
500 to 200 .I created the failure for this walkthrough in a small AWS environment; it was not a production outage. The commands and outputs are from that run on Windows 11 with PowerShell 7.6.9 and AWS CLI 2.37.0, using the
terraform-dev profile in ap-south-1 . The same evidence trail is what I would follow if this alert came from a production route.The incident signal and the evidence path
The request path was an API Gateway HTTP API route,
GET /trace , backed by a Python 3.13 Lambda function. API Gateway wrote access logs to one CloudWatch log group; Lambda wrote invocation logs to another. The HTTP API used Lambda payload format 2.0 , which passes requestContext.requestId in the event. I logged that value from the function and also recorded $context.requestId in the gateway access log. That shared value is the join key. The Lambda invocation ID is useful within the function logs, but it is a different ID. AWS HTTP API Lambda integration , access log variables .PowerShell caller → API Gateway HTTP API → Lambda function │ │ ▼ ▼ API access log Lambda log requestId apiRequestId status lambdaRequestId integrationError traceback └──── match the API request ID ────┘I made
?fail=1 trigger a missing-key read so I had a known failure to investigate. During an actual incident, I would start with the affected route, time window, deployment version, and a specific failing request.The order of checks matters during an incident. I did not start by redeploying Lambda or changing API Gateway settings. I first preserved a request that failed, then used each layer's evidence to decide where to look next:
Evidence | Question it answered in this run |
|---|---|
Client status and body | Was the reported failure reproducible for the exact URL? |
API access log | Which gateway request failed, and what did the integration report? |
Lambda invocation log | Did application code run, and which line raised the exception? |
Same request after the fix | Did the API path recover, rather than only the Lambda configuration? |
That sequence also keeps the scope of a fix small. A 500 can arise at several boundaries, so changing the function before confirming that it ran can waste time or introduce another incident.
1. Capture the client symptom precisely
I first preserved the URL, HTTP status, and response body. In PowerShell 7,
Invoke-WebRequest throws on HTTP 500, so the catch block reads the status from the response and the body from ErrorDetails.Message :$url = 'https://byoqcrdjmj.execute-api.ap-south-1.amazonaws.com/trace?fail=1'try { $response = Invoke-WebRequest -Uri $url -UseBasicParsing -ErrorAction Stop [int]$response.StatusCode $response.Content} catch { if ($null -eq $_.Exception.Response) { throw } [int]$_.Exception.Response.StatusCode $_.ErrorDetails.Message}Actual output from the failed request at 19:48:51 IST:
500{"message": "Internal Server Error"}I also sent the healthy path as a control. At 19:48:50 IST,
GET /trace returned 200 and {"apiRequestId": "HMc70iesBcwEPWw=", "result": "healthy"} . The client-facing 500 did not identify the failing component; it only established the symptom. I did not infer a Lambda code bug from that response alone.2. Read the API Gateway access log
The access log format for this API included
requestId , status , routeKey , and integrationError ( $context.integrationErrorMessage ). AWS calls out the integration error variable when troubleshooting HTTP API Lambda integrations. If an existing production stage lacks this field, add a suitable access log format through the normal change process so later failures can be classified. AWS HTTP API Lambda troubleshooting .I listed the API log streams, then read the stream containing the failing request. For an active service, inspect all streams in the incident time window; the first stream returned is not guaranteed to contain the request.
aws logs describe-log-streams ` --log-group-name '/aws/apigateway/api-trace-1db36c27' ` --profile terraform-dev --region ap-south-1 --output json
aws logs get-log-events ` --log-group-name '/aws/apigateway/api-trace-1db36c27' ` --log-stream-name 'byoqcrdjmj_.default-2026-11-21-14-18' ` --start-from-head ` --profile terraform-dev --region ap-south-1 --output jsonSelected actual output from that stream:
logStreamName: byoqcrdjmj_.default-2026-11-21-14-18{"requestId":"HMc75g-kBcwEP0w=","status":"500","routeKey":"GET /trace","integrationError":"The Lambda function returned the following error: 'missing'. Check your Lambda function code and try again."}The gateway had invoked Lambda and received a function error. That narrowed the investigation from a generic HTTP 500 to the function invocation associated with
HMc75g-kBcwEP0w= . It did not yet tell me which line failed.
3. Join the matching Lambda invocation
I read the Lambda log streams for the same time window and searched their event messages for the API request ID, rather than searching only by timestamp. The function had logged
event["requestContext"]["requestId"] as apiRequestId , alongside context.aws_request_id as lambdaRequestId .aws logs describe-log-streams ` --log-group-name '/aws/lambda/api-trace-1db36c27-function' ` --profile terraform-dev --region ap-south-1 --output json
aws logs get-log-events ` --log-group-name '/aws/lambda/api-trace-1db36c27-function' ` --log-stream-name '2026/11/21/[$LATEST]b5577487758d4c6489366fb25f515967' ` --start-from-head ` --profile terraform-dev --region ap-south-1 --output jsonSelected actual output from the matching invocation:
START RequestId: 6d010a77-94ba-4b60-96bf-0a6eefff2155 Version: $LATEST{"apiRequestId": "HMc75g-kBcwEP0w=", "lambdaRequestId": "6d010a77-94ba-4b60-96bf-0a6eefff2155", "phase": "received"}[ERROR] KeyError: 'missing'File "/var/task/lambda_function.py", line 13, in lambda_handlerresult = event["missing"]The two records shared the same API request ID. The traceback then identified the exact line. The function had reached application code and attempted to read an event key that did not exist. That was the root cause of this particular 500. A generic integration error, permission failure, timeout, or malformed response would call for a different fix; the log evidence decides which path to take.
The Lambda
START line carried 6d010a77-94ba-4b60-96bf-0a6eefff2155 , which also appeared in my structured line as lambdaRequestId . That ID identifies the invocation inside Lambda. It is not the value I used to join the gateway access log: the gateway event used HMc75g-kBcwEP0w= . Keeping these IDs named separately prevented me from treating two unrelated log lines with nearby timestamps as one request.
One collection wrinkle mattered:
filter-log-events returned empty results on some attempts even though these log streams contained the events. I did not establish why. I used describe-log-streams and get-log-events to read the exact streams, so an empty filtered result was not treated as proof that Lambda had never run.If the evidence points somewhere else
This run's gateway record explicitly said the Lambda function returned an error, and the matching Lambda log contained a traceback. When that pattern is absent, I would branch based on the record actually present:
Observation | Next investigation |
|---|---|
Integration error mentions permission or invocation failure | Check the API integration target and the function's resource-based lambda:InvokeFunction permission for that API, stage, and route. |
Gateway record has a 500 but no matching Lambda application log | Check the account, region, log group, request time window, and whether the function had permission to write logs before concluding it was never invoked. |
Lambda log shows a timeout or downstream error | Follow the Lambda invocation ID and the dependent call shown in the logs; a missing-key code change would not address that failure. |
A code fix is deployed but the same request still fails | Verify the API's integration target and the function version or alias receiving traffic, then compare the new gateway and Lambda IDs. |
Those are diagnostic branches, not failures I reproduced in this run. The point is to let the access log and function log select the branch. AWS's HTTP API troubleshooting guidance covers integration errors and invocation permissions. AWS HTTP API Lambda troubleshooting .
4. Fix the fault shown by the traceback
The traceback pointed to the branch I had placed behind
fail=1 :if query.get("fail") == "1": result = event["missing"]else: result = "healthy"I replaced that missing-key read with an explicit result for the same input:
result = "recovered" if query.get("fail") == "1" else "healthy"For a production incident I would make the corresponding change in the owning repository, review its effect on the API contract, and deploy through the service's release path. Here I updated the function ZIP directly, waited for the update, and checked its state before sending traffic again:
aws lambda update-function-code ` --function-name api-trace-1db36c27-function ` --zip-file fileb://lambda-fixed.zip ` --profile terraform-dev --region ap-south-1
aws lambda wait function-updated-v2 ` --function-name api-trace-1db36c27-function ` --profile terraform-dev --region ap-south-1
aws lambda get-function-configuration ` --function-name api-trace-1db36c27-function ` --query '{State:State,LastUpdateStatus:LastUpdateStatus,CodeSha256:CodeSha256}' ` --profile terraform-dev --region ap-south-1Actual configuration output after the waiter completed:
State: ActiveLastUpdateStatus: SuccessfulCodeSha256: zfeCAvQuQYgU3U/Xj5cf2GE+V3HmY4H9y3PGaIvSPb8=An
Active function and Successful update showed that the new package was ready. They did not, by themselves, prove that the API path had recovered.5. Repeat the same request and check both sides
I repeated the exact
GET /trace?fail=1 URL after the code update. This avoided a misleading comparison between different routes or inputs.$url = 'https://byoqcrdjmj.execute-api.ap-south-1.amazonaws.com/trace?fail=1'$response = Invoke-WebRequest -Uri $url -UseBasicParsing -ErrorAction Stop[int]$response.StatusCode$response.ContentActual output at 20:00:09 IST:
200{"apiRequestId": "HMel6iaFhcwEMCg=", "result": "recovered"}I then checked the new request ID in both log groups. The API access log recorded a 200 and no integration error. The Lambda invocation logged the same API ID and ended normally:
API access log:{"requestId":"HMel6iaFhcwEMCg=","status":"200","routeKey":"GET /trace","integrationError":"-"}
Lambda log:{"apiRequestId": "HMel6iaFhcwEMCg=", "lambdaRequestId": "6d9f95f5-ac4f-4770-9e65-d5cfe8f0bfcb", "phase": "received"}END RequestId: 6d9f95f5-ac4f-4770-9e65-d5cfe8f0bfcbREPORT RequestId: 6d9f95f5-ac4f-4770-9e65-d5cfe8f0bfcb

The same input changed from 500 to 200. The gateway log no longer reported an integration error, and the matching Lambda invocation no longer raised
KeyError . That closed the loop for this request path.On a live service I would also check the affected caller path, verify that healthy requests still work, and watch the route's error rate after deployment. This run captured a healthy baseline before the change and a successful repeat of the failing input afterward; it did not include production traffic or sustained load testing.
The habit I would keep
The request ID did the heavy lifting. The client response told me that something failed. API Gateway told me Lambda had returned an error. The matching Lambda invocation told me why. Without that join, I could easily have blamed the integration or changed the wrong function while the actual exception sat in another log group.
For the next 500, I would capture one failing URL and its time, find its API Gateway access record, and follow its request ID into Lambda before touching the code. After a fix, I would send the same request again and check both logs. If the gateway record instead points to an invoke permission or integration problem, I would investigate that boundary rather than apply this case's code change. AWS's HTTP API troubleshooting guide is a useful reference for those branches.
I would also keep the logs useful without making them a data leak: record request IDs and error context, avoid credentials and request bodies, and limit log access. The route in this walkthrough was public and used only synthetic input; a production route needs the authentication and authorization its callers require. Its Lambda role and API invocation permission should stay scoped to the service. AWS Lambda execution roles covers the role side of that boundary.
API Gateway requests, Lambda invocations and duration, and CloudWatch Logs ingestion and storage can all be chargeable. I set both log groups to three-day retention for this run. The investigation itself needed only a handful of requests and two log streams; the account's pricing eligibility and budget were not established. API Gateway pricing , Lambda pricing , CloudWatch pricing .
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article