Goroutine without a Defer Block
So recently this small mistake did cost us very badly.
A lot of developers who just started with GO have an assumption that when a child function panics and the parent had a defer block with recover, the panic can be handled by the parent.
But just hold on a minute before proceeding further with that wrong thought
This code is pretty straight forward. Whenever the anonymous function panic, the getRequestHandler function as a parent will recover from the panic created by its child and returns a 500 error response which is ideal.
But let's just consider this case where the anonymous function is a goroutine.
We will be in an assumption that the getRequestHandler function as a parent will handle the panic created by the child goroutine.
But that ain’t the case here.
The panic created by the goroutine will not be handled by the parent function which results in an unhandled panic and crashes the server.
If you’ve understood this behaviour, by this time you should’ve felt something fishy.
The Clean-Up won't happen anymore. So any open connection made at the start of the parent function will be roaming idly like a lost astronaut in the space.
This doesn’t seem to be a big problem right?
Consider your server is handling 1000 requests/sec and all thousand requests are accepted by the server for processing and just because of one goroutine panic, the entire server crashes and all those 1000 connections opened are left idle without closing.
This impacts the application on a huge note on the number of connections that can be further made.
So its always a mandatory thing to have a defer block with recover for each goroutine that can handle its panic.
The only way I think as of now to make the clean up can happen is
When your server starts, create a channel of type Signal and add a notifier of type SIGKILL and SIGTERM and spin up a goroutine that blocks forever until something is written to the channel created.
This might be the only place where I feel we can make a cleanup in case the server crashes abruptly.