← writing

Go has no async/await. Here is what it has instead.

Rudra Narayan Panda ·

Go has no async, no await, no promises, and no event loop you can point at. Yet a Go server holds tens of thousands of connections open, and the code reads like a plain blocking program. I have had to work out how that is possible more than once, because it looks like asynchronous code nowhere else.

This is the explanation I wanted each time. It starts from the problem, finds where await went, and ends with the few patterns you actually write. Every program here was run on Go 1.27.4 on an Apple Silicon Mac, and the output is what it printed. Your numbers will differ a little. Stopping work has its own post, What context.Context is actually for.

The short answer

  1. Go does not make waiting visible in the code. You write a normal blocking call.
  2. The runtime turns that wait into a cheap pause of one goroutine, and the thread goes off and runs something else.
  3. So the caller decides what runs concurrently, with go. No function has to be marked.
  4. Where other languages return a promise, Go uses channels, WaitGroup, errgroup, select and context.

the problem is waiting

Most programs spend most of their time waiting: for a database, a network reply, a disk. The CPU sits idle while they do.

handle one request
[parse] ........ wait for the database ........ [render]
  1 ms                  50 ms                      1 ms

If one worker is stuck for the whole 52 ms, then serving 1,000 requests at once takes 1,000 workers. Every approach to concurrency is an answer to one question: how do you stop a task that is waiting from tying up a worker?

the usual answer colors your functions

JavaScript, Python and Rust answer it by making the pause explicit. A function that might wait is marked async, and each place it waits is marked await:

async function getUser(id) {
  const row = await db.query("select ...", id);   // "pause me here"
  return toUser(row);
}

This works, and the marking is useful: you can see every point where other code may run. The cost is that it spreads. You can only await from inside another async function, so one slow call at the bottom forces async up through every caller above it. Bob Nystrom called this "What Color is Your Function?": the language splits into two kinds of function that do not mix freely.

Go takes the other road. There is one kind of function:

func getUser(id int) (User, error) {
	row, err := db.Query("select ...", id)   // reads like a blocking call; only this goroutine waits
	if err != nil {
		return User{}, err
	}
	return toUser(row), nil
}

Nothing in that signature says it waits, because in Go that is not part of the type. Any function can block, and any caller can decide to run it alongside other work:

u, err := getUser(7)      // run it and wait for the answer
go getUser(7)             // run the same function concurrently

The function does not know or care which one you picked. That is what "no function coloring" means in practice.

where did await go

It is still there. It moved from your code into the runtime. When a goroutine hits something that has to wait, the runtime parks it: it saves where the goroutine was, files it in a list belonging to whatever it is waiting for, and gives the thread to another goroutine. When the thing it waited for happens, the goroutine goes back into a run queue and carries on at the next line.

A goroutine parks while its thread runs other work Two lanes over time. In the goroutine G1 lane, G1 runs, then is parked, then runs again. In the thread M0 lane, M0 runs G1, then G2, then G3, then G1 again. G1 parks when it receives from a channel with nothing in it, and becomes runnable again when another goroutine sends on that channel. G1 goroutine M0 OS thread running parked: no thread, no CPU running G1 G2 G3 G1 time 1 G1 runs v := <-ch and nothing is there yet: it parks 2 another goroutine sends on ch: G1 is runnable again
The goroutine waits for a while. The thread does not. For how the scheduler picks the next goroutine, see What a goroutine actually is.

The same thing happens at every point where a goroutine would wait:

Think of every one of those as an implicit await. You just never have to write the word.

the network case is an event loop you never see

The last item is the one that matters for servers, and it is where Go does the same job as Node's event loop. Sockets are put in non-blocking mode. When a goroutine reads from one and no data has arrived, the runtime registers the socket with the operating system's readiness mechanism (epoll on Linux, kqueue on macOS and the BSDs, IOCP on Windows) and parks the goroutine. The part of the runtime that watches those events is the netpoller. When data shows up, the goroutine is made runnable.

How a blocking-looking network read works Four steps left to right. A goroutine calls conn.Read. The runtime sees no data, registers the socket with epoll or kqueue, and parks the goroutine. The thread runs other goroutines. When the socket is readable the netpoller wakes the goroutine and Read returns. goroutine conn.Read(buf) runtime no data yet: park + register fd epoll / kqueue watches the fd netpoller fd readable: wake the goroutine Read returns the bytes
The thread is free the whole time between steps 2 and 4.

I did not want to take that on faith, so I measured it. This program opens 2,000 TCP connections to itself and parks a goroutine in Read on both ends of each one, so 4,000 goroutines all stuck waiting for bytes that never come. Then it asks the runtime how many OS threads it had to create:

package main

import (
	"fmt"
	"net"
	"runtime"
	"runtime/pprof"
	"sync"
	"time"
)

func main() {
	const n = 2000
	ln, _ := net.Listen("tcp", "127.0.0.1:0")
	go func() {
		for {
			c, err := ln.Accept()
			if err != nil {
				return
			}
			go func() { // server side: blocks in Read
				buf := make([]byte, 1)
				c.Read(buf)
				c.Close()
			}()
		}
	}()

	var wg sync.WaitGroup
	conns := make([]net.Conn, n)
	for i := 0; i < n; i++ {
		c, err := net.Dial("tcp", ln.Addr().String())
		if err != nil {
			panic(err)
		}
		conns[i] = c
		wg.Add(1)
		go func() { // client side: blocks in Read
			defer wg.Done()
			buf := make([]byte, 1)
			c.Read(buf)
		}()
	}

	time.Sleep(500 * time.Millisecond)
	fmt.Println("goroutines blocked in Read:", runtime.NumGoroutine())
	fmt.Println("OS threads created:", pprof.Lookup("threadcreate").Count())
	fmt.Println("GOMAXPROCS:", runtime.GOMAXPROCS(0))

	for _, c := range conns {
		c.Close()
	}
	wg.Wait()
}
goroutines blocked in Read: 4002
OS threads created: 14
GOMAXPROCS: 12

