Request context cancels query context

Hi,

I am currently using Request context as the “parent” context for my database query context. However, this causes context canceled error in logs. If I just use a Background context as the “parent” context then all works fine. Is this expected behaviour or am I missing something?

Thanks

CURRENT (broken)

// ctx is `*http.Request.Context` which come from the handler.
func Insert(ctx context.Context) error {
	ctx, cancel := context.WithTimeout(ctx, 3 * time.Millisecond)
	defer cancel()

	qry := `INSERT INTO users (name) VALUES (?)`

	res, err := r.database.ExecContext(ctx, qry, "hello")
	// ....
}

FINE

func Insert() error {
	ctx, cancel := context.WithTimeout(context.Background(), 3 * time.Millisecond)
	defer cancel()

	qry := `INSERT INTO users (name) VALUES (?)`

	res, err := r.database.ExecContext(ctx, qry, "hello")
	// ....
}

it is expected behaviour. When the parent context will be canceled, all the child context must be canceled as well. You should debug parent context to find out why it is being canceled, potential cancelation might be timeout or network disconnection.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.