Where does Spring Boot startup time actually go?
Startup cost splits into four phases. Each has a different fix, so measure them separately.
- JVM startup. The runtime initializes before your
mainmethod runs. - Class loading. The JVM locates, verifies, and links thousands of classes from Spring, your dependencies, and your own code. Class data sharing targets this phase.
- Context refresh. Spring scans components, evaluates auto-configuration conditions, creates beans, and runs their initialization callbacks. Lazy initialization targets this phase.
- First-request readiness. Connection pools, caches, JIT warm-up, and
ApplicationRunnerwork all finish before the service can handle real traffic.
To measure context refresh, configure the application with a BufferingApplicationStartup. It records timed steps such as bean instantiation and post-processing. Expose those steps through the actuator startup endpoint and sort them by duration. For class loading, run the JVM with -Xlog:class+load or -verbose:class to see how many classes load and where they come from.
The "Started … in X seconds" log line is not a readiness metric. It is logged when the context has refreshed, before runners finish and before the readiness state changes. For readiness, measure the time until the readiness probe passes, or better, until the first real request succeeds.
Step recording has its own overhead. Use it to find hotspots, then take your final numbers with tracking disabled.
This matters most for three groups: teams that autoscale, because new instances arrive late during load spikes; teams that deploy often, because rollout time grows with the number of instances; and teams whose CI suites start many application contexts.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.metrics.buffering.BufferingApplicationStartup;
@SpringBootApplication
public class OrderServiceApplication {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(OrderServiceApplication.class);
// Record context-refresh steps (bean instantiation, post-processing,
// condition evaluation) into an in-memory buffer. The capacity caps
// how many steps are kept. This is a profiling aid, so remove it
// or gate it behind a flag before taking final timings.
app.setApplicationStartup(new BufferingApplicationStartup(2048));
app.run(args);
}
}
// application.properties: expose the recorded steps over HTTP
// management.endpoints.web.exposure.include=health,startup
//
// Read the timeline. GET leaves the buffer intact, POST drains it.
// Each event has a step name, tags such as the bean name, and a duration.
// curl -s localhost:8080/actuator/startup > startup.json
//
// Class loading is measured separately, with the tracking above turned off:
// java -Xlog:class+load:file=classload.log -jar order-service.jar
// grep -c 'source:' classload.log # rough count of loaded classes
Records Spring context-refresh steps with BufferingApplicationStartup, exposes them through the actuator startup endpoint, and logs JVM class loading as a separate measurement.
What is class data sharing and how does it speed up the JVM?
Every JVM start repeats the same work for each class it touches. It locates the class file in a JAR, reads and parses the bytecode into internal metadata, verifies it, and links it. A typical Spring Boot application loads thousands of classes from the framework, auto-configuration modules, and third-party libraries. The JVM redoes all of that on every boot, even though the classpath has not changed since the last start.
Class data sharing (CDS) avoids that repetition. During a training run, the JVM records which classes the application loads and writes their parsed, verified metadata to an archive file. On later starts, the JVM memory-maps that archive and uses the stored metadata instead of rebuilding it from the JARs. The JDK already ships a default archive for its own core classes. Application CDS extends the same mechanism to your application and library classes, which is where most of a Spring application's classes come from. When several JVMs on one host map the same archive, they can also share the read-only pages, which can reduce total memory use.
The archive is only valid for the JVM build and classpath it was created with. If either one changes, the JVM detects the mismatch and falls back to normal class loading.
CDS speeds up class loading and nothing else. If your boot time is spent waiting on database connections, schema migrations, secret fetches, or calls to remote services, CDS cannot shorten those waits. Before you expect a large gain, measure how much of your startup is actually class loading.
How do you build and verify a CDS archive for a Spring Boot app?
CDS archives are tied to an exact classpath, so start by extracting the executable JAR into an exploded layout: the application JAR plus a lib/ directory of dependency JARs. A nested fat JAR loads classes through Spring Boot's custom class loader, which the JVM cannot archive.
Next, run a training execution with -XX:ArchiveClassesAtExit=app.jsa and -Dspring.context.exit=onRefresh. The second property makes Spring stop once the application context has refreshed. Every class loaded up to that point goes into the archive, and the process exits without serving traffic. Production then launches with -XX:SharedArchiveFile=app.jsa.
Generate the archive in the same image it will ship in, typically as a step in a multi-stage Dockerfile. The JDK build, the JAR paths and order, and JVM options such as the garbage collector must match at runtime. Any mismatch causes the JVM to reject the archive, print a warning, and start normally but slower. During training the context still creates beans, so the run needs whatever those beans touch at construction time. In CI, use a profile that points the datasource at an embedded database, disables migrations, and replaces remote clients with stubs. Expect the classes loaded in that profile to differ slightly from production.
To verify, start once with -Xshare:on, which makes the JVM fail instead of silently falling back. Alternatively, check -Xlog:class+load output for classes reported as loaded from the shared objects file.
The archive often runs to tens of megabytes. The training run adds roughly one application startup to every image build.
FROM eclipse-temurin:21-jdk AS build
WORKDIR /src
COPY . .
RUN ./mvnw -q -DskipTests package && cp target/*.jar /src/app.jar
FROM eclipse-temurin:21-jre
WORKDIR /workspace
COPY --from=build /src/app.jar /tmp/app.jar
RUN java -Djarmode=tools -jar /tmp/app.jar extract --destination application \
&& rm /tmp/app.jar
WORKDIR /workspace/application
ENV JVM_OPTS="-XX:+UseG1GC"
RUN java $JVM_OPTS -XX:ArchiveClassesAtExit=app.jsa \
-Dspring.context.exit=onRefresh -Dspring.profiles.active=training \
-jar app.jar
RUN java $JVM_OPTS -Xshare:on -XX:SharedArchiveFile=app.jsa \
-Dspring.context.exit=onRefresh -Dspring.profiles.active=training \
-jar app.jar
ENTRYPOINT ["sh", "-c", "exec java $JVM_OPTS -XX:SharedArchiveFile=app.jsa -jar app.jar"]
A multi-stage Dockerfile that extracts the Spring Boot JAR, creates a CDS archive with a stubbed training profile, checks the archive with -Xshare:on during the build, and launches with the same JDK, classpath and JVM options.
How does lazy initialization work in Spring Boot, and when should you avoid it?
Setting spring.main.lazy-initialization=true marks every bean definition as lazy. During context refresh, Spring registers the definitions but defers instantiation until something requests the bean, either through injection into a bean being created or through a direct lookup. @Lazy does the same for a single bean definition. On an injection point, it injects a proxy that resolves the real bean on first method call. Under global lazy mode, @Lazy(false) opts individual beans back into eager creation.
The startup gain comes from skipping construction, dependency resolution and init callbacks for beans that are not needed yet. That work moves to a later point.
Errors move too. A missing property, an unsatisfied dependency or a bad connection string normally fails the refresh, and the deploy stops. Under lazy mode the context refreshes cleanly. Readiness probes pass, the orchestrator routes traffic, and the failure only appears when the first request reaches the affected bean. You trade a failed rollout for a partial outage.
Latency moves as well. The first request into each code path pays for bean creation, class loading and any connection setup, all on cold, unoptimised code. After every deploy or scale-out, tail latency spikes until each path has been exercised.
Avoid global lazy mode in production services that rely on readiness gating, have tight latency targets, or autoscale under load. Also avoid it where beans do useful work at creation time, such as registering listeners or warming caches. That work does not happen until something asks for the bean.
// application.properties: spring.main.lazy-initialization=true
// PaymentGatewayClient, CacheWarmer, ProductRepository and PdfRenderer
// are application classes, shown here as placeholders.
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
@Configuration
public class StartupCriticalConfig {
// Opt back into eager creation. A missing or bad URL now fails context
// refresh and stops the rollout. It no longer fails on the first live request.
@Bean
@Lazy(false)
public PaymentGatewayClient paymentGatewayClient(
@Value("${payments.gateway.url}") String url) {
return new PaymentGatewayClient(url);
}
// Does its work at creation time by warming a cache. Under lazy mode,
// nothing would ever request it, so it must stay eager.
@Bean
@Lazy(false)
public CacheWarmer cacheWarmer(ProductRepository repo) {
return new CacheWarmer(repo);
}
}
@Service
class ReportService {
private final PdfRenderer renderer;
// @Lazy on the injection point injects a proxy. The real PdfRenderer is
// created on the first method call, so the first report request pays that cost.
ReportService(@Lazy PdfRenderer renderer) {
this.renderer = renderer;
}
}
Under global lazy mode, @Lazy(false) keeps config-sensitive and side-effecting beans eager so their failures surface at startup, while @Lazy on an injection point defers an expensive dependency behind a proxy.
Applying lazy initialization selectively
Global lazy mode is a default, not a mandate. You can turn it on with spring.main.lazy-initialization=true and then opt specific beans back into eager creation. There are two mechanisms:
@Lazy(false)on a bean definition or component class. This keeps the decision next to the code, so a reader can see why the bean must exist at startup.- A
LazyInitializationExcludeFilterbean. This exempts beans by type or by a predicate. It works for classes you don't own, such as auto-configured infrastructure, where you can't add an annotation.
Good candidates for eager creation share one trait: their failure or side effect matters before the first request arrives.
- Data sources. A wrong password should stop the deploy, not fail the first user call.
- Message listener containers. Consumers must subscribe before traffic starts.
- Beans with
@Scheduledmethods. Their schedules are only registered once the bean is created. - Caches you pre-warm.
With those exemptions in place, global lazy mode earns its keep in local development and tests. Each restart in an edit-run cycle skips beans the current task never touches, and that time adds up across a team. In production, the same deferral moves cost onto the first requests and hides wiring errors until runtime. Many teams therefore enable it only in a dev profile or a test property source.
The cost is ongoing judgment. Every new bean now carries an implicit question: does this need to exist at startup? If nobody asks, a listener that never subscribes can ship unnoticed. Make the question explicit in code review. Add a line to the pull request checklist, and consider a startup test that asserts critical beans are already instantiated.
// application-dev.properties enables lazy mode only in the dev profile:
// spring.main.lazy-initialization=true
package com.example.startup;
import javax.sql.DataSource;
import org.springframework.boot.LazyInitializationExcludeFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Configuration(proxyBeanMethods = false)
@EnableScheduling
class EagerBeansConfig {
// The DataSource is auto-configured, so we can't annotate it.
// Exempt it by type so it is still created during startup.
@Bean
static LazyInitializationExcludeFilter eagerInfrastructure() {
return LazyInitializationExcludeFilter.forBeanTypes(DataSource.class);
}
}
// We own this class, so keep the decision next to the code.
// @Scheduled methods are only registered once this bean exists.
@Component
@Lazy(false)
class ProductCacheWarmer {
@Scheduled(fixedDelay = 300_000) // refresh every 5 minutes
void refresh() {
// load hot entries into the cache before users ask for them
}
}
With global lazy mode enabled in a dev profile, a LazyInitializationExcludeFilter keeps the auto-configured DataSource eager, and @Lazy(false) keeps a scheduled cache warmer eager so its schedule is registered at startup.
Which lower-effort startup fixes should you check first?
Before you introduce a training run or a new build pipeline, make sure the application isn't doing work it doesn't need. These fixes change only application code and dependencies. Each one targets a phase you should already have measured.
Trim starters and auto-configurations. Every starter adds classes to the classpath, and auto-configuration conditions are evaluated against that classpath. An unused starter can activate a whole configuration tree: a data source, a connection pool, health indicators. Run the app with debug=true and read the condition evaluation report. Remove the dependencies behind configurations you never use, and explicitly exclude the ones you can't remove. This shortens the auto-configuration and bean-creation phases.
Keep constructors and @PostConstruct cheap. Bean initialization runs serially on the main thread. A cache warm-up, a large file parse or a network handshake inside an init method adds its full duration to context refresh. Look for single beans that take an outsized share of time in your per-bean timings. Defer that work to an ApplicationReadyEvent listener or a background task, but only if callers can tolerate the bean being unready.
Narrow component scanning. A root package that sits too high in the hierarchy makes Spring scan shared libraries and test fixtures. Tighten the base packages so the scanning phase reads only the classes you own.
Move blocking calls off the critical path, where it's safe. Remote config fetches and schema migrations often dominate wall-clock time. Some migrations are safe to run as a separate pre-deploy job. Config that the app cannot run without must still block startup, because a fast boot with the wrong configuration is worse than a slow one.
What are the alternatives, and where does GraalVM native image fit?
CDS and selective lazy initialization are tuning on the same JVM. You keep the same bytecode, the same JIT, and the same libraries. GraalVM native image changes how the application is built and run. It compiles ahead of time into a standalone executable under a closed-world assumption: everything reachable must be known at build time.
| Dimension | CDS | Selective lazy init | GraalVM native image |
|---|---|---|---|
| Startup gain | Moderate: skips class parsing and verification | Varies with how many beans are deferred | Large: no class loading or JIT warm-up |
| Memory | Shared archive can reduce per-process footprint | Lower until deferred beans are created | Typically much lower resident memory |
| Build time and complexity | One training run added to the build | No build change | Slow, memory-hungry native compilation |
| Compatibility risk | Low; a stale archive is ignored, not fatal | Errors move from boot to first request | Reflection, dynamic proxies, resource loading and classpath scanning need build-time hints |
| Peak throughput | Unchanged | Unchanged | Often lower without profile-guided optimization, because there is no runtime JIT |
| Ongoing cost | Regenerate the archive when dependencies change | Review the exclusion list | Test the native build in CI; libraries must support it |
The closed-world assumption is the real cost. Spring's AOT processing turns much of the runtime classpath scanning and proxy generation into generated code. Any library that relies on reflection Spring cannot see still needs hints, and those failures often appear only at runtime in the native binary.
Native image makes sense for scale-to-zero functions, CLI tools, and dense multi-tenant deployments where cold start or memory per instance drives cost. Long-running services that scale on throughput, depend on heavily reflective libraries, or cannot afford slower builds should stay on the JVM and use CDS.
How should you report startup improvements honestly?
A startup claim is only as good as the measurement behind it. Measure before and after on the same hardware or instance type, with the same JVM flags apart from the change under test. Turn off startup step tracking and verbose or debug logging, because both add work that inflates the baseline and can exaggerate the gain. Do many runs, then report the median and the spread. State whether the OS page cache was warm, since that affects CDS results.
Do not rely on the "Started in" log line. It marks the point where the application context finished refreshing, not the point where the service can take traffic. Measure two other things instead:
- Time-to-ready: when the readiness probe first passes.
- Early latency: the first request and the tail latency over the first minute or so.
Also record when connection pools fill, when caches finish preloading, and when JIT compilation settles. Lazy initialization in particular moves cost from the log line onto these later events.
Illustrative estimate
All inputs are assumed. Without lazy init, the context refresh takes 6.0 s and the cache preload takes 2.0 s. With lazy init, the refresh drops to 3.5 s. The readiness check then forces deferred beans to initialize, which takes 2.5 s, before the same 2.0 s preload runs.
| Metric | Before | After lazy init |
|---|---|---|
| "Started in" log line | 6.0 s | 3.5 s |
| Deferred bean init | 0 s | 2.5 s |
| Cache preload | 2.0 s | 2.0 s |
| Time-to-ready | 8.0 s | 8.0 s |
With these assumed inputs, the log line in this illustrative estimate drops from 6.0 s to 3.5 s, roughly a 42% improvement. Time-to-ready, the figure the orchestrator acts on, stays at 8.0 s. This is a worked example, not a measured result. It shows how a log-line gain can hide an unchanged readiness time.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to spring boot startup time, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.