2

In the beginning of my controller I create a context with a timeout like this:

ctx, cancel := context.WithTimeout(context.Background(), time.Second * 10)
defer cancel()

And then I use this context in each database request like this:

QueryRowContext(ctx, query, ...args) // where ctx is context

However, when I load my test program, I notice that some of my requests return error "pq: canceling statement due to user request". And the more requests I make, the more errors I get.

But, if I don't use context with timeout, but rather use just context.Background(), I get no errors regardless of the amount of requests.

Each request takes about 50ms, so timeout cannot occur. I tried context with cancel context.WithCancel(context.Background()) and I also get these errors.

What may be a reason that these errors occur?

// create context to cancel working if 10 seconds passed
ctx, cancel := context.WithTimeout(context.Background(), time.Second * 10)
defer cancel()


// parses queries
var response []byte
request := model.GetProductByBarcodeRequest{}
barcode := r.URL.Query().Get("barcode")
storeID := r.URL.Query().Get("store_id")
transactionType := r.URL.Query().Get("type")


request.Barcode = &barcode
request.StoreID = &storeID
request.Type = &transactionType

// processing
result, err := model.GetProductByBarcode(ctx, request)
response = controller.ToJson(result, err)

// writing response to user
w.Write(response)
Rustam Ibragimov
  • 2,571
  • 7
  • 22
  • 33
  • Which Postgres driver you're using? – ain Mar 27 '17 at 06:01
  • @ain, "github.com/lib/pq" – Rustam Ibragimov Mar 27 '17 at 06:18
  • Please provide a [mcve], we can't guess what you're doing. – JimB Mar 27 '17 at 13:09
  • the WithTimeout starts the clock at that point. It does NOT give each query 10s. You mentioned that each query is 50ms, but do all of them combined take more than 10s from when your controller kicks in? – David Budworth Mar 27 '17 at 15:57
  • @DavidBudworth, I added almost full code of my controller. I think that when new request comes, it creates different context. – Rustam Ibragimov Mar 27 '17 at 16:02
  • This is basically your handler function? context gets created there? ultimately, it kinda depends on what `model.GetProductByBarcode(ctx, request)` does with it. by any chance is it holding on the ctx for some reason? – David Budworth Mar 27 '17 at 16:06
  • This function makes several database requests and I use context in order to pass it to each database query like ExecContex, QueryContext and so on. – Rustam Ibragimov Mar 27 '17 at 16:08

0 Answers0