4,002 is the 4,000 readers plus main and the accept loop. Fourteen threads served all of them. If each blocked Read had held a thread, this would have needed 4,000. On macOS you may need ulimit -n 10240 first, since the program holds over 4,000 file descriptors.

The exception is calls the runtime cannot park: ordinary file I/O and most cgo calls block the real thread. The runtime then hands the processor to another thread so the rest keep running. The goroutines post walks through that case.

the cheat sheet

JavaScriptGo
async function f()a plain func f()
const p = f() (starts it)go f(), or return a channel
await p<-ch, wg.Wait(), g.Wait()
Promise.all([...])errgroup or WaitGroup
Promise.race([...])select
AbortControllercontext.Context
one thread, so races only at awaitreal parallelism, so you prevent data races

The last row is the one that surprises people, and it gets its own section below.

pattern 1: a future is a channel

To start work now and collect the result later, return a channel. The receive is your await:

func slowSquare(n int) <-chan int {
	ch := make(chan int, 1)
	go func() {
		time.Sleep(time.Second)
		ch <- n * n
	}()
	return ch
}

func main() {
	start := time.Now()
	a := slowSquare(3)   // starts, returns immediately
	b := slowSquare(4)   // runs alongside a
	fmt.Println(<-a, <-b)
	fmt.Println("took", time.Since(start).Round(100*time.Millisecond))
}
9 16
took 1s

Two one-second jobs, one second in total, because they overlap. The channel has a buffer of 1 on purpose. With no buffer, the sender would block forever if the caller never read the result, and that goroutine would leak.

pattern 2: many at once, stop on the first error

errgroup (from golang.org/x/sync) is the practical Promise.all. It waits for everything, returns the first error, and cancels a shared context so the others can stop early:

g, ctx := errgroup.WithContext(context.Background())
g.Go(func() error { return fetch(ctx, "users", 100*time.Millisecond, false) })
g.Go(func() error { return fetch(ctx, "orders", 200*time.Millisecond, true) })
g.Go(func() error { return fetch(ctx, "reports", 2*time.Second, false) })
err := g.Wait()
users ok
reports cancelled: context canceled
Wait returned: orders failed
took 200ms

orders failed at 200 ms, which cancelled the context, so reports gave up instead of running its full two seconds. Call g.SetLimit(10) before starting work to cap how many run at once, which you want any time the input list is not small.

pattern 3: a timeout is a select

select waits on several channels at once and takes whichever is ready first, which makes it your Promise.race. Paired with a context it gives you timeouts and cancellation:

func slow(ctx context.Context) (string, error) {
	ch := make(chan string, 1)
	go func() {
		time.Sleep(3 * time.Second)
		ch <- "done"
	}()
	select {
	case r := <-ch:
		return r, nil
	case <-ctx.Done():
		return "", ctx.Err()
	}
}

ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
defer cancel()
_, err := slow(ctx)
context deadline exceeded after 500ms

One honest caveat: Go cannot kill a goroutine from outside. In that example the sleeping goroutine keeps running for its full three seconds, and only the caller stopped waiting. Cancellation is a request that the goroutine has to notice by checking ctx.Done(). Any long-running function you write should take a ctx and watch it. The next post covers how, and every way to create one.

the part JavaScript does not prepare you for

JavaScript runs your code on one thread, so two lines can only interleave at an await. Goroutines really do run at the same time on different cores. Two of them touching one variable is a data race, however light they are:

count := 0
for i := 0; i < 1000; i++ {
	wg.Add(1)
	go func() {
		defer wg.Done()
		for j := 0; j < 1000; j++ {
			count++
		}
	}()
}
wg.Wait()
fmt.Println("want 1000000, got", count)
want 1000000, got 549647

count++ is a read, an add and a write. Two goroutines read the same value, both add one, and one update is lost. The run above lost almost half of them, and the number changes every time. The race detector finds this for you, and it is worth running on every test:

go test -race ./...
go run -race .

WARNING: DATA RACE
Read at 0x00c00019e048 by goroutine 11:
  main.main.func1()
      race/main.go:16 +0x88

Previous write at 0x00c00019e048 by goroutine 8:
  main.main.func1()
      race/main.go:16 +0x98

The fixes, in the order I reach for them: give each goroutine its own data and combine the results afterwards, use a sync.Mutex around the shared state, use sync/atomic for a lone counter, or hand the value over through a channel so only one goroutine owns it at a time. A channel is for passing ownership or signalling an event. A mutex is for guarding a piece of state. Do not force channels onto the second job.

the mistakes I keep seeing

the version to remember

  1. go f() starts a cheap task. It is not a thread.
  2. Waiting parks the goroutine and frees the thread, so blocking code is fine.
  3. Network waiting uses epoll or kqueue underneath: an event loop you never write.
  4. Use channels to hand things over, errgroup to wait, select to race, context to cancel.
  5. Goroutines run in parallel, so protect shared data and run -race.

Two related posts: What context.Context is actually for covers how to stop work, and What a goroutine actually is has a simulator that lets you step through the scheduler one tick at a time.