Testland
Browse all skills & agents

cold-start-budget-reference

Pure-reference catalog of latency budgets across serverless runtimes: cold starts AND timeouts. Covers AWS Lambda's three-phase cold start (Init: download+unzip+runtime-bootstrap; Init code: imports + module load; Invoke: handler execution), Cloudflare Workers' isolate model (sub-millisecond cold starts via V8 isolates per developers.cloudflare.com), Vercel Edge Runtime, Lambda SnapStart for JVM (snapshot-restore for Java), and provisioned-concurrency trade-offs, plus Lambda timeout + billing budgets in references/timeout-budgets.md (the 15-minute hard limit, getRemainingTimeInMillis, per-ms billing, memory-CPU scaling, the API Gateway 29s / SQS visibility-timeout integration cascade). Use when designing latency or timeout budgets, choosing a runtime, sizing memory, or auditing cold-start variance in production.

Install with skills.sh (any agent)

npx skills add testland/qa --skill cold-start-budget-reference
View source

cold-start-budget-reference

Overview

Per aws.amazon.com/blogs/compute on cold starts (opens in new window), Lambda's cold start has three phases:

  1. Init - download deployment package, unzip, bootstrap the runtime (Node/Python/Java/etc.).
  2. Init code - execute module-level imports + global setup.
  3. Invoke - the actual handler call.

Phases 1 + 2 are the "cold" part. Phase 3 is what runs every invocation (cold or warm).

When to use

  • Designing a latency budget for a Lambda / Workers / Edge function.
  • Investigating "p95 is fine but p99 is 5s."
  • Choosing a runtime - Cloudflare's isolate model is qualitatively different from Lambda containers.
  • Auditing provisioned-concurrency / SnapStart configurations.

How to use

  1. Look up the runtime's typical range in the per-runtime budget table (e.g. Node.js 256MB is 200-700ms; Java 11 without SnapStart is 1.5-6s).
  2. Set the latency budget as two lines: p50/p95 tracks warm performance, and a separate p99 line absorbs the cold-start tail.
  3. Force a cold start (deploy, or wait past the idle-evict window) and record p95 first-invocation latency against the budget.
  4. If cold starts breach budget, apply the matching mitigation from below: SnapStart (JVM/.NET), provisioned concurrency, package-size trimming, lazy imports, or a pre-compiled runtime (Go/Rust).
  5. Add the build-step and monitoring assertions from Testable behaviours (zipped artifact < 50MB, init phase < 500ms, CloudWatch Init Duration).
  6. Re-measure after each change and confirm the p99 tail moved, not just p50/p95.

Per-runtime cold-start budgets

Per AWS, Cloudflare, Vercel docs (typical ranges; bigger packages and bigger memory-class skew higher):

RuntimeTypical cold startArchitecture
AWS Lambda Node.js (256MB)200-700msContainer (Firecracker microVM)
AWS Lambda Python (256MB)250-800msContainer
AWS Lambda Java 11 (512MB, no SnapStart)1.5-6sContainer + JVM warmup
AWS Lambda Java 11 (512MB, SnapStart)100-300msSnapshot-restore per docs.aws.amazon.com/lambda (opens in new window)
AWS Lambda .NET (1GB)1-3sContainer + .NET runtime
AWS Lambda Go (256MB)100-300msContainer; pre-compiled binary
AWS Lambda Rust (256MB)50-200msContainer; pre-compiled binary
Cloudflare Workers0-5ms (V8 isolate spawn)V8 isolate per developers.cloudflare.com/workers (opens in new window)
Vercel Edge Runtime5-30msV8 isolate (similar to Workers)
Vercel Node.js Functions200-500ms (small) to 2-3s (large)Lambda under the hood
Netlify Functions300ms-2sLambda under the hood

The "Workers / Edge" qualitative leap is the isolate model: each function is a V8 isolate, spun up in microseconds per developers.cloudflare.com (opens in new window) - no container, no OS startup.

Mitigations

Provisioned concurrency (AWS Lambda)

Per docs.aws.amazon.com/lambda (opens in new window): keeps N execution environments pre-initialised. Eliminates cold starts up to N concurrent requests; you pay for the keep-warm time.

Trade-off: cost. A constant N=10 provisioned concurrency for 30 days ≈ $30-300 depending on memory class.

Lambda SnapStart (Java / .NET)

Per docs.aws.amazon.com/lambda/latest/dg/snapstart.html (opens in new window): takes a snapshot of the initialised JVM and restores from it on each cold start. Reduces Java cold starts from 1.5-6s → 100-300ms.

Caveats:

  • State snapshot includes connections, random seeds; can't have per-instance unique values frozen.
  • Hooks beforeCheckpoint / afterRestore let you re-prime non-serializable state.

Package-size discipline

Lambda cold-start scales with deployment-package size. Per AWS: keep under 50MB (zipped) → cold start in the 200-800ms range. Larger packages → seconds.

Avoid heavy module-level imports

