Interview question
What are key performance optimization techniques for Spring Boot applications? Spring Boot applications के लिए performance optimization techniques क्या हैं?
Answer
Optimize through connection pooling, caching, async processing, lazy loading, database indexing, and HTTP caching headers. Profile applications to identify bottlenecks. Use tools like JProfiler for memory and CPU analysis.
// 1. Database Connection Pooling (HikariCP)
spring:
datasource:
hikari:
maximum-pool-size: 20
minimum-idle: 5
connection-timeout: 30000
idle-timeout: 600000
max-lifetime: 1800000
// 2. Caching Strategy
@Configuration
@EnableCaching
public class CacheConfig {
@Bean
public CacheManager cacheManager() {
CaffeineCacheManager cacheManager = new CaffeineCacheManager();
cacheManager.setCaffeine(Caffeine.newBuilder()
.expireAfterWrite(10, TimeUnit.MINUTES)
.maximumSize(1000));
return cacheManager;
}
}
@Service
public class ProductService {
@Cacheable(value = 'products', key = '#id')
public Product getProduct(Long id) {
// Database query - cached after first call
return productRepository.findById(id).orElse(null);
}
}
// 3. Lazy Loading
@Entity
public class Order {
@OneToMany(fetch = FetchType.LAZY)
private List<OrderItem> items; // Loaded only when accessed
}
// 4. Database Indexing
@Entity
public class User {
@Id
private Long id;
@Column(unique = true)
@Index(name = 'idx_email')
private String email; // Index for faster queries
}
// 5. HTTP Caching Headers
@RestController
public class ContentController {
@GetMapping('/api/static')
public ResponseEntity<Content> getStatic() {
return ResponseEntity.ok()
.cacheControl(CacheControl.maxAge(1, TimeUnit.HOURS)
.cachePublic())
.body(content);
}
}
// 6. Compression
server:
compression:
enabled: true
min-response-size: 1024
mime-types: application/json,text/html,text/xml
// 7. Thread Pool Configuration
@Configuration
public class ThreadPoolConfig {
@Bean(name = 'taskExecutor')
public Executor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setMaxPoolSize(20);
executor.setQueueCapacity(100);
executor.setThreadNamePrefix('async-');
executor.initialize();
return executor;
}
}
// 8. Database Query Optimization
@Repository
public interface OrderRepository extends JpaRepository<Order, Long> {
// N+1 query problem - use JOIN FETCH
@Query('SELECT DISTINCT o FROM Order o LEFT JOIN FETCH o.items WHERE o.customerId = ?1')
List<Order> findByCustomerIdOptimized(Long customerId);
}
// 9. Profiling and Monitoring
// JProfiler, YourKit, or JFR (Java Flight Recorder)
java -XX:+UnlockCommercialFeatures -XX:+FlightRecorder \
-XX:StartFlightRecording=delay=20s,duration=60s,filename=recording.jfr \
-jar app.jar
// 10. GC Optimization
# application.properties
spring.jvm.args=-XX:+UseG1GC -XX:MaxGCPauseMillis=200
// Benchmark Results (before/after optimization):
// Response time: 500ms -> 50ms (10x faster)
// Memory usage: 800MB -> 200MB
// QPS: 100 -> 1000Performance Optimization:
1. Connection Pooling:
HikariCP (fast, reliable)
maximum-pool-size: 20
2. Caching:
@Cacheable for frequently accessed
Caffeine (in-memory)
Redis (distributed)
3. Lazy Loading:
FetchType.LAZY
N+1 problem avoid करना
4. Database:
Proper indexing
Query optimization
JOIN FETCH use करना
5. HTTP Caching:
CacheControl headers
Browser caching
6. Compression:
Gzip enable करना
Response size reduce करना
7. Async Processing:
@Async for long operations
Thread pools properly sized
8. Monitoring:
JProfiler, YourKit
Identify bottlenecks
Results:
- 10x faster response time
- 75% memory reduction
- 10x higher throughputWas this answer clear?