AWS Lambda
HTTP Requests
Serverless Computing
Cloud Functions
API Integration

HTTP Requests in an AWS Lambda

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

Introduction

HTTP work inside AWS Lambda usually means two different things: receiving an HTTP-style event from API Gateway or Function URLs, and making outbound HTTP requests to other services. Both sides need explicit timeout, error, and logging behavior because Lambda’s short-lived execution model amplifies weak network assumptions.

Handle Inbound HTTP Events Predictably

When Lambda is fronted by API Gateway proxy integration, the event contains method, path, headers, query parameters, and body. Your handler should parse defensively and return the exact response shape that the integration expects.

python
1import json
2
3
4def handler(event, context):
5    method = event.get("httpMethod", "GET")
6    query = event.get("queryStringParameters") or {}
7    name = query.get("name", "world")
8
9    return {
10        "statusCode": 200,
11        "headers": {"Content-Type": "application/json"},
12        "body": json.dumps(
13            {
14                "message": f"hello {name}",
15                "method": method,
16                "requestId": context.aws_request_id,
17            }
18        ),
19    }

The key detail is that body must be a string for the normal proxy response contract.

Reuse Outbound HTTP Clients Across Warm Invocations

For outbound requests, create the HTTP client at module scope so warm Lambda invocations can reuse connections. Recreating a client on every invocation adds latency and can increase connection churn unnecessarily.

python
1import requests
2
3SESSION = requests.Session()
4
5
6def fetch_user(user_id: str) -> dict:
7    response = SESSION.get(
8        f"https://api.example.com/users/{user_id}",
9        timeout=(2, 5),
10    )
11    response.raise_for_status()
12    return response.json()

That pattern is simple, fast, and works well for many Python Lambda functions.

Fit HTTP Timeouts Inside the Lambda Timeout Budget

Lambda itself has a hard execution timeout. Your outbound HTTP calls should time out well before that limit so the function still has room to log, retry if appropriate, and return a controlled response.

A good mental model is:

  • short connect timeout
  • bounded read timeout
  • minimal retry count
  • enough remaining time for cleanup and response shaping

Unbounded HTTP waits are especially expensive in serverless code because they burn both time and money while producing poor diagnostics.

Map Upstream Failures Intentionally

Do not let every network problem collapse into the same generic error. Different failure modes should map to predictable caller behavior.

python
1import json
2import requests
3
4SESSION = requests.Session()
5
6
7def handler(event, context):
8    try:
9        data = SESSION.get("https://httpbin.org/get", timeout=(2, 5)).json()
10        return {"statusCode": 200, "body": json.dumps(data)}
11    except requests.Timeout:
12        return {"statusCode": 504, "body": json.dumps({"error": "upstream timeout"})}
13    except requests.RequestException:
14        return {"statusCode": 502, "body": json.dumps({"error": "upstream request failed"})}

That gives both clients and operators clearer signals than a generic unhandled exception.

Node.js Lambda Follows the Same Principles

If the function runs on Node.js, the same operational rules apply even though the syntax changes.

javascript
1export const handler = async () => {
2  const res = await fetch("https://httpbin.org/get", {
3    method: "GET",
4    headers: { Accept: "application/json" }
5  });
6
7  if (!res.ok) {
8    return {
9      statusCode: 502,
10      body: JSON.stringify({ error: "upstream request failed" })
11    };
12  }
13
14  const payload = await res.json();
15  return {
16    statusCode: 200,
17    body: JSON.stringify({ upstream: payload.url })
18  };
19};

The runtime differs, but the design does not: explicit timeouts, clear mapping, and structured output.

VPC Networking Can Break Outbound HTTP

If Lambda runs inside private subnets, outbound internet requests need proper NAT or another egress path. Missing egress often looks like a slow timeout, not a clean connection-refused error. When HTTP calls fail only in VPC mode, check route tables, security groups, and DNS first.

This is one of the most common reasons “the same code works locally but times out in Lambda.”

Protect Secrets and Improve Observability

Do not hardcode API keys or auth tokens into the function source. Use Secrets Manager or Parameter Store, and avoid logging sensitive headers. At the same time, log request IDs, destination hostnames, elapsed time, and high-level failure category so production debugging stays possible.

Good Lambda HTTP code is not just about making the request. It is about making the request diagnosable.

Common Pitfalls

  • Returning a non-proxy-compatible response shape to API Gateway.
  • Recreating the HTTP client on every invocation instead of reusing it.
  • Letting outbound HTTP timeouts exceed the Lambda execution budget.
  • Running Lambda in a VPC without correct outbound network configuration.
  • Logging credentials or auth headers while debugging failed requests.

Summary

  • Lambda HTTP work includes both inbound event handling and outbound requests.
  • Reuse HTTP clients across warm invocations for better latency and efficiency.
  • Keep outbound timeouts shorter than the Lambda timeout budget.
  • Map upstream failures into clear, stable response semantics.
  • Treat networking, secrets, and observability as part of the HTTP design.

Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.