Imagine this.

A user opens your application and requests a report. The backend starts processing the request:

  1. Fetches data from the database.
  2. Calls an external API.
  3. Processes the response.
  4. Generates the report.
  5. Returns the result to the frontend.

But halfway through, the user closes the browser tab.

The request is gone. The user doesn't need the response anymore.

Yet your backend might still be executing database queries, waiting for external APIs and consuming CPU and memory.

Why?

Because a client disconnecting does not automatically stop every operation your backend has started.

This is a particularly interesting problem in backend development. It involves HTTP request lifecycles, timeouts, goroutines, database queries, external API calls and context cancellation.

In Go, we have a powerful mechanism to handle this: context.Context.

But using context isn't just about passing it as a function parameter. We need to understand how cancellation propagates, where it stops and what happens when some part of our application ignores it.

In this article, we'll explore the problem through practical examples, reproduce it, fix it and understand when we should cancel work and when we should deliberately allow it to continue.

1. First, understand what happens when a client disconnects

Let's take a simple example.

Your frontend sends:

GET /api/reports/monthly 

The backend starts processing the request.

After two seconds, the user closes the browser tab.

What should happen next?

Ideally, if the result is no longer needed, the backend should stop unnecessary work.

But here's the important distinction:

HTTP request cancellation and application-level cancellation are not the same thing.

When a client disconnects, the server can detect that the incoming request has been canceled. However, the application must cooperate with that cancellation.

Go provides a request context through:

r.Context() 

For incoming HTTP requests, Go cancels this context when the client connection closes, an HTTP/2 request is canceled or the handler returns.

The context communicates that the request's lifetime has ended.

However, it doesn't forcibly terminate every operation started by your application.

For example:

  • A database operation using QueryContext() can respond to cancellation if the driver supports it.
  • An outbound HTTP request using NewRequestWithContext() can be canceled.
  • A goroutine that never checks its context can continue running.
  • A third-party library that doesn't support cancellation may continue doing work.

That's where developers often get caught.

2. Let's reproduce the problem

We'll start with a simple Go HTTP handler that simulates an expensive operation.

