Skip to content

Path 5 · lesson 4 of 5

Intermediate16 minJava 21 (OpenJDK 21.0.13, HotSpot) · Spring Boot 3.5.16 · Spring Framework 6.2

A 45-second startup: measure, then cut

Startup time is mostly a handful of beans doing slow work while the context is built. Record the startup steps, sort by duration, and fix the top of the list before touching anything else.

What you will learn

  • Describe what Spring Boot does between main and the first request it can serve
  • Record startup steps and name the beans that take the longest to create
  • Tell a slow bean from a slow framework phase in the recorded steps
  • Say what lazy initialisation moves, and where the moved cost and the moved errors reappear
  • Explain why a slow start becomes an outage during a deploy or a scale-out

Before you start

The concept

Between main and "ready", a Spring Boot application reads its configuration, works out which beans exist, creates every singleton bean in dependency order, and starts the web server. Creating the beans is called refreshing the context, and it is almost always where the time goes.

Bean creation runs on one thread, one bean after another. So a bean whose constructor or @PostConstruct method calls a remote system, loads a large file or warms a cache adds its full duration to the startup. Three such beans of ten seconds each are thirty seconds, whatever the rest of the application does.

Why it exists

Startup time is how long you wait for capacity. During a deploy, each new instance is useless until it is ready. During a traffic spike, an autoscaler that adds instances gets them 45 seconds too late. After a crash, it is the length of the gap.

It also interacts with the platform. An orchestrator that expects the application to answer its health check within 30 seconds will kill one that needs 45, start it again, and kill it again. The service then never comes up, although nothing is wrong with the code.

How it works inside

Spring can record its own startup. Give the application a BufferingApplicationStartup and it keeps a timeline of named steps with their durations, readable at GET /actuator/startup. The step spring.beans.instantiate appears once per bean, tagged with the bean name.

The lab has two deliberately slow beans. ExchangeRateCache sleeps for 3 seconds in @PostConstruct and ReportTemplates for 1.2 seconds. The sleeps stand in for a remote call and a compile step. Everything else in the output is measured from a real start.

Program outputjava -jar target/spring-production-lab-1.0.jar --demo=startup --lab.slow-beans=true (2 CPUs)

Real JVM output
JVM uptime when the application was ready: 7.0 s

Slowest startup steps (the same data as GET /actuator/startup):
    6515 ms  spring.context.refresh
    3012 ms  spring.beans.instantiate beanName=exchangeRateCache
    1206 ms  spring.beans.instantiate beanName=reportTemplates
     915 ms  spring.beans.instantiate beanName=&entityManagerFactory
     507 ms  spring.context.beans.post-process
     418 ms  spring.context.beandef-registry.post-process
     411 ms  spring.context.config-classes.parse
     402 ms  spring.beans.instantiate beanName=exporter
The application was ready 7.0 seconds after the JVM started. spring.context.refresh is the whole bean creation phase, so it contains the lines below it. The two slow beans are at the top with 3,012 ms and 1,206 ms: 4.2 of the 6.5 seconds are two beans. The entity manager factory, which is Hibernate starting up, is third with 915 ms.

Program outputThe same, with --spring.main.lazy-initialization=true

Real JVM output
JVM uptime when the application was ready: 2.6 s

Slowest startup steps (the same data as GET /actuator/startup):
    2160 ms  spring.context.refresh
     772 ms  spring.beans.instantiate beanName=&entityManagerFactory
     660 ms  spring.context.beans.post-process
     557 ms  spring.context.beandef-registry.post-process
     549 ms  spring.context.config-classes.parse
     362 ms  spring.beans.instantiate beanName=&orderRepository
     168 ms  spring.boot.webserver.create
      96 ms  spring.boot.application.environment-prepared
Ready after 2.6 seconds instead of 7.0. The two slow beans are no longer in the list, because nothing asked for them during startup, so they were never created. Their 4.2 seconds have not been removed. They will be paid by the first request that needs each bean.
What the timeline showsLikely causeWhere to look
One spring.beans.instantiate step of several secondsSlow work in a constructor or @PostConstruct: a remote call, a cache load, a DNS lookup that times outThat bean's own code
entityManagerFactory takes many secondsMany entities, schema validation or generation, a slow first database connectionspring.jpa.hibernate.ddl-auto, the connection pool, the database
spring.context.config-classes.parse is largeA very wide component scan or a great many auto-configurationsThe base package of @SpringBootApplication, unused starters
Time passes before the first stepThe JVM loading classes, or a migration tool running before the contextFlyway or Liquibase logs, class data sharing
No single step stands outThousands of beans, each a little slowClass data sharing and ahead-of-time processing

