Senior LevelSystem Design & Architecture
How do you diagnose and resolve silent Database Connection Pool Leaks under high traffic?
β Interview Prompt: Explain Database Connection Leaks, checkout stack trace tracking, `leakDetectionThreshold` in HikariCP, and connection auto-close patterns.
A Database Connection Leak occurs when an application checks out a database connection socket from a pool but fails to close or return it to the pool after processing:
Diagnosis & Resolution:
1
Leak Detection Threshold: Configure connection poolers (HikariCP 'leakDetectionThreshold = 2000ms') to log stack traces of threads holding connections longer than 2 seconds.
2
Auto-Close Patterns: Always wrap connection checkout statements inside 'try-with-resources' or 'using' blocks to guarantee automatic closure even if exceptions occur.
Code Implementation Example
typescript
import { dbPool } from './db';
// Safe Auto-Close Connection Pattern preventing connection leaks
export async function executeSafeQuery(sql: string) {
const client = await dbPool.connect();
try {
return await client.query(sql);
} finally {
// Guarantee connection release back to pool even on error!
client.release();
}
}π‘Releasing database connections safely in a try-finally block.
π― Interview Key Takeaway
Wrap all database connection checkouts in try-finally or try-with-resources blocks to prevent silent connection pool leaks.
#System Design#Connection Leak#HikariCP#Databases#Senior
Back to all System Design & Architecture Questionsβ