SkillSprout
Chapter 2 · Lesson 1
Intermediate
6 min read

Lambda Execution Model and Configuration

Overview

AWS Lambda runs your code in response to events without you managing servers. You upload a function, choose memory and timeout, and Lambda creates execution environments (lightweight micro-VMs) on demand, runs your handler and bills per millisecond of runtime.

Picture a taxi service. You do not own cars; when a customer calls, a taxi arrives. The first trip needs a taxi to be dispatched and warmed up (cold start), but if the same taxi is free it takes the next customer immediately (warm start). Your job is to make the passengers' trip, your handler, efficient and the dispatch short.

Understanding the lifecycle (init, invoke, shutdown), the resource limits and what persists between invocations is essential for writing correct and fast functions.

Key Concepts

  • Memory is configurable from 128 MB to 10,240 MB; CPU scales proportionally with memory (about 1 vCPU at 1,769 MB).
  • Maximum timeout is 15 minutes (900 s); default is 3 seconds.
  • Lifecycle phases: Init (extensions, runtime, your static code), Invoke (handler) and Shutdown.
  • A cold start occurs when a new environment is created; SnapStart (Java, Python, .NET) and provisioned concurrency reduce it.
  • Code outside the handler is executed once per environment, so it is the place for SDK clients and connections.
  • /tmp provides 512 MB by default (configurable up to 10,240 MB) of ephemeral storage per environment.
  • Deployment package limit: 50 MB zipped direct upload, 250 MB unzipped (including layers); container images up to 10 GB.
  • Environment variables (4 KB total) can be encrypted with KMS; use Secrets Manager or Parameter Store for secrets.

Detailed Notes

Handler anatomy

python
import json, os, boto3

# Init phase: runs once per execution environment
table = boto3.resource("dynamodb").Table(os.environ["TABLE_NAME"])

def handler(event, context):
    # Invoke phase: runs on every request
    item = table.get_item(Key={"id": event["id"]}).get("Item")
    print("remaining ms:", context.get_remaining_time_in_millis())
    return {"statusCode": 200, "body": json.dumps(item, default=str)}
javascript
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocumentClient, GetCommand } from "@aws-sdk/lib-dynamodb";

const doc = DynamoDBDocumentClient.from(new DynamoDBClient({}));

export const handler = async (event) => {
  const { Item } = await doc.send(new GetCommand({
    TableName: process.env.TABLE_NAME, Key: { id: event.id },
  }));
  return { statusCode: 200, body: JSON.stringify(Item) };
};

The context object provides the request ID, function name, remaining time and log stream.

Key limits

SettingValue
Memory128-10,240 MB
Timeoutup to 900 s
Synchronous payload6 MB request and response
Asynchronous payload256 KB
Environment variables4 KB total
/tmp512-10,240 MB
Default account concurrency1,000 per Region (can be raised)

Invocation types

TypeBehaviourExamples
SynchronousCaller waits for the result; errors returned to callerAPI Gateway, ALB, SDK RequestResponse
AsynchronousLambda queues the event, returns 202; retries twice on failureS3, SNS, EventBridge
Event source mapping (poll)Lambda polls the source and invokes with batchesSQS, Kinesis, DynamoDB Streams

Cold start tuning

  • Keep packages small and import lazily.
  • Increase memory (more CPU) to shorten init and runtime; use AWS Lambda Power Tuning to find the cost-optimal setting.
  • Use provisioned concurrency for predictable latency, SnapStart for supported runtimes.
  • Avoid attaching to a VPC unless needed (modern VPC networking has minimal penalty, but still configure subnets correctly).

Configuration as code

yaml
Transform: AWS::Serverless-2016-10-31
Resources:
  OrdersFn:
    Type: AWS::Serverless::Function
    Properties:
      Runtime: python3.12
      Handler: app.handler
      MemorySize: 512
      Timeout: 15
      Architectures: [arm64]
      Environment:
        Variables:
          TABLE_NAME: !Ref OrdersTable
      Policies:
        - DynamoDBReadPolicy:
            TableName: !Ref OrdersTable

Graviton (arm64) functions are typically cheaper per GB-second and often faster.

Logging and errors

Anything written to stdout/stderr goes to CloudWatch Logs in /aws/lambda/<function>. Unhandled exceptions return an error to synchronous callers; for async, the retry policy applies. Return a clean error object rather than letting stack traces leak.

Invoking from the CLI

bash
aws lambda invoke --function-name OrdersFn \
  --cli-binary-format raw-in-base64-out \
  --payload '{"id":"42"}' out.json && cat out.json

Billing

You pay for requests and GB-seconds (duration x memory). More memory costs more per ms but may finish faster, sometimes reducing total cost.

Execution environment lifecycle

PhaseWhat happensDeveloper impact
InitExtensions start, runtime starts, code outside the handler runsCold start; billed (up to 10 s for on-demand)
InvokeHandler runs with an event and contextNormal billed duration
ShutdownRuntime and extensions get a SIGTERM and a short grace periodFlush logs and metrics

After an invocation the environment is frozen and may be reused for later events (a warm start), but never assume reuse. Treat /tmp (512 MB default, up to 10 GB) as a cache, not storage, and never keep per-request state in globals.

python
import os, json, boto3

table = boto3.resource("dynamodb").Table(os.environ["TABLE"])   # init: reused when warm
cache = {}

def handler(event, context):
    print(json.dumps({"requestId": context.aws_request_id,
                      "remainingMs": context.get_remaining_time_in_millis()}))
    key = event["id"]
    if key not in cache:                       # warm-start optimisation only
        cache[key] = table.get_item(Key={"pk": key}).get("Item")
    return cache[key]

Runtimes, architectures and cold-start levers

Choose a supported managed runtime (Python, Node.js, Java, .NET, Ruby) or the provided.al2023 custom runtime for Go, Rust and others. arm64 (Graviton) is cheaper per GB-second and often faster. To reduce cold starts: smaller packages, lazy imports, fewer dependencies, SnapStart (Java, Python, .NET), provisioned concurrency, and avoiding unnecessary VPC attachment delays. Handler signatures differ by language, so a "handler not found" error usually means the Handler setting (file.function) does not match the code.

Real World Example

A media company had a thumbnail function that took 8 seconds at 128 MB. Raising memory to 1,024 MB cut duration to 1 second, so the cost stayed about the same while user latency fell by 85%. They also moved the S3 and Rekognition client creation outside the handler, saving roughly 150 ms per warm invocation, and used arm64 to shave another 20% off the bill.

Architecture Diagram

Lambda execution environment lifecycle
Architecture
AWS Lambda service
Event / caller

Execution environment

Initstatic code, clients
Handlerper request
CloudWatch Logs

Init once per environment, then reuse it for many invocations.

  1. 1An event arrives and Lambda finds or creates an execution environment.
  2. 2On a cold start it runs the Init phase (runtime and your top-level code).
  3. 3The handler runs and returns a result.
  4. 4The environment stays warm for later invocations and then is shut down.

Best Practices

  • ✓Initialise SDK clients and connections outside the handler.
  • ✓Right-size memory with power tuning; consider arm64.
  • ✓Keep deployment packages small and use layers for shared dependencies.
  • ✓Store secrets in Secrets Manager / Parameter Store, not plain environment variables.
  • ✓Treat functions as stateless; persist state in DynamoDB, S3 or elsewhere.

Common Interview Questions

Exam Tips

DVA-C02 focus

  • Max 15 minutes, 10 GB memory, 6 MB sync payload, 256 KB async payload.
  • Reusing connections across invocations -> create them outside the handler.
  • More CPU needed -> increase memory; there is no separate CPU setting.
  • Consistent low latency -> provisioned concurrency.

Finished this lesson?

0 of 46 lessons done · 0% of the course