A Spring Boot application may work perfectly after startup but take several seconds, or even longer, before it becomes ready to handle requests. This becomes a serious concern when applications run inside containers, scale automatically, or restart frequently during deployments.
Consider an order-management service that starts normally on a developer's machine but takes noticeably longer in a production environment. The application initializes Spring beans, configures security, creates database connections, loads configuration, starts the web server, and performs several initialization tasks.
The first reaction might be to increase the container's startup timeout or enable lazy initialization. However, neither approach identifies the actual problem.
One database initialization component may be loading thousands of records. Another bean may be making a remote API call. A third component may be scanning files or building an in-memory cache. Without startup measurements, developers cannot easily determine which operation is responsible for the delay.
Spring Boot provides startup tracking through the ApplicationStartup interface. It also integrates with Java Flight Recorder, allowing developers to examine JVM activity alongside Spring-specific startup events.
These tools help developers identify expensive initialization steps before changing application architecture or configuration.
This article explains how to track Spring Boot startup tasks, inspect startup information through Actuator, use Java Flight Recorder for deeper investigation, and optimize slow initialization without hiding problems behind configuration changes.
Understand the Spring Boot Startup Lifecycle
Before investigating slow startup, understand the major stages involved in starting a Spring Boot application.
A typical startup process includes:
Creating the SpringApplication environment.
Preparing application configuration and profiles.
Creating the ApplicationContext.
Loading and registering bean definitions.
Performing component scanning and auto-configuration.
Creating and initializing singleton beans.
Refreshing the application context.
Starting the embedded web server.
Executing ApplicationRunner and CommandLineRunner components.
Marking the application as ready to accept traffic.
Each stage can introduce delays.
For example, component scanning may take longer when the application contains a large number of classes. Bean initialization may become expensive when constructors perform database queries. A CommandLineRunner may delay readiness while loading reference data.
Spring Boot publishes lifecycle events that help identify where startup is progressing.
Some important events include:
Event | When it occurs |
|---|
ApplicationStartingEvent | At the beginning of application startup |
ApplicationEnvironmentPreparedEvent | After the environment has been prepared |
ApplicationContextInitializedEvent | After the context has been prepared |
ApplicationPreparedEvent | Before context refresh begins |
ApplicationStartedEvent | After context refresh completes |
ApplicationReadyEvent | After application and command-line runners complete |
The distinction between ApplicationStartedEvent and ApplicationReadyEvent is particularly important.
An application may have completed context initialization and started its web server but still be executing startup runners. It should not be considered fully ready until those operations have completed.
For containerized applications, this distinction helps explain why a process can be running while the application is not yet ready to receive traffic.
Enable Spring Boot Startup Tracking
Spring Framework provides the ApplicationStartup interface for recording startup activities as StartupStep objects.
Spring Boot supports BufferingApplicationStartup, which stores startup steps in memory so they can be inspected later or exported to an external monitoring system.
To enable it, customize the SpringApplication instance in the main application class.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.metrics.buffering.BufferingApplicationStartup;
@SpringBootApplication
public class OrderApplication {
public static void main(String[] args) {
SpringApplication application =
new SpringApplication(OrderApplication.class);
application.setApplicationStartup(
new BufferingApplicationStartup(2048)
);
application.run(args);
}
}
The important configuration is BufferingApplicationStartup.
The value 2048 specifies the capacity of the startup-step buffer. It is a capacity setting, not a timeout or a limit on how many beans the application can create.
This configuration enables Spring Boot to record startup steps instead of using the default no-op startup tracking implementation.
The recorded information can help identify activities such as bean initialization, configuration processing, and application context refresh operations.
For applications with a large number of startup steps, select a suitable buffer capacity and verify that the information needed for investigation is retained.
Expose Startup Information Through Spring Boot Actuator
Spring Boot Actuator provides operational endpoints that help developers inspect application behavior.
The startup endpoint can expose recorded startup steps as JSON.
First, add the Actuator dependency to the project.
For Maven:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
Then configure the startup endpoint in application.properties.
management.endpoints.web.exposure.include=health,info,startup
After starting the application, request the following endpoint:
http://localhost:8080/actuator/startup
The endpoint returns recorded startup information, including startup steps and their timing information.
This makes it easier to inspect the startup sequence without manually adding timing statements to every configuration class.
For example, the output can help identify whether bean initialization, configuration processing, or another startup operation is taking longer than expected.
The startup endpoint should be exposed carefully. Operational endpoints can reveal information about application structure and internal behavior. In production, restrict access through authentication, network controls, and appropriate endpoint exposure policies.
Do not expose every Actuator endpoint publicly simply to investigate startup performance.
Identify Expensive Startup Steps
Once startup tracking is enabled, the next task is to identify which operations contribute most to startup time.
Suppose an application contains the following initialization activities:
Startup activity | Observed duration |
|---|
Configuration processing | 450 ms |
Database initialization | 2,800 ms |
Security configuration | 320 ms |
Cache initialization | 1,900 ms |
Web server initialization | 700 ms |
These values are illustrative. They demonstrate how startup measurements can help prioritize investigation.
In this example, database initialization and cache initialization deserve attention before developers spend time optimizing small configuration operations.
However, startup-step durations must be interpreted carefully. Some steps can be nested, and a parent step may include time spent in child operations.
Do not add every displayed duration together and assume the result equals the total startup time. Instead, inspect the hierarchy and determine which operation actually consumes the time.
A useful investigation process is:
Identify the slowest startup steps.
Inspect their parent and child operations.
Find the application component responsible for the work.
Determine whether the work is required before readiness.
Measure the operation independently.
Optimize or relocate the work.
Repeat the startup measurement to verify the improvement.
This approach prevents developers from optimizing the wrong component.
Use Java Flight Recorder for Deeper Investigation
Spring Boot startup tracking explains what Spring is doing, but some performance problems originate at the JVM level.
For example, an application may spend time loading classes, allocating objects, performing garbage collection, or executing expensive initialization methods.
Java Flight Recorder (JFR) helps investigate these activities.
Spring Framework provides FlightRecorderApplicationStartup, which adds Spring-specific startup events to a Java Flight Recorder recording.
To configure it, update the main application class:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.metrics.jfr.FlightRecorderApplicationStartup;
@SpringBootApplication
public class OrderApplication {
public static void main(String[] args) {
SpringApplication application =
new SpringApplication(OrderApplication.class);
application.setApplicationStartup(
new FlightRecorderApplicationStartup()
);
application.run(args);
}
}
The FlightRecorderApplicationStartup implementation connects Spring startup information with JVM-level events.
Next, start the application with Flight Recorder enabled:
java -XX:StartFlightRecording:filename=startup.jfr,duration=30s \
-jar order-service.jar
The JVM creates a JFR recording named startup.jfr.
You can inspect the recording using Java Mission Control or other tools that support JFR files.
Look for activities such as:
Class loading.
Object allocation.
Garbage collection.
Thread activity.
Method execution.
Lock contention.
Spring startup events.
For example, suppose the startup endpoint indicates that a particular bean takes a long time to initialize. A JFR recording can help determine whether the delay comes from excessive object allocation, expensive method execution, class loading, or thread contention.
This combination is more useful than relying on startup logs alone because it connects framework-level activities with JVM behavior.
Flight Recorder also provides useful information for investigating problems that do not appear as a single slow Spring startup step.
Measure Custom Initialization Tasks
Spring's built-in startup tracking records many framework operations, but application developers may also need to measure their own initialization logic.
For example, an application may load product categories, initialize a local cache, or retrieve configuration from an external service.
You can use the ApplicationStartup interface to create custom StartupStep measurements.
The following example shows how to measure a custom operation:
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.metrics.ApplicationStartup;
import org.springframework.core.metrics.StartupStep;
import org.springframework.stereotype.Component;
@Component
public class ReferenceDataInitializer
implements ApplicationRunner {
private final ApplicationStartup applicationStartup;
public ReferenceDataInitializer(
ApplicationStartup applicationStartup) {
this.applicationStartup = applicationStartup;
}
@Override
public void run(ApplicationArguments args) {
StartupStep step =
applicationStartup.start(
"application.reference-data.initialize"
);
try {
loadReferenceData();
} finally {
step.end();
}
}
private void loadReferenceData() {
// Load required reference data.
}
}
The custom startup step records the duration of the reference-data initialization operation.
The finally block ensures that the step is ended even if initialization throws an exception.
This is useful when the built-in startup information shows that a general lifecycle stage is expensive but does not provide enough detail about the application's own work.
Custom step names should describe the operation clearly. Names such as application.cache.initialize or application.configuration.load are easier to interpret than generic names such as custom.task.
Avoid creating excessive startup steps for tiny operations. Focus on meaningful initialization tasks that may affect readiness.
Investigate Slow Database Initialization
Database initialization is a common reason for slow Spring Boot startup.
Consider an application that loads all product records into memory during startup.
@Component
public class ProductCacheInitializer
implements ApplicationRunner {
private final ProductRepository repository;
public ProductCacheInitializer(
ProductRepository repository) {
this.repository = repository;
}
@Override
public void run(ApplicationArguments args) {
repository.findAll()
.forEach(this::cacheProduct);
}
private void cacheProduct(Product product) {
// Add product to application cache.
}
}
This approach may be acceptable for a small reference dataset, but it becomes expensive as the database grows.
If the table contains hundreds of thousands of records, loading everything during startup can increase memory consumption, database load, and readiness time.
Before changing the implementation, determine whether all records are actually required before the application can accept requests.
Possible improvements include:
Loading only the required columns.
Fetching records in batches.
Adding appropriate database indexes.
Loading frequently accessed data first.
Moving nonessential refresh work to a background process.
Using an external cache when appropriate.
Avoiding repeated database queries during bean construction.
For example, instead of loading every product, the application might load only active product categories required for initial request processing.
The important point is to optimize the actual data requirement rather than simply increasing database connection timeouts or container startup limits.
Review CommandLineRunner and ApplicationRunner Tasks
CommandLineRunner and ApplicationRunner are commonly used for initialization tasks that must run after the application context has been refreshed but before the application is considered ready.
They are useful for operations such as validating required configuration, preparing essential application data, or performing controlled startup checks.
However, developers sometimes place too much work inside these components.
For example, a runner may perform several unrelated operations:
@Component
public class StartupInitializer
implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) {
loadReferenceData();
rebuildSearchIndex();
sendStartupNotification();
refreshExternalCache();
}
private void loadReferenceData() {
// Required initialization.
}
private void rebuildSearchIndex() {
// Potentially expensive operation.
}
private void sendStartupNotification() {
// External communication.
}
private void refreshExternalCache() {
// Cache initialization.
}
}
This design makes it difficult to identify which operation is delaying application readiness.
It also creates unnecessary dependencies between tasks that may not need to run sequentially.
A better approach is to separate initialization responsibilities and measure each operation independently.
For example, loading essential configuration may be required before accepting traffic, while rebuilding a large search index may be better handled by a background job or a separate maintenance process.
Do not move work to the background automatically. First determine whether requests depend on the result. If an application accepts traffic before required data is available, it may return incorrect responses or fail during the first request.
Spring Boot's readiness state should reflect whether the application can actually serve its intended workload.
Use Lazy Initialization Carefully
Spring Boot supports lazy initialization, which delays bean creation until a bean is required.
You can enable it through application.properties:
spring.main.lazy-initialization=true
This can reduce startup time when many beans are not needed immediately.
However, lazy initialization changes when work happens rather than necessarily eliminating that work.
For example, a service that initializes a complex reporting component during startup may start faster with lazy initialization. The first request that uses reporting functionality may then experience a delay while the component is created.
Lazy initialization can also delay the discovery of configuration problems. A bean that would normally fail during startup may not fail until a request attempts to use it.
For this reason, consider using lazy initialization selectively.
You can explicitly make an important bean eager even when lazy initialization is enabled:
@Component
@Lazy(false)
public class RequiredStartupValidator {
public RequiredStartupValidator() {
validateRequiredConfiguration();
}
private void validateRequiredConfiguration() {
// Validate configuration required by the application.
}
}
This ensures that the validator is initialized during startup.
Use this approach when early validation is important. Do not make every bean eager simply to compensate for an incorrectly designed initialization process.
Separate Application Startup Time From Readiness Time
One of the most common mistakes in startup optimization is treating the time when the JVM starts as the same as the time when the application is ready.
There are several distinct milestones:
Process start: The operating system starts the Java process.
Spring startup: Spring initializes the application context.
Web server startup: The embedded server begins accepting connections.
Application readiness: Required startup tasks have completed and the application can accept traffic.
These milestones can occur at different times.
For example, the embedded web server may start before a CommandLineRunner completes. A container health check that only verifies whether the process exists may therefore report success too early.
Spring Boot provides liveness and readiness states for this purpose.
Liveness indicates whether the application is functioning internally or needs to be restarted. Readiness indicates whether it can currently accept traffic.
When using Kubernetes, configure probes to use the appropriate health endpoints rather than relying only on process availability.
This prevents traffic from reaching an instance that has started but has not completed its required initialization.
Build a Repeatable Startup Performance Test
Startup optimization should be based on repeatable measurements.
A useful test process should use the same application build, JDK, container resources, environment configuration, and dependency versions.
Record the following measurements:
Measurement | What it tells you |
|---|
Process startup time | How quickly the JVM process begins |
Spring context initialization | How long framework initialization takes |
Web server startup | When the HTTP server becomes available |
Application readiness | When the application can accept traffic |
Database initialization | Time spent preparing database access |
Custom initialization duration | Cost of application-specific startup work |
CPU and memory usage | Resource consumption during startup |
First request latency | Whether startup work has shifted to the first request |
Run the test multiple times and compare the results. The first execution may behave differently because of operating system file caching, class loading, container image extraction, or external dependency initialization.
For a meaningful comparison, use the same measurement method before and after every change.
If you enable lazy initialization, for example, measure both readiness time and first-request latency. Otherwise, an apparent startup improvement may simply represent work being delayed until the first request.
Common Startup Optimization Mistakes
Some changes make startup logs look better without solving the underlying problem.
Increasing startup timeouts may prevent a deployment from failing, but it does not make the application faster.
Enabling lazy initialization may reduce initial bean creation, but it can move delays to request processing.
Moving initialization into asynchronous tasks may improve readiness time, but it can also create a period when the application is accepting traffic without required data.
Increasing the JVM heap may help when startup causes excessive garbage collection, but it will not fix an unnecessarily expensive database query.
The correct optimization depends on the measurement.
Use Spring startup tracking to identify expensive framework operations, custom StartupStep measurements to investigate application code, and JFR when JVM activity needs deeper analysis.
Conclusion
Slow Spring Boot startup is rarely caused by one universal problem. It can result from bean initialization, database queries, external service calls, class loading, application runners, or JVM-level activity.
Spring Boot's ApplicationStartup support provides a practical way to inspect the startup sequence. BufferingApplicationStartup makes startup steps available for analysis, while the Actuator startup endpoint exposes the recorded information as JSON.
For deeper investigation, FlightRecorderApplicationStartup connects Spring startup events with Java Flight Recorder data. Developers can then examine class loading, allocations, garbage collection, and other JVM activities.
The most effective approach is to measure first, identify the operation responsible for the delay, and optimize that specific operation. Keep essential initialization separate from optional background work, validate readiness correctly, and compare both startup time and first-request performance after every change.
This makes startup optimization a measurable engineering process rather than a collection of configuration guesses.
Join the conversation! Your thoughts help the community grow.