Cloud Explainers
Home › Go (Golang) › Golang Idioms for Beginners, episode 5

Golang context.Context in 5 Minutes

Go (Golang)5 min video

Go's context.Context for beginners, in five minutes, on a real Go web server: why a server keeps working after the customer leaves, passing r.Context() down to an outgoing request, context.WithTimeout with defer cancel, why your own loops must select on ctx.Done(), the context package's rules, and go vet's lost-cancel check.

6 seconds of work for nobody

Your Go server keeps working for customers who already left: here, six seconds after one gave up.

Work done after the customer left: figure of 6 seconds John's server kept working after the customer gave up, source: John's server log, Go 1.27.4

Jen asks John's garden center if the ferns are in stock, and gives up after two seconds. Here, curl plays Jen, and its max-time flag is her two-second patience. John's server keeps asking the plant supplier anyway, and logs the answer at eight seconds. That's six seconds after she left. The ferns, for the record, were in stock. Why didn't it stop? That's the job of context.Context, and in five minutes this server will stop the moment she leaves.

John's laptop: a customer (curl)
curl --max-time 2 'localhost:8080/stock?plant=fern'curl: (28) Operation timed out after 2006 milliseconds with 0 bytes received
John's laptop: a customer (curl)
go run .garden shop listening on :8080
fern: 12 in stock (8.0s)
signal: interrupt

What a context is

Picture the garden center's yard. A clerk sends a runner to the far greenhouse to count ferns. If the runner carries a walkie-talkie, the clerk can radio: stop, she left. Without one, the runner counts every fern, and walks back to an empty counter.

A runner with a walkie-talkie: diagram of the clerk, with a radio, without one

In Go, the walkie-talkie is a context. It's a value you pass to every function that handles one request. It carries a cancel signal. It can also carry a deadline, if you set one. Go's built-in HTTP package makes one for every request. Every handler receives the incoming request, usually named r, and you get its context by calling r.Context(). When the customer disconnects, Go cancels it for you. Every function you passed it to can hear that, and stop.

One context, passed down every call: diagram of Jen, stock handler, askSupplier, the supplier, John's server

Pass it down

John's function that calls the supplier, askSupplier, never got the radio. So he adds a context as its first parameter, called ctx by convention. Plain http.Get can't hear a context. So he builds the request with NewRequestWithContext. That attaches ctx to it. Then he sends it with http.DefaultClient.Do. And the handler passes r.Context() in.

Pass the request's context down: code change of main.go, func askSupplier(ctx context.Context, plant string) (string, error) { (ctx first), req, err:= http.NewRequestWithContext(ctx, "GET", url, nil) (a request that carries ctx)

Jen gives up at two seconds again. This time the log says: context canceled, at two point oh seconds. The request to the supplier stopped the moment she left.

John's laptop: a customer (curl)
curl --max-time 2 'localhost:8080/stock?plant=fern'curl: (28) Operation timed out after 2005 milliseconds with 0 bytes received
John's laptop: a customer (curl)
go run .garden shop listening on :8080
fern: Get "http://localhost:9000/fern": context canceled (2.0s)
signal: interrupt

A deadline of your own

Canceling only helps when someone leaves. If Jen keeps waiting, she waits eight seconds. So John sets a limit of his own: context.WithTimeout, three seconds. It takes the request's context and makes a new one from it. That new one is canceled at three seconds, or when Jen leaves, whichever comes first. It also hands back a cancel function. Go's defer keyword runs it when the handler finishes. That way, the three-second timer doesn't keep running after Jen has her reply. Now, at three seconds, Jen gets a reply that says: supplier didn't answer. And the log shows why: not context canceled this time, but context deadline exceeded.

John's laptop: the server
sed -n '30,32p' main.go    ctx, cancel := context.WithTimeout(r.Context(), 3*time.Second)
    defer cancel()
    answer, err := askSupplier(ctx, plant)
