15 Proven Spring Boot Performance Hacks to Supercharge Your Apps
This guide presents fifteen practical Spring Boot performance techniques—from lazy initialization and context indexing to JVM tuning, connection‑pool tweaks, caching strategies, JSON serialization, and native image compilation—providing concrete configurations, code snippets, and best‑practice advice for faster startup, lower memory usage, and higher throughput.
1. Startup Speed Optimizations
Technique 1: Lazy Initialization
What it is: Spring Boot 2.2 can defer bean creation until the bean is first used.
Why it works: It shortens startup time, ideal for micro‑service scaling and rolling releases.
Usage: spring.main.lazy-initialization=true Precautions:
Errors may surface later at runtime.
The first request can be slower.
Critical beans such as database pools should stay eager ( @Lazy(false)).
Technique 2: Spring Context Indexer
What it is: Generates META-INF/spring.components at compile time to avoid costly class‑path scanning.
Why it works: The more components, the greater the startup gain.
Usage:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-indexer</artifactId>
<optional>true</optional>
</dependency>Technique 3: Exclude Unnecessary Auto‑Configuration
What it is: Spring Boot may load modules you don’t need (e.g., both MySQL and MongoDB).
Why it works: Reduces unused beans, cutting startup time and memory.
Usage:
@SpringBootApplication(exclude = {
DataSourceAutoConfiguration.class,
KafkaAutoConfiguration.class
})
public class MyApplication {}Best practice: Run with --debug to see which auto‑configurations are active before excluding them.
2. JVM and Memory Tuning
Technique 4: JVM Parameter Optimization
Why it works: Default JVM flags are generic; tailored settings improve GC behavior and reduce pause times.
Example flags:
-Xms2g -Xmx2g
-XX:+UseG1GC
-XX:MaxMetaspaceSize=256m
-Xlog:gc*:file=./gc.log:time:filecount=5,filesize=10mTechnique 5: GC Monitoring and Analysis
Why it works: Frequent or long Full GCs degrade performance.
Approach:
Enable GC logging.
Monitor with Spring Boot Actuator + Prometheus + Grafana.
Analyze logs using tools like GCeasy or GarbageCat to spot leaks or poor allocation.
3. Runtime Performance Optimizations
Technique 6: Connection‑Pool Tuning (HikariCP)
Why it works: Database connections are a common bottleneck; proper pool settings lower wait times and protect the DB.
Configuration example:
spring.datasource.hikari.maximum-pool-size=10
spring.datasource.hikari.minimum-idle=5
spring.datasource.hikari.max-lifetime=1800000
spring.datasource.hikari.connection-timeout=30000
spring.datasource.hikari.connection-test-query=SELECT 1Technique 7: Reduce Reflection and AOP Overhead
Why it works: Excessive use of reflection and proxies slows high‑concurrency workloads.
Optimizations:
Define precise pointcuts; avoid broad patterns like execution(* com.example..*.*(..)).
Minimize reflective calls in business code.
For extreme performance, consider Spring Native / AOT to eliminate reflection.
Technique 8: Effective Caching
Why it works: Caching dramatically reduces database and remote‑call pressure.
Usage example:
@Cacheable(value = "user", key = "#id")
public User getUserById(Long id) { ... }Practical tips:
Local cache with Caffeine.
Distributed cache with Redis.
Design expiration policies to avoid cache avalanche and stampede.
Technique 9: Log Optimization
Why it works: Log I/O is a frequent performance bottleneck.
Methods:
Use INFO / ERROR levels in production.
Enable asynchronous logging (Logback AsyncAppender or Log4j2 AsyncAppender).
Rotate log files to avoid oversized single files.
Technique 10: Asynchronous Processing and Batch Operations
Why it works: Synchronous blocking reduces throughput; async processing boosts it.
Practices:
Use @Async or message queues (Kafka, RabbitMQ) for long‑running tasks.
Batch insert/update SQL instead of row‑by‑row execution.
Technique 11: JSON Serialization Optimization
Why it works: API latency often stems from (de)serialization.
Improvements:
Apply @JsonIgnore to drop unnecessary fields.
Add Jackson Afterburner module for faster processing:
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-afterburner</artifactId>
</dependency>For ultra‑high performance, replace JSON with Protobuf or Avro.
Technique 12: Avoid N+1 Queries
Why it works: ORM frameworks can generate excessive SQL statements.
Solutions:
Use JPA join fetch or MyBatis resultMap with associations.
Batch queries instead of looping.
Cache hot data.
Technique 13: Reduce Unnecessary HTTP Requests
Why it works: Fewer requests lower bandwidth usage and server load.
Optimizations:
Leverage HTTP caching headers (ETag, Cache‑Control).
Serve high‑frequency endpoints via CDN.
Reuse connections with pools (OkHttp, HttpClient).
4. Architecture & Deployment Optimizations
Technique 14: Profile‑Based Environment Configuration
Why it works: Mixing dev and prod settings can waste resources.
Approach:
Separate files such as application-dev.yml and application-prod.yml.
Disable debug mode and unnecessary Actuator endpoints in production.
Technique 15: Spring Native / GraalVM AOT Compilation
Why it works: GraalVM ahead‑of‑time compiles Spring Boot apps into native images, dramatically speeding startup and cutting memory usage.
Suitable scenarios:
Serverless / Function‑as‑a‑Service environments.
Containerized micro‑services requiring sub‑second start‑up.
5. Summary & Checklist
Performance tuning is an iterative process: measure → locate bottlenecks → optimize → re‑measure . Use APM tools (SkyWalking, Pinpoint), profilers (JProfiler), and metrics stacks (Prometheus + Grafana) to continuously discover and resolve issues.
Enable lazy initialization.
Add Spring Context Indexer.
Exclude unused auto‑configurations.
Fine‑tune JVM flags.
Monitor and analyze GC.
Configure connection pools wisely.
Limit reflection and AOP scope.
Apply caching strategically.
Optimize logging I/O.
Adopt async processing and batch writes.
Speed up JSON handling.
Avoid N+1 database queries.
Reduce redundant HTTP traffic.
Separate environment profiles.
Consider native image compilation for extreme cases.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Ray's Galactic Tech
Practice together, never alone. We cover programming languages, development tools, learning methods, and pitfall notes. We simplify complex topics, guiding you from beginner to advanced. Weekly practical content—let's grow together!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
