The “Web Crawler” exercise in A Tour of Go asks you to turn a naive recursive crawler that re-fetches pages into a breadth-first, deduplicated crawler using sync.Mutex and a map[string]bool, so that each URL is fetched at most once and the program terminates instead of recursing forever. It appears in the Concurrency section of the tour, after the sync.Mutex page, and the exercise's own note (“in this exercise we'll use sync.Mutex”) tells you the intended tool: a mutex-guarded set of seen URLs plus a sync.WaitGroup to know when all fetches have finished. Because the tour is published in more than one edition and editor (the golang.org English tour, the go-tour offline binary, and translations that occasionally show slightly different starter code), the exact wording you see can vary; the mechanism below is stable across editions. This answer assumes the standard English tour skeleton in which Crawl calls crawl and each fetched page reports its own links back through a Fetcher interface.

The starter code, and why it fails

The classic skeleton is:

Two problems are built in. First, nothing records which URLs have already been visited, so a page that links back to an earlier page—the tour's fake graph has cycles, including a self-link—causes repeated fetches and, once links form a loop, unbounded recursion within the depth limit. Second, if you later parallelize the loop with goroutines, nothing waits for them, so Crawl can return (and main exit) before the fetches finish. The exercise exists to force you to solve both.

The intended teaching is not clever graph theory; it is the basic concurrency pattern “shared map, mutex, sync.WaitGroup.” The tour's note points at the sync.Mutex page immediately preceding the exercise, where a SafeCounter type wraps a map and a sync.Mutex.

What “breadth-first” actually requires here

The tour's comment says “Crawl uses fetcher to recursively crawl pages starting with url, to a maximum of depth.” Its fake fetcher contains a small graph that goes several levels deep. A correct solution must ensure no URL is fetched twice across the whole crawl, not merely within one depth level. Deduplication at fetch time—checking and setting the map before calling Fetch, under lock—is the standard approach. If you check after fetching, two goroutines can both fetch the same URL before either records it; the map must be claimed before the fetch, not after.

There is a subtlety worth naming because it appears in many published solutions: if you mark a URL seen before fetching, you must still handle fetch errors without “un-marking” it (a URL that errored should count as attempted, or you introduce races). The tour's fake fetcher never errors for the listed URLs, so this is a design choice rather than a test failure, but the cleaner pattern is “claim, then fetch, then log.”

Parallelism is optional for correctness but is the natural use of the goroutine-plus-WaitGroup pattern. The tour does not require concurrency; a serial breadth-first search with a mutex-guarded set passes. Nevertheless, the exercise sits in the Concurrency chapter, and the idiomatic solution launches each unvisited link as a goroutine and waits.

A complete, working solution

The sync import is required; if your skeleton already contains the Fetcher type in a separate file, only the crawler half needs to be replaced, not the fake fetcher. A main and a fake fetcher such as the tour's own fakeFetcher round it off:

That fake fetcher is the tour's, but a correct crawler must not depend on its exact links: the tour's grader (the offline go-tour) compares output with the reference behavior of the same fake fetcher it ships, and many published solutions rely on the same graph. If you replace the fake fetcher with your own, do not assume the URLs above; drive Crawl with whatever your fetcher exposes. The point being tested is not the exact set of URLs but the property that each URL is visited once and the call returns.

Why the map-before-fetch ordering matters

Consider what would happen if you checked the map after the fetch:

In a parallel crawl, links to and pkg/ links back to the root; two goroutines working on sibling branches can race on the same link and both pass the seen check before either writes it. You would see duplicate found: lines. Marking seen before fetching closes that window: the first goroutine to acquire the lock sets the flag, and the second returns early. That is the lesson, not the exact counting.

Also consider the interaction of defer c.wg.Done() with the early return when a URL is already seen. Because Done is deferred at the top, every call decrements the counter exactly once, including the no-op duplicates. If you place wg.Done() only at the end of the function you will likely skip it on early returns and hang on wg.Wait. This is a common failure mode: the program prints some “found” lines and then sits forever. The fix is a defer immediately after the entry to crawl, not conditional calls scattered through the body.

Where it stops applying: this is an exercise, not a crawler

The tour explicitly fakes the network; fakeFetcher has no latency, no rate limiting, no robots.txt, no cookies, no redirects, no TLS, and no memory bounds. Real crawlers must respect site policy (robots.txt), throttle requests, cancel in-flight requests via context.Context, and bound concurrency to avoid hammering a host; the tour's design handles none of this, and the exercise is not teaching it. The fake fetcher also returns the same fixed graph each run, which is why “which URLs appear” is a poor test; the warranty is about the deduplication and termination pattern, not the graph. Do not carry the recursive-goroutine fan-out to a production crawler: unbounded goroutines from a page with thousands of links will exhaust memory. A worker pool with a bounded semaphore or a context-scoped worker model is the standard extension.

