StackPractices
advanced By Mathias Paulenko

Reduce AWS Lambda Cold Start with Provisioned Concurrency

Minimize Lambda cold start latency using provisioned concurrency, ARM64 Graviton, lighter dependencies, and initialization code optimization.

Overview

A cold start is the delay AWS adds when it has to create a fresh execution environment for your function — downloading the code and layers, booting the runtime, running your module-level code — before the first line of the handler executes. On Python with light dependencies it’s usually 200-500ms; pull in pandas or a framework and it jumps to 1-3 seconds. On synchronous APIs that’s latency users feel, and it compounds under bursty traffic because every scale-out event is another cold start.

This recipe works through the full toolbox: measuring init duration properly, provisioned concurrency for the paths that must be fast, lazy initialization and package trimming for everything else, ARM64 for a free speedup, and warm-up pings as a budget alternative. Each one is shown as working code, with the trade-off spelled out — provisioned concurrency eliminates cold starts but bills you 24/7, warm-up plugins are cheap but leaky.

When to Use This

  • Lambda functions serving synchronous HTTP APIs with strict latency requirements
  • Functions with heavy dependencies (pandas, SQLAlchemy, SDK clients)
  • Production workloads where cold starts cause user-visible delays or timeouts
  • Functions that need predictable response times under variable traffic
  • Java functions where SnapStart alone can’t cover the remaining init gap

Skip most of this when the function runs async — queue consumers, cron jobs, and event processors tolerate cold starts because nobody is waiting on the response. And before paying for provisioned concurrency, check that the cold start is actually the problem: if the handler itself is slow, warming the environment will not help.

Prerequisites

  • Python 3.11+ Lambda function
  • AWS CLI with permissions to configure concurrency
  • Understanding of your function’s initialization cost

Solution

1. Measure Cold Start

Every new execution environment logs Init Duration in its REPORT line — that is the number you are optimizing. To flag cold starts inside the function itself, use a module-level flag, not a context attribute (nothing on context tells you the environment is new):

import json
import time

# Module-level: True only for the first invocation in this environment
cold_start = True

def lambda_handler(event, context):
    global cold_start
    start = time.time()
    is_cold_start = cold_start
    cold_start = False

    response = {
        "cold_start": is_cold_start,
        "init_time_ms": round((time.time() - start) * 1000, 2),
        "remaining_time_ms": context.get_remaining_time_in_millis(),
    }

    return {
        "statusCode": 200,
        "headers": {"Content-Type": "application/json"},
        "body": json.dumps(response),
    }

Log cold starts with CloudWatch Insights:

filter @type = "REPORT"
| parse @message "* Duration: * ms Billed Duration: * ms Memory Size: * MB Max Memory Used: * MB*" as type, duration, billed, memory, maxMemory
| parse @message "* Init Duration: * ms*" as type2, initDuration
| filter ispresent(initDuration)
| stats avg(initDuration), max(initDuration), count() by bin(1h)

2. Provisioned Concurrency

Pre-warm execution environments so they’re ready to serve immediately. This is the only technique that guarantees no cold start — everything else only reduces the odds or the impact. The catch is pricing: provisioned concurrency bills for the GB-seconds of capacity you reserve whether requests flow or not, roughly $10/month for one always-on unit of a 1GB function. Set it to your baseline traffic, never to peak.

# Enable provisioned concurrency on an alias
aws lambda put-provisioned-concurrency \
  --function-name my-api \
  --qualifier prod \
  --provisioned-concurrent-executions 10
# template.yaml (SAM)
Resources:
  ApiFunction:
    Type: AWS::Serverless::Function
    Properties:
      FunctionName: my-api
      Handler: lambda_function.lambda_handler
      Runtime: python3.11
      CodeUri: src/
      AutoPublishAlias: prod
      ProvisionedConcurrencyConfig:
        ProvisionedConcurrentExecutions: 10

Provisioned concurrency only applies to published versions or aliases — it doesn’t work on $LATEST. If traffic exceeds the provisioned pool, the overflow still cold-starts, so pair it with the init-time optimizations below.

3. Lazy Initialization

Move expensive initialization inside the handler — only runs on first request, not on cold start:

import json

# BAD: Module-level initialization — runs on every cold start
# import pandas as pd
# df = pd.read_csv('data.csv')  # 2-3 seconds

# GOOD: Lazy initialization — only runs when needed
_pd = None
_df = None

def get_pandas():
    global _pd
    if _pd is None:
        import pandas as pd
        _pd = pd
    return _pd

