Lambda API returns 200 on request timeout error

0

I have a login lambda function that is integrated with a API gateway. when the lambda is timed out the status code returned to me is 200 why, and how can I make return 408 instead? { "errorMessage": "##### Task timed out after 3.55 seconds" } And the status code is 200

2 Answers
4

When a Lambda function times out, API Gateway will return a 200 HTTP status code by default. This behavior occurs because the Lambda function successfully completed its execution from API Gateway's perspective, even though it might have timed out internally.

To return a different status code, such as 408 for request timeout, you can implement error handling within your Lambda function and explicitly return the desired status code along with the response. Here's how you can modify your Lambda function to return a 408 status code for timeouts:`

def lambda_handler(event, context): try: # Your login logic here # If the operation takes too long and times out, the following line will cause a timeout error # Simulating a timeout error import time time.sleep(5)

    # If login successful, return success response
    return {
        "statusCode": 200,
        "body": "Login successful"
    }
except Exception as e:
    # If an exception occurs, check if it's a timeout error
    if "Task timed out" in str(e):
        # Return 408 status code for request timeout
        return {
            "statusCode": 408,
            "body": "Request timed out"
        }
    else:
        # For other exceptions, return 500 status code
        return {
            "statusCode": 500,
            "body": "Internal server error"
        }

`

answered 25 days ago
1
Accepted Answer

Hi

Suggestions: https://aws.amazon.com/blogs/compute/error-handling-patterns-in-amazon-api-gateway-and-aws-lambda/

  • Increase the Lambda timeout if your function genuinely needs more time (up to 15 minutes).
  • Consider asynchronous processing (e.g., SQS queues) for long-running tasks to avoid timeouts altogether.

Map the response status codes for API Gateways:https://repost.aws/knowledge-center/api-gateway-status-codes-http-api

This Video Some More clear to you --> https://www.youtube.com/watch?v=uC2IQwlMJQU

profile picture
EXPERT
GK
answered 25 days ago
profile picture
EXPERT
reviewed 24 days ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions