AWS Builder Center
Welcome to LazyTown: How Being Lazy Made My Python Lambda 96.81% Faster

Welcome to LazyTown: How Being Lazy Made My Python Lambda 96.81% Faster

I cut Python Lambda cold starts from 2.5 s to 80 ms (96.81%) without switching to Go. Python's own importtime showed where init went, then right-version .pyc files, lazy imports, ARM64 and memory tuning fixed it, measured over 30 cold starts per variant.

Cloud Security Engineer | Metal Riff Master 🎸
  • AWS SAM CLI:   sam build  command reference How I cut Python Lambda cold starts by 96.81% by asking Python where its init time actually goes, then fixing it with Python's own tools (precompiled bytecode, lazy imports, ARM64, and the right memory size) instead of assuming "just use Go" was the only fix.
Updated November 2026: I rewrote this article after re-running every benchmark on Python 3.14 for my Python Pizza Istanbul talk. The new numbers include two levers the first version missed, precompiled  .pyc  files and Python 3.15's  lazy import , and a fairer final race where every variant runs the same app. I also re-ran all 19 tests from the original version: every one landed within 5% of its earlier result.
In LazyTown, Sportacus spends every episode chasing people away from the couch. In my benchmark, being lazy on purpose, in exactly the right place, turned out to be the best decision I made.
Python baseline Cold Total P50 2506.73 ms
Optimized Python Cold Total P50 79.84 ms

Improvement 96.81%

Same language. Same app. A very different setup.
This article is the write-up behind my talk at Python Pizza Istanbul, and it's about that setup: what I changed, what I measured, and which of my assumptions turned out to be wrong.

Why I Ran This Experiment

Every AWS Lambda cold-start conversation eventually arrives at the same sentence:
"Just use Go."
Go is genuinely a strong fit for a lot of serverless workloads: compiled binary, fast start, thin runtime. Nobody needs convincing of that, and this article isn't trying to un-convince anyone.
The question I cared about was different. In the talk, Go is Sportacus and Python is Robbie Rotten: the runner with the great ecosystem who can't get out of bed until he's done all his morning imports. Our problem isn't Sportacus. It's Robbie. What do we have to change to get Robbie race-ready?
So I built a small benchmark rig, picked one app, and changed one thing at a time until I had an answer.

First, What Am I Actually Measuring?

A Lambda invocation, simplified, looks like this:
COLD START (no ready execution environment)

+---------+ +-----------------------+ +---------+ +----------+
| REQUEST | -> | INIT | -> | HANDLER | -> | RESPONSE |
+---------+ | - start the runtime | +---------+ +----------+
| - import your modules |
| - run top-level code |
+-----------------------+
^ Init Duration ^ Duration

WARM INVOCATION (environment already running)

+---------+ +---------+ +----------+
| REQUEST | ------------------------------> | HANDLER | -> | RESPONSE |
+---------+ +---------+ +----------+

If there's no ready execution environment, Lambda builds one from scratch: the runtime starts, your module is imported, and your init code runs. Only after that does the handler see the request. That's a cold start, and it happens after idle periods, after deploys, and while scaling out. If an environment is already warm, the request goes straight to the handler.
Here's the sentence the rest of this article hangs on: the  INIT  box looks like "runtime startup," but your imports and all of your module-level code run there too.
For every variant in this benchmark, I collected:
  •  Init P50 
  •  Cold Total P50 
  •  Warm P50 
  •  Cold P90 
 Cold Total P50  is the number this whole article is built around, and it's worth being precise about it, because it isn't a metric AWS hands you. It's one I defined:
Cold Total = Init Duration + Duration

I ran 30 cold invocations and 30 warm invocations per variant, and I only accepted a sample as "cold" when the Lambda  REPORT  line actually included an  Init Duration . My benchmark script forces a fresh execution environment before every cold sample by updating the function's  Description  with a unique nonce and waiting for the update to finish. It's a best-effort way to force a cold start, not an official AWS API for it:
def force_refresh(function_name: str) -> None:
nonce = f"lazytown-bench-{uuid.uuid4().hex[:16]}"
run([
"aws", "lambda", "update-function-configuration",
"--function-name", function_name,
"--description", nonce,
"--output", "json",
])
run([
"aws", "lambda", "wait", "function-updated",
"--function-name", function_name,
])

And here's the part of the parser that decides whether a sample even counts as cold:
def parse_report(log_text: str) -> dict:
m = REPORT_RE.search(log_text)
if not m:
raise RuntimeError(f"REPORT line not found:\n{log_text}")

duration = float(m.group("duration"))
init = float(m.group("init")) if m.group("init") else None

return {
"duration_ms": duration,
"init_ms": init,
"cold_total_ms": (duration + init) if init is not None else None,
"is_cold": init is not None,
}

One more honesty note before the results: these numbers describe this experiment, this workload, this region, and these runtime versions. They're not a universal Lambda performance guarantee, and I'll keep saying "in this experiment" throughout, not as a disclaimer reflex, but because it's genuinely the only claim the data supports.

Round 1: Wait... That's It?

I started small, on purpose: a tiny handler, tiny JSON in, tiny JSON out. ARM64, 512 MB, same payload for both runtimes.
Go Cold Total P50 50.89 ms
Python 3.14 Cold Total P50 79.59 ms

Difference 28.70 ms

About 29 ms. That's it. For a workload this small, the number is set by Lambda's own initialization, not by the language.
A side note for Python folks: the same code on the Python 3.13 runtime came in at 63.83 ms, so moving to 3.14 added about 16 ms to the cold start in this test. That's one tiny handler, not a general rule. The message is simpler: measure your runtime upgrades too.
But a real Python app doesn't arrive empty-handed. It arrives with imports. That's where the actual race starts.

Robbie's Morning: Ask Python Where Init Goes

I took a Lambda that uses pandas and asked Python itself where the time goes.  PYTHONPROFILEIMPORTTIME=1  is the environment-variable form of  python -X importtime , and its output lands directly in CloudWatch Logs:
Environment:
Variables:
PYTHONPROFILEIMPORTTIME: "1"

The answer:
Init P50 716.31 ms
import pandas 634 ms
Other imports 59.93 ms
Modules loaded 624

pandas share of init ~89%

One line,  import pandas , is about 89% of init.
Small honesty note: the 634 ms and 59.93 ms come from a single cold start with the profiler switched on, and the profiler adds some overhead of its own. The 716.31 ms is the median of 30 cold starts. So the parts don't add up exactly to the total, but the proportion holds.
One more result, because it was my favorite surprise in the first version of this article: I once shipped a roughly 125 MB pile of dependencies the handler never imported, and the cold start didn't care. I measured it again for this version. Still nothing:
Never-imported dependencies +0 ms

Shipping a dependency is free. Importing it is not. Robbie's morning isn't lost packing the suitcase; it's lost at breakfast.

Training #1: Be Lazy on Purpose

Picture a Lambda function with two request paths:
  •  simple : doesn't touch pandas
  •  report : genuinely needs pandas
Setup for this round: ARM64, 512 MB, Python 3.14, with correctly precompiled  .pyc  files (more on why that matters in Training #2).

The eager version

import json
import pandas as pd

def lambda_handler(event, context):
request_type = event.get("type", "simple")

if request_type == "simple":
return {
"statusCode": 200,
"body": json.dumps({"mode": "simple", "ok": True}),
}

rows = event.get("rows", [])
frame = pd.DataFrame(rows)
total = int(frame["value"].sum()) if not frame.empty else 0

return {
"statusCode": 200,
"body": json.dumps({"mode": "report", "total": total}),
}

Every single  simple  request pays for  import pandas as pd , even though  simple  never touches a DataFrame.

The lazy version

import json

def lambda_handler(event, context):
request_type = event.get("type", "simple")

if request_type == "simple":
return {
"statusCode": 200,
"body": json.dumps({"mode": "simple", "ok": True}),
}

import pandas as pd

rows = event.get("rows", [])
frame = pd.DataFrame(rows)
total = int(frame["value"].sum()) if not frame.empty else 0

return {
"statusCode": 200,
"body": json.dumps({"mode": "report", "total": total}),
}

Same handler.  pandas  just moved from the top of the file to the one branch that actually needs it.
For a  simple  request:
Eager Cold Total P50 719.49 ms
Lazy Cold Total P50 82.46 ms

Improvement 88.54%

That's the number that gets applause. But there's a second half to it that matters just as much.
For a  report  request, the one that actually needs pandas:
Eager report Cold Total P50 739.08 ms
Lazy report Cold Total P50 2689.39 ms

3.64x slower

Same import. Same work. So why is it more than three and a half times slower?
In the first version of this article, my honest answer was "I don't know." This time I measured it. The eager version's init barely moves with memory:
Eager Init P50 at 128 MB 716.61 ms
Eager Init P50 at 1769 MB 712.48 ms

Memory doesn't change init. During init, Lambda appears to give the function more CPU regardless of the memory setting. AWS doesn't document this; it's my observation from these numbers. In the handler, on the other hand, CPU scales with memory, and 512 MB is roughly a third of a vCPU. Move the import into the handler and the exact same work runs on a throttled CPU. Give the lazy version 1769 MB and its  report  path drops to 792.49 ms.
Cost caveat: since August 2025, the INIT phase is billed for on-demand functions packaged as ZIP files with managed runtimes. Putting work in init is faster, but it isn't free anymore.
If you remember one sentence from this section, make it this: did you remove the work, or did you just postpone it? Be lazy when you can skip the work entirely, not when you're only postponing it to a worse moment.

Training #2: Pre-compile

This is, I think, the most Python-specific part of the whole experiment.
When Python imports a module, it first looks for compiled bytecode (a  .pyc  file) in  __pycache__ . If there isn't one, it compiles the source and tries to write the result back there. On Lambda, your code lives in  /var/task , which is read-only. Python can't write the cache. So if your package arrives without  .pyc  files, the hundreds of files inside pandas get compiled from scratch on every single cold start.
How do you end up there without noticing?  uv pip install  doesn't produce  .pyc  files by default.  pip  does, but with your build machine's Python version, which may not be your Lambda runtime's.
The measurement, pandas app, 512 MB:
No .pyc 2039.99 ms
.pyc for 3.13 2045.19 ms
.pyc for 3.14 719.49 ms

Right .pyc -> 64.73% lower Cold Total P50
Wrong-version .pyc = no .pyc

Look at the middle row. Bytecode compiled for Python 3.13, shipped to the 3.14 runtime, does nothing. Python only reads  .pyc  files tagged for its own version ( module.cpython-314.pyc ), so wrong-version bytecode is exactly as good as no bytecode.
The fix is one command, run with the same Python version as your runtime:
python3.14 -m compileall -q --invalidation-mode unchecked-hash .

 --invalidation-mode unchecked-hash  makes Python trust the bytecode without comparing it against source timestamps, so ZIP file timestamps can't trip it up.
And unlike everything else in this article, this one isn't a trade-off. Both  simple  and  report  get faster. It's the no-regret step.

Training #3:  lazy import  (Python 3.15, PEP 810)

Python 3.15 brings PEP 810: explicit lazy imports. You don't have to move the import into the function anymore. You write it at the top of the file:
import json
lazy import pandas as pd

def lambda_handler(event, context):
request_type = event.get("type", "simple")

if request_type == "simple":
return {
"statusCode": 200,
"body": json.dumps({"mode": "simple", "ok": True}),
}

rows = event.get("rows", [])
frame = pd.DataFrame(rows) # pandas is loaded here, on first use
total = int(frame["value"].sum()) if not frame.empty else 0

return {
"statusCode": 200,
"body": json.dumps({"mode": "report", "total": total}),
}

The name  pd  is bound immediately, and the module is actually loaded the first time it's used.
Python 3.15 on Lambda is currently in public preview. I measured it anyway, at 1024 MB:
Eager Lazy

simple 753.34 ms -> 79.97 ms (89.38% lower)
report 747.79 ms -> 1328.80 ms (1.78x slower)

Same trade-off as the in-function import: the cost is still postponed, not removed. But no code moves. The imports stay at the top of the file, where people expect to read them.
Two warnings: linter and type-checker support for the new syntax is still fresh, and 3.15 on Lambda is still a preview. This is for tomorrow, not for production today.

Training #4: Free Wins

Two gains that need no change to your Python code at all.

ARM64

Same pandas app, only the architecture changed:
x86_64 Cold Total P50 948.03 ms
arm64 Cold Total P50 719.49 ms

Improvement 24.11%

On Lambda,  arm64  runs on AWS Graviton processors, and the SAM change is one line:
Resources:
LazyTownFunction:
Type: AWS::Serverless::Function
Properties:
Runtime: python3.14
Handler: app.lambda_handler
Architectures:
- arm64
MemorySize: 1024

Before you flip it, check that all your dependencies publish ARM64 wheels. If any of them ship native binaries, build for the target architecture ( sam build --use-container  before  sam deploy --guided ).

Memory Is Also CPU

A CPU-bound handler, with nothing changed except  MemorySize :
Memory Cold Total P50

128 MB 2196.22 ms
512 MB 608.72 ms
1024 MB 346.86 ms
1769 MB 225.15 ms

Warm cost (GB-ms) 264 / 262 / 266 / 214

At 1769 MB, a function gets the equivalent of one full vCPU. In this test, that made the warm path 17x faster and 19% cheaper than 128 MB. More memory finished the work so much faster that the bill went down.
What memory does not change is init-time imports. As Training #1 showed, init stays the same at every size. Memory speeds up the handler, not the imports you do at module level.

The Final Race

This time the race is fair: the same app, the same dependencies, both  simple  and  report  requests, and 30 cold starts per cell. Each row adds one thing on top of the row before it:
Variant SIMPLE REPORT

Baseline (x86, 512, no .pyc) 2,506.73 ms 2,507.44 ms
+ ARM64 + 1024 MB 2,033.68 ms 2,038.55 ms
+ .pyc 736.52 ms 725.17 ms
+ .pyc + lazy import 79.84 ms 1,340.81 ms
+ .pyc + SnapStart 389.80 ms 559.00 ms
Go (reference) 49.40 ms 50.10 ms

Reading it row by row:
  • Baseline: x86, 512 MB, no  .pyc . If you package with uv and don't compile, this is you. 2.5 seconds.
  • ARM64 + 1024 MB: about 2 seconds. Better, still slow.
  • +  .pyc : 737 ms. The no-regret step: about 64% lower than the previous row, on both paths.
  • + lazy import:  simple  drops to 80 ms,  report  climbs to 1,341 ms. That's the trade-off from Training #1, and Python 3.15's  lazy import  gives the same result.
  • + SnapStart: if most of your traffic takes the  report  path, SnapStart wins it at 559 ms. It's a paid feature, though.
  • Go: 49 ms.
A note on the SnapStart row: you can't force a snapshot restore the way I force a regular cold start, so I collected SnapStart's cold samples with 30 concurrent requests instead.
The number I actually care about:
2506.73 ms -> 79.84 ms
96.81% lower Cold Total P50

Go still wins the final line, and I'm not going to pretend otherwise:
Go 49.40 ms
Optimized Python 79.84 ms

But that was never the bet I was making. This was never "Python beats Go." Robbie went from 2.5 seconds to 80 milliseconds. We didn't change the language. We changed how Python wakes up.
One honest caveat before I move on: the baseline-to-optimized jump stacks several changes at once (architecture, memory, bytecode, import strategy). It's a combined configuration result, not proof that any single lever alone is worth 96.81%. Each lever's isolated contribution is exactly what the training sections above measured separately.

What Actually Moved the Needle

Laid out side by side, this is the part I'd put on a slide:
Pre-compile (.pyc) 2039.99 -> 719.49 ms (64.73% lower) <- both paths
Lazy import 719.49 -> 82.46 ms (88.54% lower) <- simple path only
PEP 810 lazy import 753.34 -> 79.97 ms (89.38% lower) <- simple path only
ARM64 948.03 -> 719.49 ms (24.11% lower)
Memory tuning 2196.22 -> 225.15 ms (89.75% lower) <- handler, not init
Unused 125 MB deps +0 ms
Final Python 2506.73 -> 79.84 ms (96.81% lower)

Two of these are worth staring at together:
Right-version .pyc -> faster on every path
Lazy import -> faster on one path, 3.64x slower on the other

Both sound like reasonable serverless advice on their own. Only actually measuring told me that one is free and the other is a trade-off. That's exactly why I'm not turning this into a universal checklist ("always use ARM64," "always allocate 1769 MB," "always lazy-load everything"). That would be the wrong lesson from a right result.
The lesson I'm actually taking is a loop, not a list:
MEASURE -> FIND THE BOTTLENECK -> CHANGE ONE THING -> MEASURE AGAIN


What I'd Actually Do in Production

When you go back to your own Lambda functions, start with three questions:
  • What runs at init?  python -X importtime  (or  PYTHONPROFILEIMPORTTIME=1  on Lambda) will tell you.
  • Is it precompiled, and for the right Python version?
  • Does every request actually need that import?
Then:
  1. Look at distributions, not single runs. P50, P90, P99: one lucky invocation tells you nothing.
  1. Keep cold and warm behavior separate. They're different execution paths with different costs.
  1. Ship  .pyc  files built by your runtime's Python version. It's the cheapest win in this article.
  1. Audit your module-level imports. An expensive top-level import is an invisible tax on every cold start.
  1. Use lazy imports where a real share of traffic skips the expensive path, not everywhere by default.
  1. Test ARM64 compatibility early, especially if native dependencies are involved.
  1. Tune memory against latency and cost together. In this test, more memory was also cheaper.
  1. Measure runtime upgrades. 3.13 to 3.14 wasn't free in my tiny-handler test.

Reproducing This

The code and every raw measurement are in the repository. The v3 folders hold the numbers in this version of the article; the original folders are kept for the re-run comparison:
lazytown-lambda-cold-starts/
├── README.md
├── scripts/
│ ├── benchmark.py
│ ├── summarize.py
│ └── v3/
│ ├── build.py
│ ├── deploy.py
│ └── run_all.py
├── experiments-v3/
│ ├── app/
│ ├── go/
│ ├── payloads/
│ └── variants.json
├── results-v3/
│ ├── raw.csv
│ ├── summary.csv
│ ├── importtime.txt
│ └── reproducibility.md
├── experiments/
├── results/
└── tests/

Command-line shape, for anyone who wants to point this at their own function:
python scripts/benchmark.py \
--function-name your-function-name \
--label optimized-python \
--payload payload.json \
--cold 30 \
--warm 30 \
--output results/raw.csv

python scripts/summarize.py \
results/raw.csv \
--csv results/summary.csv \
--md results/summary.md

The exact CLI matters less than what it enforces: the benchmark stays repeatable, the raw samples get preserved (not just the final chart), and P50/P90 get calculated from the actual data every time, not eyeballed off one lucky run.

Measure First

What I learned from Robbie: not doing unnecessary work is a performance strategy too.
  • Your imports run in init. An expensive top-level import is a tax every cold invocation pays, whether it needs the dependency or not.
  • Bytecode compiled for the wrong Python version is the same as no bytecode.
  • A big dependency you ship but never import costs nothing at cold start; the same dependency imported lazily on the wrong path can cost you more than importing it eagerly.
  • Memory is CPU for your handler, but not for your init.
  • None of this generalizes automatically to your workload. Rerun the measurement before you trust the conclusion.
Go still finished ahead: 49.40 ms to 79.84 ms. But Python recovered 96.81% of its own baseline cold-start time without a single line of it being rewritten in another language, and that's the number I actually walked away caring about.
Measure first. Optimize what actually hurts.



References

  • 
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article