Lambda times out even though the code works.”



Issue:
AWS Lambda function times out, even though the code runs fine locally or in a test environment.

Credits: Illustration by Mamaz Alaei

Context:
This happens a lot, especially when calling external APIs, accessing RDS, or using VPCs. The function executes, but hangs, then fails with Task timed out after X seconds.


Checklist / Fix:

  1. Check the Lambda Timeout Setting
    • Go to Lambda → Configuration → General Configuration
    • Make sure timeout is set high enough for your use case. Default is 3 seconds, which is often too low for anything network-related.
    • Increase it to 10–15 seconds to start.
  2. Are You Using a VPC?
    • Go to Lambda → Configuration → VPC
    • If your function is in a private subnet without NAT Gateway or NAT Instance, it won’t have internet access — so any outbound HTTP calls will silently hang and then time out.
    • Options:
      • If internet access is needed: Add a NAT gateway or move Lambda to a public subnet.
      • If only internal access needed (e.g., RDS): Ensure security groups and routing are correct.
  3. Check External Calls (APIs, DB, etc.)
    • External services (e.g., REST APIs, RDS) can delay or fail. Add timeouts to all outbound calls in your code: requests.get(url, timeout=5)
    • Without explicit timeouts, the function can hang until Lambda’s timeout limit.
  4. Check for Infinite Loops or Await Hangs
    • In Node.js or Python, make sure there’s no forgotten await, promise, or infinite loop.
    • Common issue in async functions — especially in try/catch blocks where errors are swallowed.
  5. Enable CloudWatch Logs and Look for Hangs
    • Look at the last line printed before timeout.
    • If nothing prints, the issue is early (e.g., network or DNS).
    • If some logs appear, the problem is likely after a request or DB query.

Conclusion:
If Lambda times out:

  • First, increase timeout.
  • Then check VPC network settings, especially if using RDS or calling APIs.
  • Add timeouts to all external calls.
  • Watch for hidden hangs in async code.
  • Use CloudWatch logs to trace the exact line it hangs on.

This issue almost always comes down to network config or code not handling slow responses properly.