package main import ( "log" "net/http" "time" ) func reportHandler(w http.ResponseWriter, r *http.Request) { log.Println("Report generation started") // Simulate expensive processing. time.Sleep(10 * time.Second) log.Println("Report generation completed") w.Write([]byte("Report generated successfully")) } func main() { http.HandleFunc("/api/reports/monthly", reportHandler) log.Println("Server running on :8080") log.Fatal(http.ListenAndServe(":8080", nil)) } 

Start the application:

go run main.go 

Now make a request:

curl http://localhost:8080/api/reports/monthly 

The server takes 10 seconds to respond.

Now try canceling the request before it completes:

curl --max-time 2 http://localhost:8080/api/reports/monthly 

The client stops waiting after two seconds.

But look at the server logs.

You may still see:

Report generation started Report generation completed 

The server continued sleeping for the remaining eight seconds.

Why?

Because time.Sleep() has no knowledge of the HTTP request context.

The client canceled its request, but our handler never checked whether that request was still active.

This is a simplified demonstration, but the same problem can happen with expensive computations, external calls and other long-running operations.

Let's fix it.

3. The solution: Use context cancellation

Go's context package provides a standard way to propagate cancellation and deadlines across function calls.

Instead of sleeping without considering the request lifecycle, we can wait for either:

  • The operation to finish.
  • The request context to be canceled.

Here's the improved handler:

func reportHandler(w http.ResponseWriter, r *http.Request) { ctx := r.Context() log.Println("Report generation started") select { case <-time.After(10 * time.Second): log.Println("Report generation completed") w.Write([]byte("Report generated successfully")) case <-ctx.Done(): log.Printf( "Report generation canceled: %v", ctx.Err(), ) return } } 

Let's understand this:

case <-time.After(10 * time.Second): 

This branch executes when the simulated operation finishes.

case <-ctx.Done(): 

This branch executes when the request context is canceled or its deadline expires.

The Done() method returns a channel that is closed when the context is canceled.

The select statement allows our handler to respond to either event.

Now, when you cancel the request using curl, the handler can stop waiting for the simulated operation.

Notice something important:

Context cancellation is cooperative.

Go doesn't kill a goroutine just because its context is canceled.

The goroutine must either:

  • Listen to ctx.Done().
  • Call a context-aware operation.
  • Periodically check ctx.Err() during CPU-intensive work.

This is a fundamental concept to understand.

4. The most common mistake: Starting goroutines without propagating context

Now let's look at something that happens frequently in real applications.

Imagine your report-generation handler calls a service:

func GenerateReport(ctx context.Context) error { // Fetch report data. // Process data. // Generate response. return nil } 

The handler starts this operation in a goroutine:

func reportHandler(w http.ResponseWriter, r *http.Request) { go GenerateReport(context.Background()) w.Write([]byte("Report generation started")) } 

Can you spot the problem?

We're using:

context.Background() 

This creates a context that isn't canceled when the incoming HTTP request is canceled.

The report-generation operation has no connection to the request's lifecycle.

Even if the client disconnects, the operation continues.

A better approach, when the work belongs to the request, is:

func reportHandler(w http.ResponseWriter, r *http.Request) { ctx := r.Context() err := GenerateReport(ctx) if err != nil { log.Printf("Report generation failed: %v", err) http.Error(w, "Report generation failed", 500) return } w.Write([]byte("Report generated successfully")) } 

Here, the operation uses the incoming request context.

If the client disconnects, the context is canceled and the service can respond accordingly.

But there's another important consideration.

What if report generation is intentionally asynchronous?

We might want the report to finish even if the user closes the browser.

In that case, tying the job to the HTTP request context is the wrong design.

We'll come back to this distinction.

5. Context propagation across service layers

This is where context becomes especially important in real backend applications.

Imagine an API that performs three operations:

HTTP Handler | v Report Service | +----> User Repository | +----> Order Repository | +----> External Payment API 

If the request gets canceled, we want the cancellation signal to reach all operations that are still running.

A common mistake is using context.Background() inside lower-level functions instead of passing the caller's context.

Let's see an example.

Incorrect implementation

func GetOrders() ([]Order, error) { rows, err := db.Query( "SELECT id, total FROM orders", ) if err != nil { return nil, err } defer rows.Close() // Scan rows... return orders, nil } 

This function has no way to receive the caller's cancellation signal.

Better implementation

func GetOrders(ctx context.Context) ([]Order, error) { rows, err := db.QueryContext( ctx, "SELECT id, total FROM orders", ) if err != nil { return nil, err } defer rows.Close() var orders []Order for rows.Next() { var order Order if err := rows.Scan( &order.ID, &order.Total, ); err != nil { return nil, err } orders = append(orders, order) } if err := rows.Err(); err != nil { return nil, err } return orders, nil } 

Now the caller can pass its context:

func reportHandler(w http.ResponseWriter, r *http.Request) { orders, err := GetOrders(r.Context()) if err != nil { log.Printf("Failed to fetch orders: %v", err) return } // Generate report... _ = orders } 

If the request context is canceled, QueryContext() can propagate that cancellation to the database driver.

Whether the underlying database operation stops immediately depends on driver and database behavior, but context-aware methods give the driver the opportunity to cancel it.

This is particularly important when dealing with long-running queries.

Remember our previous article about database connection pooling?

A query that continues running unnecessarily can keep a database connection occupied.

Proper cancellation helps avoid wasting resources on work that no longer needs to happen.

A useful rule: Pass context from the HTTP handler through your service and repository layers. Don't create a new background context at every layer.

6. What about external HTTP API calls?

The same problem exists when your backend calls another service.

Consider:

resp, err := http.Get( "https://api.example.com/orders", ) 

This request doesn't receive your incoming HTTP request's context.

If your user disconnects, this external API call may continue.

Instead, create an outbound request using the context:

func FetchOrders(ctx context.Context) error { req, err := http.NewRequestWithContext( ctx, http.MethodGet, "https://api.example.com/orders", nil, ) if err != nil { return err } client := &http.Client{ Timeout: 5 * time.Second, } resp, err := client.Do(req) if err != nil { return err } defer resp.Body.Close() // Process response... return nil } 

Now two things are controlling the operation:

  1. The incoming context can cancel the outbound request.
  2. The HTTP client's timeout provides an upper bound on the request duration.

These are complementary mechanisms.

The context might be canceled because the user disconnected, while the client timeout might expire because the external service is too slow.

Also, remember that a timeout on the HTTP client covers the entire request, including reading the response body.

For applications making many external requests, it's usually better to configure and reuse a shared http.Client rather than constructing one for every request.

7. Context cancellation vs context timeout

These two concepts are related, but they aren't interchangeable.

Context cancellation

A context can be canceled when the caller no longer needs the operation.

ctx, cancel := context.WithCancel( context.Background(), ) defer cancel() 

You can cancel it explicitly:

cancel() 

This is useful when:

  • A user cancels an operation.
  • A parent operation fails.
  • Multiple concurrent tasks should stop when one condition is met.
  • An operation is no longer required.

Context timeout

A timeout automatically cancels the context after a specified duration.

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

This means the operation has at most five seconds before its context is canceled.

Useful for:

  • Database operations.
  • External API calls.
  • Service-to-service communication.
  • Operations that must have bounded execution time.

What if the parent context is already canceled?

A derived context inherits cancellation from its parent.

For example:

ctx, cancel := context.WithTimeout( r.Context(), 5*time.Second, ) defer cancel() 

This is generally a good pattern for an operation that belongs to the incoming request.

The operation ends when either:

  • The HTTP request is canceled.
  • The five-second timeout expires.

The earlier of these events wins.

Important: A timeout is not a guarantee that the underlying work has stopped. It signals cancellation. The operation must support and respond to that signal.

8. A practical example: Multiple operations running concurrently

Now let's make things more interesting.

Suppose your API needs to fetch:

  • User information.
  • Order information.
  • Payment information.

These operations are independent, so running them concurrently can improve response time.

But what happens if one operation fails?

Should the other operations continue?

Often, no.

We can use errgroup from golang.org/x/sync/errgroup to manage concurrent operations with shared cancellation.

Install it:

go get golang.org/x/sync/errgroup 

Example:

func GetDashboard(ctx context.Context) error { g, ctx := errgroup.WithContext(ctx) g.Go(func() error { return FetchUser(ctx) }) g.Go(func() error { return FetchOrders(ctx) }) g.Go(func() error { return FetchPayments(ctx) }) return g.Wait() } 

What's happening here?

  1. Three operations start concurrently.
  2. They all receive the derived context.
  3. If one operation returns a non-nil error, the shared context is canceled.
  4. The other operations can detect cancellation and stop.
  5. g.Wait() waits for all goroutines to return and reports an error.

One important detail: cancellation doesn't force the other goroutines to terminate. They must cooperate with the context.

Also, if you only care about the first failure, this is a useful pattern. If you need all three results even when one fails, you'll need a different error-collection strategy.

This is much safer than starting arbitrary goroutines and hoping they all finish.

9. When should work continue even after the client disconnects?

Here's an important architectural decision.

Not all operations should be canceled when a client disconnects.

Consider two scenarios.

Scenario A: Fetching a dashboard

The user requests a dashboard.

The backend fetches data and prepares a response.

The user closes the page.

Do we still need to finish fetching all that data?

Usually, no.

This work belongs to the HTTP request. Canceling it saves resources.

Scenario B: Processing a payment

The user submits a payment request.

The backend sends the payment instruction to a payment provider.

The user closes the browser before receiving the response.

Should we cancel the payment just because the user disconnected?

Absolutely not as a general rule.

The payment may already have been accepted by the provider. Canceling the local HTTP request doesn't reverse a remote financial operation.

The application must handle the payment lifecycle independently of the browser connection.

This is where background jobs, durable queues, idempotency and payment status reconciliation become important.

For example:

Client | v POST /payments | v Backend | +----> Validate request | +----> Create payment record | +----> Enqueue payment job | v Background Worker | v Payment Provider | v Update payment status 

The API can return:

HTTP/1.1 202 Accepted Content-Type: application/json 
{ "paymentId": "pay_123", "status": "processing" } 

The worker processes the job independently of the original HTTP request.

If the user closes the browser, the job can still continue.

This is a crucial distinction:

Request-scoped work should generally follow the request's lifecycle. Durable business operations should have their own lifecycle.

Don't simply replace r.Context() with context.Background() and assume you've built a reliable background job system.

A goroutine running with context.Background() is not durable. It can disappear if the application restarts or crashes.

For work that must survive process failures, use a persistent queue or another durable job mechanism.

10. How to debug context cancellation in production

Now imagine your application logs show:

context canceled context deadline exceeded 

Are these errors?

Technically, yes. But they don't always represent application failures.

They can be expected outcomes of normal request cancellation.

For example:

  • A user navigates away.
  • A reverse proxy cancels an upstream request.
  • A client timeout expires.
  • A parent operation fails and cancels child operations.

The important thing is to understand where cancellation originated.

Step 1: Distinguish cancellation from actual errors

Use errors.Is():

if err != nil { switch { case errors.Is(err, context.Canceled): log.Println("Operation was canceled") case errors.Is(err, context.DeadlineExceeded): log.Println("Operation exceeded its deadline") default: log.Printf("Unexpected error: %v", err) } } 

This helps avoid treating every cancellation as a server-side failure.

However, don't blindly ignore all cancellation errors. A deadline exceeded error might indicate a slow database query or an external dependency problem.

The reason for cancellation matters.

Step 2: Log operation duration

When debugging slow operations, measure how long each stage takes.

func FetchOrders(ctx context.Context) error { start := time.Now() defer func() { log.Printf( "FetchOrders completed in %v", time.Since(start), ) }() // Database operation... return nil } 

You can improve this by logging whether the operation completed, failed or was canceled.

Step 3: Check whether context is actually propagated

Search your codebase for:

context.Background() context.TODO() 

These aren't inherently bad. They're appropriate at application entry points and for intentionally independent lifecycles.

But pay attention to their use inside request-handling code.

Look for:

  • db.Query() instead of db.QueryContext().
  • db.Exec() instead of db.ExecContext().
  • http.Get() instead of context-aware outbound requests.
  • Goroutines that don't receive a context.
  • Long-running loops that never check cancellation.
  • Third-party libraries that don't support cancellation.

Step 4: Inspect goroutine leaks

A canceled context doesn't guarantee that every goroutine has exited.

For example:

go func() { for { doSomeWork() } }() 

This goroutine has no stopping condition.

It can continue running even after the original request has finished.

During debugging, Go provides:

runtime.NumGoroutine() 

You can monitor goroutine counts over time.

For deeper investigation, use Go's pprof goroutine profile:

go tool pprof http://localhost:6060/debug/pprof/goroutine 

This requires net/http/pprof to be enabled and exposed in your application. Protect profiling endpoints appropriately, especially in production.

Look for goroutines stuck in the same function or waiting on channels that are never closed.

Step 5: Check proxy and client timeouts

Sometimes cancellation originates outside your application.

For example:

Frontend | v Load Balancer | v API Gateway | v Backend | v Database 

Each layer can have its own timeout or connection behavior.

If your gateway has a 10-second timeout but your backend allows 60 seconds, the gateway might stop waiting while the backend continues processing unless cancellation is propagated and honored.

Compare timeout configurations across the entire request path.

Don't assume that a timeout at one layer automatically stops every operation in the layers behind it.

11. Best practices for handling cancellation

Let's summarize the practices that make a real difference.

1. Always propagate the request context

Start with:

ctx := r.Context() 

Pass it through your handler, service, repository and external API calls.

2. Prefer context-aware database methods

Use:

db.QueryContext(ctx, query) db.ExecContext(ctx, query) db.BeginTx(ctx, nil) 

Where supported, these allow database operations to respond to cancellation.

3. Use context-aware HTTP requests

Prefer:

http.NewRequestWithContext(ctx, method, url, body) 

over requests that don't receive the caller's context.

4. Give operations sensible deadlines

Don't let database queries or external calls wait indefinitely.

Choose timeouts based on actual service requirements and the remaining request deadline.

5. Make goroutines cancellation-aware

Every long-running goroutine should have a clearly defined stopping condition.

For example:

for { select { case <-ctx.Done(): return case <-ticker.C: doSomeWork() } } 

If doSomeWork() is itself long-running, it should also support cancellation.

6. Don't hold resources after cancellation <...