In Golang, I am fairly new to the intentions of passing contexts
downstream to other methods and functions. I understand how a context
works, how it is used, how it holds its values, how it's related to the parent context
and their behaviors -- I just don't understand why to use a context in the first place.
In a more specific example, which is the actual reason of this question, in the company I work for, we have identified some very long-running queries that happen every so often due to an edge case.
An obvious solution we decided to take, given our constraints until we invest time to fix the root cause, is to kill the queries that take more than 5 minutes.
The method that runs our transactions accepts a context
which is originally initiated in the API call. This context
is passed down all the way to the transaction function. At that moment I found 2 solutions to kill that query:
1) Using a new context:
Initiate a new
context.WithTimeout(ctx, time.Duration( 5 * time.Minute) )
Watch the
Done
channel in ago routine
and kill the transaction when there's a signal there- If the transaction finished successfully in a timely manner, just
cancel
the context and commit the transaction as expected.
2) Using a Timer
:
- Create a
Timer
with 5 minutes duration - If the time is over, kill the transaction
- Else, commit the transaction.
Logically speaking, they are the same solution, however, when and how to decide whether to use a context
with a set Deadline or a good old Timer
?