def get_data():
    global _df
    if _df is None:
        pd = get_pandas()
        _df = pd.read_csv('data.csv')
    return _df

def lambda_handler(event, context):
    df = get_data()
    result = df.head(10).to_dict(orient="records")
    return {
        "statusCode": 200,
        "body": json.dumps(result),
    }

Lazy init doesn’t make the cost disappear — it moves it to the first real request. For endpoints hit on every request that ‘s a wash; for optional code paths (admin routes, report generation) it is a clean win because most invocations never pay it.

4. Switch to ARM64 (Graviton2)

ARM64 Graviton2 processors run Python’s C extensions measurably faster and cost ~20% less per GB-second:

# Update function architecture
aws lambda update-function-configuration \
  --function-name my-api \
  --architectures arm64

# Rebuild layer for ARM64
docker run --rm --platform linux/arm64 \
  -v "$PWD/layer":/var/task \
  public.ecr.aws/lambda/python:3.11-arm64 \
  /bin/sh -c "pip install -r requirements.txt --target /var/task/python"

Remember to rebuild your layers for arm64 — an x86 wheel in a layer will fail on Graviton at import time, and the error only shows up on cold start.

5. Reduce Package Size

Cold start time tracks package size because phase one is literally downloading your code. Strip everything that isn’t needed at runtime:

# Remove tests, docs, __pycache__
find layer/python -type d -name "tests" -exec rm -rf {} +
find layer/python -type d -name "__pycache__" -exec rm -rf {} +
find layer/python -type f -name "*.pyc" -delete
find layer/python -type f -name "*.so" -exec strip {} \;

# Use lighter alternatives
# Instead of pandas: use polars (10x smaller, faster init)
# Instead of requests: use urllib3 or boto3's built-in HTTP client
# Instead of SQLAlchemy: use raw psycopg2 or aiobotocore

Layers help here too: Lambda caches layer downloads more aggressively than the function zip, so moving dependencies to a layer trims the repeated part of every cold start.

6. Connection Reuse Outside Handler

Initialize clients once at module level so they persist across warm invocations. This is the one piece of module-level code you’d want — SDK clients are cheap to build and expensive to rebuild per-request:

import json
import boto3
import os

# Module-level: runs once per execution environment
# These persist across warm invocations
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table(os.environ['TABLE_NAME'])

# But keep it light — only clients, not data
def lambda_handler(event, context):
    # Warm invocation reuses the table client
    response = table.get_item(Key={'id': event['pathParameters']['id']})
    return {
        "statusCode": 200,
        "body": json.dumps(response.get('Item', {})),
    }

7. Use Lambda Powertools for Structured Logging

Avoid heavy logging frameworks that slow initialization:

from aws_lambda_powertools import Logger
from aws_lambda_powertools.logging import correlation_paths

logger = Logger()

@logger.inject_lambda_context(correlation_id_path=correlation_paths.API_GATEWAY_REST)
def lambda_handler(event, context):
    logger.info("Processing request", extra={"path": event["path"]})
    return {"statusCode": 200, "body": json.dumps({"ok": True})}

8. Warm-Up Plugin (Serverless Framework)

Keep functions warm with periodic invocations:

# serverless.yml
service: my-api

provider:
  name: aws
  runtime: python3.11

functions:
  api:
    handler: lambda_function.lambda_handler
    events:
      - http: { path: /data, method: get }

plugins:
  - serverless-plugin-warmup

custom:
  warmup:
    warmerName: 'warmer'
    schedule: 'rate(5 minutes)'
    concurrency: 5
    batchSize: 1

Warm-up keeps environments alive but guarantees nothing: Lambda decides when to recycle environments, and a traffic spike still cold-starts beyond whatever capacity happens to be warm. Treat it as a cost optimization, not an SLA tool.

How It Works

  1. Cold start phases: (1) Download function code + layers, (2) Initialize runtime (Python interpreter), (3) Load modules and run module-level code, (4) Execute handler. Phases 1-3 are the “init duration” shown in CloudWatch — everything outside the handler.
  2. Provisioned concurrency: AWS pre-creates execution environments and keeps them ready. Requests are routed to pre-warmed environments with zero init time. Scale-from-zero only happens beyond the provisioned capacity.
  3. Lazy initialization: Module-level code runs on every cold start. Moving expensive operations (file reads, heavy imports) into functions that run on first use defers the cost to when it’s actually needed.
  4. ARM64: Graviton2 processors have different instruction pipelines that can be faster for Python’s C extensions. The runtime itself is also optimized for ARM.
  5. Warm invocations: After a cold start, the execution environment persists for roughly 5-15 minutes of activity. Subsequent invocations reuse it — no init duration. Warm-up plugins send periodic pings to keep environments alive.
