---
title: "Context in Go: timeouts and cancellation"
slug: "context-and-cancellation"
description: "Pass a context.Context to running work, cancel it with WithCancel, set limits with WithTimeout and check ctx.Err(). Fix a function that ignores its context."
published: "2026-12-03"
updated: "2026-12-03"
canonical: "https://aifree.dev/courses/learn-go/context-and-cancellation"
---

# Context in Go: timeouts and cancellation

How do you tell running work to stop?

## Predict

```go
package main

import (
	"context"
	"fmt"
	"time"
)

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
	defer cancel()

	select {
	case <-ctx.Done():
		fmt.Println(ctx.Err())
	case <-time.After(time.Second):
		fmt.Println("finished")
	}
}
```

What does this program print?

- finished
- context deadline exceeded
- Nothing, it waits one second and exits

Answer: context deadline exceeded — After 20 ms the context is done, so its Done channel closes and ctx.Err() reports the deadline.

Output:

```
context deadline exceeded
```

ctx.Done() closes after 20 ms, long before time.After fires, and ctx.Err() says why.

## What a Context is

A `context.Context` carries a cancel signal, an optional deadline and values across function calls. Pass it as the **first parameter**, named `ctx`. Work that can stop watches `ctx.Done()`, a channel that closes when the context ends. Create one with `context.WithCancel(parent)`. It returns a new context and a `cancel` function. Always `defer cancel()`, so the resources are released.

## Stop a worker with WithCancel

```go
package main

import (
	"context"
	"fmt"
)

func worker(ctx context.Context, steps <-chan int, done chan<- int) {
	count := 0
	for {
		select {
		case <-ctx.Done():
			done <- count
			return
		case <-steps:
			count++
		}
	}
}

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	steps := make(chan int)
	done := make(chan int)
	go worker(ctx, steps, done)

	for i := 0; i < 3; i++ {
		steps <- i
	}
	cancel()

	fmt.Println("steps done:", <-done)
	fmt.Println(ctx.Err())
}
```

Output:

```
steps done: 3
context canceled
```

The worker counts the steps it receives. After `cancel()`, its `ctx.Done()` case runs, it reports the count and returns. `ctx.Err()` is `context.Canceled`.

Playground: https://go.dev/play/p/Mf6PxCs0t20

## Timeouts and deadlines

`context.WithTimeout(parent, d)` cancels itself after `d`; `WithDeadline` takes a fixed time. When it ends, `ctx.Err()` is `context.DeadlineExceeded`, or `context.Canceled` after a `cancel()` call. Test for them with `errors.Is(err, context.DeadlineExceeded)`. Contexts form a tree: when a parent is cancelled, every child made from it is cancelled too.

## An operation that respects its context

```go
package main

import (
	"context"
	"errors"
	"fmt"
	"time"
)

func slowOp(ctx context.Context, d time.Duration) error {
	select {
	case <-time.After(d):
		return nil
	case <-ctx.Done():
		return ctx.Err()
	}
}

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
	defer cancel()

	fmt.Println(slowOp(ctx, time.Millisecond))

	err := slowOp(ctx, time.Second)
	fmt.Println(err)
	fmt.Println(errors.Is(err, context.DeadlineExceeded))
}
```

Output:

```
<nil>
context deadline exceeded
true
```

`slowOp` waits for the timer or for `ctx.Done()`, whichever comes first. The first call ends in 1 ms, the second is cut off by the 50 ms timeout.

Playground: https://go.dev/play/p/CkII2ghsx-T

## Fix it

```go
package main

import (
	"context"
	"fmt"
	"time"
)

func slowOp(ctx context.Context, d time.Duration) error {
	time.Sleep(d)
	return nil
}

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
	defer cancel()

	if err := slowOp(ctx, 300*time.Millisecond); err != nil {
		fmt.Println("stopped:", err)
		return
	}
	fmt.Println("done")
}
```

The timeout is 20 ms, but the program prints done after 300 ms. What is wrong?

- WithTimeout only works with a Background parent
- slowOp sleeps and never looks at ctx, so nothing can stop it
- The deadline needs defer cancel() to start

Answer: slowOp sleeps and never looks at ctx, so nothing can stop it — A context only signals. The function must select on ctx.Done() to react.

Fixed:

```go
package main

import (
	"context"
	"fmt"
	"time"
)

func slowOp(ctx context.Context, d time.Duration) error {
	select {
	case <-time.After(d):
		return nil
	case <-ctx.Done():
		return ctx.Err()
	}
}

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
	defer cancel()

	if err := slowOp(ctx, 300*time.Millisecond); err != nil {
		fmt.Println("stopped:", err)
		return
	}
	fmt.Println("done")
}
```

Output:

```
stopped: context deadline exceeded
```

## Say it back

In your own words: why does defer cancel() matter?

Our sentence: A context keeps a timer and links to its parent until it ends. Calling cancel releases them at once, even when the work finishes before the timeout.

## Mission (12 min)

Write a program that prints a counter every 100 ms and stops after a one-second timeout set with a context. When it stops, print the reason from ctx.Err().

```sh
go run .
```

## Common questions

### Why is ctx the first parameter in Go?

It is a convention that the standard library and most packages follow, written as ctx context.Context. A fixed place makes calls easy to read and lets tools and reviewers see at a glance which functions can be cancelled. Do not store a context in a struct field; pass it to each call that needs it, so every call can have its own limit.

### Does cancelling a context stop my goroutine automatically?

No. Cancelling only closes the channel returned by ctx.Done() and sets ctx.Err(). Your code must watch that channel, usually in a select, and return when it closes. A goroutine that never checks the context keeps running. That is why standard library functions that accept a context check it for you.

### What is the difference between context.Canceled and DeadlineExceeded?

Both are values of ctx.Err() after a context ends. Canceled means someone called the cancel function, or a parent was cancelled. DeadlineExceeded means a timeout or deadline passed. Use errors.Is to test for them, because they are often wrapped, and use the difference to decide whether to retry or to report a timeout to the user.

## Sources

- https://pkg.go.dev/context (read 2026-12-03)
- https://go.dev/blog/context (read 2026-12-03)
- https://go.dev/doc/database/cancel-operations (read 2026-12-03)

Measured with go1.27.4 darwin/arm64 on 2026-12-03.
