Fix Go "panic: sync: negative WaitGroup counter" — Extra Done Calls, Add(-1) Past Zero, and the Add-Before-Go Rule
This panic is an accounting error, not a scheduling mystery: somewhere, the subtractions outnumbered the additions. Below, each way the counter goes negative gets its own section with the exact panic, then the ordering rules that keep Add and Done paired, the reuse rule, and the fixes — defer Done in exactly one place, prefer WaitGroup.Go, and guard any callback that can fire twice.
Written November 21, 2026 · Tested with Go 1.26.4 · 20 min read
- The working baseline: Add before go, Done deferred, then Wait
- The same baseline with WaitGroup.Go
- The panic itself: one extra Done
- Add with a negative delta past zero
What this guide is
You hit panic: sync: negative WaitGroup counter when the subtractions from a sync.WaitGroup counter outnumber the additions, and the counter tries to step below zero.
The model is one integer. Add(delta) adds delta, which may be negative, to the counter. Done decrements the counter by one; it is equivalent to Add(-1), which is why the stack trace of this panic names Add even when the only call in your code was Done. Wait blocks until the counter is zero. If the counter goes negative, Add panics — that sentence is in the documentation for Add itself, and it is the whole mechanism. There is no second cause hiding behind this message: every program below that panics does so because, at the moment of one specific call, the running total of additions minus subtractions was already zero and one more subtraction arrived.
That framing tells you where to look. The panic line in the trace points at the subtraction that crossed zero, but the bug is almost never on that line. The bug is the mismatch: an Add that never ran, a Done that ran twice, a callback registered in two places, or an Add(-2) written against a counter the author believed held 2 when it held 1. Count the additions and the subtractions along every path the code can take, including error paths and early returns, and the extra subtraction shows itself.
All examples use Go 1.26.4. Each one is a single main.go in one module. Make the module once, from an empty directory:
$ mkdir waitgroup
$ cd waitgroup
$ go mod init example.com/waitgroup
go: creating new go.mod: module example.com/waitgroup
After that, swap in each program as the new main.go. Transcripts come from go run -trimpath main.go. The -trimpath flag shortens file paths in the trace, you see ./main.go:14 instead of a long absolute path. Line numbers match either way. Tested with Go 1.26.4.
The working baseline: Add before go, Done deferred, then Wait
Before the failures, the pattern every fix returns to. The Add runs in the parent, before each go statement. Each worker defers its Done as its first act, so the subtraction is registered before any of the worker's own code can return, panic, or take an unexpected branch. Wait runs last:
// main.go
package main
import (
"fmt"
"sync"
)
func main() {
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
fmt.Println("worker done")
}()
go func() {
defer wg.Done()
fmt.Println("worker done")
}()
wg.Wait()
fmt.Println("all workers done")
}
$ go run -trimpath main.go
worker done
worker done
all workers done
Two additions, two subtractions, counter back at exactly zero, Wait returns, and the completion line prints. Both workers print the same line here deliberately: with distinct lines, the two worker lines can print in either order from run to run, because nothing orders the two goroutines against each other. What is guaranteed is the part that matters — both worker lines print before all workers done, because Wait cannot return until both deferred Done calls have brought the counter to zero.
The documentation for Add states the ordering behind this shape: calls with a positive delta that occur when the counter is zero must happen before a Wait, and typically the calls to Add should execute before the statement creating the goroutine or other event to be waited for. The baseline obeys both halves literally: Add(2) precedes the go statements, and it precedes Wait.
The same baseline with WaitGroup.Go
Since Go 1.25 there is a form that removes the pairing by hand entirely. Go calls a function in a new goroutine and adds that task to the WaitGroup; when the function returns, the task is removed. There is no Add to write and no Done to forget or duplicate:
// main.go
package main
import (
"fmt"
"sync"
)
func main() {
var wg sync.WaitGroup
wg.Go(func() {
fmt.Println("worker done")
})
wg.Go(func() {
fmt.Println("worker done")
})
wg.Wait()
fmt.Println("all workers done")
}
$ go run -trimpath main.go
worker done
worker done
all workers done
Identical output, and the class of bug this guide is about cannot be written in this shape: the addition and the subtraction are the same method call, so they cannot drift apart across edits, error paths, or a second call site. The documentation for Add, Done, and the WaitGroup type itself all steer callers the same way: callers should prefer WaitGroup.Go. Two constraints come with it, both from the documentation for Go: the function passed to Go must not panic, and if the WaitGroup is empty, Go must happen before a Wait — the same Add-before-Wait rule, carried into the new form.
Reach for the explicit Add/Done form when the work is not a goroutine you are starting — an event, a callback, a task handed to code you do not control. Reach for Go whenever you are starting the goroutine yourself, which in most code is most of the time.
The panic itself: one extra Done
Here is the title panic in its smallest form. One addition, two subtractions, written sequentially so there is no scheduling question about which call crosses zero — the second Done does:
// main.go
package main
import (
"fmt"
"sync"
)
func main() {
var wg sync.WaitGroup
wg.Add(1)
fmt.Println("before extra Done")
wg.Done()
wg.Done()
fmt.Println("after")
}
$ go run -trimpath main.go
before extra Done
panic: sync: negative WaitGroup counter
goroutine 1 [running]:
sync.(*WaitGroup).Add(0xedd6b906020, 0xffffffffffffffff)
sync/waitgroup.go:118 +0x23a
sync.(*WaitGroup).Done(...)
sync/waitgroup.go:156
main.main()
./main.go:14 +0x89
exit status 2
Read the trace from the bottom up. main.main at ./main.go:14 is the second Done. Done forwards to Add — the frame sync.(*WaitGroup).Done(...) at sync/waitgroup.go:156 calls sync.(*WaitGroup).Add with the delta 0xffffffffffffffff, which is -1 in two's complement, and Add panics at sync/waitgroup.go:118 because the counter was already zero. The after line never prints. (The hex address in the Add frame is the WaitGroup's address and differs between runs; every other line of this trace is stable.)
In real code the extra Done rarely sits on the next line like this. It hides in shapes like these:
- A worker that defers
Doneand also callsDoneexplicitly on its success path, so success subtracts twice and only the error path subtracts once. - A
Donein a cleanup orfinally-style helper that also runs when the worker already completed normally. - A retry loop that re-runs a completion callback without re-running the matching
Add. - Two libraries, or a library and its caller, both taking responsibility for the same task's
Done.
The common thread is two owners for one subtraction. The fix is never to count more carefully at the panic site; it is to give each addition exactly one owner for its subtraction, which the fixed programs at the end do.
Add with a negative delta past zero
Done is not the only subtraction. Add itself accepts negative deltas, and a negative delta that overshoots the current counter panics in the same call, with the same message:
// main.go
package main
import (
"fmt"
"sync"
)
func main() {
var wg sync.WaitGroup
wg.Add(1)
fmt.Println("before Add(-2)")
wg.Add(-2)
fmt.Println("after")
}
$ go run -trimpath main.go
before Add(-2)
panic: sync: negative WaitGroup counter
goroutine 1 [running]:
sync.(*WaitGroup).Add(0x2848b6f8e060, 0xfffffffffffffffe)
sync/waitgroup.go:118 +0x23a
main.main()
./main.go:13 +0x76
exit status 2
The counter held 1. Add(-2) asks for a counter of -1, and Add panics instead of granting it. The trace is shorter this time — no Done frame, because the subtraction was written as Add directly — and the delta in the Add frame is 0xfffffffffffffffe, -2. This shape appears in code that batches completions: a finisher that subtracts the size of a completed batch, where the batch size was counted by different code than the code that performed the matching additions. When additions are counted in one place and subtractions in another, the two counts are two separate facts that can disagree; the panic is where the disagreement surfaces.
The defensive rule is mechanical: a negative Add is a claim that at least that many tasks are outstanding. If the code cannot point at the additions it is canceling, the subtraction does not belong there. Prefer one Done per completed task, issued by the task's owner, over arithmetic on the counter from a distance.
Done on a WaitGroup that was never Added to
The limiting case needs no additions at all. A single Done on a fresh WaitGroup is already one subtraction too many:
// main.go
package main
import (
"fmt"
"sync"
)
func main() {
var wg sync.WaitGroup
fmt.Println("before Done")
wg.Done()
fmt.Println("after")
}
$ go run -trimpath main.go
before Done
panic: sync: negative WaitGroup counter
goroutine 1 [running]:
sync.(*WaitGroup).Add(0x3d5a71a5a060, 0xffffffffffffffff)
sync/waitgroup.go:118 +0x23a
sync.(*WaitGroup).Done(...)
sync/waitgroup.go:156
main.main()
./main.go:12 +0x6d
exit status 2
Same message, same frames: Done at ./main.go:12 forwards -1 to Add, and a counter of zero minus one is negative. This shape matters because it is what the other shapes look like from the inside. Whenever the matching Add was skipped — an early return before it, a setup branch that registers the completion handler but not the addition, a task submitted to a pool whose Add lives in a wrapper that was bypassed — the first Done that arrives is this program, whatever the surrounding code intended. When you meet this panic in a log, do not only hunt for a doubled Done; hunt for a missing Add with equal suspicion. The trace cannot tell you which side of the pair went wrong, only that the totals disagree.
A completion callback that fires twice
Between the toy shapes and production code sits the shape that produces most real reports: a named completion function, called from more than one place. Here it is, reduced until the double call is visible:
// main.go
package main
import (
"fmt"
"sync"
)
func main() {
var wg sync.WaitGroup
wg.Add(1)
complete := func() {
wg.Done()
}
fmt.Println("before double complete")
complete()
complete()
fmt.Println("after")
}
$ go run -trimpath main.go
before double complete
panic: sync: negative WaitGroup counter
goroutine 1 [running]:
sync.(*WaitGroup).Add(0x7829e0f2060, 0xffffffffffffffff)
sync/waitgroup.go:118 +0x23a
sync.(*WaitGroup).Done(...)
sync/waitgroup.go:156
main.main.func1(...)
./main.go:13
main.main()
./main.go:17 +0x8b
exit status 2
The trace names the closure: main.main.func1 at ./main.go:13 is the wg.Done() line inside complete, reached from the second call at ./main.go:17. One task, one addition, and a completion signal with two call sites — a success handler and a deferred cleanup, a callback and a timeout, a message handler and its acknowledgment path. Any event that can be delivered twice, retried, or raced against a timeout will eventually call such a function twice, and the WaitGroup is where the second delivery becomes a crash instead of a no-op. The fixed version of this exact program is the last program in this guide.
Add inside the goroutine: the ordering rule
The remaining cause is not a wrong count but a wrong order. The documentation rule, stated for Add, is that calls with a positive delta that occur when the counter is zero must happen before a Wait. This program breaks it — the Add(1) sits inside the goroutine it is meant to register:
// main.go
package main
import (
"fmt"
"sync"
)
func main() {
var wg sync.WaitGroup
go func() {
wg.Add(1)
defer wg.Done()
fmt.Println("worker done")
}()
wg.Wait()
fmt.Println("main done")
}
There is no transcript for this program, deliberately: its outcome is a race, and printing one run's output as if it were the output would misstate what the program does. Two orderings are both legal executions. If the goroutine runs first, its Add(1) lands while the counter is zero but before Wait has returned, the worker prints, its deferred Done returns the counter to zero, and Wait releases. If the main goroutine runs first — the common outcome, since the new goroutine has to be scheduled — Wait sees a counter of zero and returns immediately, main done prints, and the program can exit before the worker prints at all: the work was never waited for, silently, with no panic. Variants of this shape are worse than either outcome alone: pair it with a Done owed to a different WaitGroup or a second Wait elsewhere, and the late Add lands against a counter state the author never pictured, which is one of the routes by which ordering bugs turn into the negative-counter panic in larger programs.
The rule that prevents all of it is the baseline's shape: the positive Add executes in the goroutine that is about to create the work, before the go statement, never inside the created goroutine. The documentation for Go carries the same rule in its own terms — if the WaitGroup is empty, Go must happen before a Wait — which is automatic when Go is called from the parent, as in the second program above, since calling Go is what creates the goroutine.
Reusing a WaitGroup after Wait
A WaitGroup is not single-use, but reuse has its own rule, stated in the documentation for both Add and Go: if a WaitGroup is reused to wait for several independent sets of events, new Add calls must happen after all previous Wait calls have returned. Sequential reuse — finish a set, wait for it, then start the next set — is legal and works:
// main.go
package main
import (
"fmt"
"sync"
)
func main() {
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
fmt.Println("first set done")
}()
wg.Wait()
fmt.Println("first Wait returned")
wg.Add(1)
go func() {
defer wg.Done()
fmt.Println("second set done")
}()
wg.Wait()
fmt.Println("second Wait returned")
}
$ go run -trimpath main.go
first set done
first Wait returned
second set done
second Wait returned
Four lines, in this order, every run: each set has one worker, so there is no second goroutine to race its line against, and each Wait orders its set's worker line before the line that follows it. The second Add(1) is legal precisely because it executes after the first Wait returned — the counter is zero, the previous set is fully finished, and the new positive addition starts a fresh set under the same Add-before-Wait rule as the first. What the rule forbids is overlap: starting the next set's additions while another goroutine is still inside the previous Wait, or worse, still working. If sets can overlap in your design, each set gets its own WaitGroup; sharing one across overlapping sets makes the counter a sum of two sets' tasks, and Wait then waits for both, which is a hang or an early return rather than a panic — a quieter bug than this guide's, and just as unwelcome.
One more reuse-adjacent rule from the type documentation, worth stating because violating it produces undefined behavior rather than a clean panic: a WaitGroup must not be copied after first use. Pass it by pointer, or declare it where all users share the one value; copying splits the counter into two counters that each see half the traffic.
The fixed callback: guard the subtraction, not the panic
Return to the double-firing callback. The task it signals still completes exactly once as far as the WaitGroup is concerned, because the completion event itself is idempotent in reality — the work finished once, and the second signal is a duplicate delivery, not a second completion. The fix makes the code say so, with a sync.Once standing between the callback and the Done:
// main.go
package main
import (
"fmt"
"sync"
)
func main() {
var wg sync.WaitGroup
var once sync.Once
wg.Add(1)
done := func() {
once.Do(func() { wg.Done() })
}
done()
done()
wg.Wait()
fmt.Println("completed once")
}
$ go run -trimpath main.go
completed once
Both calls to done run; only the first reaches wg.Done(), because once.Do runs its function exactly once no matter how many times it is called. The counter receives one subtraction for its one addition, Wait returns, and the duplicate delivery is absorbed where it arrives instead of detonating at the counter. An atomic flag compared-and-swapped around the Done does the same job; the Once is the clearer statement of intent. Use this guard only where duplicate delivery is a real property of the event — a callback, a completion handler, a close signal. Where the caller is your own sequential code, a doubled Done is a plain bug, and the guard would hide it; fix the call sites instead. And note what this fix is not: it is not a recover around the panic. Recovering would leave the counter's state unknown and the next Wait waiting on arithmetic nobody can reconstruct.
The fixes, ranked
Prefer WaitGroup.Go when you are starting the goroutine. The addition and the subtraction live in one method call and cannot be separated by an edit, an error path, or a second call site. Its constraints are that the function must not panic and that Go, like a positive Add on an empty WaitGroup, must happen before Wait.
Pair every explicit Add with exactly one Done, owned in one place. The worker that the addition registers is the owner of the subtraction: defer wg.Done() as the worker's first line, and no other Done for that task anywhere — not on the success path, not in cleanup, not in the caller.
Never call Done, or a negative Add, to clean up. A subtraction is a claim that a specific task finished. Conditional clean-up calls — a Done in an error handler for a task that may not have started, a batch Add(-n) for tasks counted elsewhere — are claims the code cannot back, and they are this panic's favorite habitat.
Keep positive Add calls in the parent, before the go statement and before Wait. An Add inside the goroutine it registers races the Wait it is meant to hold back. The same placement rule covers Go on an empty WaitGroup.
Reuse sequentially, or not at all. New additions for a fresh set come after every previous Wait has returned. Overlapping sets get separate WaitGroups. Never copy a WaitGroup after first use.
Guard genuinely duplicate-prone completion signals with sync.Once or an atomic flag. Callbacks, timeouts, and retried deliveries can fire twice by design; the guard absorbs the duplicate at the signal, so the counter only ever sees one subtraction per addition.
Which fix for which cause
- Extra
Donein the trace, delta -1 in theAddframe Cause: Two subtractions own one addition — a deferredDoneplus an explicit one, orDonein both a worker and its cleanup. Fix: One owner per task,defer wg.Done()once, remove every otherDonefor that task Addframe with a large negative delta, noDoneframe Cause: A negativeAddovershot the counter, usually a batch subtraction counted separately from the additions. Fix: Subtract per completed task withDonefrom the task's owner; drop counter arithmetic from a distance- Panic on the first
Doneof a task Cause: The matchingAddnever ran — an early return, a skipped setup branch, or a bypassed wrapper. Fix: Move theAddto the point of registration, before the work or handler exists, and audit the paths that reachDonewithout passing it - Panic inside a named completion callback or closure Cause: The callback can fire twice — success plus cleanup, delivery plus retry, work plus timeout. Fix: Guard the
Donewithsync.Onceor an atomic flag, after confirming duplicate delivery is a real property of the signal - Work intermittently not waited for, or a panic that comes and goes with load Cause: A positive
Addinside the goroutine it registers, racingWait. Fix: Move theAddinto the parent, before thegostatement; or switch the shape toWaitGroup.Gocalled from the parent - Panic or early
Waitreturn after a WaitGroup is reused Cause: The next set's additions began before the previousWaitreturned, or overlapping sets share one counter. Fix: Start each new set only after the previousWaitreturns; give overlapping sets their own WaitGroups
Checklist
- Count additions and subtractions along every path, including error paths, retries, and early returns. Any path where the totals differ is a panic or a hang waiting for its input.
- Search for every
Doneand every negativeAdd. For each one, name theAddit cancels and the single owner of the pair. A subtraction you cannot pair on sight is the bug, whether or not it has panicked yet. - Check that every worker's
Doneis deferred as its first statement, and that no task is also completed by a caller, a cleanup helper, or a success branch. - Check that every positive
Addexecutes before thegostatement that creates its work and before anyWaitthat must observe it — and that noAddsits inside the goroutine it registers. - Check reuse: new sets start only after all previous
Waitcalls have returned, and no WaitGroup is ever copied after first use. - List every completion callback that can be delivered twice, and confirm each is guarded by a
sync.Onceor an atomic flag before it reachesDone. - Where you start the goroutine yourself, convert the shape to
WaitGroup.Goand delete the manual pair entirely.
Related guides on this site
- Fix Go "panic: runtime error: comparing uncomparable type []int" — Slice, Map and Function Values as Map Keys and in == Comparisons, the neighboring interface panic: a comparison the compiler could not check detonating at run time, where this guide's panic is a counter the runtime refuses to take below zero.
- Fix Go "panic: runtime error: index out of range", Index Past the End, Negative Index, and the Off-by-One That Reaches Production, another off-by-one that reaches production — an index one step past the end there, a subtraction one step past zero here.
Sources
- The Go Programming Language, Package sync, for the WaitGroup documentation (a WaitGroup is a counting semaphore typically used to wait for a group of goroutines or tasks to finish; a WaitGroup must not be copied after first use), for
Add(adds delta, which may be negative, to the WaitGroup task counter; if the counter becomes zero, all goroutines blocked onWaitare released; if the counter goes negative,Addpanics; calls with a positive delta that occur when the counter is zero must happen before aWait; typically the calls toAddshould execute before the statement creating the goroutine or other event to be waited for; if a WaitGroup is reused to wait for several independent sets of events, newAddcalls must happen after all previousWaitcalls have returned; callers should preferWaitGroup.Go), forDone(decrements the WaitGroup task counter by one; it is equivalent toAdd(-1)), forGo(calls a function in a new goroutine and adds that task to the WaitGroup; when the function returns, the task is removed; the function must not panic; if the WaitGroup is empty,Gomust happen before aWait; if a WaitGroup is reused, newGocalls must happen after all previousWaitcalls have returned), and forWait(blocks until the WaitGroup task counter is zero).
Keep Exploring
The full Go hub \u2014 slices and maps, concurrency, and the standard library.
Every guide on the site in one list, grouped by topic.
Every browser-only checker and verifier on the site.
The C++, Python, Sysadmin, Rust, Go, and TypeScript hubs.