gogo-http

Should I reuse context object in http server when calling other service?


I am developing a server application with the net/http package. Everytime a request arrives, the net/http package reads the request and create a http.Request object. My server needs to call AWS DynamoDB to serve every request, when calling DynamoDB's QueryWithContext function, I pass the context object in http.Request object, something like this:

ctx := request.Context()
ctx := context.WithValue(ctx, myKey, myVal)

input := &dynamodb.QueryInput{
   ....
}

result, err := dbclient.QueryWithContext(ctx, input)

Recently I saw several context canceled errors returned from QueryWithContext, I am thinking it might because the context object is reused and somehow the request is canceled so service call to DynamoDB also got canceled?

Should I reuse the context object when calling another service (like DynamoDB) or should I always create a new one? Thanks.


Solution

  • Should I reuse the context object when calling another service (like DynamoDB) or should I always create a new one? Thanks.

    That depends.

    Do you want the DynamoDB requests to be tied to the request, or not?

    In other words, if the HTTP request is cancelled, should the DynamoDB requst continue, or abort?