Health Checks & Graceful Shutdown
Health Check Endpoint (Express)
app.get('/health/live', (req, res) => {
res.json({ status: 'ok' }); // App process is running
});
app.get('/health/ready', async (req, res) => {
const checks = await Promise.allSettled([
checkDatabase(),
checkRedis(),
checkExternalApi(),
]);
const results = checks.map((c, i) => ({
name: ['database', 'redis', 'external-api'][i],
status: c.status === 'fulfilled' ? 'up' : 'down',
...(c.status === 'rejected' && { error: c.reason.message }),
}));
const allHealthy = results.every((r) => r.status === 'up');
res.status(allHealthy ? 200 : 503).json({ status: allHealthy ? 'ready' : 'degraded', checks: results });
});
async function checkDatabase() {
await db.$queryRaw`SELECT 1`;
}
async function checkRedis() {
await redis.ping();
}
Graceful Shutdown (Node.js)
const server = app.listen(3000);
async function shutdown(signal: string) {
console.log(`${signal} received, starting graceful shutdown`);
// 1. Stop accepting new connections
server.close();
// 2. Wait for in-flight requests (with timeout)
const timeout = setTimeout(() => process.exit(1), 30000);
try {
// 3. Close dependencies
await db.$disconnect();
await redis.quit();
await queue.close();
clearTimeout(timeout);
process.exit(0);
} catch {
process.exit(1);
}
}
process.on('SIGTERM', () => shutdown('SIGTERM'));
process.on('SIGINT', () => shutdown('SIGINT'));
Kubernetes Probes
containers:
- name: app
livenessProbe:
httpGet: { path: /health/live, port: 3000 }
initialDelaySeconds: 10
periodSeconds: 15
failureThreshold: 3
readinessProbe:
httpGet: { path: /health/ready, port: 3000 }
initialDelaySeconds: 5
periodSeconds: 10
failureThreshold: 2
startupProbe:
httpGet: { path: /health/live, port: 3000 }
failureThreshold: 30
periodSeconds: 2
lifecycle:
preStop:
exec:
command: ["sh", "-c", "sleep 5"] # Allow LB to drain
Spring Boot Actuator
management:
endpoints:
web:
exposure:
include: health,info
endpoint:
health:
show-details: when_authorized
group:
readiness:
include: db,redis,diskSpace
liveness:
include: ping
health:
redis:
enabled: true
Probe Types
| Probe |
Purpose |
Failure Action |
| Liveness |
Is the process alive? |
Restart container |
| Readiness |
Can it serve traffic? |
Remove from load balancer |
| Startup |
Has it finished initializing? |
Don't check liveness yet |
Anti-Patterns
| Anti-Pattern |
Fix |
| Liveness check hits database |
Liveness = process alive only; readiness = dependencies |
| No graceful shutdown |
Handle SIGTERM, drain connections |
| Immediate process.exit() |
Wait for in-flight requests to complete |
| No startup probe |
Slow-starting apps killed by liveness before ready |
| Health check returns 200 when degraded |
Return 503 when dependencies are down |
Production Checklist
1---2name: health-checks3description: |4 Health check and graceful shutdown patterns. Liveness and readiness probes,5 dependency health checks, Kubernetes probes, Spring Actuator health,6 and zero-downtime shutdown.78 USE WHEN: user mentions "health check", "liveness", "readiness", "probe",9 "graceful shutdown", "SIGTERM", "health endpoint", "/healthz"1011 DO NOT USE FOR: monitoring dashboards - use `error-tracking` or `opentelemetry`;12 deployment strategies - use `deployment-strategies`13allowed-tools: Read, Grep, Glob, Write, Edit14metadata:15 source: https://skillmd.com/skills/claude-dev-suite/health-checks16---1718# Health Checks & Graceful Shutdown1920## Health Check Endpoint (Express)2122```typescript23app.get('/health/live', (req, res) => {24 res.json({ status: 'ok' }); // App process is running25});2627app.get('/health/ready', async (req, res) => {28 const checks = await Promise.allSettled([29 checkDatabase(),30 checkRedis(),31 checkExternalApi(),32 ]);3334 const results = checks.map((c, i) => ({35 name: ['database', 'redis', 'external-api'][i],36 status: c.status === 'fulfilled' ? 'up' : 'down',37 ...(c.status === 'rejected' && { error: c.reason.message }),38 }));3940 const allHealthy = results.every((r) => r.status === 'up');41 res.status(allHealthy ? 200 : 503).json({ status: allHealthy ? 'ready' : 'degraded', checks: results });42});4344async function checkDatabase() {45 await db.$queryRaw`SELECT 1`;46}47async function checkRedis() {48 await redis.ping();49}50```5152## Graceful Shutdown (Node.js)5354```typescript55const server = app.listen(3000);5657async function shutdown(signal: string) {58 console.log(`${signal} received, starting graceful shutdown`);5960 // 1. Stop accepting new connections61 server.close();6263 // 2. Wait for in-flight requests (with timeout)64 const timeout = setTimeout(() => process.exit(1), 30000);6566 try {67 // 3. Close dependencies68 await db.$disconnect();69 await redis.quit();70 await queue.close();71 clearTimeout(timeout);72 process.exit(0);73 } catch {74 process.exit(1);75 }76}7778process.on('SIGTERM', () => shutdown('SIGTERM'));79process.on('SIGINT', () => shutdown('SIGINT'));80```8182## Kubernetes Probes8384```yaml85containers:86 - name: app87 livenessProbe:88 httpGet: { path: /health/live, port: 3000 }89 initialDelaySeconds: 1090 periodSeconds: 1591 failureThreshold: 392 readinessProbe:93 httpGet: { path: /health/ready, port: 3000 }94 initialDelaySeconds: 595 periodSeconds: 1096 failureThreshold: 297 startupProbe:98 httpGet: { path: /health/live, port: 3000 }99 failureThreshold: 30100 periodSeconds: 2101 lifecycle:102 preStop:103 exec:104 command: ["sh", "-c", "sleep 5"] # Allow LB to drain105```106107## Spring Boot Actuator108109```yaml110management:111 endpoints:112 web:113 exposure:114 include: health,info115 endpoint:116 health:117 show-details: when_authorized118 group:119 readiness:120 include: db,redis,diskSpace121 liveness:122 include: ping123 health:124 redis:125 enabled: true126```127128## Probe Types129130| Probe | Purpose | Failure Action |131|-------|---------|---------------|132| **Liveness** | Is the process alive? | Restart container |133| **Readiness** | Can it serve traffic? | Remove from load balancer |134| **Startup** | Has it finished initializing? | Don't check liveness yet |135136## Anti-Patterns137138| Anti-Pattern | Fix |139|--------------|-----|140| Liveness check hits database | Liveness = process alive only; readiness = dependencies |141| No graceful shutdown | Handle SIGTERM, drain connections |142| Immediate process.exit() | Wait for in-flight requests to complete |143| No startup probe | Slow-starting apps killed by liveness before ready |144| Health check returns 200 when degraded | Return 503 when dependencies are down |145146## Production Checklist147148- [ ] Separate liveness and readiness endpoints149- [ ] Readiness checks all critical dependencies150- [ ] Graceful shutdown handles SIGTERM151- [ ] In-flight requests drained before exit152- [ ] Kubernetes probes configured with proper thresholds153- [ ] Startup probe for slow-initializing apps