hemerajs / fastify-graceful-shutdown

Gracefully shutdown fastify
MIT License
70 stars 13 forks source link

Doesn't seem to wait for timeout or in flight requests to terminate #42

Closed paymog closed 6 months ago

paymog commented 10 months ago

I've tried adding this to my fastify v3 server like in the readme. However, I'm finding that this doesn't wait for any in-flight requests to terminate before shutting down the app and also does not wait for the timeout if the in flight requests do not finish in time. It seems that my fastify server just shuts down immediately even with this registered.

StarpTech commented 6 months ago

Hi @paymog, we use fastify.close method to shutdown. Can you reproduce it with fastify alone?

paymog commented 6 months ago

Yup, figured it out with fastify.close

type GracefulShutdownOptions = {
  timeout_msec: number;
};

const gracefulShutdownPlugin = async (
  fastify: FastifyInstance,
  opts: GracefulShutdownOptions
) => {
  let isShuttingDown = false;

  const gracefulShutdown = async (signal: NodeJS.Signals) => {
    if (isShuttingDown) return;
    isShuttingDown = true;

    fastify.log.info(`${signal} received. Gracefully shutting down.`);

    const timeout = setTimeout(() => {
      fastify.log.warn(
        `Forcefully shutting down after ${opts.timeout_msec} milliseconds.`
      );
      process.exit(1);
    }, opts.timeout_msec);

    timeout.unref();

    try {
      await fastify.close();
      fastify.log.info("Closed out remaining connections.");
      clearTimeout(timeout);
      process.exit(0);
    } catch (err) {
      fastify.log.error("Error during graceful shutdown", err);
      process.exit(1);
    }
  };

  // the shutdown is async but we can't pass async functions to process.on
  // so we wrap them
  process.on("SIGTERM", (signal) => {
    gracefulShutdown(signal).catch((err) => {
      fastify.log.error("Error during graceful shutdown", err);
      process.exit(1);
    });
  });
  process.on("SIGINT", (signal) => {
    gracefulShutdown(signal).catch((err) => {
      fastify.log.error("Error during graceful shutdown", err);
      process.exit(1);
    });
  });
};
StarpTech commented 6 months ago

@paymog do you mean you can reproduce it with fastify.close alone?

paymog commented 6 months ago

ah sorry! No I mean that I implemented this on my own using the above code and didn't use this plugin

StarpTech commented 6 months ago

Did you find out the issues? Why did you not create a PR?

paymog commented 6 months ago

I didn’t find the root cause which is why I didn’t make a PR. The above is totally custom.