Scrivio Interview library
ScenarioIntermediate7 min read · updated 12 November 2026

A team enabled spring.main.lazy-initialization=true to speed up startup, and now the first requests after deployment are slow and some fail with bean creation errors. What do you advise?

Lazy initialisation did not remove the startup work; it moved it to the first requests, which is why they are slow, and it stopped Spring from checking configuration at startup, which is why bad deployments now pass health checks and fail with bean creation errors under real traffic. I would advise keeping spring.main.lazy-initialization for local development and tests, turning it off in production or at least excluding critical beans with @Lazy(false), fixing the beans that are actually slow, and making readiness wait for a warm-up if first-request latency matters.

Why this question is asked

Startup time matters more than it used to, because containers are started and stopped all the time and slow startups slow every deployment and scale-out. Spring Boot's lazy-initialization property looks like a free win, and a team that measures only the startup time will see a big improvement. Interviewers give this scenario to see whether we understand what the property really does and can advise a team without simply telling them to turn it off. In this answer, we will see what the property changed, why the first requests became slow, why errors now escape the health check, and what to do instead, from measuring the real slow beans to a warm-up before readiness.

1What the Property Actually Changed

Normally Spring Boot creates every singleton bean while the application starts, in the last phase of the context refresh. spring.main.lazy-initialization=true marks every bean definition as lazy, so Spring only creates the beans the startup path itself touches. A controller, the service it calls, the repository and perhaps a heavy client are now created when the first request needs them.

Notice that the total work is the same. The same constructors run, the same connection pools open, the same caches load. The property only changes when it happens. A service whose startup dropped from 40 seconds to 12 seconds still has roughly 28 seconds of bean creation waiting somewhere, and the first users pay for it.

Where the work goes with lazy initialisation
Eager (default)Lazy initialisation on
Startup time40 s12 s
First request to /orders80 ms6 s (creates controller, service, client)
Missing property in a beanstartup fails, rollout stopsapp starts, first request fails
Health check after deployonly passes when beans are finepasses before most beans exist
Illustrative numbers from one service; the shape, not the exact values, is the point.

2Why the First Requests Are Slow

When the first request reaches a lazy controller, Spring has to create it right then, and with it every lazy dependency down the chain. Creating a bean can be expensive: loading and initialising classes, building a Hibernate metamodel, opening the first connections of a pool, fetching configuration from a remote server, warming a cache. All of that happens inside the request, on the request thread, while the user waits.

In a deployment with many replicas, this becomes a pattern of latency spikes. Each new pod serves its first requests slowly, so every rolling update and every autoscaling event shows a burst of slow responses and possibly timeouts in callers that have tight deadlines. Load balancers that send a new pod its full share of traffic immediately make it worse.

3Why Bad Deployments Now Pass Health Checks

The bean creation errors are the more serious problem. Suppose a new version needs a property payment.api-url, and someone forgets to add it to the production configuration.

Java
@Service
class PaymentClient {
PaymentClient(@Value("${payment.api-url}") String url) { /* ... */ }
}
// Eager (default): the rollout stops at the first pod
// APPLICATION FAILED TO START ... Could not resolve placeholder 'payment.api-url'
// Lazy initialisation on: the pod starts, /actuator/health returns UP
// First POST /payments:
// BeanCreationException: Error creating bean with name 'paymentClient':
// Could not resolve placeholder 'payment.api-url' in value "${payment.api-url}"

With eager creation, Spring checks this at startup, the new pods never become ready and Kubernetes keeps the old version running. That is one of the most valuable safety nets we have, and it costs nothing. With lazy initialisation the health endpoint reports UP because the beans that would fail do not exist yet. The rollout completes, the old pods are gone, and the error reaches customers. So the team traded a startup check for faster startup, probably without realising it.

4What I Would Advise

First, I would keep lazy initialisation where it shines: local development and tests. A developer restarting the application thirty times a day gains a lot from a 12 second startup, and a test that starts a context for a few beans gains too. Spring Boot profiles make this easy, with the property set in application-dev.properties only.

Second, for production I would turn it off and look for the real slow beans. Spring Boot can record startup steps: with a BufferingApplicationStartup set on the SpringApplication, the actuator startup endpoint shows how long each bean took to create. Often two or three beans account for most of the time, for example a client that downloads metadata or a cache that loads a whole table, and fixing those, by loading the data asynchronously or on a schedule, gives most of the gain while keeping every other check at startup.

Third, if the team really wants laziness in production, I would at least mark the beans that must be checked or ready with @Lazy(false), such as clients with required configuration, schedulers and message listeners, so errors in them still stop the deployment.

