Trying Out Python 3.15 on AWS Lambda with Event Functions and Web Functions

Trying Out Python 3.15 on AWS Lambda with Event Functions and Web Functions

The Python 3.15 runtime is now GA for Event Functions and in public preview for Web Functions, so I tested both. New features like frozendict and sentinel worked, and FastAPI ran on Web Functions.
2026.11.22

This page has been translated by machine translation. View original

Introduction

On November 20, 2026, support for Python 3.15 was added to AWS Lambda.

https://aws.amazon.com/about-aws/whats-new/2026/11/aws-lambda-python-315/

The Lambda Python 3.15 runtime was available as a public preview in August 2026.

https://dev.classmethod.jp/articles/lambda-preview-python315-node26/

This time, I'll share the results of trying the Python 3.15 runtime with Event Functions and with Web Functions, which has started to be offered as a public preview.

Test Environment

  • Region: Tokyo (ap-northeast-1)
  • AWS CLI: 2.42.1
  • Event Function architecture: x86_64
  • Event Function memory: 128 MB

Event Functions

Creating and Running the Function

I created a function that uses frozendict, sentinel, and lazy import with the python3.15 runtime. I saved the following code as lambda_function.py.

import sys

# explicit lazy import: sqlite3 is not loaded at this point
lazy import sqlite3

MISSING = sentinel("MISSING")

def lookup(config, key):
    value = config.get(key, MISSING)
    return "not set" if value is MISSING else value

def lambda_handler(event, context):
    result = {"sys.version": sys.version}

    # frozendict
    config = frozendict(region="ap-northeast-1", memory=128)
    result["frozendict"] = {
        "repr": repr(config),
        "hashable": isinstance(hash(config), int),
        "lookup_region": lookup(config, "region"),
        "lookup_timeout": lookup(config, "timeout"),
    }
    try:
        config["memory"] = 256
    except TypeError as e:
        result["frozendict"]["setitem_error"] = str(e)

    # sentinel
    result["sentinel"] = {
        "repr": repr(MISSING),
        "type": type(MISSING).__name__,
        "is_not_None": MISSING is not None,
    }

    # lazy import
    result["lazy_import"] = {
        "sqlite3_loaded_before_use": "sqlite3" in sys.modules,
    }
    result["lazy_import"]["sqlite_version"] = sqlite3.sqlite_version
    result["lazy_import"]["sqlite3_loaded_after_use"] = "sqlite3" in sys.modules

    return result

I prepared an execution role.

Creating the execution role

I saved the trust policy as trust-policy.json.

{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"Service":"lambda.amazonaws.com"},"Action":"sts:AssumeRole"}]}
aws iam create-role --role-name yattemita-py315-event --assume-role-policy-document file://trust-policy.json --query Role.RoleName
aws iam attach-role-policy --role-name yattemita-py315-event --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole

I packaged the single file into a zip and created the function with --runtime python3.15.

zip event.zip lambda_function.py
aws lambda create-function --function-name yattemita-py315-event --runtime python3.15 --handler lambda_function.lambda_handler --role arn:aws:iam::111122223333:role/yattemita-py315-event --zip-file fileb://event.zip --query '{FunctionName:FunctionName,Runtime:Runtime,Architectures:Architectures,State:State,PackageType:PackageType}'
{
    "FunctionName": "yattemita-py315-event",
    "Runtime": "python3.15",
    "Architectures": [
        "x86_64"
    ],
    "State": "Pending",
    "PackageType": "Zip"
}

Immediately after creation, the State is Pending, so I waited until it became Active before running it.

aws lambda wait function-active-v2 --function-name yattemita-py315-event
aws lambda invoke --function-name yattemita-py315-event --log-type Tail --cli-binary-format raw-in-base64-out --payload '{}' --query '{StatusCode:StatusCode,LogResult:LogResult}' response.json
cat response.json
{"sys.version": "3.15.2 (main, Oct 27 2026, 20:23:37) [GCC 11.5.0 20240719 (Red Hat 11.5.0-5)]", "frozendict": {"repr": "frozendict({'region': 'ap-northeast-1', 'memory': 128})", "hashable": true, "lookup_region": "ap-northeast-1", "lookup_timeout": "not set", "setitem_error": "'frozendict' object does not support item assignment"}, "sentinel": {"repr": "MISSING", "type": "sentinel", "is_not_None": true}, "lazy_import": {"sqlite3_loaded_before_use": false, "sqlite_version": "3.40.0", "sqlite3_loaded_after_use": true}}

sys.version showed that the function ran on Python 3.15.2.

Checking the New Features of 3.15

frozendict and sentinel could be used as-is without importing. Assigning to an element of a frozendict raised a TypeError, and hash() returned an integer. MISSING, created with sentinel, worked as the default value for config.get.

