Go race detection and failing fast

Go remains one of the languages I’m most productive in. Its combination of the rigour of static typing, but fluidity of Python, makes it both robust and easy to code in.
It’s also got some innovative features that help you catch those tough-to-find issues, particularly when they only occur in production. An example is the Go Race Detector.


The Race Detector detects when two, or more goroutines, access the same variable, and one of those access changes the variable. The most common way to enable the detector is during testing like so:

go test -race mytests

What’s also useful is that you can pass the flag to the build process and get a race-enabled binary to run in production.

Race reporting

When a race is detected a trace is printed, and execution continues. While this makes sense in a production environment it is often more useful for your tests to exit immediately — to make them fail fast. This is particularly useful when you have a large number of tests in your test suite, and unless the tests exit immediately, you find yourself wading through large amounts of output looking for the race report.
Fortunately you can change this behaviour easily by setting a specific option in the race detector, via an environment variable:

GORACE="halt_on_error=1" go test -race mytests

This highly useful option only gets a single mention in the Race Detector documentation, making it easy to miss. I now enable this option in all my Go-based unit testing. So make your race-detection tests easier to work with — make them fail fast.

Leave a Reply

Your email address will not be published. Required fields are marked *