Scrivio Interview library
ScenarioIntermediate7 min read · updated 12 November 2026

A Spring Cloud Function running on AWS Lambda has p99 cold starts of 6 seconds, and the business wants under 1 second. What options do you have and what are their trade-offs?

First we measure where the 6 seconds go, JVM start, Spring context initialization and the first request, and trim auto-configuration and dependencies. Then we choose among AWS Lambda SnapStart, which restores a snapshot of the initialized runtime but needs care with anything that must be unique, a GraalVM native image built with Spring Boot AOT, which starts very fast at the cost of longer builds and a closed-world model, provisioned concurrency, which removes cold starts for a fixed cost, or moving steady traffic to a container service.

Why this question is asked

A cold start happens when Lambda has no warm execution environment for a request and must create one: start a JVM, load our code and run Spring's initialization before the first event is handled. For Java with Spring this is often several seconds, and at p99 it is what users notice. Interviewers ask this because there is no single fix; each option trades build complexity, money or correctness for speed. In this answer, we will measure the cold start, trim it, and then compare SnapStart, native images, provisioned concurrency and containers, with what each costs.

1Measuring Before Changing Anything

A cold start has three parts. The JVM start and class loading of the runtime itself, Spring's context initialization, which creates beans, runs auto-configuration and opens connections, and the first request, which is slow because classes are loaded lazily and the JIT compiler has not optimized anything yet. Lambda reports an Init Duration in the REPORT log line for cold invocations, which covers the first two parts, and the Duration of that same invocation shows the slow first request.

Suppose the numbers are: 0.8 seconds JVM start, 3.9 seconds Spring init and 1.3 seconds first request. That tells us Spring init is the main target, and that even a perfect init still leaves a slow first request unless we warm the code paths.

Where the 6 seconds go (example)
PhaseMeasuredTypical fixes
JVM start0.8 sSnapStart, native image, more memory (more CPU)
Spring context init3.9 sTrim auto-configuration, lazy beans, SnapStart
First request1.3 sPriming before snapshot, tiered compilation settings

2Trimming the Application

The cheapest gains come from doing less. Every starter on the classpath brings auto-configurations that Spring evaluates at startup, so removing unused dependencies, such as a web starter in a function that does not serve HTTP, often saves a second on its own. We can exclude auto-configurations we do not need, avoid component scanning of large packages, and make heavy beans lazy so they are created only when an event needs them.

Lambda allocates CPU in proportion to memory, so raising the function from 512 MB to 2 GB often cuts init time sharply for a small price per invocation. And the JVM flag -XX:TieredStopAtLevel=1, set through JAVA_TOOL_OPTIONS, makes the JIT compile quickly with simpler optimizations, which helps short-lived functions. Together these may bring 6 seconds to 3, which is good but not under 1.

3Option 1: SnapStart

SnapStart, available for Java managed runtimes, runs the init phase once when we publish a version, takes a snapshot of the memory and disk of the initialized environment, and restores new environments from that snapshot instead of initializing again. Restores typically take a few hundred milliseconds, so the Spring init cost almost disappears from the cold path. Check which Java runtimes and regions support it today.

But there is a catch: every environment restored from one snapshot starts with the same memory. A random number generator seeded during init produces the same sequence in every copy, a UUID generator may repeat, and network connections opened during init point to sockets that no longer exist. SnapStart supports runtime hooks based on the CRaC API, where beforeCheckpoint and afterRestore methods let us close connections before the snapshot and reopen or reseed after restore. Spring Boot supports these lifecycle hooks, so beans that implement Lifecycle are stopped and started around the checkpoint.

Java
public class Priming implements org.crac.Resource {
public Priming() { org.crac.Core.getGlobalContext().register(this); }
@Override public void beforeCheckpoint(org.crac.Context<? extends org.crac.Resource> c) {
invoiceFunction.apply(sampleOrder()); // run the hot path so classes load before the snapshot
dataSource.close(); // never snapshot an open connection
}
@Override public void afterRestore(org.crac.Context<? extends org.crac.Resource> c) {
dataSource.reopen(); // fresh connection in each restored copy
}
}
// cold start after SnapStart + priming: about 400 ms restore + about 150 ms first request (example)

Notice the priming call in beforeCheckpoint. Running a sample request before the snapshot means the snapshot already contains loaded classes, which attacks the slow first request too.

4Option 2: A GraalVM Native Image

A native image compiles the application ahead of time into a standalone executable. Spring Boot's AOT processing analyzes the context at build time and generates the bean definitions as code, so at runtime there is almost nothing to discover. Startup is typically well under a second, often around 100 to 300 ms, and memory use is much lower, which also lowers the Lambda price.

