Go Concurrency, Explained Through a Busy Ride-Sharing App

Imagine this…

Imagine you just launched a ride-sharing app. At rush hour, ride requests pour in, one every millisecond. For each request your server has to find nearby drivers, estimate the fare, and notify the best match. Say that takes about 200 milliseconds per request.

Do the math. One worker handling one request at a time finishes 5 requests per second. Meanwhile 1,000 requests per second are arriving. Pretty soon you have a very long queue and some very stranded riders.

So you need to do many things at once, and you need to do it safely. That is exactly what Go’s concurrency tools are for. In this post we will build the toolbox piece by piece, and for each tool we will ask the same question: what problem does this solve for our ride-sharing app?

Disclaimer: a real ride-sharing app is far more complicated than the one in this post. Production systems typically rely on event-driven processing, durable message queues, and many separate services. Treat this app as a simplified story that makes Go’s concurrency tools easy to picture, not as an architecture to copy.

1. Goroutines: doing more than one thing at once

A goroutine is a function running concurrently with the rest of your program. You start one by putting go in front of a function call.

func say(s string) {
	for i := 0; i < 5; i++ {
		time.Sleep(100 * time.Millisecond)
		fmt.Println(s)
	}
}

func main() {
	go say("world")
	say("hello")
}

Three things are worth noticing:

  • go say("world") returns immediately. It does not wait for the function to finish.
  • Both loops now run at the same time, and each prints after its own 100 ms sleep. Which line appears first in each round is up to the scheduler, so the output order can change from run to run.
  • When main returns, the whole program exits and any goroutine still running is killed. That is why you sometimes see 9 lines instead of 10: the last “world” never got its turn.

Both loops run at once, and the program ends the moment main does.

For our app: a goroutine per ride request is like assigning a dispatcher to every rider. Goroutines are cheap enough (a few KB each) that this is realistic.

2. WaitGroup: “tell me when everyone is done”

That early-exit problem needs a fix. sync.WaitGroup is a counter: Add increments it, Done decrements it, and Wait blocks until it reaches zero.

var wg sync.WaitGroup
for i := 0; i < 3; i++ {
	wg.Add(1) // add BEFORE starting the goroutine
	go func() {
		defer wg.Done()
		process()
	}()
}
wg.Wait() // blocks until all three have called Done

A common point of confusion: wg.Add(1) increments the counter, it does not set it to 1. wg.Add(3) once and wg.Add(1) three times are the same. You do not need to know the total up front. The real rule is to call Add in the goroutine that starts the work, before the go statement. If you call it inside the new goroutine, Wait might run first, see zero, and return too early.

Wait only returns once every Add has been matched by a Done.

For our app: the WaitGroup is how main knows every ride request has been handled before shutting down.

3. Channels: passing data between goroutines

A WaitGroup only says “done”. It carries no data. When goroutines need to hand results to each other, you use a channel.

func sum(s []int, c chan int) {
	total := 0
	for _, v := range s {
		total += v
	}
	c <- total // send
}

func main() {
	s := []int{7, 2, 8, -9, 4, 0}
	c := make(chan int)
	go sum(s[:len(s)/2], c)
	go sum(s[len(s)/2:], c)
	x, y := <-c, <-c // two receives
	fmt.Println(x, y, x+y)
}

Even though make is also used for slices, c is not a slice. A channel is a pipe, not a container. There is no c[0]. You send with c <- v and receive with <-c, and each receive removes the value. So x, y := <-c, <-c is simply two receives, one after the other.

The receive also synchronizes. <-c blocks until a value arrives, so main cannot print before both sums are ready. No WaitGroup needed here. Also notice that x could be either half’s sum, because whichever goroutine finishes first sends first.

Whichever goroutine finishes first sends first, so x may hold either half’s total.

For our app: a channel is the ride-request queue itself, a pipe from whoever receives requests to whoever matches them with drivers.

4. Buffered channels: a little room in the pipe

The channel above is unbuffered: it holds zero values, so a send waits until a receiver is ready. A buffered channel has some capacity:

ch := make(chan int, 2)
ch <- 1
ch <- 2
// ch <- 3 would block forever here: fatal error, deadlock!
fmt.Println(<-ch, <-ch)
Operation Unbuffered Buffered (capacity N)
Send blocks until a receiver is ready blocks only when the buffer is full
Receive blocks until a sender is ready blocks only when the buffer is empty

Overfilling does not drop or overwrite anything. The sender simply waits. If nothing can ever unblock it (as in the example above, where main is the only goroutine), Go detects it and crashes with all goroutines are asleep - deadlock!.

A full buffer makes the sender wait. It never drops or overwrites a value.

