Closing other services while shutting down HTTP server

Hi,

Just wondering if I am over-engineering the application shutdown by manually closing other service connections.

This is what I am currently doing. Is there a benefit of calling DB.Close or REDIS.Close at all? I mean the HTTP server is shutdown so I believe all the other services will be killed automatically. Am I right?

func shutdown( // ...) {
	// ...

	// chan := make(chan os.Signal, 1)
	// signal.Notify(signChan, os.Interrupt, syscall.SIGTERM)

	if err := HTTPServer.Shutdown(ctx); err != nil {
		// ...
	}

	if err := DB.Close(); err != nil {
		// ...
	}

	if err := REDIS.Close(); err != nil {
		// ...
	}
}

Closing connections to external resources manually will usually enforce clean disconnection and also wait for other go-routines still writing to the socket, while a hard exit will indeed close the connection, but the external service might take a while to realise it due to timeouts or currently running transactions might be canceled/rollbacked.

1 Like

@NobbZ Thanks for the prompt answer and explanation. One last thing to clarify, since the HTTP shutdown is listening on certain OS signals in order to gracefully shutdown the server, I believe manually closing external resources to enforce clean disconnection, as you said, is an ideal way of doing things. Am I correct to assume this?

The rule is to clean up after oneself. This means, properly closing connections, files, deleting lock files, etc.

1 Like

Besides the fact that is a good practice to clean up after you, in your particular case, using Redis seems that is mandatory to do this beacause you can’t be sure if the database have a timeout or not.

By default recent versions of Redis don’t close the connection with the client if the client is idle for many seconds: the connection will remain open forever.

However if you don’t like this behavior, you can configure a timeout, so that if the client is idle for more than the specified number of seconds, the client connection will be closed.

1 Like

Thank you @geosoft1. Good to know the details. I’ll stick with explicitly closing connections to other services too.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.