Member-only story
Understanding Context in Golang
Demystifying the ctx variable

If you are new to Golang, chances are, you have seen the context
module almost everywhere but at times find it confounding, if not abstract.
The fact is, the context
module is ubiquitous for a reason. It plays a vital role in maintaining your application performance.
In this blog post, I will save you the trouble of going through the source code, and tell you everything you need to know about the context
module!
Let’s get started!
Why Do We Need the Context Module?

Imagine being the person taking orders in a restaurant.
When an order arrives, you delegate it to one of your many chefs.
What would you do if the customer suddenly decides to walk away?
Without a doubt, you will stop your chef from further processing the order to prevent any waste of ingredients!
That’s what the context
module does!
It’s an argument passed to your functions and Goroutines and allows you to stop them promptly should you not require them anymore.
What Is the Context Module?
Typical usage of the context
module is when a client terminates the connection with a server.
What if the termination occurs while the server is in the middle of some heavy lifting work or database query?
The context
module allows these processes to be stopped instantly as soon as they are not further in need.
The usage of the context
module boils down to three primary parts
- Listening to a cancellation event
- Emitting a cancellation event
- Passing request scope data
Let’s discuss them separately.