123DevOps··11 min read

AWS Lambda: a practical guide to limits, runtimes, deployment, and SQS

Learn what AWS Lambda is and when to use it, the current limits and runtimes, three ways to deploy (zip, Terraform, and container), SnapStart, streaming, function URLs, SQS with partial batch responses, cold starts, observability, and the cost dimensions.

Cloud

AWS Lambda runs your code in response to events, with no server to manage: you hand over a function, AWS takes care of machines, patching, scaling, and high availability, and you pay for what ran. It looks simple, and it is, until you hit a limit, a cold start, or a queue that reprocesses the same message forever. This guide gathers what you need to run Lambda in production in 2026, with code tested locally.

What Lambda is and when to use it

A Lambda function is a handler that receives an event (an HTTP request, an SQS message, a new S3 object, an EventBridge schedule) and returns a response. Each execution environment serves one request at a time. If a hundred arrive at once, Lambda spins up to a hundred environments.

A naming change: according to the 2026 docs, classic functions are now called Lambda Event Functions, alongside newer siblings such as Web Functions (HTTP-native, Node.js only, in select Regions). The API, the CLI, and the AWS::Lambda::Function resource did not change, and the aws lambda create-function help itself already says “Event Function.” Since the product is still being reorganized, check the current docs.

Good fit Poor fit
APIs with spiky or low traffic High, constant traffic around the clock
Processing queues, streams, and files Long-running processes with in-memory state
Automation and glue code between AWS services Long-lived persistent connections
Scheduled jobs and tasks of a few minutes Workloads that need GPUs or specific hardware (except Managed Instances)

To compare with containers and VMs, see containers vs. virtual machines vs. serverless.

Limits that matter

Values come from the research notes of Nov 25, 2026 and the AWS CLI 2.42.1 help. Limits change, so check the current docs.

Resource Limit
Timeout up to 1,800 s (30 min), new in November 2026; 5,400 s (90 min) for asynchronous and event-source-mapping invocations on Lambda Managed Instances
Memory 128 to 10,240 MB, in 1 MB steps (1,769 MB is about 1 vCPU)
/tmp (ephemeral storage) 512 to 10,240 MB
Synchronous payload 6 MB for the request and 6 MB for the response
Streamed response 200 MB
Asynchronous payload 1 MB
Zip package 50 MB zipped, 250 MB unzipped; container images up to 10 GB
Layers and environment variables 5 layers per function; 4 KB total for variables
Concurrency 1,000 per Region by default (adjustable quota)

Runtimes

Every managed runtime runs on x86_64 and arm64.

  • Python: python3.15, python3.14, python3.13, python3.12, and python3.11.
  • Node.js: nodejs26.x (November 2026), nodejs24.x, and nodejs22.x.
  • Java: java25, java21, and .al2023 variants for 17, 11, and 8.
  • .NET: dotnet10. dotnet8 was deprecated on Nov 10, 2026; migrate.
  • Ruby: ruby4.0, ruby3.4, and ruby3.3.
  • Go, Rust, and custom binaries: provided.al2023.

Amazon Linux 2 reached end of life on Jun 30, 2026, and runtimes based on it get only critical patches until their deprecation. After deprecation, AWS first blocks creating and later updating functions. Always prefer the two newest versions of your language.

A Python handler: environment variables and logs

import json
import logging
import os

logger = logging.getLogger()  # the level comes from ApplicationLogLevel

# INIT phase: runs once per execution environment, not on every invocation.
# SDK clients and connections created here are reused.
TABLE = os.environ["TABLE"]
GREETING = os.environ.get("GREETING", "Hello")


def handler(event, context):
    name = (event.get("queryStringParameters") or {}).get("name", "world")
    logger.info("greeting %s", name)
    return {
        "statusCode": 200,
        "headers": {"content-type": "application/json"},
        "body": json.dumps({"message": f"{GREETING}, {name}!", "table": TABLE,
                            "remaining_ms": context.get_remaining_time_in_millis()}),
    }

Everything outside the handler runs in the INIT phase, once per execution environment. That is the place to read configuration, create SDK clients, and open connections. Environment variables are for non-secret configuration (see environment variables and the 12-factor app). For secrets, use Secrets Manager or Parameter Store.

With LogFormat=JSON, Lambda writes each logging line as JSON, with the level and the requestId, and the minimum level comes from ApplicationLogLevel, with no code changes. For structured logs, metrics, and tracing with less code, Powertools for AWS Lambda (Python, TypeScript, Java, and .NET) is the de facto standard.

Three ways to deploy

1. A zip with the AWS CLI

Flags checked with aws lambda create-function help on CLI 2.42.1. The role must trust lambda.amazonaws.com and have at least the AWSLambdaBasicExecutionRole policy.

zip -j function.zip app.py

aws lambda create-function --function-name hello-lambda \
  --runtime python3.14 --architectures arm64 \
  --handler app.handler --zip-file fileb://function.zip \
  --role arn:aws:iam::123456789012:role/hello-lambda-role \
  --timeout 30 --memory-size 512 \
  --environment 'Variables={TABLE=orders-dev,GREETING=Hi}' \
  --logging-config LogFormat=JSON,ApplicationLogLevel=INFO,SystemLogLevel=WARN

