Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk6 min

Why an AWS Lambda Function Fails Only on Warm Starts, and How to Diagnose It

An AWS Lambda function that works once and fails on the next call usually reuses state from an earlier invocation. Here are the four mechanisms behind warm-only failures and how to diagnose each one.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

When an AWS Lambda function succeeds on one invocation and fails on the next, something from the first call is usually surviving into the second. Lambda reuses execution environments, and whatever the code left behind in them can carry over: a global variable, a callback that has not finished, memory that keeps growing, or a database connection that has gone idle. “Warm-start-only bug” is best read as a diagnostic pattern, not a single root cause. A fresh environment often makes the symptom disappear, but that only clears the leftover state. It does not show that the code is correct.

How Lambda reuses an execution environment

Lambda runs your initialization code once, when it creates an execution environment. On a warm invocation it runs the handler without rerunning that initialization. Anything created at module level or during initialization therefore stays alive for later calls. AWS’s troubleshooting guidance states this directly: “Global variables and objects stored in the INIT phase of a Lambda invocation retain their state between warm invocations.” (Amazon Web Services, Troubleshoot configuration issues in Lambda, “Memory leakage between invocations.”)

As an Amazon Associate I earn from qualifying purchases.

Files written to /tmp can also persist across warm invocations, according to AWS’s lifecycle documentation, so they carry the same risk. The lifecycle documentation also describes the freeze and reuse behavior that makes an environment’s state unpredictable from one call to the next.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What the symptom looks like

A user discussion describes the pattern in its own words: clicking the Test button again to re-run a function “fails with an old error message,” and the same post mentions database operations against a closed connection. That is one anecdote, not a representative sample, but it matches the mechanisms AWS documents. The headline question most engineers end up asking is: why does my Lambda work once, then fail on the next invocation?

The table below lists the four mechanisms that most often explain a failure that appears only when an environment is reused.

Mechanism What carries over Typical symptom on the next call First check
Mutable global state Module-level variables, caches, and objects created during initialization Values from a previous request appear in a later response Search for module-level variables that are written to inside the handler
Unfinished background work Callbacks, promises, or timers still pending when the handler returns Output or errors tied to an earlier event show up during a later invocation Confirm every async operation is awaited or completed before return
Growing memory Data retained in a global collection across calls Duration rises over successive invocations, then timeouts or environment termination Compare memory and duration metrics for each invocation
Idle connections A database or network connection opened during an earlier invocation A connection error on the first query after the environment has been idle Check how the driver detects and replaces an invalid connection

Diagnosing and fixing it, in order

Work through these steps in sequence. The first one tells you whether reuse is involved at all.

1. Compare invocations instead of single runs

A single successful cold invocation proves very little. Look at several invocations that ran in the same environment. In CloudWatch Logs, group them by log stream, and record the request ID, any sequence number your code logs, the error class, duration, and memory used. AWS’s memory-leak walkthrough shows duration rising and then errors appearing as a retained global array grows, which is the trend to look for.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

2. Audit globals and module-level singletons

List every variable defined outside the handler and check whether the handler writes to it. Reusable clients, parsed configuration, and immutable lookup data are fine to keep. Request data, user data, and events are not. AWS’s best practices guidance is explicit: “To avoid potential data leaks across invocations, don’t use the execution environment to store user data, events, or other information with security implications.” (Amazon Web Services, Best practices for working with AWS Lambda functions, “Function code.”)

The following illustrative Python shows the pattern to look for. It is a sketch of the problem, not a tested benchmark.

# Problem: the list lives for the life of the environment and grows on every warm call
results = []

def handler(event, context):
    results.append(event["payload"])
    return {"count": len(results)}

# Safer: request-specific state is created inside the handler
def handler(event, context):
    results = []
    results.append(event["payload"])
    return {"count": len(results)}

If a cache is genuinely needed across calls, give it a deliberate size limit and make sure one caller’s entries cannot be read by another.

3. Check libraries that retain data

AWS warns that some database and logging libraries may grow memory across warm invocations. Look at each library’s documentation for per-request caches, statement caches, result buffers, or log handlers that accumulate entries, and check whether it offers an option to limit or disable them. A library can be the source of growth even when your own code looks clean.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

4. Finish asynchronous work before the handler returns

If a callback, promise, or timer is still running when the handler exits, it can resume when Lambda reuses the environment, which is how output from one invocation can appear during a later one. AWS illustrates exactly this: a callback from one invocation running during a later invocation. Await every promise the handler starts, and clear any timers or listeners it registers. Then confirm the function’s output does not depend on work scheduled after the response.

5. Treat connections as reusable but fallible

Keeping a database connection open between invocations is a reasonable optimization, but AWS warns that Lambda purges idle connections over time, and reusing one can return a connection error. Detect an invalid connection and use the recovery behavior your runtime or driver documents, such as its validation or reconnect options. A safe retry policy depends on the language, driver, database, and operation. Retrying a write that may already have succeeded can duplicate the change, so there is no single reconnect snippet that fits every case.

6. Make duplicate events harmless

Lambda invocations can be retried or delivered more than once, so the handler should behave correctly when it sees the same event twice. AWS recommends idempotent Lambda code. Use a stable event identifier to detect repeats where the operation changes data, and keep request-local state inside the handler so a repeated event starts clean.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Cold-start latency and warm correctness are separate problems

Fixing a cold-start delay and fixing a warm-only failure call for different work, and a change that improves one can hide the other. AWS states that cold starts typically occur in under 1% of invocations. That is a general statement about cold-start frequency in its lifecycle documentation, not a measure of how often warm-start failures happen.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Provisioned concurrency pre-initializes execution environments to reduce cold starts. It does not establish that mutable state or stale connections are safe. A function that passes a test after a fresh deployment has only shown that a new environment works. To verify a warm-start fix, run several invocations in the same environment and check the logs for the trends described in step 1.

What the evidence does and does not establish

  • No prevalence figure exists for warm-start bugs. The official sources reviewed for this article do not publish how often this failure occurs in production, so treat the pattern as a set of causes to check, not a measured frequency.
  • AWS’s demonstration parameters are not thresholds. AWS’s memory-leak example uses a 128 MB function and describes behavior after about 1,000 invocations. These values describe that demonstration only. They do not mark a point where every function will fail.
  • The user report is anecdotal. The closed-connection symptom comes from one discussion and should be read as a description of what the failure can look like, not as evidence of how common it is.
  • Each mechanism is a candidate, not a verdict. Global state, unfinished callbacks, growing memory, and idle connections can all produce warm-only symptoms. Logs and metrics from several invocations are what tell them apart.

Lambda reuse is an optimization, not durable storage. Environments are not guaranteed to persist, so correct behavior must never depend on an environment surviving or being reused.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.