The lazily imported sqlite3 was not in sys.modules before use, and it was included after referencing sqlite3.sqlite_version.

Init Duration with lazy import

Measurement Method

Modules imported with lazy import are not loaded until they are used. I created a function that loads the same 16 standard library modules with regular imports (eager version) and a function that loads them with lazy import (lazy version), and compared their Init Duration. The handler doesn't use any of the modules; it just returns how many of the 16 are in sys.modules.

The creation steps are the same as in the previous section, and the function names are yattemita-py315-lazy and yattemita-py315-eager. I updated an environment variable to trigger a cold start and measured the Init Duration in the REPORT line 10 times for each.

Lazy version code and creation command

lambda_function.py (lazy version):

import sys

lazy import asyncio
lazy import ssl
lazy import sqlite3
lazy import decimal
lazy import http.client
lazy import email.mime.text
lazy import xml.dom.minidom
lazy import unittest
lazy import zipfile
lazy import tarfile
lazy import argparse
lazy import csv
lazy import multiprocessing
lazy import concurrent.futures
lazy import urllib.request
lazy import pydoc

MODULES = "asyncio ssl sqlite3 decimal http.client email.mime.text xml.dom.minidom unittest zipfile tarfile argparse csv multiprocessing concurrent.futures urllib.request pydoc".split()

def lambda_handler(event, context):
    loaded = [m for m in MODULES if m in sys.modules]
    return {"mode": "lazy", "listed": len(MODULES), "loaded_at_handler": len(loaded)}
zip lazy.zip lambda_function.py
aws lambda create-function --function-name yattemita-py315-lazy --runtime python3.15 --handler lambda_function.lambda_handler --role arn:aws:iam::111122223333:role/yattemita-py315-event --zip-file fileb://lazy.zip --query '{FunctionName:FunctionName,Runtime:Runtime,Architectures:Architectures,MemorySize:MemorySize}'

The eager version is the same code except that lazy is removed from each import statement and "mode" in the returned dictionary is set to "eager". In the creation command, I replaced lazy in the function name and zip file name with eager.

Measurement script

I saved it as measure-init.sh and ran it with bash measure-init.sh <function-name> 10.

#!/bin/bash
# Change the environment variable to force a cold start and extract the REPORT line
# usage: measure-init.sh <function-name> <count>
set -euo pipefail
fn=$1; n=$2
for i in $(seq 1 "$n"); do
  aws lambda update-function-configuration --function-name "$fn" \
    --environment "Variables={ROUND=$i-$(date +%s)}" --query LastUpdateStatus --output text >/dev/null
  aws lambda wait function-updated-v2 --function-name "$fn"
  aws lambda invoke --function-name "$fn" --log-type Tail --payload '{}' \
    --cli-binary-format raw-in-base64-out --query LogResult --output text /tmp/out-$fn.json \
    | base64 -d | grep REPORT | sed "s/^/$fn run$i: /"
done

Measurement Results

The values in the table are the aggregated Init Duration from 10 cold starts (in ms, x86_64, 128 MB). The measurement loops for the lazy and eager versions were run in parallel.

Version Median Mean Min Max
lazy version 118.0 115.5 92.8 139.1
eager version 259.0 295.9 216.1 538.7

Even the fastest run of the eager version (216.08 ms) was slower than the slowest run of the lazy version (139.06 ms).

The handler's return value loaded_at_handler was 16 for the eager version and 2 for the lazy version. The 2 modules loaded in the lazy version were decimal and concurrent.futures, which were loaded at handler execution time even in a function that imports nothing. The difference in the table is the result of the remaining 14 being deferred.

Web Functions

ASGI App with Only the Standard Library

For the Web Function, I defined an ASGI app named app in main.py. I saved the app, written using only the standard library, as web-min/main.py. To check whether frozendict also works in Web Functions, I included its repr in the response.

import json
import sys

async def app(scope, receive, send):
    if scope["type"] != "http":
        return
    body = json.dumps({
        "message": "Hello from Lambda Web Functions",
        "sys.version": sys.version,
        "method": scope["method"],
        "path": scope["path"],
        "frozendict": repr(frozendict(path=scope["path"])),
    }).encode()
    await send({
        "type": "http.response.start",
        "status": 200,
        "headers": [(b"content-type", b"application/json")],
    })
    await send({"type": "http.response.body", "body": body})

I deployed with aws lambda-web deploy, specifying a directory for --code and python for --runtime.

aws lambda-web deploy --name yattemita-py315-web --code web-min --runtime python --create
Creating deployment package ...
Preparing Amazon S3 bucket ...
Preparing AWS IAM execution role ...
Uploading deployment package ...
Creating Lambda Web Function ...
Waiting for endpoint to become active (timeout 600s) ...
Waiting for endpoint to become active (state Pending, 0s elapsed, timeout 600s) ...
Waiting for endpoint to become active (state Pending, 5s elapsed, timeout 600s) ...
https://<ID>.r8m.lambda-web.ap-northeast-1.on.aws