aws lambda wait function-active-v2 --function-name hello-lambda

aws lambda invoke --function-name hello-lambda \
  --cli-binary-format raw-in-base64-out \
  --payload '{"queryStringParameters":{"name":"ana"}}' out.json && cat out.json

# later deploys
aws lambda update-function-code --function-name hello-lambda --zip-file fileb://function.zip

The parameters were also validated with the botocore 1.44.11 Stubber, which checks everything against the real service model. To master --query, profiles, and aws login, see how to manage AWS with the AWS CLI.

2. Terraform

The lab didn’t have the archive provider cached, so the example uses a prebuilt zip (zip -j build/worker.zip sqs_worker.py) and filebase64sha256 to detect changes. With the archive provider, a data "archive_file" builds the zip for you. The code passed terraform validate and fmt -check with hashicorp/aws 6.74.0, without plan or apply. This function is the worker from the SQS section further down.

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 6.0"
    }
  }
}

provider "aws" {
  region = "sa-east-1"
}

resource "aws_iam_role" "worker" {
  name = "orders-worker"
  assume_role_policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Effect    = "Allow"
      Principal = { Service = "lambda.amazonaws.com" }
      Action    = "sts:AssumeRole"
    }]
  })
}

resource "aws_iam_role_policy_attachment" "sqs" {
  role       = aws_iam_role.worker.name
  policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaSQSQueueExecutionRole"
}

resource "aws_iam_role_policy_attachment" "xray" {
  role       = aws_iam_role.worker.name
  policy_arn = "arn:aws:iam::aws:policy/AWSXRayDaemonWriteAccess"
}

resource "aws_cloudwatch_log_group" "worker" {
  name              = "/aws/lambda/orders-worker"
  retention_in_days = 14
}

resource "aws_lambda_function" "worker" {
  function_name    = "orders-worker"
  role             = aws_iam_role.worker.arn
  runtime          = "python3.14"
  architectures    = ["arm64"]
  handler          = "sqs_worker.handler"
  filename         = "${path.module}/build/worker.zip"
  source_code_hash = filebase64sha256("${path.module}/build/worker.zip")
  memory_size      = 512
  timeout          = 60
  publish          = true

  environment {
    variables = { POWERTOOLS_SERVICE_NAME = "orders" }
  }

  logging_config {
    log_format            = "JSON"
    application_log_level = "INFO"
    system_log_level      = "WARN"
  }

  tracing_config {
    mode = "Active"
  }

  depends_on = [aws_cloudwatch_log_group.worker]
}

resource "aws_lambda_alias" "live" {
  name             = "live"
  function_name    = aws_lambda_function.worker.function_name
  function_version = aws_lambda_function.worker.version
}

publish = true creates an immutable version on every change, and the live alias points to it. Point triggers and permissions at the alias: rollback becomes just moving the alias.

3. A container image

Use an image when the package goes past 250 MB, when you need native dependencies, or when the team already lives in containers. The AWS base images ship the runtime and an emulator for local tests.

FROM public.ecr.aws/lambda/python:3.14
COPY requirements.txt ${LAMBDA_TASK_ROOT}
RUN pip install --no-cache-dir -r requirements.txt
COPY app.py ${LAMBDA_TASK_ROOT}
CMD ["app.handler"]

After pushing to ECR, create the function with --package-type Image --code ImageUri=123456789012.dkr.ecr.sa-east-1.amazonaws.com/hello-lambda:1.0, without --runtime or --handler. We didn’t build this base image in the lab. We validated the alternative instead: a python:3.14-slim image with the runtime interface client (awslambdaric) installed, which built and imported the handler. For smaller images, see Docker multi-stage builds.

Features that change the game

Feature What it does Watch out
arm64 (Graviton) Same code, different architecture Native dependencies must be built for arm64
SnapStart Restores a snapshot of the INIT phase Java 11+, Python 3.12+, and .NET 8+; published versions only; no provisioned concurrency, EFS, or /tmp above 512 MB
Response streaming Sends the response progressively, up to 200 MB Native on Node.js; other languages via a custom runtime or the Lambda Web Adapter
Function URLs A direct HTTPS endpoint, no API Gateway Auth AWS_IAM or NONE; with NONE, the function is public
Layers Share libraries across functions 5 at most; they count toward the 250 MB limit
Durable functions Checkpointed steps, waits, and callbacks, suspending for up to 1 year Launched in December 2025; check supported languages
Managed Instances Functions on EC2 in your account, via a capacity provider Many requests per environment, GPUs possible, EC2 pricing

Turn on SnapStart, publish a version with an alias, and create an IAM-protected function URL:

aws lambda update-function-configuration --function-name hello-lambda \
  --snap-start ApplyOn=PublishedVersions
aws lambda wait function-updated-v2 --function-name hello-lambda