John's laptop: the server
curl 'localhost:8080/stock?plant=fern'supplier didn't answer
John's laptop: the server
go run .garden shop listening on :8080
fern: Get "http://localhost:9000/fern": context deadline exceeded (3.0s)
signal: interrupt

Your code has to listen

What if the slow work is John's own code? John's server has a second address, care, that builds a care guide for a plant. It's five pages long, and each page takes one second. He passes ctx in, just like he did for askSupplier. Jen leaves at two and a half seconds. Guess first: when does the loop stop? At five seconds. All five pages. A context doesn't stop your code by itself. It's only a signal, and your code has to listen for it.

John's laptop: the server
sed -n '43,46p' main.go    for page := 1; page <= 5; page++ {
        time.Sleep(time.Second) // slow work: one page of the care guide
        log.Printf("%s: care page %d", plant, page)
    }
John's laptop: the server
curl --max-time 2.5 'localhost:8080/care?plant=fern'curl: (28) Operation timed out after 2505 milliseconds with 0 bytes received
John's laptop: the server
go run .garden shop listening on :8080
fern: care page 1
fern: care page 2
fern: care page 3
fern: care page 4
fern: care page 5
fern: care sheet done (5.0s)
signal: interrupt

So inside the loop, John uses select, which waits for whichever happens first. One option is the next page: a one-second timer from time.After. The other is ctx.Done(): that's the walkie-talkie, and it crackles the moment the context is canceled. If the context is done first, he returns its error. Now the log stops after page two: context canceled, at two and a half seconds.

John's laptop: the server
sed -n '43,53p' main.go    for page := 1; page <= 5; page++ {
        select {
        case <-ctx.Done():
            return ctx.Err()
        case <-time.After(time.Second): // slow work: one page
        }
        log.Printf("%s: care page %d", plant, page)
    }
    return nil
}
John's laptop: the server
curl --max-time 2.5 'localhost:8080/care?plant=fern'curl: (28) Operation timed out after 2506 milliseconds with 0 bytes received
John's laptop: the server
go run .garden shop listening on :8080
fern: care page 1
fern: care page 2
fern: context canceled (2.5s)
signal: interrupt

The rules

There are a few rules, and if you break them, the stop signal never reaches the code doing the work. They're in the context package's own docs. Every request gets a context. Every function from the handler down to your outgoing calls passes it along. When it's canceled, every context made from it is canceled too, like John's three-second one. Don't store it somewhere to reuse later: it belongs to one request only. Pass it as the first parameter, named ctx.

The rules: browser screenshot from the video

One rule is checked for you, by go vet, Go's built-in code checker. If John throws the cancel function away with an underscore, go vet stops him: the cancel function should be called, not discarded, to avoid a context leak. That's exactly the leak John's defer cancel line prevents.

John's laptop: the server
sed -n '30p' main.go    ctx, _ := context.WithTimeout(r.Context(), 3*time.Second)
John's laptop: the server
go vet .main.go:30:7: the cancel function returned by context.WithTimeout should be called, not discarded, to avoid a context leak

Recap

So: Jen left, and John's server kept working. Passing ctx down let it stop, WithTimeout gave it a deadline, and select made his own loop listen.

Pass ctx down, and listen for Done: diagram of Jen, stock handler, askSupplier, the supplier, John's server

If context makes sense now, a like helps YouTube show this to more beginners, and subscribing brings the next Go idiom: structs.

All the lab files and commands are linked in the description. Thanks for watching Cloud Explainers.

Sources

Demos: one container on our own Mac standing in for a laptop; the garden center and its supplier are made up. Every command, error and number was real. Watch the full video on YouTube.

More videos

PostgreSQL9 min

Every PostgreSQL Setting to Change After You Install It

Docker9 min

What Happens When You Install Docker on Ubuntu

Python8 min

How to Fix Python 'Address Already in Use' Errors

Go (Golang)5 min

Golang Interfaces and Mocks in 5 Minutes