Architecture

Drawing diagram…

A flowchart of startup phases from left to right: main, reading configuration and profiles, parsing configuration classes and finding bean definitions, creating every singleton bean one after another, starting the web server, and ready. A dotted arrow from bean creation shows that a slow constructor or PostConstruct method adds seconds to startup.

flowchart LR
    M["main()"] --> E["Read configuration and profiles"]
    E --> P["Parse configuration classes, find bean definitions"]
    P --> B["Create every singleton bean, one after another"]
    B --> W["Start the web server"]
    W --> R["Ready: runners, then accepting traffic"]
    B -. "slow constructor or @PostConstruct" .-> S["Seconds added to startup"]
The phases of a Spring Boot start. Bean creation is single-threaded and usually dominates.
  • Every phase before "ready" is on the path of a deploy. The health check only begins to pass after the last one.
  • Because beans are created in sequence, slow beans add up. Nothing is done in parallel unless you arrange it.

Step by step

Drawing diagram…

A sequence diagram. The orchestrator starts a container. The new instance creates its beans and calls an exchange rate API in a PostConstruct method. The API is slow and takes 40 seconds. After 30 seconds the orchestrator's startup check gets no answer, so it kills and restarts the instance, which calls the API again. The instance never becomes ready.

sequenceDiagram
    participant K as Orchestrator
    participant A as New instance
    participant X as Exchange rate API
    K->>A: start container
    A->>A: create beans
    A->>X: load rates in @PostConstruct
    Note over X: slow today, 40 s
    K->>A: startup check after 30 s
    A--xK: no answer yet
    K->>A: kill and restart
    A->>X: load rates again
    Note over K,A: the instance never becomes ready
A startup that depends on a remote system, under a 30-second startup limit.
  1. The application did not change. A dependency became slower, and because it is called during startup, that slowness now decides whether the service can start at all.
  2. Restarting makes it worse: every attempt repeats the slow call and adds load to the system that is already struggling.

In a real system

Startup time grows unnoticed. Each new client, cache and scheduled job adds a second, nobody measures, and one day a routine deploy on a busy afternoon cannot bring instances up fast enough. The habit that prevents it is cheap: log the startup time on every start and alert when it crosses a limit.

  • Do not call remote systems while the context starts. Load in the background after startup, serve a safe default until the data is there, and report readiness accordingly.
  • Let repositories start in the background. spring.data.jpa.repositories.bootstrap-mode=deferred creates repository proxies without waiting for Hibernate to finish.
  • Give the platform a startup allowance. A Kubernetes startup probe with enough failures allowed keeps the liveness check from killing a slow but healthy start.
  • Use class data sharing for the JVM's part. Spring Boot documents how to build an archive of already loaded classes from an extracted application, which shortens class loading on every start.

Java and Spring Boot

Recording the startup, and moving a slow load off the startup path. The first file is how the lab is wired; the second is the shape of the repair.

src/main/java/lab/LabApplication.javaJava
@SpringBootApplicationpublic class LabApplication {  public static void main(String[] args) {    SpringApplication app = new SpringApplication(LabApplication.class);    app.setApplicationStartup(new BufferingApplicationStartup(4096));    app.run(args);  }}

Why it is written this way

  • BufferingApplicationStartup keeps the first 4,096 steps in memory. Without it the startup endpoint has nothing to show.
  • Expose the endpoint with management.endpoints.web.exposure.include=startup. Do this in a test environment; the endpoint is not meant to be public.

Wrong, then right

A team wants a faster start and switches on lazy initialisation for everything. The corrected version fixes the two beans the measurement pointed at.

Incorrect implementation

application.properties (incorrect)Properties
# startup was 45 s, now 6 sspring.main.lazy-initialization=true

Why it is written this way

  • The number on the dashboard improves at once, which is what makes this tempting.

Why it fails

  • No work was removed. Each bean is now created by the first request that needs it, so the first customers after every deploy wait for the slow beans, one after another.
  • A bean that cannot be created, because of a missing property or an ambiguous dependency, no longer stops the deploy. It fails in production on the first request that reaches it.
  • The instance reports ready while it is not able to serve at normal speed, so the load balancer sends it full traffic at its slowest moment.

Corrected implementation

application.properties (corrected)Properties
# eager by default: wiring errors still stop the deployspring.main.lazy-initialization=false# repositories are initialised while the rest of the context startsspring.data.jpa.repositories.bootstrap-mode=deferred

Why it is written this way

  • Together with the ExchangeRateCache change above: the slow load happens after startup, in the background, and everything else is still created and checked before the instance takes traffic.

Trade-offs

  • The application must now work with an empty cache for a short time, which is extra code and an extra state to test.
  • Targeted fixes take a measurement and a code change per slow bean. The global switch is one line, which is why it remains useful in development, where restart speed matters more than first-request latency.

Configuration

The settings this lesson uses. Defaults are those of Spring Boot 3.5.

spring.main.lazy-initializationDefault false
What it does
When true, beans are created on first use and not during startup.
When to change it
Useful in development. In production it moves cost to the first requests and turns startup failures into runtime failures.
management.endpoints.web.exposure.includeDefault health
What it does
Which actuator endpoints are reachable over HTTP.
When to change it
Add startup where you measure. The endpoint also needs a BufferingApplicationStartup set on the application.
spring.data.jpa.repositories.bootstrap-modeDefault default
What it does
Whether Spring Data JPA repositories are created eagerly, deferred until the context is refreshed, or lazily on first use.
When to change it
deferred shortens startup when there are many repositories and keeps the check that they are valid.
debugDefault false
What it does
Starting with --debug prints the conditions evaluation report: every auto-configuration and why it did or did not apply.
When to change it
Use it to find auto-configurations you pay for and do not use.

Hands-on exercise

Find the slow beans, then hide them, then fix one

Reproduce the two measurements above and see for yourself where lazy initialisation puts the cost.

Steps · 0 of 4 done

What can go wrong

Optimising without the timeline
Symptom
A week of removing starters saves two seconds of a 45-second startup.
Cause
The time was in a few beans doing slow work, which trimming the framework does not touch.
Fix
Record the startup steps first and work down the list from the longest.
Reading nested steps as a sum
Symptom
The durations in the startup endpoint add up to far more than the real startup time.
Cause
Steps are nested. spring.context.refresh contains every bean step, and a bean step contains the beans it had to create first.
Fix
Compare steps at the same level, and use the parent id in the endpoint's output to see what contains what.
A liveness check that fires during startup
Symptom
Pods restart in a loop after a deploy, and the logs end partway through startup each time.
Cause
The liveness check starts before the application can answer and kills it.
Fix
Add a startup probe, or lengthen the initial delay, so that liveness is only judged once the application has started.

How to troubleshoot

Startup is slow and you do not know where

Check

GET /actuator/startup, sorted by duration, filtered to spring.beans.instantiate
How to read it
The bean names at the top are where to look. A bean you do not recognise is usually created by an auto-configuration.
Startup hangs with no output for many seconds

Check

jcmd <pid> Thread.print, and read the stack of the main thread
How to read it
The main thread's top frames show what it is waiting for: a socket read to a remote system, a DNS lookup, or a database connection attempt.
Startup time differs greatly between environments

Check

The line "Started ... in N seconds (process running for M)" in each environment's log
How to read it
A large gap between environments with the same build points at something outside the code: CPU limits on the container, a slower database, or a dependency called during startup.

Key takeaways

  • Startup is mostly bean creation, on one thread, in sequence. A few slow beans usually account for most of it.
  • Record the steps with BufferingApplicationStartup and read /actuator/startup before changing anything.
  • Lazy initialisation removes no work. It moves the cost, and any wiring errors, to the first requests.
  • Keep remote calls out of constructors and @PostConstruct. A slow dependency should not decide whether your service can start.

Practical check

Small scenarios, one decision each. Pick what you would do, then read why.

Scenario 1 of 2

A service takes 45 seconds to start. The startup endpoint shows spring.context.refresh at 43 s. Below it, spring.beans.instantiate for pricingRulesLoader takes 31 s and entityManagerFactory takes 6 s. Nothing else is above 1 s.

What do you look at first?

Scenario 2 of 2

A team sets spring.main.lazy-initialization=true in production. Startup drops from 40 s to 5 s. A week later a deploy goes out in which a new bean needs a property that is missing from the production configuration.

What happens?

References

References: Spring Boot reference: SpringApplication (lazy initialisation, application startup tracking, startup events) ↗ · Spring Boot Actuator REST API: the startup endpoint (steps, durations, parent ids, tags) ↗ · Spring Boot how-to: Class Data Sharing ↗ · Spring Boot reference: common application properties (spring.main.lazy-initialization, spring.data.jpa.repositories.bootstrap-mode) ↗ · Report a problem