For our app: the buffer is the waiting area. It absorbs a burst of ride requests without making the intake wait.

5. Closing channels and the closer goroutine

How does a receiver know no more values are coming? Someone closes the channel. A for v := range c loop keeps receiving until the channel is closed and drained.

Two rules to remember:

  • Only the sender closes, never the receiver, and only once. Sending on a closed channel panics, and so does closing twice.
  • Closing is a signal, not cleanup. Channels are garbage collected anyway. You only need close when a receiver is waiting for the signal, like a range loop.

With several senders, none of them can safely close the channel, because each one does not know whether the others are done. The classic fix combines the two tools we have seen:

go func() {
	wg.Wait()      // all senders finished
	close(results) // now it is safe
}()
for r := range results {
	fmt.Println(r)
}

The closer must be its own goroutine. If main called wg.Wait() before starting to receive, the senders would be blocked waiting for a receiver and main would be blocked waiting for the senders. Deadlock.

The closer waits on its own, so main stays free to receive.

6. The worker pool

Now we can build the heart of our ride-sharing app: a fixed set of workers pulling ride requests from a shared channel.

func worker(id int, jobs <-chan int, wg *sync.WaitGroup) {
	defer wg.Done()
	for j := range jobs {
		time.Sleep(200 * time.Millisecond) // simulate work
		fmt.Println("worker", id, "matched request", j)
	}
}

func main() {
	jobs := make(chan int, 10)
	var wg sync.WaitGroup

	for w := 1; w <= 3; w++ {
		wg.Add(1)
		go worker(w, jobs, &wg)
	}

	for j := 1; j <= 20; j++ {
		jobs <- j
	}
	close(jobs) // no more requests
	wg.Wait()   // let workers finish what they are holding
}

What is going on:

  • Each worker handles one request at a time. Three workers means at most three requests in flight. That is your concurrency limit.
  • Each request goes to exactly one worker, because a receive removes the value.
  • Work balances itself: whoever is free first takes the next request, so one slow request does not stall the others.
  • <-chan int makes the parameter receive-only, so the compiler stops a worker from accidentally sending or closing.

Each request is received by exactly one worker.

A common misconception: with an unbuffered channel the 20 jobs do not sit in the channel. It holds zero. The producer blocks on each send until a worker is free. With a buffer of 3, the producer gets three requests ahead and then waits. Only a buffer of 20 would hold all of them at once.

7. When requests arrive faster than workers can cope

Back to the real problem: 1,000 requests per second against three workers that finish about 15 per second. Whatever you do, the excess has to go somewhere. You have three honest choices.

The three choices below are the branches of that last decision.

Backpressure. Use an unbuffered or small channel and let the producer wait. Nothing is lost and memory stays flat, but the producer slows to the workers’ pace. Great for a file reader, bad for a rider waiting on an HTTP request.

A bounded buffer. Absorb short bursts, then fall back to one of the other policies when it fills. It delays the problem under sustained load, it does not solve it.

Load shedding. Make the send non-blocking with select and default:

select {
case jobs <- req:
	// queued
default:
	// queue is full: reject, or save it somewhere durable
}

The one thing not to do is use an unbounded queue. It looks like it solves everything, until memory grows without limit and the process dies.

If you want a cap on concurrency without a fixed pool, a buffered channel also works as a semaphore:

sem := make(chan struct{}, 3)
for req := range requests {
	sem <- struct{}{} // blocks if 3 are already running
	go func(r int) {
		defer func() { <-sem }()
		process(r)
	}(req)
}

And sometimes the answer is simply more workers. The number you need is arrival rate times processing time: 1,000 per second times 0.2 seconds is about 200 workers. For I/O-bound work like waiting on driver location updates and payment providers, 200 goroutines is cheap. For CPU-bound work, more workers than cores adds nothing, and downstream limits (database connections, API rate limits) are your real ceiling. At serious scale, systems like Kafka or SQS hold the queue durably outside your process, and the same ideas apply.

8. select, quit signals, and that odd go func(){}()

select waits on several channel operations at once and runs whichever is ready first. A classic use is a stop signal:

func fibonacci(c, quit chan int) {
	x, y := 0, 1
	for {
		select {
		case c <- x:
			x, y = y, x+y
		case <-quit:
			return
		}
	}
}

The generator keeps handing out numbers while someone is receiving. The moment a value arrives on quit, it stops.

The select serves whichever case is ready, and after the tenth value only quit is.

You will also see goroutines started like this:

go func() {
	// body
}()

It is not special. func() { ... } is an anonymous function, the trailing () calls it, and go runs that call in a new goroutine. Because it is a closure, it can use variables from the surrounding code. The trailing parentheses are required: go needs a function call, not just a function value.