The costs are real. Builds take minutes and need a lot of memory. The closed-world model means everything must be known at build time: reflection, dynamic proxies and resources used by libraries need hints, and libraries without native support may fail at runtime in ways the JVM never showed. Peak throughput can be lower than a warmed-up JIT for long-running work. On Lambda the native executable runs on a custom runtime, so we also own that packaging. It is a strong option for a small function with well-supported libraries.

5Option 3: Provisioned Concurrency, and Option 4: Containers

Provisioned concurrency keeps a number of environments initialized and ready at all times, so requests up to that number never see a cold start. It needs no code change, which makes it the fastest way to meet the target. The price is a fixed hourly cost for each provisioned environment whether it is used or not, and traffic above the provisioned level still gets cold starts, so it suits predictable load, possibly scheduled up during business hours.

Finally, we should ask whether a function is the right shape. If the service receives steady traffic all day, a container on a managed service such as ECS with Fargate or on Kubernetes runs warm all the time, starts once per deployment, and can be cheaper than functions once traffic is high and constant. Functions shine for spiky or rare work; for a steady API they may cost more and add cold starts we then pay to remove.

Step throughChoosing an option
  1. Measure and trimremove dependencies, more memory, lazy beans
  2. Under 1 s now?
    YesDoneNoContinue
  3. Traffic steady all day?
    YesConsider a container serviceNoKeep functions
  4. Can the code handle snapshot restore?
    YesSnapStart with hooks and primingNoNative image or provisioned concurrency

4 steps in order. Play them, or step through them one at a time.

6What I Would Recommend

I would trim first, then try SnapStart, because it usually delivers sub-second cold starts with the normal JVM, normal libraries and a modest code change for connections and randomness. If the function has strict latency at all times and predictable traffic, provisioned concurrency on top of it covers the peak hours. A native image is the next step if SnapStart is not supported for our runtime or the gains are not enough, and the libraries are known to work natively. And I would look at the traffic graph, because if it is flat, moving to containers may solve cost and latency together.

7Follow-up questions

What breaks when a SnapStart snapshot is restored?

Anything that assumed it was created once. Random seeds and SecureRandom state captured in the snapshot are shared by all restored copies, so values meant to be unique may repeat; the JDK reseeds some sources, but our own generators need afterRestore hooks. Network connections opened during init, such as database pools or HTTP clients with keep-alive, are dead after restore. Cached credentials and tokens may have expired, and timestamps computed at init, such as a start time used in ids, are stale. The fix is to avoid creating these during init or to recreate them in afterRestore.

Does increasing memory really help init?

Yes, because Lambda gives CPU in proportion to memory, and Spring init is CPU-bound. Doubling memory often nearly halves init time, and since we pay per millisecond, the cost increase is smaller than it seems.

Is Spring Cloud Function itself the problem?

Rarely. Most of the time goes to the libraries and beans the application loads, not to the function adapter.

8Conclusion

In this answer, we split the 6-second cold start into JVM start, Spring init and the first request, and trimmed dependencies, auto-configuration and memory settings first. We then compared SnapStart, which restores an initialized snapshot but needs hooks for uniqueness and connections, a native image with Spring Boot AOT, which starts fastest but brings build and closed-world costs, provisioned concurrency, which removes cold starts for a fixed price, and containers for steady traffic.

What to say in the interviewAbout 80 seconds aloud

Open with

I would start by measuring. Lambda's Init Duration and the first invocation's duration tell me how much is JVM start, Spring context init and the slow first request, and usually Spring init dominates.

Then, if they want more

The first round is trimming: remove unused starters and auto-configurations, make heavy beans lazy, raise memory because CPU scales with it, and use tiered compilation level 1. That often halves the time but rarely reaches one second. Then the real options.

SnapStart snapshots the initialized environment and restores it, typically in a few hundred milliseconds, and I can prime the hot path before the snapshot. The catch is uniqueness and resources: random seeds, generated ids, open connections and cached credentials are shared or stale after restore, so I use the CRaC hooks to close and reopen them.

A GraalVM native image with Spring Boot AOT starts in a fraction of a second and uses less memory, but builds are slow, reflection needs hints, and the closed-world model can break libraries. Provisioned concurrency removes cold starts without code changes but costs a fixed amount per environment.

And if traffic is steady, a container service may be cheaper and simpler. My usual recommendation is trim, then SnapStart, adding provisioned concurrency for peak hours if needed.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
Spring Boot reference
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A Spring Cloud Function running on AWS Lambda has p99 cold starts of 6 seconds, and the...": https://scrivio-interview-library.netlify.app/spring-boot/spring-projects/204416c616/