Mermaid flowchart LR diagram

Variants

SnapStart (Java)

For Java functions, SnapStart caches the initialized JVM:

# SAM template
Resources:
  JavaFunction:
    Type: AWS::Serverless::Function
    Properties:
      Runtime: java21
      Handler: com.example.Handler
      SnapStart:
        ApplyOn: PublishedVersions

Custom Runtime with Minimal Init

# Use a minimal ASGI adapter instead of a full framework
# Instead of Flask/FastAPI (heavy init), use a raw handler
def lambda_handler(event, context):
    method = event['httpMethod']
    path = event['path']

    if method == 'GET' and path == '/health':
        return {"statusCode": 200, "body": '{"status":"ok"}'}

    if method == 'GET' and path.startswith('/products/'):
        product_id = path.split('/')[-1]
        return handle_get_product(product_id)

    return {"statusCode": 404, "body": '{"error":"not found"}'}

EFS for Large Dependencies

Mount EFS instead of packaging large files in the deployment:

Resources:
  ApiFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: lambda_function.lambda_handler
      Runtime: python3.11
      CodeUri: src/
      FileSystemConfigs:
        - Arn: !GetAtt AccessPoint.Arn
          LocalMountPath: /mnt/data

EFS trades the download cost for a network filesystem dependency — worth it for models or datasets that would never fit in a deployment package, not worth it to shave a few MB.

Best Practices

  • For a deeper guide, see Package Python Dependencies for AWS Lambda with Layers.
  • Profile before optimizing: Use CloudWatch Insights to measure init duration. Don’t guess — measure.
  • Move only expensive init to lazy: Module-level clients (boto3) are cheap. File reads, heavy imports, and data processing should be lazy.
  • Right-size memory: More memory = more CPU. 1024MB often halves cold start vs 256MB. Test different sizes.
  • Use provisioned concurrency for critical paths: Only enable it for functions where cold start is user-visible (APIs). Background workers can tolerate cold starts.
  • Minimize dependencies: Every import adds to init time. Use pip install --no-deps to check what a package pulls in.
  • Keep handler code small: The handler zip should be under 5MB. Move dependencies to layers.

Common Mistakes

  • Importing everything at module level: import pandas at the top adds 1-2 seconds to every cold start. Use lazy imports.
  • Reading files at module level: open('config.json').read() runs on every cold start. Cache it in a global with lazy init.
  • Over-provisioning concurrency: Provisioned concurrency costs money 24/7. Set it to your baseline traffic, not peak.
  • Ignoring memory configuration: Lambda allocates CPU proportional to memory — about one full vCPU at ~1,769MB. A 128MB function is CPU-starved and slow to init.
  • Using heavy frameworks: Flask + Werkzeug add 200-500ms of init. Use lightweight handlers or API Gateway + Lambda proxy integration.
  • Checking context for cold starts: There is no context.warm attribute — the detection pattern is a module-level flag, as shown in step 1.

Further Reading

Frequently Asked Questions

What is a typical cold start duration?

Python functions with light dependencies: 200-500ms. With pandas/numpy: 1-3 seconds. Java with Spring: 5-10 seconds (use SnapStart). Provisioned concurrency reduces this to near zero.

Does provisioned concurrency eliminate cold starts entirely?

For requests within the provisioned capacity, yes. If traffic exceeds provisioned concurrency, new environments are created with normal cold starts. Set provisioned concurrency to your expected baseline.

How does memory affect cold start?

Lambda allocates CPU proportional to memory — roughly one full vCPU at ~1,769MB. A 256MB function gets about 1/7 of a vCPU, so initialization is proportionally slower. For most functions, 1024-2048MB is the sweet spot.

Can I avoid cold starts without provisioned concurrency?

You can reduce them with warm-up plugins (periodic pings), but not eliminate them. Warm environments eventually expire. Provisioned concurrency is the only guarantee.

How much does provisioned concurrency actually cost?

It bills per GB-second of reserved capacity — roughly $10/month for one unit of a 1GB function held 24/7, regardless of traffic. Size it to baseline load and let on-demand environments absorb the peaks.

Does SnapStart work for Python?

No. SnapStart is Java-only. It captures the initialized JVM state as a snapshot and restores it in milliseconds. For Python, use provisioned concurrency and lazy initialization.