Context in Go: timeouts and cancellation

Learn Go · Beginner · 12 min · After Goroutines and channels: work at the same time

How do you tell running work to stop?

  1. 1Guess

    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?
  2. 2Read

    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.

  3. 3Code

    Stop a worker with WithCancel

    1 / 2
    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())
    }
    

    Read the program. What will it print?

    Run it in the playground

  4. 4Read

    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.

  5. 5Code

    An operation that respects its context

    1 / 2
    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))
    }
    

    Read the program. What will it print?

    Run it in the playground

  6. 6Fix

    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?
  7. 7Say it back

  8. 8Mission · 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().

    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

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

Published Dec 3, 2026 · Updated Dec 3, 2026

Never miss new offers and news

New tools, credits, and AI news are added regularly. Pick how you want to hear about them.

Telegram channel

Join @aifree_dev and get new free AI offers and news right in your Telegram feed.

Browser notifications

Turn on push notifications and get an alert on this device whenever something new is posted. No account needed.

Email newsletter

A weekly digest of new, changed and expiring free AI offers. Double opt-in, one-click unsubscribe. See the latest issue.

Unsubscribe anytime. Privacy

Frequently asked questions

What is aifree.dev?

aifree.dev helps everyone access AI through a curated directory of free AI tools, API credits, free tiers, and startup programs for coding, image, voice, video, and students - verified regularly.

How are offers presented?

Each offer includes its access details, free models when available, and expiration information when provided. Limited-time deals stay visible so they are easy to compare.

Do education and startup programs need verification?

Yes. Providers usually ask students to verify their status with a school email, student ID, or a program like the GitHub Student Pack, and ask startups to verify company details such as age, funding, or website. Check each offer’s claim page for the exact requirements.

What kinds of free AI offers are listed?

Free tiers and free trials from AI providers, free API credits, startup and student programs, and free tools for coding, image generation, voice, and video.

How can I suggest a tool or report a broken link?

Use the submit form: paste the offer page URL and a short note. A person checks every submission before anything is listed. Broken links and changed terms go through the same form.

Know a good one?

Tell us about an AI tool worth knowing. Found a broken link? We want to hear that too.

Submit an offer