Init code runs once but on every cold start. Heavy imports (database connection pool init, large dependency trees) inflate init time.

# Bad: top-level
import heavy_lib            # 2s import time
def handler(event, ctx):
    return heavy_lib.do_thing(event)

# Better: lazy-import
def handler(event, ctx):
    import heavy_lib
    return heavy_lib.do_thing(event)

Lazy imports add per-warm-call latency but reduce cold-start spike.

Runtime choice

Pre-compiled runtimes (Go, Rust) have far lower cold starts than managed runtimes (Java, Python). For latency-critical paths, runtime choice is a primary lever.

Timeout budgets

Cold start is the front of the latency budget; the back is the timeout. Lambda's 15-minute hard limit, the getRemainingTimeInMillis early-return pattern, per-ms billing and the memory-CPU relationship, and the integration timeout cascade (API Gateway's hard 29s, SQS visibility timeouts, Lambda@Edge limits) are cataloged in references/timeout-budgets.md.

Testable behaviours

BehaviourTest
Cold start within budgetForce cold (deploy or wait > idle-evict time); measure p95 first-invocation latency
Warm performanceSubsequent invocations (50+) → p95 well within prod budget
SnapStart effectivePre/post SnapStart cold start delta
Provisioned concurrency keeps warmRun for an hour; no cold-start spikes observed
Package size in budgetBuild-step assertion: zipped artifact < 50MB
No heavy init-time importsProfile init phase; assert < 500ms

Worked example

A Java 11 Lambda (512MB) serves a low-traffic checkout callback. Users report occasional multi-second waits, though the dashboard p95 looks healthy.

  1. The per-runtime table puts Java 11 without SnapStart at 1.5-6s cold start; p95 hides it because cold starts land in the p99 tail.
  2. Enable SnapStart, which snapshot-restores the initialised JVM and drops the cold start to the 100-300ms range.
  3. Re-prime non-serializable state in an afterRestore hook so a stale pooled DB connection is not frozen into the snapshot.
  4. Force a cold start (wait past idle-evict) and compare Init Duration before and after; confirm the p99 line, not just p95, falls.

Result: the cold-start tail drops from ~5s to the 100-300ms range with no provisioned-concurrency spend.

Anti-patterns

Anti-patternWhy it failsFix
p99 latency surpriseCold starts at the tail; not visible in p50/p95Watch p99; explicit cold-start monitoring (CloudWatch Init Duration metric)
Large dependency tree on init pathCold start inflated 2-5xAudit imports; lazy-import non-critical
Java on Lambda without SnapStart5s cold startsEnable SnapStart
Provisioned concurrency without size analysisPay for unused warm instancesTune to actual concurrency p99
Cold-start test only on the local dev environmentLocal doesn't simulate Lambda initDeploy + test against AWS / Workers / Edge
Treat cold starts as "rare"Bursty traffic → cold starts clusterAccount for both steady-state and burst patterns
Ignore module bundlingWebpack-bundled is smaller AND has fewer import resolution hopsBundle for production Lambdas

Limitations

  • Cold-start measurement is platform-side. CloudWatch Init Duration metric is canonical for Lambda; Workers / Edge expose their own.
  • SnapStart caveats are subtle. State that survives the snapshot may be wrong (random seeds, connection state).
  • Provisioned-concurrency is regional. Multi-region Lambdas need PC per region.
  • Workers / Edge are not free of all variance. First request per (script, region) still has 5-30ms init.
  • Doesn't address steady-state throughput. Cold start is one metric; concurrency-limit + duration are separate.

References

AWS Lambda timeout + billing budgets

View source (opens in new window)

AWS Lambda timeout + billing budgets

AWS Lambda's wall-clock limit is 15 minutes (900 seconds) per invocation. Per docs.aws.amazon.com/lambda configuration-timeout (opens in new window): "The default value for this setting is 3 seconds, but you can adjust this in increments of 1 second up to a maximum value of 900 seconds (15 minutes)." For longer work use Step Functions, AWS Batch, or ECS Fargate - don't architect around the limit.

Timeout vs deadline at runtime

Per docs.aws.amazon.com/lambda python-context (opens in new window), the Context object exposes get_remaining_time_in_millis() (Python) / getRemainingTimeInMillis() (Node/JVM). Break out proactively:

def handler(event, context):
    while not_done:
        if context.get_remaining_time_in_millis() < 5000:
            save_checkpoint()
            return {"status": "partial", "checkpoint": ...}
        do_work_chunk()
    return {"status": "complete"}

The 5-second cushion lets the handler return cleanly; without it the Lambda is force-killed at timeout (no SIGTERM grace) and the caller gets a 504-equivalent.

Billing semantics

Per docs.aws.amazon.com/lambda lambda-pricing (opens in new window):

Cost componentDetail
Request charge$0.20 per 1M requests (us-east-1)
Compute chargeMemory-class × GB-seconds (billed per ms)
Init durationFree; not billed (per AWS; historically has changed - verify current docs)

