@@ -21,6 +21,9 @@ import {
2121 listen as webSocketListen ,
2222} from './websockets/server'
2323
24+ // Grace period for graceful shutdown
25+ const SHUTDOWN_GRACE_PERIOD_MS = 30 * 60 * 1000
26+
2427const app = express ( )
2528const port = env . PORT
2629
@@ -91,12 +94,11 @@ server.listen(port, () => {
9194 logger . debug ( `🚀 Server is running on port ${ port } ` )
9295 console . log ( `🚀 Server is running on port ${ port } ` )
9396} )
94-
9597webSocketListen ( server , '/ws' )
9698
9799let shutdownInProgress = false
98100// Graceful shutdown handler for both SIGTERM and SIGINT
99- function handleShutdown ( signal : string ) {
101+ async function handleShutdown ( signal : string ) {
100102 flushAnalytics ( )
101103 if ( env . NEXT_PUBLIC_CB_ENVIRONMENT === 'dev' ) {
102104 server . close ( ( error ) => {
@@ -109,7 +111,9 @@ function handleShutdown(signal: string) {
109111 return
110112 }
111113 shutdownInProgress = true
112- console . log ( `\nReceived ${ signal } . Starting graceful shutdown...` )
114+ console . log (
115+ `\nReceived ${ signal } . Starting ${ SHUTDOWN_GRACE_PERIOD_MS / 60000 } minute graceful shutdown period...` ,
116+ )
113117
114118 // Don't shutdown, instead ask clients to disconnect from us
115119 sendRequestReconnect ( )
@@ -119,14 +123,12 @@ function handleShutdown(signal: string) {
119123 process . exit ( 0 )
120124 } )
121125
122- // If graceful shutdown is not achieved after 5 minutes,
123- // force exit the process
124- setTimeout ( ( ) => {
125- console . error (
126- 'Could not close connections in time, forcefully shutting down' ,
127- )
128- process . exit ( 1 )
129- } , 300000 ) . unref ( )
126+ // Wait for the grace period to allow clients to switch to new instances
127+ await new Promise ( ( resolve ) => setTimeout ( resolve , SHUTDOWN_GRACE_PERIOD_MS ) )
128+
129+ console . log ( 'Grace period over. Proceeding with final shutdown...' )
130+
131+ process . exit ( 1 )
130132}
131133
132134process . on ( 'SIGTERM' , ( ) => handleShutdown ( 'SIGTERM' ) )
0 commit comments