Performance Optimization, Monitoring & DevOps
Monitor and deploy Spring Boot. Learn Actuator metrics, profiling, Docker configurations, garbage collection, and query optimizations.
Downloaded from PrepIQ (https://prepiq.online)
Q1. What is Spring Boot Actuator and what are its key endpoints?
Spring Boot Actuator provides built-in endpoints for monitoring and managing applications. Expose health, metrics, and environment information via HTTP or JMX. Essential for production applications to track performance and troubleshoot issues.
| Endpoint | Purpose | Example |
|---|---|---|
| /actuator/health | Application health status | UP, DOWN, DEGRADED |
| /actuator/metrics | Application metrics | JVM, HTTP requests |
| /actuator/env | Environment properties | Active profiles |
| /actuator/loggers | Logger configuration | Change log levels |
| /actuator/threaddump | Thread information | Deadlock detection |
// Enable Actuator
// pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
// application.yml
management:
endpoints:
web:
exposure:
include: health,metrics,info,env,loggers
endpoint:
health:
show-details: always
metrics:
export:
prometheus:
enabled: true
// Custom Health Check
@Component
public class CustomHealthIndicator implements HealthIndicator {
@Override
public Health health() {
try {
// Check critical service
checkDatabaseConnection();
return Health.up()
.withDetail('database', 'connected')
.build();
} catch (Exception e) {
return Health.down()
.withDetail('error', e.getMessage())
.build();
}
}
private void checkDatabaseConnection() {
// Verify database is accessible
}
}
// Custom Metrics
@Component
public class BusinessMetrics {
private final MeterRegistry meterRegistry;
public BusinessMetrics(MeterRegistry meterRegistry) {
this.meterRegistry = meterRegistry;
}
public void recordOrderCreated() {
meterRegistry.counter('orders.created').increment();
}
public void recordOrderValue(double value) {
meterRegistry.timer('order.processing.time').record(
value, TimeUnit.MILLISECONDS);
}
}
// Access endpoints
// http://localhost:8080/actuator/health
// http://localhost:8080/actuator/metrics
// http://localhost:8080/actuator/metrics/http.server.requests
Q2. What is Micrometer and how do you expose metrics to Prometheus?
Micrometer is a metrics facade supporting multiple monitoring systems (Prometheus, Datadog, New Relic). Spring Boot Actuator uses Micrometer by default. Export metrics to Prometheus for visualization in Grafana dashboards.
// Micrometer Configuration
// pom.xml
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
// application.yml
management:
endpoints:
web:
exposure:
include: prometheus
metrics:
tags:
application: order-service
environment: production
// Custom Metrics
@Service
public class OrderMetricsService {
private final MeterRegistry meterRegistry;
private final Counter ordersCreated;
private final Timer orderProcessingTimer;
public OrderMetricsService(MeterRegistry meterRegistry) {
this.meterRegistry = meterRegistry;
this.ordersCreated = Counter.builder('orders.total')
.description('Total orders created')
.tag('type', 'business')
.register(meterRegistry);
this.orderProcessingTimer = Timer.builder('order.processing')
.description('Order processing time')
.register(meterRegistry);
}
public void processOrder(Order order) {
orderProcessingTimer.recordCallable(() -> {
// Process order
ordersCreated.increment();
return null;
});
}
public void recordInventoryLevel(int level) {
meterRegistry.gauge('inventory.level', level);
}
}
// Prometheus Configuration (docker-compose.yml)
version: '3.8'
services:
app:
image: app:latest
ports:
- '8080:8080'
prometheus:
image: prom/prometheus:latest
ports:
- '9090:9090'
volumes:
- ./prometheus.yml:/etc/prometheus/prometheus.yml
grafana:
image: grafana/grafana:latest
ports:
- '3000:3000'
environment:
- GF_SECURITY_ADMIN_PASSWORD=admin
// prometheus.yml
global:
scrape_interval: 15s
scrape_configs:
- job_name: 'spring-boot-app'
static_configs:
- targets: ['localhost:8080']
metrics_path: '/actuator/prometheus'
// Grafana Queries
// Total orders: sum(orders_total)
// Order processing rate: rate(order_processing_seconds_sum[5m])
// P95 latency: histogram_quantile(0.95, order_processing_seconds)
// Key Micrometer Metrics:
// 1. Counter - incrementing metric
// 2. Timer - timing operations
// 3. Gauge - current value
// 4. Distribution Summary - distribution of values
Q3. What are logging best practices in Spring Boot? How do you configure Logback?
Use SLF4J facade with Logback implementation. Configure different log levels, outputs, and patterns. Use contextual logging for request tracking. Implement proper log rotation to prevent disk space issues.
// logback-spring.xml
<?xml version='1.0' encoding='UTF-8'?>
<configuration>
<property name='LOG_PATTERN'
value='%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n'/>
<property name='LOG_FILE' value='logs/app.log'/>
<!-- Console Appender -->
<appender name='CONSOLE' class='ch.qos.logback.core.ConsoleAppender'>
<encoder>
<pattern>${LOG_PATTERN}</pattern>
</encoder>
</appender>
<!-- File Appender with Rotation -->
<appender name='FILE' class='ch.qos.logback.core.rolling.RollingFileAppender'>
<file>${LOG_FILE}</file>
<encoder>
<pattern>${LOG_PATTERN}</pattern>
</encoder>
<rollingPolicy class='ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy'>
<fileNamePattern>logs/app.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<maxFileSize>10MB</maxFileSize>
<maxHistory>30</maxHistory>
</rollingPolicy>
</appender>
<!-- Logger Configuration -->
<logger name='com.example.app' level='DEBUG'/>
<logger name='org.springframework' level='INFO'/>
<logger name='org.hibernate' level='WARN'/>
<!-- Root Logger -->
<root level='INFO'>
<appender-ref ref='CONSOLE'/>
<appender-ref ref='FILE'/>
</root>
</configuration>
// application.yml - Dynamic Log Levels
logging:
level:
root: INFO
com.example.app: DEBUG
org.springframework.web: DEBUG
org.hibernate: WARN
file:
name: logs/app.log
pattern:
console: '%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n'
file: '%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n'
// Structured Logging with SLF4J
public class OrderService {
private static final Logger logger = LoggerFactory.getLogger(OrderService.class);
public void processOrder(String orderId, String customerId) {
// Contextual logging
MDC.put('orderId', orderId);
MDC.put('customerId', customerId);
try {
logger.info('Processing order started');
// Business logic
logger.info('Order processed successfully');
} catch (Exception e) {
logger.error('Error processing order', e);
} finally {
MDC.clear();
}
}
}
// Async Logging (high throughput)
<appender name='ASYNC_FILE' class='ch.qos.logback.classic.AsyncAppender'>
<queueSize>512</queueSize>
<discardingThreshold>0</discardingThreshold>
<appender-ref ref='FILE'/>
</appender>
// Best Practices:
// 1. Use SLF4J - facade pattern
// 2. Set appropriate log levels
// 3. Implement log rotation
// 4. Use async logging for performance
// 5. Structured logging with MDC
// 6. Never log passwords/secrets
// 7. Use appropriate log levels (DEBUG < INFO < WARN < ERROR)
Q4. What is Distributed Tracing and how do you implement it with Spring Cloud Sleuth?
Distributed tracing tracks requests across microservices using trace IDs and span IDs. Spring Cloud Sleuth integrates with Zipkin/Jaeger for visualization. Essential for debugging in microservices architecture.
// Maven Dependency
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-sleuth</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-sleuth-zipkin</artifactId>
</dependency>
// application.yml
spring:
application:
name: order-service
sleuth:
enabled: true
sampler:
probability: 1.0 # 100% sampling (use 0.1 in prod)
zipkin:
base-url: http://zipkin:9411
// Automatic Tracing (no code changes needed)
@RestController
@RequestMapping('/api/orders')
public class OrderController {
// Spring Sleuth automatically adds trace IDs
// Logs show: [order-service,abc123,def456,true]
// trace-id=abc123, span-id=def456
@GetMapping('/{id}')
public ResponseEntity<Order> getOrder(@PathVariable String id) {
// Sleuth automatically tracks this
return ResponseEntity.ok(orderService.getOrder(id));
}
}
// Manual Span Creation
@Service
public class OrderService {
@Autowired
private Tracer tracer;
public Order processOrder(String orderId) {
// Create custom span
Span span = tracer.nextSpan().name('processOrder').start();
try (Tracer.SpanInScope ws = tracer.withSpan(span)) {
// Business logic
return new Order();
} finally {
span.end();
}
}
}
// Cross-Service Tracing (RestTemplate, WebClient)
@Configuration
public class RestTemplateConfiguration {
@Bean
public RestTemplate restTemplate(
RestTemplateBuilder builder,
ClientHttpRequestFactory factory) {
// Sleuth automatically injects trace headers
return builder
.requestFactory(factory)
.build();
}
}
// Docker Compose - Zipkin Setup
version: '3.8'
services:
order-service:
image: app:latest
ports:
- '8080:8080'
environment:
SPRING_ZIPKIN_BASE_URL: http://zipkin:9411
payment-service:
image: app:latest
ports:
- '8081:8081'
environment:
SPRING_ZIPKIN_BASE_URL: http://zipkin:9411
zipkin:
image: openzipkin/zipkin:latest
ports:
- '9411:9411'
// Trace Flow Visualization in Zipkin:
// 1. User request hits Order Service
// 2. Order Service calls Payment Service
// 3. Payment Service calls Database
// 4. All steps tracked with same trace-id
// 5. Zipkin shows timeline and latency
// Key Concepts:
// Trace ID - unique request identifier
// Span ID - individual operation
// Parent Span ID - call hierarchy
// Timestamp - when operation started
// Duration - how long it took
Q5. How do you containerize a Spring Boot application with Docker?
Create Dockerfile to package Spring Boot app as container image. Use multi-stage builds to optimize image size. Spring Boot provides spring-boot-maven-plugin for efficient layered images.
// Dockerfile - Multi-stage Build
FROM maven:3.8-openjdk-11 AS builder
WORKDIR /app
COPY pom.xml .
COPY src ./src
RUN mvn clean package -DskipTests
# Runtime Stage
FROM openjdk:11-jre-slim
WORKDIR /app
COPY --from=builder /app/target/*.jar app.jar
# Expose port
EXPOSE 8080
# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=40s --retries=3 \
CMD curl -f http://localhost:8080/actuator/health || exit 1
# Run application
ENTRYPOINT ['java', '-jar', 'app.jar']
// Optimized Dockerfile (Spring Boot 2.3+)
FROM openjdk:11-jre-slim
WORKDIR /app
# Extract layers
COPY target/dependency/BOOT-INF/lib /app/lib
COPY target/dependency/BOOT-INF/classes /app
COPY target/dependency/META-INF /app/META-INF
EXPOSE 8080
ENTRYPOINT ['java', '-cp', 'app:app/lib/*',
'com.example.Application']
// pom.xml - Maven Plugin
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<layers>
<enabled>true</enabled>
</layers>
</configuration>
</plugin>
</plugins>
// Docker Build Command
docker build -t app:1.0 .
// docker-compose.yml - Complete Stack
version: '3.8'
services:
app:
image: app:1.0
container_name: app
ports:
- '8080:8080'
environment:
SPRING_DATASOURCE_URL: jdbc:mysql://mysql:3306/appdb
SPRING_DATASOURCE_USERNAME: root
SPRING_DATASOURCE_PASSWORD: password
SPRING_PROFILES_ACTIVE: docker
depends_on:
- mysql
- redis
networks:
- app-network
mysql:
image: mysql:8.0
container_name: mysql
ports:
- '3306:3306'
environment:
MYSQL_ROOT_PASSWORD: password
MYSQL_DATABASE: appdb
volumes:
- mysql-data:/var/lib/mysql
networks:
- app-network
redis:
image: redis:alpine
container_name: redis
ports:
- '6379:6379'
networks:
- app-network
volumes:
mysql-data:
networks:
app-network:
driver: bridge
// Docker Run Commands
# Build image
docker build -t myapp:1.0 .
# Run container
docker run -d -p 8080:8080 --name myapp myapp:1.0
// Best Practices:
// 1. Use Alpine for smaller images
// 2. Multi-stage builds
// 3. Layer caching optimization
// 4. Health checks
// 5. Non-root user
// 6. Resource limits
// 7. Environment variables
Q6. How do you deploy Spring Boot applications on Kubernetes?
Create Kubernetes manifests (Deployment, Service, ConfigMap) to run containerized Spring Boot apps. Use kubectl for deployment, manage scaling, and enable service discovery in cluster.
// deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: app
labels:
app: app
spec:
replicas: 3
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 1
maxUnavailable: 0
selector:
matchLabels:
app: app
template:
metadata:
labels:
app: app
spec:
containers:
- name: app
image: app:1.0
imagePullPolicy: IfNotPresent
ports:
- containerPort: 8080
env:
- name: SPRING_PROFILES_ACTIVE
value: 'kubernetes'
- name: SPRING_DATASOURCE_URL
valueFrom:
configMapKeyRef:
name: app-config
key: db-url
resources:
requests:
memory: '512Mi'
cpu: '250m'
limits:
memory: '1024Mi'
cpu: '500m'
livenessProbe:
httpGet:
path: /actuator/health/liveness
port: 8080
initialDelaySeconds: 30
periodSeconds: 10
readinessProbe:
httpGet:
path: /actuator/health/readiness
port: 8080
initialDelaySeconds: 10
periodSeconds: 5
// service.yaml
apiVersion: v1
kind: Service
metadata:
name: app-service
spec:
type: LoadBalancer
selector:
app: app
ports:
- protocol: TCP
port: 80
targetPort: 8080
// configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: app-config
data:
db-url: 'jdbc:mysql://mysql-service:3306/appdb'
log-level: 'INFO'
// Deployment Commands
# Apply manifests
kubectl apply -f deployment.yaml
kubectl apply -f service.yaml
kubectl apply -f configmap.yaml
# Check deployment status
kubectl get deployments
kubectl get pods
kubectl logs -f pod-name
# Scale application
kubectl scale deployment app --replicas=5
// Liveness vs Readiness Probes
// Liveness: Is app alive? (restart if false)
// Readiness: Can app handle traffic? (remove from LB if false)
// Production Checklist:
// 1. Resource limits (CPU, memory)
// 2. Health checks (liveness, readiness)
// 3. Rolling updates
// 4. Service discovery
// 5. ConfigMap for config
// 6. Secrets for credentials
// 7. Persistent volumes for data
// 8. Horizontal Pod Autoscaler (HPA)
Q7. What are key performance optimization techniques for Spring Boot applications?
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 -> 1000
Q8. What are security best practices for production Spring Boot applications?
Use HTTPS, implement authentication/authorization, validate inputs, use parameterized queries, manage secrets, enable security headers, and keep dependencies updated. Follow OWASP top 10.
// 1. HTTPS Configuration
server:
ssl:
key-store: classpath:keystore.p12
key-store-password: ${SSL_PASSWORD}
key-store-type: PKCS12
key-alias: tomcat
// 2. Security Configuration
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.https()
.requiresChannel()
.anyRequest()
.requiresSecure()
.and()
.csrf().disable() // Use CSRF tokens
.headers()
.contentSecurityPolicy('default-src \'self\'');
}
}
// 3. Input Validation
@RestController
public class UserController {
@PostMapping('/users')
public ResponseEntity<?> createUser(@Valid @RequestBody UserRequest req) {
// @Valid ensures validation
// Never trust user input
}
}
public class UserRequest {
@NotBlank(message = 'Email required')
@Email(message = 'Valid email required')
private String email;
@Size(min = 8, message = 'Password min 8 chars')
private String password;
}
// 4. SQL Injection Prevention
// Use JPA (parameterized queries automatically)
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
@Query('SELECT u FROM User u WHERE u.email = ?1')
Optional<User> findByEmail(String email); // Parameterized
// NEVER do this:
// repository.find('SELECT * FROM users WHERE email = ' + email);
}
// 5. Secrets Management
spring:
datasource:
password: ${DB_PASSWORD} # From environment
jwt:
secret: ${JWT_SECRET}
// Or use Vault/AWS Secrets Manager
@Component
public class SecretProvider {
@Autowired
private VaultOperations vaultOps;
public String getDatabasePassword() {
return vaultOps.read('secret/data/db', String.class);
}
}
// 6. JWT Token Implementation
@Component
public class JwtTokenProvider {
@Value('${jwt.secret}')
private String jwtSecret;
public String generateToken(Authentication authentication) {
return Jwts.builder()
.setSubject(authentication.getName())
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + 86400000))
.signWith(SignatureAlgorithm.HS512, jwtSecret)
.compact();
}
}
// 7. Dependency Updates
# Check for vulnerabilities
mvn dependency-check:check
// 8. Audit Logging
@Component
@Aspect
public class AuditLogAspect {
@Before('execution(* com.example.service.*.*(..))')
public void auditLog(JoinPoint joinPoint) {
// Log sensitive operations
logger.info('User: {}, Action: {}',
SecurityContextHolder.getContext().getAuthentication(),
joinPoint.getSignature().getName());
}
}
// 9. Rate Limiting
@Configuration
public class RateLimitConfig {
@Bean
public RateLimiter rateLimiter() {
return RateLimiter.create(100); // 100 requests/sec
}
}
// 10. Security Headers
spring:
security:
headers:
content-security-policy: 'default-src \'self\''
x-frame-options: DENY
x-content-type-options: nosniff
x-xss-protection: '1; mode=block'
// OWASP Top 10:
// 1. Injection
// 2. Broken Authentication
// 3. Sensitive Data Exposure
// 4. XML External Entities (XXE)
// 5. Broken Access Control
// 6. Security Misconfiguration
// 7. XSS
// 8. Insecure Deserialization
// 9. Using Components with Known Vulnerabilities
// 10. Insufficient Logging & Monitoring
Q9. How do you manage configuration across different environments in Spring Boot?
Use Spring Profiles for environment-specific configuration. Externalize configuration using application-{profile}.yml or environment variables. Implement ConfigServer for centralized management in microservices.
// application.yml (base)
spring:
application:
name: app
profiles:
active: ${SPRING_PROFILES_ACTIVE:dev}
// application-dev.yml
spring:
datasource:
url: jdbc:mysql://localhost:3306/appdev
password: dev123
jpa:
hibernate:
ddl-auto: create-drop
cache:
type: simple
// application-prod.yml
spring:
datasource:
url: jdbc:mysql://mysql-prod:3306/appprod
password: ${DB_PASSWORD} # From environment
jpa:
hibernate:
ddl-auto: validate
cache:
type: redis
redis:
host: ${REDIS_HOST}
port: ${REDIS_PORT}
logging:
level:
root: WARN
// Programmatic Profile Usage
@Configuration
@Profile('prod')
public class ProdConfig {
@Bean
public DataSource prodDataSource() {
// Production database config
}
}
@Configuration
@Profile('dev')
public class DevConfig {
@Bean
public DataSource devDataSource() {
// H2 in-memory for testing
}
}
// Spring Cloud Config Server (Centralized)
// config-server-pom.xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
// Config Server application.yml
spring:
cloud:
config:
server:
git:
uri: https://github.com/config-repo
searchPaths: configs/**
// Config Client
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
// bootstrap.yml (Config Client)
spring:
cloud:
config:
uri: http://config-server:8888
name: app
profile: prod
// Accessing Config
@Component
public class AppConfig {
@Value('${database.host}')
private String databaseHost;
@Value('${cache.ttl:3600}')
private int cacheTtl; // Default value
}
// Runtime Property Refresh
@RestController
@RefreshScope // Allows refresh without restart
public class ConfigController {
@Value('${feature.flag}')
private boolean featureFlag;
// POST /actuator/refresh to reload
}
// Environment Variables (Priority)
// 1. Command line arguments
// 2. System properties
// 3. OS environment variables
// 4. application-{profile}.yml
// 5. application.yml
// Running with different profiles
java -jar app.jar --spring.profiles.active=prod
java -Dspring.profiles.active=staging -jar app.jar
export SPRING_PROFILES_ACTIVE=prod && java -jar app.jar
Q10. What is a production readiness checklist for Spring Boot applications?
Production checklist includes health checks, monitoring, logging, security, scalability, disaster recovery, documentation, testing, and compliance. Ensure application can handle production loads and failures gracefully.
// PRODUCTION READINESS CHECKLIST
// 1. APPLICATION HEALTH
// ✓ Actuator endpoints enabled
// ✓ Liveness/readiness probes configured
// ✓ Health checks for dependencies
management:
endpoint:
health:
show-details: always
health:
livenessstate:
enabled: true
readinessstate:
enabled: true
// 2. MONITORING & OBSERVABILITY
// ✓ Metrics exported to Prometheus
// ✓ Logs aggregated (ELK stack)
// ✓ Distributed tracing enabled (Zipkin)
// ✓ Alerts configured
management:
endpoints:
web:
exposure:
include: metrics,health,info,zipkin
// 3. SECURITY
// ✓ HTTPS enabled
// ✓ Authentication implemented
// ✓ Authorization configured
// ✓ Secrets management
// ✓ Input validation
// ✓ Security headers set
server:
ssl:
enabled: true
key-store: ${SSL_KEYSTORE}
// 4. SCALABILITY
// ✓ Horizontal scaling ready
// ✓ Connection pooling configured
// ✓ Caching implemented
// ✓ Database query optimized
// ✓ Async processing enabled
spring:
datasource:
hikari:
maximum-pool-size: 20
// 5. PERFORMANCE
// ✓ Response time < 1s (p95)
// ✓ Memory footprint < 512MB
// ✓ CPU usage < 80%
// ✓ GC pauses < 100ms
// ✓ Database queries optimized
// 6. RESILIENCE
// ✓ Circuit breakers implemented
// ✓ Retry logic with backoff
// ✓ Timeouts configured
// ✓ Graceful degradation
// ✓ Dead letter queues for messages
@Configuration
public class ResilienceConfig {
@Bean
public CircuitBreaker circuitBreaker() {
// Circuit breaker implementation
}
}
// 7. DATA PERSISTENCE
// ✓ Database backups configured
// ✓ Transactions properly handled
// ✓ Connection pools monitored
// ✓ Migrations tested
// ✓ Data retention policies
// 8. DISASTER RECOVERY
// ✓ Backup strategy implemented
// ✓ Recovery time objective (RTO) defined
// ✓ Recovery point objective (RPO) defined
// ✓ Failover mechanism tested
// ✓ Disaster recovery drills
// 9. TESTING
// ✓ Unit tests > 80% coverage
// ✓ Integration tests written
// ✓ Load testing completed
// ✓ Security testing done
// ✓ Chaos engineering tested
// 10. DOCUMENTATION
// ✓ API documentation (Swagger)
// ✓ Deployment guide written
// ✓ Troubleshooting guide
// ✓ Runbook for operations
// ✓ Architecture diagrams
// 11. COMPLIANCE
// ✓ Data privacy (GDPR, CCPA)
// ✓ PCI DSS for payments
// ✓ Audit logging
// ✓ Legal requirements met
// ✓ Accessibility (WCAG)
// 12. OPERATIONS
// ✓ Deployment pipeline automated
// ✓ Blue-green deployments
// ✓ Canary releases capability
// ✓ Quick rollback capability
// ✓ On-call support process
// 13. INFRASTRUCTURE
// ✓ Load balancing configured
// ✓ Auto-scaling policies
// ✓ Resource quotas defined
// ✓ Network policies
// ✓ Cost monitoring
// Production Deployment Checklist Script
#!/bin/bash
echo '=== Production Readiness Checklist ==='
echo '[] Actuator health checks pass'
echo '[] Metrics export working'
echo '[] Logging level set to INFO'
echo '[] HTTPS configured'
echo '[] Authentication working'
echo '[] Database backups working'
echo '[] Load testing passed (1000 req/sec)'
echo '[] Memory < 512MB'
echo '[] Response time p95 < 1s'
echo '[] Security scan passed'
echo '[] Documentation complete'
echo '[] Team trained'
echo '==================================='
// Common Production Issues & Solutions:
// Issue: High memory usage
// Solution: Heap dump analysis, GC tuning
// Issue: Slow queries
// Solution: Query optimization, indexing
// Issue: Connection pool exhaustion
// Solution: Increase pool size, query optimization
// Issue: OutOfMemory errors
// Solution: Increase heap size, fix memory leaks
Performance Optimization, Monitoring & DevOps
Monitor and deploy Spring Boot. Learn Actuator metrics, profiling, Docker configurations, garbage collection, and query optimizations.
What is Spring Boot Actuator and what are its key endpoints?
Spring Boot Actuator provides built-in endpoints for monitoring and managing applications. Expose health, metr...
What is Micrometer and how do you expose metrics to Prometheus?
Micrometer is a metrics facade supporting multiple monitoring systems (Prometheus, Datadog, New Relic). Spring...
What are logging best practices in Spring Boot? How do you configure Logback?
Use SLF4J facade with Logback implementation. Configure different log levels, outputs, and patterns. Use conte...
What is Distributed Tracing and how do you implement it with Spring Cloud Sleuth?
Distributed tracing tracks requests across microservices using trace IDs and span IDs. Spring Cloud Sleuth int...
How do you containerize a Spring Boot application with Docker?
Create Dockerfile to package Spring Boot app as container image. Use multi-stage builds to optimize image size...
How do you deploy Spring Boot applications on Kubernetes?
Create Kubernetes manifests (Deployment, Service, ConfigMap) to run containerized Spring Boot apps. Use kubect...
What are key performance optimization techniques for Spring Boot applications?
Optimize through connection pooling, caching, async processing, lazy loading, database indexing, and HTTP cach...
What are security best practices for production Spring Boot applications?
Use HTTPS, implement authentication/authorization, validate inputs, use parameterized queries, manage secrets,...
How do you manage configuration across different environments in Spring Boot?
Use Spring Profiles for environment-specific configuration. Externalize configuration using application-{profi...
What is a production readiness checklist for Spring Boot applications?
Production checklist includes health checks, monitoring, logging, security, scalability, disaster recovery, do...