GB-second formula: memory_GB * duration_seconds. A 512MB Lambda running 1000ms costs 0.5 * 1.0 * $0.0000166667 = $0.00000833; per million 1s invocations at 512MB: ~$8.54 including the request charge.

Memory ↔ CPU relationship

Per docs.aws.amazon.com/lambda configuration-memory (opens in new window): "The amount of CPU available to a function is proportional to the memory you allocate to it. At 1,769 MB, a function has the equivalent of one vCPU." Compute-bound workloads should size memory by CPU need; the sweet spot is usually the memory class where wall-clock time stops dropping (often 1024-2048MB).

Integration timeout cascade

The integration's timeout is often the operational ceiling:

IntegrationTimeoutLambda config
API Gateway (REST + HTTP API)29 seconds (hard)Lambda timeout MUST be < 29s
Application Load Balancer4s default; configurable to 4000sConfigurable both sides
CloudFront (Lambda@Edge)5s viewer functions; 30s originTight viewer limit
SQS (event source)Per-queue visibility timeout (default 30s)Visibility > Lambda timeout × 6 (AWS recommendation)
DynamoDB Streams6h batch windowPer-batch limit
EventBridge (async)Retries on timeoutIdempotency required
Step FunctionsPer-task timeout; default 60sPer-task tuning

The API Gateway 29-second hard limit is the most-encountered surprise: a Lambda configured for 60s still times out at 29s because API Gateway gives up first.

Testable behaviours

BehaviourTest
Completes within timeout under prod loadk6 / load run against the deployed function
Graceful return via remaining-time checkInject slowness; assert "partial", not 504
API Gateway 29s budget honouredLong-running endpoint via API GW URL; assert ≤ 29s
SQS visibility > Lambda timeoutForce a timeout; observe SQS re-delivery
Memory sweet spot foundRun at 256/512/1024/2048 MB; chart duration
Cost at p99 within budgetLatency × memory × invocations × price/GB-s at p99, not average

Anti-patterns

Anti-patternWhy it failsFix
Timeout = 900s "for safety"Stuck Lambdas burn 15min; concurrency limits hitMatch timeout to p99 + buffer
Lambda timeout > API Gateway's 29sAPI GW kills first; Lambda runs unusedTimeout < 29s behind API GW
SQS visibility < Lambda timeoutIn-flight message re-delivered → duplicatesVisibility > timeout × 6
No remaining-time checkForce-kill; no progress savedCheck + early-return
Sizing memory by RAM need onlyCompute-bound work wastes wall-clockTune by p95 duration
Cost calculated from the averagep99 spikes blow the budgetCalculate against p99

Notes

  • Per-region pricing varies; the figures above are us-east-1.
  • Workers / Edge have different models: Cloudflare Workers 10ms CPU free / 50ms paid, 30s wall-clock; Vercel Edge Functions 30s wall-clock max.

References

Related skills

aws-sam-local-testing

Wraps AWS SAM (Serverless Application Model) Local CLI for testing Lambda functions locally: `sam local invoke` (single invocation with event payload), `sam local start-api` (local API Gateway emulator), `sam local start-lambda` (local Lambda invoke endpoint for AWS SDK clients), and event-payload generation (`sam local generate-event`). For C#/.NET Lambdas, references/dotnet.md covers handler-direct testing with Amazon.Lambda.TestUtilities (TestLambdaContext, TestLambdaLogger) and the dotnet-lambda CLI. Use when testing Lambda + API Gateway + integrated AWS services locally.

azure-functions-tests

Runs Azure Functions locally using Azure Functions Core Tools v4 (`func start`), Azurite storage emulation, and framework-native unit tests for handler code (.NET isolated worker model, Node.js v4, Python v2). Covers HTTP, queue, and timer trigger testing, admin-endpoint invocation for non-HTTP triggers, and binding verification via local.settings.json. Use when testing Azure Functions before deployment, reproducing trigger behaviour without live Azure services, or gating function handler logic in CI.

cloudflare-workers-miniflare

Wraps Miniflare 3 (the official Cloudflare Workers simulator) and Wrangler dev for testing Workers locally. Covers Miniflare's getMiniflare() programmatic API (workerd-backed simulation matching prod), the wrangler dev local-mode (live-reload during dev), KV / Durable Objects / R2 / D1 bindings emulation, and Vitest + @cloudflare/vitest-pool-workers for in-process tests. Use when testing Cloudflare Workers code locally.

serverless-integration-test-builder

Workflow-driven skill that builds the integration-test suite for a serverless application from its IaC definition (SAM template / serverless.yml / Wrangler config / Vercel functions / Netlify functions). Walks through: identifying the function inventory + event sources, picking the right local-emulator per function (sam local / Miniflare / netlify dev / vercel dev / serverless-offline), generating test events per event source, asserting on cold-start + timeout budgets, and emitting the test directory + CI config. Use when introducing integration tests to a serverless project.