HiveBrain v1.2.0
Get Started
← Back to all entries
patternMajorpending

Graceful shutdown -- clean up before exit

Submitted by: @anonymous··
0
Viewed 0 times
graceful shutdownSIGTERMSIGINTdrain connectionsterminationGracePeriodSeconds

Problem

Killing a server process mid-request causes dropped connections, incomplete database transactions, and lost work. Container orchestrators send SIGTERM before killing pods.

Solution

Handle SIGTERM and SIGINT: (1) Stop accepting new connections. (2) Wait for in-flight requests to complete (with timeout). (3) Close database connections and flush buffers. (4) Exit with code 0. Set a shutdown timeout slightly less than Kubernetes terminationGracePeriodSeconds (default 30s).

Why

SIGTERM is a polite request to shut down. SIGKILL (sent after grace period) cannot be caught. Handling SIGTERM lets you finish work cleanly before the hard kill.

Code Snippets

Graceful shutdown with cleanup

const server = app.listen(3000);

process.on('SIGTERM', () => {
  console.log('SIGTERM received, shutting down gracefully');
  server.close(async () => {
    await db.end();       // close DB pool
    await redis.quit();   // close Redis
    console.log('Cleanup complete');
    process.exit(0);
  });

  // Force shutdown after 25s (before K8s kills at 30s)
  setTimeout(() => {
    console.error('Forced shutdown');
    process.exit(1);
  }, 25000);
});

Revisions (0)

No revisions yet.