Skip to content
Visual explainer 3h to learn 5 steps

Build a small HTTP API with Lambda and API Gateway

Deploy a Lambda function behind API Gateway and explain its payload limits, timeouts, concurrency and latency.

By Invicly Tech, , in AWS Cloud Engineering. About 13 minutes to read.

Topic 13 of 38

In short

AWS Lambda runs your function only when an event arrives, and Amazon API Gateway turns HTTPS requests into those events. Together they give you a small HTTP API with no servers, billed per request and per millisecond of run time. The design limits are what you must learn: payload sizes, timeouts on both services, how many copies of the function can run at once, and the extra delay of a cold start.

Think of it like this: Lambda is a taxi rank: cars appear when passengers arrive, the first one may take a moment to start its engine, and the rank has a limit on how many cars can be out at once.

Explained simply

AWS Lambda runs a function when something happens, such as an HTTP request or a file landing in S3. You upload the code; AWS starts a small environment to run it, scales up when many requests arrive and scales to zero when none do. You pay per request and for the time your code runs.

Amazon API Gateway gives the function a public HTTPS address. A client calls GET /files/42, API Gateway turns the request into an event and invokes the function, then sends the function's answer back as an HTTP response. The HTTP API type is the simple, cheaper choice for this.

There are limits to respect. An HTTP API waits at most 30 seconds for the function. A synchronous request or response can be at most 6 MB. Big uploads should go straight to S3 with a presigned URL, and long jobs should go onto a queue.

The first request to a new copy of your function is slower, because Lambda has to start the runtime and load your code. This is a cold start. Later requests reuse the warm copy. Watching cold and warm times, and how many copies run at once, is how you size a Lambda API.

Press Play on a diagram to walk through it one step at a time.

SequenceOne request through an HTTP API and Lambda
Client
API Gateway
Lambda service
Function code
  1. 1GET /files/42 over HTTPS
    Client to API Gateway: GET /files/42 over HTTPS
  2. 2Invoke with payload format 2.0 event
    API Gateway to Lambda service: Invoke with payload format 2.0 event
  3. 3Cold start: init, then handler(event)
    Lambda service to Function code: Cold start: init, then handler(event)
  4. 4Return statusCode, headers, body
    Function code to Lambda service: Return statusCode, headers, body
  5. 5Response within the integration timeout
    Lambda service to API Gateway: Response within the integration timeout
  6. 6HTTP 200 with JSON
    API Gateway to Client: HTTP 200 with JSON
CycleLife of a Lambda execution environment
  1. 1
    Init

    Start runtime, run code outside the handler

  2. 2
    Invoke

    Run the handler for one request

  3. 3
    Idle and frozen

    Kept warm for possible reuse

  4. 4
    Reused for next request

    Warm start, no Init Duration

  5. 5
    Shut down

    After idle time or a new version

  6. Back to step 1

In depth

Wiring API Gateway to Lambda

API Gateway has REST APIs and HTTP APIs. HTTP APIs are cheaper and simpler and support JWT authorizers, Lambda authorizers and CORS settings; REST APIs add features such as API keys with usage plans, request validation and direct AWS WAF attachment. For a small Lambda backend, start with an HTTP API.

