简体   繁体   中英

Context timeout not working as expected in golang

Helo All,

New to golang and was debugging timeout issues in a production environment. Before making a call to the server we add a timeout of 50ms to context and fire a server call. If the response is not received within 50 ms we expect the application to move on and not wait for the response.

But while debugging, I capture the duration between we fire a server call and the response received (or error out), to my surprise the value at the time is much higher than 50 ms.

Client syntax -

    ctx, cancel := context.WithTimeout(ctx, e.opts.Timeout)
    defer cancel()
    fireServerCall(ctx)
..
..

def fireServerCall(ctx context:Context){
  startTime:=time.Now()
  //call to the server
  res, err:=callToServer(ctx)
  if err!=nil{
   //capture failure latency
   return ....
  }
   //capture success latency
   return ....
}

Has anyone ever faced any similar issue? Is this expected behaviour? How did you handle such cases?

Am I doing something incorrectly? Suggestions are welcome:)

Edit:

I am passing context in my original code but forgot to mention it here, just added it. That mean, I am passing the same context on which my client is waiting for server to respond within 50 ms.

  1. You should pass created context to fireServerCall and callToServer functions
  2. callToServer should consider passed context and monitor ctx.Done() channel to stop its execution accordingly

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM