Druid Crashed in Production? Essential Optimizations for Spring Boot
The article explains why Druid connection pools can fail in production and provides a step‑by‑step guide to extreme optimization, covering environment setup, core pool parameter tuning, monitoring with StatFilter and web UI, security hardening, leak detection, dynamic adjustments, and common pitfalls.
1. Basic Environment Preparation
Use the latest stable Druid version (recommended 1.2.38+) and exclude older dependencies in pom.xml:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.38</version>
</dependency>2. Core Connection‑Pool Parameter Tuning
Adjust parameters according to business QPS, database type, and hardware resources.
2.1 Connection‑Pool Capacity Control
initialSize : set to CPU cores / 2 (e.g., 2 for a 4‑core machine) to avoid heavy startup cost.
minIdle : set to CPU cores * 1.5 (e.g., 6 for 4 cores) but not exceeding the DB max_connections (MySQL default 151).
maxActive : calculate as single‑connection QPS * 1.2 (e.g., 120 for 100 QPS). Beware of setting it too high (e.g., >200) which may cause Too many connections errors.
2.2 Connection Lifecycle Management
maxWait : set to 3000ms to prevent long thread blocking.
timeBetweenEvictionRunsMillis : reduce to 10000ms to reclaim idle connections faster.
minEvictableIdleTimeMillis : shrink to 60000ms for short‑lived HTTP requests.
validationQuery : configure a lightweight SQL such as SELECT 1 (MySQL) or SELECT 1 FROM DUAL (Oracle) and enable testWhileIdle=true to avoid full table scans.
testWhileIdle / testOnBorrow / testOnReturn : testWhileIdle=true (recommended) – validates idle connections. testOnBorrow=false – skips validation on checkout. testOnReturn=false – skips validation on return.
3. Monitoring System Construction (Key Optimization Points)
Druid provides built‑in monitoring; expose metrics and integrate with alerting.
3.1 Enable StatFilter (SQL Statistics)
spring:
datasource:
druid:
stat-filter:
enabled: true
slow-sql-millis: 2000
merge-sql: true
log-slow-sql: trueStatFilter records execution count, latency, affected rows, and flags slow SQL (e.g., >2 s).
3.2 Configure Web Monitoring Page
spring:
datasource:
druid:
web-stat-filter:
enabled: true
url-pattern: /*
exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"
stat-view-servlet:
enabled: true
url-pattern: /druid/*
allow: 127.0.0.1
login-username: admin
login-password: 123456
reset-enable: falseThe page shows active/idle connections, waiting queue length, SQL statistics, and URI call stats. In production, restrict access to internal IPs and enable authentication.
3.3 Log Integration (ELK or Prometheus + Grafana)
ELK solution: configure logback-spring.xml to route Druid logs to Logstash and visualize with Kibana.
<logger name="com.alibaba.druid.pool.DruidDataSource" level="DEBUG">
<appender-ref ref="LOGSTASH"/>
</logger>Prometheus + Grafana solution: add micrometer-registry-prometheus and druid-prometheus-exporter dependencies and expose metrics for Grafana dashboards.
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.38</version>
</dependency>4. Security Enhancements
4.1 Prevent SQL Injection (WallFilter)
spring:
datasource:
druid:
filters: wall,stat,slf4j
wall:
enabled: true
delete-allow: false
update-allow: false
procedure-allow: false
config:
select-allow: trueWallFilter blocks dangerous statements such as DELETE/UPDATE without WHERE and stored procedures.
4.2 Password Encryption
Generate an encryption key via a custom DruidPasswordCallback implementation and configure encrypted passwords in application.yml:
public class MyPasswordCallback extends DecryptPasswordCallback {
public MyPasswordCallback() {
super("your-encryption-key"); // replace with actual key
}
} spring:
datasource:
druid:
url: jdbc:mysql://...
username: root
password: encryptedPassword
filters: stat,wall
connection-properties: config.decrypt=true;config.decrypt.key=myKey4.3 Defend Against CC Attacks (Connection Rate Limiting)
spring:
datasource:
druid:
stat-filter:
enabled: true
max-sql-execution-count-per-ip-per-minute: 1000
max-sql-execution-count-per-uri-per-minute: 500This limits the number of SQL executions per IP or URI per minute.
5. Connection Leak Detection (Production‑Essential)
Enable leak detection to avoid pool exhaustion when connections are not closed:
spring:
datasource:
druid:
remove-abandoned: true
remove-abandoned-timeout: 300
log-abandoned: trueWhen a connection is held longer than remove-abandoned-timeout seconds, Druid forcibly reclaims it and logs the stack trace for debugging. Use only for long‑running transactions; short‑lived connections typically do not need this.
6. Advanced Optimization Techniques
6.1 Dynamic Runtime Adjustment
Expose the DruidDataSource via JMX or programmatically adjust parameters during traffic spikes:
@Autowired
private DataSource dataSource;
public void adjustPoolSize() {
if (dataSource instanceof DruidDataSource) {
DruidDataSource druid = (DruidDataSource) dataSource;
druid.setMaxActive(200);
druid.setMinIdle(50);
}
}After adjustment, monitor DB load to avoid sudden pressure.
6.2 Connection Pre‑Warm (Cold‑Start Optimization)
spring:
datasource:
druid:
initial-size: 10
test-on-borrow: falsePre‑create a batch of connections at startup to reduce first‑request latency.
6.3 Transaction Isolation Level Optimization
spring:
datasource:
druid:
default-transaction-isolation: 2 # TRANSACTION_READ_COMMITTEDSet the isolation level according to business consistency requirements.
7. Pitfall Avoidance Guide
Avoid over‑configuring maxActive; leave ~20 % headroom below the DB max_connections limit.
Base all parameter changes on real monitoring data (pool utilization, wait queue length).
Disable debug‑heavy features (e.g., log-abandoned=true) in production after testing.
Ensure Druid version compatibility with Spring Boot and the JDBC driver (e.g., MySQL 8.0 requires com.mysql.cj.jdbc.Driver).
8. Summary
Extreme Druid optimization requires aligning business scenarios (high concurrency, low latency) with database characteristics (connection limits, QPS ceiling) and continuously tuning based on monitoring data. The core steps are:
Basic parameter tuning (capacity, lifecycle).
Monitoring system setup (SQL stats, connection status).
Security hardening (SQL injection protection, leak detection).
Iterative refinement driven by metrics.
The ultimate goal is to balance connection utilization, performance stability, and security.
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.
Java Architect Handbook
Focused on Java interview questions and practical article sharing, covering algorithms, databases, Spring Boot, microservices, high concurrency, JVM, Docker containers, and ELK-related knowledge. Looking forward to progressing together with you.
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.