9. Mutex: protecting shared data

Sometimes goroutines do not pass data, they just all touch the same variable. Say 1,000 goroutines each increment a ride counter in a map. c.v[key]++ looks like one step but is really read, add, write, and a Go map is not safe for concurrent writes. A sync.Mutex lets one goroutine in at a time:

type SafeCounter struct {
	mu sync.Mutex
	v  map[string]int
}

func (c *SafeCounter) Inc(key string) {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.v[key]++
}

The increments happen one after another, so none are lost.

The mutex protects memory. It does not tell you when the goroutines are done, and it does not pass anything between them. That is why a program like this still needs a WaitGroup, and why time.Sleep(time.Second) to “wait long enough” is just a guess.

Here is the whole decision in one table:

Tool The question it answers Carries data?
sync.Mutex Who may touch this shared variable right now? No, it guards memory
sync.WaitGroup Have all the goroutines finished? No, it is a counter
Channel How do I hand a value or a signal to another goroutine? Yes

A design alternative: let a single goroutine own the data and have everyone else send it messages over a channel. No lock needed, because nothing is shared. That is the Go saying “share memory by communicating”. For a simple counter or cache, though, the mutex is less machinery. For a single integer, sync/atomic is lighter still.

10. Two classic exercises that tie it together

Walking a binary tree with a channel. To compare whether two differently shaped trees hold the same values, walk each one in order in its own goroutine and stream the values into a channel:

func Walk(t *tree.Tree, ch chan int) {
	walk(t, ch) // recursive in-order traversal
	close(ch)   // the sender closes
}

Same then reads one value from each channel at a time and compares them. The v, ok := <-ch form tells you whether a channel was closed, which is how you detect that one tree is shorter than the other. Here the channel is the right tool: values flow from the walker to the comparer.

A parallel web crawler. Fetch pages in parallel, but never fetch the same URL twice. This needs a Mutex and a WaitGroup, and no channel at all:

func (v *visitedSet) TryVisit(url string) bool {
	v.mu.Lock()
	defer v.mu.Unlock()
	if v.seen[url] {
		return false
	}
	v.seen[url] = true
	return true
}

The subtle part: the check and the write happen under one lock. If you lock, check, unlock, then lock again to write, two goroutines can both see “not visited” and both fetch the page. The WaitGroup then lets Crawl wait for every spawned goroutine, with Add(1) called in the parent before each go statement.

Every branch ends in a Done, so the counter always reaches zero.

11. Concurrency is not the same as parallelism

One last distinction. Concurrent means several things are in progress at once and their steps can interleave. Parallel means they are literally running on different CPU cores at the same instant. Go guarantees the first and lets the runtime decide about the second.

A program can be perfectly concurrent and barely parallel. The Fibonacci example, for instance, has two goroutines that meet at an unbuffered channel and move in lockstep, so most of the time one is waiting for the other. Parallelism pays off for independent CPU-heavy work. For I/O-bound work like our driver-lookup and payment calls, concurrency alone already gets you the win, because goroutines spend most of their time waiting and the scheduler fills the gaps.

Cheat sheet

You want to… Reach for
Run something in the background go f()
Wait for a group of goroutines to finish sync.WaitGroup
Send results or work between goroutines a channel
Smooth out bursts between fast and slow sides a buffered channel
Tell receivers there is nothing more coming close by the sender
Limit how many things run at once a worker pool or a semaphore channel
Refuse work when overloaded select with default
Wait on several channels, or add a stop signal select
Protect a shared map or variable sync.Mutex
Update a single number safely sync/atomic

These tools combine freely, as the crawler and the worker pool show.

Wrapping up

Back to our ride-sharing app. The ride requests arrive on a bounded channel. A pool of goroutines pulls them off and processes them. A WaitGroup tells main when it is safe to exit. A mutex guards any shared statistics. A select with default decides what to do when the queue is full, and a quit channel shuts it all down cleanly.

All the pieces from this post in one picture.

None of these tools is complicated on its own. The skill is knowing which question you are asking: who may touch this, who is done, or what needs to be passed along. Once you can tell those apart, the right tool is usually obvious.

Happy hacking!

Citation

Please cite this work as:

Makonda, Barnabas, "Go Concurrency, Explained Through a Busy Ride-Sharing App", Barnabas Makonda's blog, Oct 2026.

Or use the BibTeX citation:

bibtex
@misc{makonda2026concurrency,
  author = {Barnabas Makonda},
  title = {Go Concurrency, Explained Through a Busy Ride-Sharing App},
  howpublished = {Barnabas Makonda's blog},
  year = {2026},
  month = {oct},
  url = {https://blog.barnabasmakonda.workers.dev/posts/go-concurrency/},
}