VERSION=$(aws lambda publish-version --function-name hello-lambda --query Version --output text)
aws lambda create-alias --function-name hello-lambda --name live --function-version "$VERSION"

# BUFFERED is the default; RESPONSE_STREAM is for functions that stream (e.g. Node.js)
aws lambda create-function-url-config --function-name hello-lambda \
  --qualifier live --auth-type AWS_IAM --invoke-mode BUFFERED

Durable functions and Managed Instances are recent (December and November 2025) and evolving fast; treat the details above as a starting point and check the current docs.

SQS with partial batch responses

With SQS, Lambda polls the queue and delivers batches. Without care, one bad message sends the whole batch back to the queue. With ReportBatchItemFailures, the function returns only the IDs that failed:

import json
import logging

logger = logging.getLogger()


def process(order):
    if order.get("amount", 0) <= 0:
        raise ValueError(f"invalid amount in order {order.get('id')}")
    logger.info("order %s processed", order["id"])


def handler(event, context):
    failures = []
    for record in event["Records"]:
        try:
            process(json.loads(record["body"]))
        except Exception:
            logger.exception("message %s failed", record["messageId"])
            failures.append({"itemIdentifier": record["messageId"]})
    # Only the listed messages go back to the queue; the rest are deleted
    return {"batchItemFailures": failures}

In Terraform, the queue has a DLQ and the event source mapping connects the queue to the alias:

resource "aws_sqs_queue" "dlq" {
  name = "orders-dlq"
}

resource "aws_sqs_queue" "orders" {
  name                       = "orders"
  visibility_timeout_seconds = 360 # 6x the function timeout
  redrive_policy = jsonencode({
    deadLetterTargetArn = aws_sqs_queue.dlq.arn
    maxReceiveCount     = 5
  })
}

resource "aws_lambda_event_source_mapping" "orders" {
  event_source_arn                   = aws_sqs_queue.orders.arn
  function_name                      = aws_lambda_alias.live.arn
  batch_size                         = 100
  maximum_batching_window_in_seconds = 5
  function_response_types            = ["ReportBatchItemFailures"]

  scaling_config {
    maximum_concurrency = 10
  }
}

We tested the handler locally with a three-message event, one of them with a zero amount. It returned {"batchItemFailures": [{"itemIdentifier": "m-2"}]}: only the bad message goes back, and after five receives it moves to the DLQ. Two practical rules: set the queue visibility timeout to at least six times the function timeout (common AWS guidance), and use maximum_concurrency so you don’t drown your database. To choose between SQS, SNS, and EventBridge, see the SNS, SQS, and EventBridge guide.

Cold starts and how to reduce them

A cold start is the time it takes to create a new environment: download the code, start the runtime, and run INIT. It happens on the first call, after idle time, and when scaling up.

  • Lean package: fewer dependencies, less load time.
  • Heavy work in INIT, and only what’s needed: clients created once and reused.
  • SnapStart: restores a snapshot instead of initializing from scratch.
  • Provisioned concurrency: prewarmed environments on an alias, for APIs with tight latency.
  • arm64 and more memory: more memory also brings more CPU, which speeds up INIT.
  • Managed Instances and Web Functions: keep environments warm by design.

Observability

  • Logs: CloudWatch Logs, in JSON, with retention set on the log group.
  • Metrics: Invocations, Errors, Throttles, Duration, and ConcurrentExecutions. With SQS, also watch the queue’s ApproximateAgeOfOldestMessage.
  • Tracing: tracing_config { mode = "Active" } sends traces to X-Ray. The Powertools Tracer or OpenTelemetry add your own spans.
  • Alarms: errors and throttles above zero, duration close to the timeout, and messages in the DLQ.

Costs: the dimensions

No prices here, because they vary by Region and change. What goes into the bill:

  • Requests: each invocation.
  • Duration in GB-seconds: configured memory times execution time, with different rates for arm64 and x86_64.
  • Ephemeral storage above 512 MB.
  • Provisioned concurrency: billed while configured, even with no traffic.
  • SnapStart on Python and .NET: snapshot caching and restores.
  • Data transfer and the services around it (CloudWatch Logs, X-Ray, SQS).
  • Managed Instances: follow EC2 pricing and accept Savings Plans and Reserved Instances.

To cut waste, see FinOps on AWS and Savings Plans and Reserved Instances. To expose functions as a secure API, see API Gateway + Cognito + Lambda.

Checklist

  • Supported runtime (no dotnet8, python3.10, or AL2 for new functions) and arm64 when possible
  • Timeout and memory measured, not guessed
  • JSON logs with retention, and alarms for errors, throttles, and the DLQ
  • Deploys through Terraform or the CLI with published versions and a live alias
  • SQS with ReportBatchItemFailures, a DLQ, and visibility of at least 6x the timeout
  • A cold start strategy (lean package, SnapStart, or provisioned concurrency)
  • Cost dimensions tracked per function and per environment

Lambda shines when you let AWS handle the server and you handle the limits, queues, and metrics yourself.

Get updates on new posts and stay in the loop!