ProgramGuru

Context and Request Lifecycle Management

Start with Context and Request Lifecycle Management

Learn context and request lifecycle management through an executable example, then connect the small demonstration to production code.

What you’ll learn

  • Explain the main purpose of context and request lifecycle management.
  • Read and run the complete Go example in this lesson.
  • Apply the concept and recognize common mistakes.

Understand the idea

Every HTTP request has a Context. Pass r.Context() to downstream operations so cancellations and deadlines can interrupt slow work when appropriate. Do not store contexts on long-lived structs as ordinary configuration.

The example cancels a request-derived context and checks its error deterministically.

Visualize how it works

Follow this diagram before executing the example. Check where a value or decision changes what runs next.

Visual explanation for request contextCancel dependent work when the request is no longer needed.HTTP requestStep 1Derive contextStep 2Call dependenciesStep 3Cancel on endStep 4Cancel dependent work when the request is no longer needed.
Cancel dependent work when the request is no longer needed.

Tools, syntax and practical notes

For example, db.QueryContext(r.Context(), query) ties database work to the request lifetime. A driver must support cancellation for the desired behavior.

Run a complete Go example

This example is a complete program. Save it as main.go or paste it into the Go Playground.

Go code

package main

import (
	"context"
	"fmt"
	"net/http/httptest"
)

func main() {
	request := httptest.NewRequest("GET", "/tasks", nil)
	ctx, cancel := context.WithCancel(request.Context())
	request = request.WithContext(ctx)
	cancel()
	fmt.Println("Cancelled:", request.Context().Err() == context.Canceled)
}

Output

Cancelled: true

Trace what the program does

The request inherits a new cancelable context. Calling cancel marks that context canceled; the next check compares its error to context.Canceled.

Avoid common mistakes

  • Always invoke returned cancellation functions, normally with defer, when their scope ends.
  • Context cancellation does not undo a database transaction already committed.

Try it yourself

Use context.WithTimeout in a helper function and defer cancel; explain how a DB query would receive the context.

Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.

Check your understanding

What context should a handler normally pass to QueryContext?
Choose one answer. You can try again.

Answer and explanation

The request context

Correct. The request inherits a new cancelable context.

What you should remember

You have practiced Context and Request Lifecycle Management in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.

Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Graceful Shutdown →