There is also an ambiguity in “breadth-first.” The tour's own wording is “recursively crawl,” and with goroutines you cannot guarantee the order of found: lines—goroutine scheduling means output from a deeper page can appear before a shallower one that was launched later. If your output differs from the tour's reference output by ordering only, that is not a correctness bug; the go-tour grader has historically compared printout loosely (it retries, because goroutine output is nondeterministic), but confirm the behavior of the specific edition you are running rather than assuming. If you want strict output order, you have to serialize, which defeats the concurrency the chapter is teaching—usually not worth it.

Common failure modes on the grader

Several versions of the tour accept a range of solutions, but a few classes of bugs consistently fail. The first is unbounded recursion: the naive crawler loops through a cycle and never reaches depth limits when the depth limit is high. The second is a hung program from missing wg.Done on error or duplicate paths. The third is a “deadlock” caused by holding c.mu while calling fetcher.Fetch, which blocks all goroutines until the (fake, but conceptually slow) fetch returns; the lock should guard only the map access, not the network call. A fourth is a data race on c.seen that the race detector (go test -race or go run -race) will catch; a sync.Mutex is required, and map[string]bool alone is not safe for concurrent writers.

A further trap is launching goroutines in the loop without copying the URL. On Go 1.22 and later, loop variables are per-iteration, so for _, u := range urls { go c.crawl(u, ...) } is safe. On older toolchains (before Go 1.22), you must shadow the variable with u := u. The tour's published material predates the 1.22 change; if you copy an older solution and run it on an old installation, you can see the classic “all goroutines crawl the last URL” bug. The code above passes u as an argument, which avoids the issue entirely regardless of Go version.

Language and environment notes

The exercise is Go, not any other language, and the tour editors show fmt.Printf("found: %s %q\n", ...) as the output format; some translators change the phrasing, so match the format line your edition provides if a grader compares exact strings. The relevant Go standard packages are sync (for Mutex, WaitGroup) and fmt; you do not need sync/atomic here, though a counter-based alternative can use it. The tour pages are versioned with the Go release they ship with, and the concurrency lesson itself has been stable in its core (goroutines, channels, sync.Mutex) for many years. If you encounter a variant that passes a Crawl parameter as map[string]bool shared through a pointer or uses sync.Mutex embedded in a struct, treat it as an equivalent solution so long as deduplication happens before fetch and WaitGroup accounting is balanced.

Frequently asked questions about the exercise

Does the crawler have to be concurrent? No. A serial version that checks the seen map before each fetch and returns when depth reaches zero passes the exercise's correctness criteria. The concurrency is pedagogically the point because the exercise follows the sync.Mutex page, but the tour does not grade on parallelism.

How many “found” lines should I see? The tour's fake fetcher graph yields a fixed set for the given depth (roughly the root, pkg, cmd, fmt, and os when the depth allows); the exact count depends on the fake fetcher your edition ships and the depth in main. If you replace the fetcher, expect whatever URLs it defines, deduplicated. Do not hard-code a count.

Why does my program print and then hang? Almost always a missing WaitGroup.Done on an early-return path, or a seen map write while another goroutine is calling Fetch without the lock. Add defer c.wg.Done() at the top of crawl and hold the mutex only while touching the map.

Can I use a channel instead of a mutex? Yes, and it is idiomatic; a channel guarding a single “seen” verdict (a chan bool-returning token check) or a sync.Map with LoadOrStore are common alternatives. The tour notes mutex, so the canonical answer uses a mutex, but the graders generally accept equivalent deduplication.

Does the grader check exact output ordering? Historically the go-tour grader has been lenient about interleaving because goroutine output is nondeterministic; it retries rather than requiring a strict order. If you serialize the crawl, output is deterministic, but that is a choice, not a requirement. If you are worried, run the race detector and compare your set of URLs against the fake fetcher's graph rather than the line order.

The exercise is a compact demonstration of the pattern “claim a shared resource under a lock, then act, and count outstanding work with a WaitGroup.” Its lesson transfers to any fan-out task where duplicates must be suppressed—link checking, dependency resolution, cache warming—not just to crawling, which is why the tour uses it as the capstone of the concurrency section.