A route such as GET /files/{id} links to a Lambda proxy integration. API Gateway needs permission to invoke the function, granted by a resource-based policy on the function (lambda add-permission with principal apigateway.amazonaws.com and the API's source ARN). The console adds it for you; infrastructure as code must add it explicitly. HTTP APIs default to payload format version 2.0, where the method is in requestContext.http.method, the path in rawPath and path variables in pathParameters. The function returns statusCode, headers and body as a string.

  • HTTP API: cheaper, JWT auth, payload format 2.0
  • REST API: usage plans, request validation, WAF
  • Function needs a resource policy for apigateway.amazonaws.com
  • Return body as a string; set isBase64Encoded for binary

Payload size and timeouts on both sides

Two services, two sets of limits. Lambda allows 6 MB for a synchronous request and 6 MB for the response, and 1 MB for asynchronous invocations. HTTP APIs accept payloads up to 10 MB, so the Lambda limit bites first. For file uploads, have the API return a presigned S3 URL and let the client upload directly.

Timeouts work the same way. The Lambda function timeout defaults to 3 seconds and can be raised a long way, but an HTTP API's integration timeout is at most 30 seconds. If the function runs longer, the client receives a 503 while the function keeps running and billing. Set the function timeout a little below the API's, and move slow work (such as processing a large file) to SQS and a worker, returning 202 Accepted with a job ID the client can poll.

CompareDo it in the request or hand it off?
Handle inside the request
  • Finishes in well under 30 seconds
  • Payload under 6 MB
  • Client needs the answer now
  • Example: look up a file's status
Hand off to a queue
  • Work can take minutes
  • Large files via S3 presigned URLs
  • Return 202 with a job ID
  • Example: process an uploaded CSV

Concurrency: reserved, provisioned and throttling

Concurrency is how many requests a function handles at the same instant. A handy estimate is requests per second times average duration in seconds: 200 requests per second at 250 ms needs about 50 concurrent environments. Each Region has an account concurrency quota, 1,000 by default, shared by all functions; new accounts can start lower and AWS raises it with usage.

Reserved concurrency carves part of that pool out for one function. It guarantees capacity and caps the function, which protects a database from too many connections. Setting it to 0 stops all invocations, a handy emergency brake. Provisioned concurrency keeps a number of environments initialised so they never cold start, and you pay for them while configured. When a function is throttled, API Gateway returns a 429 or 5xx and the Throttles metric rises in CloudWatch.

  • Concurrency is about RPS x duration
  • Default account quota: 1,000 per Region
  • Reserved: guarantee plus cap; 0 disables
  • Provisioned: no cold starts, billed while on

Measuring cold and warm latency

Every invocation writes a REPORT line to CloudWatch Logs with Duration, Billed Duration, Memory Size and Max Memory Used. Cold starts add Init Duration, the time spent starting the runtime and running code outside the handler. Compare p50 and p99 of Duration, and count how many lines include Init Duration, to see how often users hit a cold start.

To reduce cold starts, keep the deployment package small, create SDK clients once outside the handler so warm calls reuse them, and avoid heavy imports. More memory also means proportionally more CPU, so a function at 1,024 MB may start and run faster than at 128 MB and cost about the same overall. Measure end-to-end latency too: API Gateway adds its own overhead, which appears in the API's Latency and IntegrationLatency metrics.

Learn it in 5 short steps

About 35m each. Track them with a timer in your plan.

  1. 1
    Wire an API Gateway integration~35m
  2. 2
    Handle the event payload~35m
  3. 3
    Set timeout and memory~35m
  4. 4
    Reserve or limit concurrency~35m
  5. 5
    Measure cold and warm latency~35m

Key points

  • HTTP APIs have a 30-second maximum integration timeout, so keep request work short and push long jobs to a queue.
  • Synchronous Lambda payloads are limited to 6 MB each way; send large files through S3 presigned URLs.
  • The default function timeout is 3 seconds; set it just above your real worst case.
  • Concurrency is about requests per second times average duration; the default account quota is 1,000 per Region, and new accounts may start lower.
  • Cold starts show as Init Duration in the REPORT log line; provisioned concurrency removes them for a price.

Key terms

Tap a card to flip it. 0/6 known

Examples

python
import json

def handler(event, context):
    method = event["requestContext"]["http"]["method"]
    file_id = (event.get("pathParameters") or {}).get("id")
    if method != "GET" or not file_id:
        return {"statusCode": 400, "body": json.dumps({"error": "bad request"})}
    return {
        "statusCode": 200,
        "headers": {"content-type": "application/json"},
        "body": json.dumps({"id": file_id, "status": "processed"}),
    }

A handler for an HTTP API route GET /files/{id} using payload format version 2.0.

Lab: deploy GET /files/{id} as an HTTP API

Prerequisites: an execution role for Lambda with the AWSLambdaBasicExecutionRole managed policy, the handler from the explainer saved as app.py, and a budget alert. Cost: Lambda and HTTP APIs have pay-per-request pricing and a small test usually stays within the Free Tier; check current terms. Step 1: zip and create the function. Step 2: quick-create an HTTP API targeting it, which also adds the invoke permission. Step 3: add the route. Evidence: curl returns JSON with status processed. Cleanup: delete the API, the function and the log group.

bash
zip fn.zip app.py
aws lambda create-function --function-name files-get --runtime python3.13 \
  --handler app.handler --zip-file fileb://fn.zip --timeout 10 --memory-size 512 \
  --role arn:aws:iam::111122223333:role/files-lambda-basic
API=$(aws apigatewayv2 create-api --name files-http --protocol-type HTTP \
  --target arn:aws:lambda:eu-west-1:111122223333:function:files-get \
  --query ApiId --output text)
# Quick create adds a default route; also add GET /files/{id} to the same integration
curl https://$API.execute-api.eu-west-1.amazonaws.com/files/42

Measure cold starts and cap concurrency

Step 1: send 50 requests after the function has been idle for a while. Step 2: query the REPORT lines with CloudWatch Logs Insights to compare cold and warm durations. Evidence: a few lines show Init Duration of a few hundred milliseconds; warm calls are much faster. Step 3: set reserved concurrency to 5 and run a load test with 50 parallel requests. Evidence: some calls fail with throttling, and the function's Throttles metric rises. Rollback: delete the reserved concurrency setting.

bash
# Logs Insights query on /aws/lambda/files-get
# filter @type = "REPORT"
# | stats count(@initDuration) as cold, count(*) as total,
#         pct(@duration, 50) as p50, pct(@duration, 99) as p99
aws lambda put-function-concurrency --function-name files-get \
  --reserved-concurrent-executions 5
# after the test:
aws lambda delete-function-concurrency --function-name files-get

Quick reference

  • HTTP API max integration timeout: 30 s; set the function timeout just below it
  • Lambda payload: 6 MB sync request and response, 1 MB async
  • Default Lambda timeout is 3 s; memory 128 to 10,240 MB, CPU scales with memory
  • Concurrency needed is about requests per second x average duration in seconds
  • Account concurrency default: 1,000 per Region, shared by all functions
  • Reserved concurrency caps and guarantees; 0 stops the function
  • Cold starts: REPORT lines with Init Duration; fix with smaller code or provisioned concurrency
  • Big files: presigned S3 URLs, not the API payload

Common mistakes

  • Setting a 60-second function timeout behind an HTTP API, so clients get a 503 at 30 seconds while the function keeps running and billing.
  • Uploading files through the API and hitting the payload limit instead of using presigned S3 URLs.
  • Letting one busy function use all account concurrency and throttle every other function in the Region.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1A function behind an HTTP API sometimes runs for 45 seconds. What does the client see?

Question 2

2Users need to upload 50 MB files. What is the right design?

Question 3

3An API serves 400 requests per second at 100 ms each. About how much concurrency does it use?

Question 4

4How do you spot cold starts in the logs?

Question 5

5Which setting protects a small database from too many Lambda connections?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Extend the handler to return 404 when the id is not one of 1, 2 or 42, and a JSON error body.

  2. Exercise 2medium

    Choose timeout, memory and reserved concurrency for an API with peaks of 150 requests per second, average 200 ms, p99 1.5 s, in front of a database allowing 100 connections.

  3. Exercise 3hard

    Redesign POST /files/{id}/process, which takes up to 4 minutes, so it works behind an HTTP API.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

HTTP API or REST API?
Choose an HTTP API for a simple Lambda backend with JWT auth; it is cheaper and faster to set up. Choose a REST API when you need usage plans and API keys, request validation, or direct WAF attachment.
Are cold starts a real problem?
For most APIs they affect a small share of requests and add from tens of milliseconds to around a second, depending on runtime and package size. Measure first; use provisioned concurrency only where latency targets demand it.
Can Lambda run for a long time?
Lambda functions can run for many minutes, but an API request cannot wait that long. Put long work behind a queue and give the client a job ID to check.
Does Lambda need to be in a VPC?
Only if it must reach private resources such as an RDS database. A function attached to a VPC uses your subnets, so calls to the internet then need NAT or VPC endpoints.

Go deeper

ShareXLinkedInWhatsApp