Git7 min

How to Fix Git 'Detached HEAD' State

Linux21 min

Linux Firewall with ufw: Full Tutorial for Beginners

Go (Golang)5 min

Golang defer Statements in 5 Minutes

Auth (OAuth, JWT)9 min

How to Fix OAuth 'invalid_grant' Errors

Databases & SQL11 min

The SQL Roadmap for Beginners

Go (Golang)5 min

Golang make() for Slices and Maps in 5 Minutes

Networking7 min

How to Fix Network 'No Route to Host' Errors on Linux

Linux6 min

How to Fix Linux 'Too Many Open Files' Errors

Django (Python web framework)11 min

Every Django Concept a Beginner Needs to Know

Linux24 min

SSH on Linux: Full Tutorial for Beginners

Go (Golang)5 min

Golang for range Loops in 5 Minutes

Databases & SQL10 min

SQL Databases: SQLite vs PostgreSQL

Django (Python web framework)10 min

The Django Roadmap for Beginners

Go (Golang)5 min

Golang Structs in 5 Minutes

Caching & Redis22 min

Redis: Full Tutorial for Beginners

Databases & SQL7 min

How to Fix MySQL Database Error 1045: Access Denied for User

Go (Golang)5 min

Golang Method Receivers in 5 Minutes

Python8 min

How to Fix Python SSL: CERTIFICATE_VERIFY_FAILED Errors

Django (Python web framework)9 min

How to Fix Django Static Files Not Loading in Production

OpenRouter (one API for many AI models)8 min

OpenRouter vs Direct API Keys: Which One Should You Use?

Go (Golang)5 min

Golang if err != nil Checks in 5 Minutes

Go (Golang)8 min

How to Fix Golang 'go.mod File Not Found' Errors

AI agents & MCP22 min

MCP Servers: Full Tutorial for Beginners

Go (Golang)5 min

Golang Error Return Values in 5 Minutes

Python8 min

How to Fix Python ModuleNotFoundError: No Module Named

Go (Golang)5 min

Golang Pointers in 5 Minutes

Kubernetes8 min

How to Fix a Kubernetes Pod Stuck in CrashLoopBackOff

Homelab & self-hosting9 min

How to Fix a Homelab ESXi Host Not Responding

PostgreSQL24 min

PostgreSQL: Full Tutorial for Beginners

Load balancing & Nginx9 min

How a Load Balancer Works with HAProxy

Python9 min

How Python Virtual Environments Work

Homelab & self-hosting9 min

How to Fix Cloudflare Tunnel Errors in a Homelab

APIs9 min

How to Fix API CORS Errors: No 'Access-Control-Allow-Origin'

Auth (OAuth, JWT)9 min

How Authenticator App Login Codes Work (TOTP)

Git22 min

Git and GitHub: Full Tutorial for Beginners

Homelab & self-hosting10 min

How a Homelab Hypervisor Works (VMware ESXi)

Kubernetes9 min

How to Fix Kubernetes ImagePullBackOff Errors

DNS8 min

How to Fix DNS 'Temporary Failure in Name Resolution' on Linux

AWS8 min

How to Fix AWS CLI 'Unable to Locate Credentials'

Homelab & self-hosting10 min

Proxmox vs ESXi for Your Homelab: When Each One Wins

PostgreSQL10 min

PostgreSQL UUID vs Auto Increment: Which Primary Key Should You Use?

Kubernetes21 min

Kubernetes: Full Tutorial for Beginners

Networking9 min

How TCP Sockets Work

PostgreSQL7 min

How to Fix PostgreSQL 'Could Not Connect to Server'

Claude & the Claude Developer Platform9 min

Claude Code Hooks Will Finally Make Sense After This

DevOps & CI/CD9 min

DevOps with Ansible Will Finally Make Sense After This

Networking9 min

How SNMP Network Monitoring Works

Git8 min

How to Fix GitHub 'Permission Denied (publickey)' Errors