Java
// main(): record startup steps so /actuator/startup can show the slow beans
SpringApplication app = new SpringApplication(OrderApp.class);
app.setApplicationStartup(new BufferingApplicationStartup(2048));
app.run(args);
// GET /actuator/startup (expose the endpoint first)
// ... "name": "spring.beans.instantiate", "tags": [{"key": "beanName", "value": "catalogCache"}], "duration": "PT14.2S"

5Warm Up Before Readiness

If first-request latency matters, the cleanest pattern is a warm-up that runs after startup and before the pod reports ready. Kubernetes uses a readiness probe, an HTTP check that decides whether a pod receives traffic, and Spring Boot exposes one at /actuator/health/readiness. We can add our own health indicator to that readiness group, so the probe stays OUT_OF_SERVICE until the warm-up has finished.

Java
@Component
class WarmUpHealthIndicator implements HealthIndicator { // contributes as "warmUp"
private final CatalogService catalog;
private volatile boolean done;
WarmUpHealthIndicator(CatalogService catalog) { this.catalog = catalog; }
@EventListener(ApplicationReadyEvent.class)
void warm() {
Thread.ofVirtual().start(() -> {
catalog.findTop(50); // creates the beans on this path, fills caches
done = true;
});
}
@Override public Health health() {
return done ? Health.up().build() : Health.outOfService().build();
}
}
# application.properties
management.endpoint.health.group.readiness.include=readinessState,warmUp
# GET /actuator/health/readiness -> OUT_OF_SERVICE during warm-up, UP afterwards
Step throughDeployment with a warm-up before readiness
  1. Pod starts, context refresheseager beans created, config checked
  2. ApplicationReadyEventwarm-up starts, readiness OUT_OF_SERVICE
  3. Warm-up calls the hot pathsbeans and caches ready
  4. Did warm-up succeed?
    YesReadiness UP, pod gets trafficNoStay not ready, rollout stops

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

Notice that the warm-up runs on its own thread, so startup is not blocked, and readiness combines Spring Boot's own readiness state with ours. The pod receives traffic only after the expensive paths have run once. With eager initialisation this warm-up mostly fills caches and lets the JIT compile hot code; with lazy initialisation it also creates the beans, so it partly restores the startup check. A real warm-up also needs a timeout and a decision about what to do if it fails.

6Follow-up questions

Is lazy initialisation ever right for production?

It can be for short-lived jobs or rarely used admin services where startup cost dominates and only a few code paths run. Even then I would keep @Lazy(false) on anything with required configuration, so a broken deployment still fails at startup rather than in the middle of the job.

Would CDS or AOT be a better way to speed up startup?

Often yes. Class data sharing and Spring AOT reduce the cost of starting without moving bean creation to the first request, so the startup checks stay in place. They are worth measuring before reaching for lazy initialisation.

How do we stop the new pod from getting full traffic at once?

Besides a warm-up before readiness, many load balancers and service meshes support slow start, which ramps traffic up to a new instance over a minute or so. Combined with a warm-up it smooths the first-request latency nearly completely.

7Conclusion

In this answer, we saw that spring.main.lazy-initialization=true moves bean creation from startup to the first requests, which explains both the slow first requests and the bean creation errors that now escape the health check. We advised keeping it for development and tests, turning it off in production or keeping critical beans eager with @Lazy(false), finding the truly slow beans with the startup actuator endpoint, and holding readiness back until a warm-up has run.

What to say in the interviewAbout 80 seconds aloud

Open with

The property made startup look faster, but it did not remove any work: every bean is now created when the first request needs it, so the first requests pay for class loading, connection pools and cache loading on the request thread, and every new pod shows latency spikes.

Then, if they want more

The bigger problem is that Spring no longer validates the beans at startup. A missing property or a broken bean used to stop the rollout at the first pod; now the pod starts, the health endpoint says UP, the old version is removed, and the error hits a customer as a BeanCreationException.

So my advice is to keep lazy initialisation for local development and tests, through a dev profile, and turn it off in production. Then I would measure which beans are really slow, using BufferingApplicationStartup and the actuator startup endpoint, and fix those two or three, for example by loading big caches asynchronously.

If the team still wants laziness, I would mark beans with required configuration, schedulers and listeners with @Lazy(false). And if first-request latency matters, I would add a warm-up after ApplicationReadyEvent and a readiness health indicator that stays out of service until the hot paths have run once.

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.
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 team enabled spring.main.lazy-initialization=true to speed up startup, and now the...": https://scrivio-interview-library.netlify.app/spring-boot/dependency-injection/52fbd23de0/