Middle · Testing and performance
Parallel tests without shared state
Why does a test pass alone but fail with t.Parallel?
Try explaining this aloud before opening the answer. State your assumptions and trace a boundary case.
Reveal a strong answer
Parallel cases can overlap access to global variables, files, environment, shared database rows and fake servers. A shared mutable fixture makes outcomes depend on scheduling.
Create independent fixtures and unique names/temporary directories, and register cleanup with the right lifetime. Do not use sleep to order tests. Process-wide environment changes are incompatible with uncontrolled parallel execution.
Distinguish a flaky assertion from an actual product race. Use the race detector on representative paths and synchronize test barriers so failures reproduce without timing guesses.
Common trap
Capturing a loop variable is not the only cause of parallel-test bugs; modern loop semantics do not isolate fixtures.
Try it
Two tests clear the same Redis database before running. How do you make them safely parallel?
Worked solution
Use dedicated test instances or unique namespaced keys with scoped cleanup and no global FLUSHDB. Ensure the test account cannot reach production. A unique prefix does not help if cleanup still deletes every key.
Change the constraint
What changes if a subtest owns a resource whose parent defers Close before children run?
How did you do?
Self-assessment, not a compiler pass or interview score. Explain the reasoning unaided before marking understood.
Not marked. Progress stays on this browser, separate from course completion.
Primary references
Checked 2026-10-20. Use documentation for your pinned runtime, driver and tool version.