Docker21 min

Docker: Full Tutorial for Beginners

PostgreSQL7 min

How to Fix PostgreSQL 'Password Authentication Failed'

Linux8 min

Why One Linux Server Handles More Users Than You Think

Networking7 min

How to Fix Network 'Connection Refused' Errors

DevOps & CI/CD9 min

DevOps Pipelines: Jenkins vs GitHub Actions

Linux11 min

Linux Nginx Reverse Proxy: Full Tutorial for Beginners

Networking11 min

Every Networking Term a Beginner Needs in 12 Minutes

Docker6 min

How to Fix Docker 'Permission Denied' on docker.sock

Git7 min

How to Fix Git 'Updates Were Rejected' When You Push

Linux7 min

How to Fix nginx 502 Bad Gateway Errors on Linux

Linux8 min

How to Fix Linux apt 'Could Not Get Lock' Errors (Ubuntu)

Networking9 min

How Email Works on the Internet (SMTP) in 10 Minutes

Python8 min

The Python Roadmap for Beginners

Go (Golang)21 min

Golang REST API with Gin: Full Tutorial for Beginners

Networking10 min

How a WireGuard VPN Network Works

Linux9 min

Linux Makefiles Will Finally Make Sense After This

Auth (OAuth, JWT)9 min

SAML vs OAuth vs OpenID Connect: What's the Difference?

Python7 min

How to Fix Python cron Jobs That Never Run

Linux22 min

Linux Bash Scripting: Full Tutorial for Beginners

Networking10 min

How PXE Network Boot Works

Active Directory9 min

How Active Directory Works

Linux10 min

How to Fix a Linux systemd Service That Won't Start

Linux9 min

Linux Logs: syslog vs journald

Auth (OAuth, JWT)9 min

JWT vs Session Cookies: Which One Should You Use?

Docker10 min

Docker vs Docker Compose: Which One Should You Use?

Docker9 min

How to Fix Docker Compose Containers That Can't Talk to Each Other

Django (Python web framework)22 min

Django Full Tutorial for Beginners

Linux9 min

How Linux systemd Works

Networking8 min

How to Fix 'Windows Cannot Access' Network Share Errors (SMB)

APIs10 min

REST vs gRPC: Which One Should You Use?

Certificates & PKI (ADCS)9 min

How to Fix SSL Certificate Chain Errors (Missing Intermediate)

Python9 min

Every Python Concept for Beginners in 10 Minutes

Databases & SQL9 min

Every SQL Join Type in 10 Minutes

OpenRouter (one API for many AI models)9 min

Why OpenRouter Free Models Hit Their Limit So Fast

Gemini API & Google AI Studio9 min

Why Your Gemini API Free Tier Runs Out So Fast

OpenRouter (one API for many AI models)10 min

OpenRouter Will Finally Make Sense After This

Caching & Redis10 min

How Redis Caching Works

Gemini API & Google AI Studio10 min

Gemini API vs Vertex AI: Which One Should You Use?

Gemini API & Google AI Studio8 min

How to Fix a Leaked Gemini API Key

Go (Golang)9 min

Why Golang Uses Goroutines Instead of Threads

Gemini API & Google AI Studio9 min

How to Fix Gemini API Error 429: Resource Exhausted

Claude & the Claude Developer Platform10 min

Claude Token Pricing Will Finally Make Sense After This

Python11 min

Why Python Web Scraping Returns Nothing (and the Fix)

Python10 min

Python uv vs pip: Which One Should You Use?

Python22 min

Python Automation: Full Tutorial for Beginners

Auth (OAuth, JWT)9 min

How OAuth Login Works

Gemini API & Google AI Studio10 min

Google AI Studio Will Finally Make Sense After This

Docker10 min

What Happens When You Run a Docker Container

Claude & the Claude Developer Platform8 min

How to Fix Claude Code Billing Your API Key Instead of Your Plan

Auth (OAuth, JWT)9 min

Why Passkeys Can't Be Phished Like Passwords

PowerShell10 min

PowerShell vs Bash: Which One Should You Learn?

Linux10 min

The Linux Roadmap for Beginners

Django (Python web framework)9 min

Django vs FastAPI: Which One Should You Use?

Databases & SQL10 min

Why SQLite Is the Most Used Database in the World

Databases & SQL11 min

How a NoSQL Database Like MongoDB Works

Python11 min

How to Fix Python pip error: externally-managed-environment

Databases & SQL9 min

How to Fix MySQL Too Many Connections Database Errors

Go (Golang)9 min

Golang Concurrency Will Finally Make Sense After This

AWS10 min

How Amazon S3 Works

Kubernetes10 min

How Kubernetes Works

Git10 min

How Git Works

Docker10 min

How to Fix Docker Port Already Allocated Errors

PostgreSQL10 min

How PostgreSQL Works

Git8 min

How to Fix Git Merge Conflicts

Linux9 min

How to Fix No Space Left on Device in Linux

Networking10 min

How the Internet Works

Databases & SQL9 min

SQL vs NoSQL: When Each One Wins

Auth (OAuth, JWT)8 min

How to Fix JWT Token Expired Errors (401 Unauthorized)

Claude & the Claude Developer Platform9 min

Claude API vs Claude Pro: Why Your Subscription Doesn't Include It

AI agent skills9 min

Why AI Agent Skills Beat Giant Prompts

Linux10 min

Linux Cron Jobs Will Finally Make Sense After This

Cybersecurity10 min

Security Logs Will Finally Make Sense After This

Cybersecurity8 min

How to Fix a Security Leak: An API Key Pushed to GitHub

DNS9 min

DNS Will Finally Make Sense After This

Cybersecurity9 min

Never Ignore a Security Update

Auth (OAuth, JWT)9 min

Two-Factor Authentication Will Finally Make Sense

Networking8 min

Never Expose a Database to the Internet

Cybersecurity10 min

SSH Keys vs Passwords: Which Is Safer for Security?

Linux10 min

The 5 Levels of Linux Boot: From Power On to Login

Networking12 min

The 5 Levels of Network Firewalls

Cybersecurity10 min

Password Security: Why Hackers Crack Weak Passwords

Linux9 min

Why Your Linux Server Runs Out of Memory

Networking10 min

HTTP vs HTTPS: What Actually Changes on Your Network

Linux12 min

Every Linux File Permission You Need to Know

Linux10 min

Linux Processes vs Threads: When Each One Wins

Networking11 min

The OSI Model Will Finally Make Sense After This

Git11 min

The 7 Levels of Git

Networking10 min

Every Network Troubleshooting Command You Need

Cybersecurity10 min

Hashing vs Encryption in Cybersecurity: When Each One Wins

Networking11 min

Why the Internet Ran Out of IP Addresses

Linux11 min

Linux Package Managers: apt vs Snap vs Flatpak

Python9 min

Why Python Is Slow (and When It Doesn't Matter)

Networking11 min

TCP vs UDP: When Each One Wins

Linux8 min

Stop Running Linux as Root (Do This Instead)

Linux11 min

Linux Users and Groups Will Finally Make Sense

Cybersecurity9 min

Why Phishing Beats Good Security (and How to Spot It)

Docker12 min

The 7 Levels of Docker

AI agents & MCP12 min

AI Agents Will Finally Make Sense After This

Git8 min

Stop Using git push --force (Use This Instead)

AI agent skills10 min

Agent Skills vs MCP: When Each One Wins

Networking12 min

Networking Will Finally Make Sense After This

Linux12 min

Every Linux Command You Actually Need

Cybersecurity12 min

The 7 Levels of Cybersecurity

System design12 min

Every System Design Concept You Need, in One Diagram

PostgreSQL10 min

Why PostgreSQL Ignores Your Index