When --runtime python is specified, the revision's runtimeConfig becomes python3.15. I confirmed this with aws lambda-web get-web-function-revision.

"runtimeConfig": {
    "runtime": "python3.15"
}

I sent a request with curl to the output endpoint.

curl -sS -i -m 60 'https://<ID>.r8m.lambda-web.ap-northeast-1.on.aws/hello?x=1'
HTTP/1.1 200 OK
Server: uvicorn
Date: Sat, 21 Nov 2026 15:34:41 GMT
date: Sat, 21 Nov 2026 15:34:41 GMT
Content-Type: application/json
lambda-web-logstream: 2026/11/21/yattemita-py315-web[rev-rpuuo]<ID>
Transfer-Encoding: chunked
lambda-web-request-id: SMEGUYQFBBW2YWE3SUOHQDRVB4

{"message": "Hello from Lambda Web Functions", "sys.version": "3.15.2 (main, Nov 12 2026, 21:19:02) [GCC 11.5.0 20240719 (Red Hat 11.5.0-5)]", "method": "GET", "path": "/hello", "frozendict": "frozendict({'path': '/hello'})"}

The following warning was output to the CloudWatch Logs log group /aws/lambda/web/yattemita-py315-web.

LAMBDA_WARNING: This is a preview runtime version and should not be used for production workloads. For further information and to provide feedback, see https://docs.aws.amazon.com/lambda/latest/dg/web-functions-runtimes.html

This warning did not appear in the Event Function's execution logs.

FastAPI App

The help for deploy says that Web Functions run on arm64 and that deploy does not install dependencies. It also includes an example of installing for arm64 with uv pip install, which uses --python-platform aarch64-manylinux_2_34 --python-version 3.15. Here, I used the Docker python:3.15 image to install the arm64 cp315 wheels into the project directory.

web-fastapi/requirements.txt contains just one line.

fastapi
docker run --rm --user "$(id -u):$(id -g)" -e HOME=/tmp -v "$(pwd)/web-fastapi:/app" -w /app python:3.15 pip install -r requirements.txt --target . --only-binary=:all: --python-version 3.15 --platform manylinux2014_aarch64 --platform manylinux_2_28_aarch64 --platform manylinux_2_34_aarch64
Downloading pydantic_core-2.50.5-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.whl (2.1 MB)
...
Successfully installed annotated-doc-0.0.7 annotated-types-0.8.0 anyio-4.16.0 fastapi-0.165.0 idna-3.20 opentelemetry-api-1.45.2 pydantic-2.14.4 pydantic-core-2.50.5 starlette-1.10.0 typing-extensions-4.16.0 typing-inspection-0.4.5

pydantic-core has a cp315 arm64 wheel, so it could be installed without building from source. I wrote the app in web-fastapi/main.py.

import sys

from fastapi import FastAPI

app = FastAPI()

@app.get("/hello-world")
async def hello_world():
    return {
        "message": "Hello from Lambda Web Functions",
        "sys.version": sys.version,
        "frozendict": repr(frozendict(framework="fastapi")),
    }

The deployment is the same as in the previous section, and I specified the directory with the installed dependency packages for --code.

aws lambda-web deploy --name yattemita-py315-fastapi --code web-fastapi --runtime python --create
curl -sS -i -m 60 https://<ID>.r8m.lambda-web.ap-northeast-1.on.aws/hello-world
HTTP/1.1 200 OK
Server: uvicorn
Date: Sat, 21 Nov 2026 15:35:38 GMT
date: Sat, 21 Nov 2026 15:35:38 GMT
Content-Type: application/json
Content-Length: 191
lambda-web-logstream: 2026/11/21/yattemita-py315-fastapi[rev-kxmgs]<ID>
lambda-web-request-id: 7TZPR5T33Z2ILBHQNBPEMRY3VE

{"message":"Hello from Lambda Web Functions","sys.version":"3.15.2 (main, Nov 12 2026, 21:19:02) [GCC 11.5.0 20240719 (Red Hat 11.5.0-5)]","frozendict":"frozendict({'framework': 'fastapi'})"}

Without specifying --entry-point or the environment variable AWS_LAMBDA_PYTHON_ENTRYPOINT, FastAPI worked with the default main:app.

Summary

With the Python 3.15 runtime, which is GA for Lambda Event Functions and has started to be offered as a public preview for Web Functions, I was able to confirm the behavior of frozendict, sentinel, lazy import, and more.

Also, Python can now be used with Web Functions, which had previously been Node.js only, and both an ASGI app using only the standard library and FastAPI worked.

If you want to use something other than Node.js with Web Functions, give the Python 3.15 runtime a try.

Share this article

AWSのお困り事はクラスメソッドへ