javascriptsveltemysql-connectorsveltekit

How to shutdown gracefully in sveltekit?


I am using adapter-node and a mysql pool in a sveltekit web app.

Previously, using just nodejs and express and no sveltekit, I found I needed to shutdown the mysql pool connections cleanly or mysql could hang when restarting the app.

I had something like:

  process.on('SIGINT', () => server.close(() => pool.end()));

How would I achieve the same result in a sveltekit app? Or is it not necessary (and why)?

I can see in the sveltekit implementation where it creates the server, but does not seem to have any way to access it so I can call close(). I don't think it would be safe to call pool.end() before the server closes.

I also couldn't find any discussion of graceful shutdown in the sveltekit docs. There was 1 github issue but it was closed over a year ago and that change has since been removed from the code.

I found a similar issue asked in the svelte github. It has no resolution, so there is likely no official solution yet. https://github.com/sveltejs/kit/issues/6841


Solution

  • From version 5.1.0 onwards, adapter-node gracefully shuts down the http server and also emits a shutdown event which can be listened to.

    Example usage:

    // hooks.server.ts
    import type { ServerInit } from "@sveltejs/kit";
    
    export const init: ServerInit = async () => {
      console.info("Server created, registering shutdown hooks")
    
      process.on('sveltekit:shutdown', async (reason) => {
        console.info("SvelteKit has shutdown because of", reason)
    
        // Your custom logic for closing app specific resources
        closeDB()
        console.info("DB closed")
      });
    };