Spring Boot makes it easy to build applications without manually configuring every framework component. It provides automatic configuration, dependency injection, embedded servers, database integration, security, monitoring, and many other features.
However, as an application grows, its startup time can increase. A small service that starts in a few seconds may take much longer after adding database integrations, security configurations, messaging systems, monitoring libraries, and multiple application modules.
Startup performance becomes especially important in cloud environments, microservices, and containerized applications. When Kubernetes creates a new pod, when an application scales out, or when a failed instance restarts, the application must become ready to handle requests as quickly as possible.
Reducing startup time is not simply about changing one Spring Boot property. It requires understanding what happens during application startup, identifying expensive operations, and selecting optimizations that address the actual bottlenecks.
This article explains practical ways to improve Spring Boot application startup time using startup profiling, dependency optimization, lazy initialization, Spring Ahead-of-Time processing, JVM AOT caching, Class Data Sharing, and container-level improvements.
Understanding Spring Boot Application Startup
Before optimizing startup performance, it is important to understand what happens when a Spring Boot application starts.
When the application executes its main method, Spring Boot initializes the application context and prepares the environment required to run the application.
A simplified startup process includes:
- JVM initialization and class loading.
- Spring application environment preparation.
- Component scanning and configuration processing.
- Auto-configuration evaluation.
- Bean definition registration.
- Dependency injection and bean initialization.
- Embedded server initialization.
- Application runners and startup tasks.
- Application readiness.
Each stage contributes to the total startup time.
For example, an application using Spring MVC, Spring Security, Spring Data JPA, Hibernate, and PostgreSQL may need to initialize several framework components before it can accept requests.
The database connection pool may also need to initialize connections, while Hibernate may inspect entity mappings and database metadata.
The important point is that not every application spends most of its startup time in the same place. One application may be slow because of class loading, while another may be waiting for a database connection or executing expensive initialization code.
Therefore, measure startup performance before changing configuration.
Measuring Spring Boot Startup Performance
The first step is to establish a reliable baseline.
Spring Boot logs provide basic startup information:
Starting CustomerApplication using Java 25
Tomcat initialized with port 8080
Root WebApplicationContext: initialization completed
Tomcat started on port 8080
Started CustomerApplication in 4.101 seconds
The Started CustomerApplication message provides a useful indication of application startup duration.
However, the total time does not explain which component consumed the most time.
Spring Boot provides startup tracking through the ApplicationStartup infrastructure.
Using BufferingApplicationStartup
BufferingApplicationStartup records startup steps so developers can inspect the application initialization process.
Configure it 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 CustomerApplication {
public static void main(String[] args) {
SpringApplication application =
new SpringApplication(CustomerApplication.class);
application.setApplicationStartup(
new BufferingApplicationStartup(2048)
);
application.run(args);
}
}
The buffer size controls how many startup events can be retained for analysis.
You can expose the startup information through Spring Boot Actuator.
Add the Actuator dependency if it is not already present:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
Then configure the startup endpoint:
management:
endpoints:
web:
exposure:
include: health,info,startup
After starting the application, access:
http://localhost:8080/actuator/startup
The endpoint returns startup information as JSON.
This makes it easier to identify expensive initialization steps and understand which components contribute to startup delays.
The startup endpoint should not be exposed publicly without appropriate security controls. In production, restrict management endpoints to authorized monitoring systems.
Using Java Flight Recorder
Java Flight Recorder (JFR) provides another way to investigate startup performance.
It records JVM events such as class loading, garbage collection, thread activity, and memory allocation.
Start the application with a recording:
java \
-XX:StartFlightRecording=filename=startup.jfr,duration=30s \
-jar customer-api.jar
After the recording completes, open the JFR file in Java Mission Control.
You can inspect class loading, thread activity, garbage collection, and other JVM operations.
For Spring-specific startup steps, Spring Framework also provides FlightRecorderApplicationStartup, which can be used to correlate Spring lifecycle events with JVM activity.
Use these tools when application logs do not provide enough information to identify the bottleneck.
Reducing Unnecessary Dependencies
One of the most effective ways to improve startup performance is to reduce unnecessary dependencies.
Every additional library can increase the number of classes that the JVM needs to load and the amount of configuration Spring needs to process.
For example, consider an application that includes these dependencies:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
This configuration may be appropriate for a complex application. However, if the application does not use Redis or JPA, those dependencies should not be included.
Review the dependency tree using Maven:
mvn dependency:tree
For Gradle:
./gradlew dependencies
Look for libraries that are no longer used, duplicated dependencies, unnecessary integrations, and dependencies that introduce expensive auto-configuration.
Removing unused dependencies can reduce class loading, configuration processing, memory usage, and packaging size.
Do not remove a dependency simply because it appears large. First verify whether another library depends on it or whether the application uses it indirectly.
Enabling Lazy Initialization
Spring normally creates singleton beans during application context initialization.
This means that many beans are created before the application begins accepting requests, even if some of them are not immediately required.
Lazy initialization changes this behavior. Instead of creating every bean during startup, Spring creates a bean when it is first needed.
Enable lazy initialization using application.yml:
spring:
main:
lazy-initialization: true
With this configuration, Spring delays the creation of eligible beans until they are requested.
For example:
import org.springframework.stereotype.Service;
@Service
public class ReportService {
public ReportService() {
System.out.println("ReportService initialized");
}
public String generateReport() {
return "Report generated";
}
}
Without lazy initialization, the service is normally created during application startup.
With lazy initialization enabled, its creation can be delayed until another component requests it.
Disabling Lazy Initialization for Important Beans
Not every bean should be initialized lazily.
For example, a critical payment configuration or security component may need to be initialized during startup so configuration errors are discovered immediately.
You can explicitly disable lazy initialization for selected beans:
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
@Service
@Lazy(false)
public class PaymentService {
public PaymentService() {
System.out.println("PaymentService initialized");
}
}
This allows the application to use lazy initialization generally while keeping important components eager.
When Should You Use Lazy Initialization?
Lazy initialization is useful when an application contains many optional or infrequently used components.
However, it introduces a trade-off.
A bean that fails during initialization may no longer cause the application to fail during startup. Instead, the problem may appear when the first request uses that bean.
This can create unexpected delays during the first request.
It can also increase memory pressure later because more beans may eventually be created while the application is handling traffic.
For production applications, test lazy initialization with realistic workloads and monitor the first-request latency.
Optimizing Component Scanning and Auto-Configuration
Spring Boot uses component scanning and auto-configuration to discover and configure application components.
These features reduce manual configuration, but unnecessarily broad scanning and unused auto-configurations can add startup work.
Keep Component Scanning Focused
Consider this configuration:
@SpringBootApplication(
scanBasePackages = "com"
)
public class CustomerApplication {
}
Scanning the entire com package may include unrelated applications, libraries, and components.
Prefer a focused package structure:
com.example.customer
CustomerApplication.java
controller/
service/
repository/
configuration/
Then use the default component scanning behavior:
@SpringBootApplication
public class CustomerApplication {
}
Spring scans the application package and its subpackages.
This keeps component discovery more predictable.
Excluding Unused Auto-Configuration
Spring Boot uses conditional auto-configuration to configure features based on the application classpath and environment.
If an application does not use a particular integration, avoid adding the corresponding dependency.
For example, if the application does not use Redis, do not include Redis starter dependencies simply because another project uses them.
You can also exclude specific auto-configurations when appropriate:
@SpringBootApplication(
exclude = {
SomeUnusedAutoConfiguration.class
}
)
public class CustomerApplication {
}
Use exclusions carefully. Removing an auto-configuration that another component requires can cause startup failures.
It is better to remove unnecessary dependencies than to maintain a large collection of exclusions.
Using Spring Ahead-of-Time Processing
Spring Ahead-of-Time (AOT) processing moves some application preparation work from runtime to build time.
During normal startup, Spring performs configuration processing, evaluates bean definitions, and prepares the application context.
AOT processing performs supported parts of this work during the build and generates code that can be used during application startup.
Spring Boot supports AOT processing for both native images and JVM-based deployments.
Enabling AOT Processing With Maven
For Maven projects, Spring Boot provides AOT support through its Maven plugin.
The Spring Boot documentation describes activating the native profile:
mvn -Pnative package
The profile must be configured in the project so that the AOT processing required by the build is executed.
After building the application, run the generated JAR with AOT enabled:
java \
-Dspring.aot.enabled=true \
-jar target/customer-api.jar
Spring Boot then uses the generated initialization code.
Using AOT With Gradle
For Gradle projects, include the Spring Boot AOT plugin as part of the build configuration.
The exact configuration should follow the Spring Boot version and Gradle plugin documentation used by the project.
After building the application with AOT processing enabled, run it with:
java -Dspring.aot.enabled=true -jar customer-api.jar
Important AOT Limitations
AOT processing makes some application decisions at build time.
This means the application classpath and bean configuration are expected to remain fixed.
For example, profile-specific configuration and conditional bean registration may behave differently because some decisions have already been made during the build.
Review the following areas before enabling AOT:
- Runtime profile changes.
- Conditional bean registration.
- Dynamic classpath changes.
- Programmatic bean registration.
- Reflection-based configuration.
- Runtime-generated components.
AOT can improve startup performance, but it is not suitable for every application configuration without additional work.
Using JVM AOT Cache and Class Data Sharing
Spring Boot 4.2 supports JVM-level caching techniques that can reduce class loading and startup overhead.
These features are especially useful when applications repeatedly start using the same application artifact and Java runtime.
The two important technologies are JVM AOT Cache and Class Data Sharing (CDS).
JVM AOT Cache
JVM AOT Cache is available with Java 25 and later in the Spring Boot 4.2 documentation.
It stores reusable JVM information generated during a training run. The JVM can use this information during later application startups.
First, extract the executable JAR:
java -Djarmode=tools \
-jar customer-api.jar \
extract --destination application
Move into the extracted application directory:
cd application
Generate the AOT cache:
java \
-XX:AOTCacheOutput=app.aot \
-Dspring.context.exit=onRefresh \
-jar customer-api.jar
This produces the app.aot cache file.
Start the application using the generated cache:
java \
-XX:AOTCache=app.aot \
-jar customer-api.jar
The cache can be reused while the application artifact and Java version remain compatible with the training run.
The extracted application format is required for this Spring Boot workflow. Using the cache with the original packaged JAR does not provide the intended benefit.
Class Data Sharing
If the application runs on a Java version earlier than Java 25, CDS is an alternative.
CDS allows the JVM to share class metadata between application processes through an archive.
First, extract the application:
java -Djarmode=tools \
-jar customer-api.jar \
extract --destination application
Create the CDS archive:
cd application
java \
-XX:ArchiveClassesAtExit=application.jsa \
-Dspring.context.exit=onRefresh \
-jar customer-api.jar
Start the application using the archive:
java \
-XX:SharedArchiveFile=application.jsa \
-jar customer-api.jar
The archive should be regenerated when the application changes in ways that affect its classpath or loaded classes.
AOT Cache vs CDS
Feature | JVM AOT Cache | Class Data Sharing |
|---|
Purpose | Reuses JVM initialization and profiling information | Shares class metadata |
Spring Boot 4.2 guidance | Preferred with Java 25+ | Use with earlier Java versions |
Java support | Java 25+ in Spring Boot 4.2 guidance | Earlier Java versions |
Startup benefit | Reduces repeated JVM startup work | Reduces class loading work |
Cache generation | Training run | Training run |
Application changes | Regenerate when application changes | Regenerate when application changes |
For Java 25 or later, Spring Boot recommends using AOT Cache instead of CDS.
These JVM features can also be combined with Spring's own AOT processing for additional startup improvements.
Reducing Expensive Initialization Tasks
Not all startup delays come from Spring itself.
Applications often execute custom initialization code during startup.
For example, a service may load thousands of database records, call an external API, initialize a search index, or prepare an in-memory cache.
These operations can increase startup time significantly.
Consider the following example:
@Component
public class ApplicationInitializer {
private final ProductService productService;
public ApplicationInitializer(ProductService productService) {
this.productService = productService;
}
@PostConstruct
public void initialize() {
productService.loadAllProducts();
productService.prepareSearchIndex();
productService.refreshCache();
}
}
If these operations take several seconds, they delay application initialization.
Review whether all operations must finish before the application becomes ready.
For example, if the search index can be prepared asynchronously after startup, it may be possible to move that work into a controlled background process.
However, do not move required initialization to the background if the application cannot safely handle requests without it.
Use ApplicationRunner for Startup Tasks
Spring Boot provides ApplicationRunner and CommandLineRunner for tasks that must execute after the application context has started but before startup completes.
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class StartupConfiguration {
@Bean
ApplicationRunner initializeApplication(
ProductService productService) {
return args -> {
productService.loadRequiredConfiguration();
};
}
}
This is useful for required initialization that should run as part of the application startup lifecycle.
If a task is optional, expensive, and not required before traffic is accepted, consider a separate background process with explicit readiness and failure handling.
Optimizing Database Initialization
Database configuration is another common source of slow startup.
Applications using Spring Data JPA and Hibernate may perform database metadata inspection, entity validation, schema checks, and connection pool initialization.
For example:
spring:
datasource:
url: jdbc:postgresql://localhost:5432/customerdb
username: appuser
password: ${DB_PASSWORD}
hikari:
maximum-pool-size: 10
minimum-idle: 2
jpa:
hibernate:
ddl-auto: validate
The connection pool settings should reflect the application's workload.
A large minimum idle connection count may cause unnecessary database connections during startup.
For services that need only a few initial connections, review whether a smaller minimum idle setting is appropriate.
Avoid using schema creation or update modes in production unless there is a specific reason. Production database schema changes are generally better managed through migration tools such as Flyway or Liquibase.
Also review database connection timeouts and network connectivity. A database that responds slowly can make the application appear to have a Spring startup problem.
Optimizing Container and Deployment Startup
Application startup time is only one part of the deployment experience.
Container image size, image download time, JVM initialization, and Kubernetes readiness checks also affect how quickly a new instance becomes available.
Use an Efficient Container Image
A multi-stage Docker build can keep the final runtime image smaller.
For example:
FROM eclipse-temurin:25-jdk AS build
WORKDIR /app
COPY . .
RUN ./mvnw clean package -DskipTests
FROM eclipse-temurin:25-jre
WORKDIR /app
COPY --from=build \
/app/target/customer-api.jar \
customer-api.jar
ENTRYPOINT ["java", "-jar", "customer-api.jar"]
This example separates the build environment from the runtime environment.
The final image contains the JRE and application artifact rather than the entire build toolchain.
For production, use trusted base images, pin image versions, and scan images for vulnerabilities.
Configure Kubernetes Readiness Correctly
Kubernetes uses readiness probes to determine whether a container should receive traffic.
Spring Boot provides readiness and liveness support through Actuator.
A basic configuration might look like this:
management:
endpoint:
health:
probes:
enabled: true
The application can expose health endpoints for Kubernetes probes:
/actuator/health/liveness
/actuator/health/readiness
A readiness probe should indicate whether the application can safely handle requests.
Do not mark an application ready simply because the JVM has started. Required startup tasks and dependencies must be ready before traffic is routed.
At the same time, avoid adding unnecessary external dependency checks to the liveness probe. A temporary database failure should not automatically cause every application instance to restart.
Avoid Misleading Startup Improvements
Reducing the readiness delay by weakening health checks does not necessarily improve actual application performance.
For example, lazy initialization may allow the server to start quickly, but the first request may still trigger expensive bean creation.
Measure both startup time and first-request latency.
A useful production metric is the time between container creation and the point at which the application can safely serve real traffic.
Common Mistakes When Optimizing Startup Time
Enabling Lazy Initialization Without Testing
Lazy initialization may reduce startup time, but it can move failures to the first request.
Test important endpoints and startup-dependent components before deploying the configuration.
Removing Dependencies Without Understanding Them
A dependency may be used indirectly by another library or integration.
Review the dependency tree and application behavior before removing it.
Using AOT Without Reviewing Runtime Configuration
AOT processing assumes a relatively fixed application configuration.
Applications that rely heavily on runtime profile changes or dynamic bean registration may require adjustments.
Creating JVM Cache Files From the Wrong Artifact
AOT Cache and CDS depend on a compatible application classpath and runtime.
Generate cache files from the exact application artifact and Java version intended for deployment.
Moving Required Initialization Into Background Tasks
If the application needs a cache, database connection, or configuration before processing requests, starting the background operation after readiness can create failures.
Keep required initialization inside the readiness lifecycle.
Optimizing Without Measuring
A configuration change may improve one startup phase while increasing memory usage or first-request latency.
Always compare measurements before and after each change.
Best Practices for Production Applications
- Measure startup time before making optimization changes.
- Use
BufferingApplicationStartup to identify expensive Spring initialization steps. - Use Java Flight Recorder to investigate JVM-level startup activity.
- Remove unused dependencies and unnecessary integrations.
- Keep component scanning focused on the application package.
- Use lazy initialization selectively.
- Prefer Spring AOT processing when the application's configuration is compatible.
- Use JVM AOT Cache with Java 25 or later when supported by the deployment environment.
- Use CDS for earlier Java versions where appropriate.
- Avoid expensive external API calls during bean initialization.
- Review database connection pool settings.
- Use small, trusted runtime container images.
- Configure Kubernetes readiness and liveness probes correctly.
- Benchmark startup time and first-request latency separately.
- Regenerate AOT and JVM cache artifacts when application or runtime compatibility changes.
Advantages and Disadvantages of Startup Optimization
Advantages
- Reduces application startup time.
- Improves scaling behavior in cloud environments.
- Helps services recover faster after failures.
- Reduces delays during rolling deployments.
- Improves resource utilization in containerized platforms.
- Can reduce repeated JVM class loading and initialization work.
- Makes application startup behavior easier to understand through profiling.
Disadvantages
- Some optimizations require additional build configuration.
- Lazy initialization can delay the discovery of configuration errors.
- AOT processing introduces restrictions on dynamic application configuration.
- JVM cache generation adds build and deployment complexity.
- Dependency removal requires careful testing.
- Smaller startup times do not always mean lower first-request latency.
- Some optimizations may increase memory usage or shift work to runtime.
Conclusion
Reducing Spring Boot application startup time requires more than enabling a single configuration property. Developers should first identify where startup time is being spent and then apply optimizations that address the actual bottleneck.
Spring Boot provides useful tools such as BufferingApplicationStartup and Actuator's startup endpoint for analyzing application initialization. Dependency cleanup, focused component scanning, selective lazy initialization, and reduced startup work can improve performance without changing the overall architecture.
For more advanced optimization, Spring AOT processing can move supported initialization work to build time. JVM AOT Cache provides additional startup benefits with Java 25 and later, while CDS remains useful for earlier Java versions.
In production environments, also consider database initialization, container image size, JVM configuration, and Kubernetes readiness behavior.
The best results come from measuring startup time, applying one optimization at a time, and testing both application readiness and first-request performance. This approach helps build Spring Boot services that start faster without sacrificing reliability or maintainability.
Join the conversation! Your thoughts help the community grow.