Go / Advanced: Safety, Performance, and Service Design / Lesson 21
Once initialization and failure ownership
Coordinate Go sync.Once initialization and failure ownership.
On this page
Lesson goals
- Use sync.Once for a single initialization.
- Design explicit failure and completion handling.
- Interpret Once publication and the boundaries of later mutation, failure and panic.
- Design resource ownership or a synchronized retry state machine when once is insufficient.
Define initialization ownership
Some shared state must be initialized once before concurrent callers use it. sync.Once coordinates one invocation of a function for a particular Once value and makes completion visible to callers returning from Do. Define what is initialized, who owns it, and whether failure is recoverable before selecting this mechanism. A Once must not be copied after its first use.
Run initialization once
Every caller supplies a function to Do, but only the first call for that Once executes one. The sequential example prints the initialization message once even though Do is called twice. Which caller wins under concurrency is not a useful ordering guarantee. Keep the initialization function focused and avoid recursively invoking Do on the same Once, which would wait for itself.
package main
import (
"fmt"
"sync"
)
func main() {
var once sync.Once
init := func() { fmt.Println("initialized") }
once.Do(init)
once.Do(init)
}
initialized
Both calls share one Once, so initialization runs once.
Coordinate concurrent callers
The concurrent example starts several goroutines, each using the same Once, and waits for all of them before reading the result. The initialized value is written once and is read after worker completion. Its output does not depend on which goroutine invoked initialization. In a real program, protect later mutations separately; Once only coordinates the initialization function, not arbitrary subsequent access.
package main
import (
"fmt"
"sync"
)
func main() {
var once sync.Once
var workers sync.WaitGroup
value := 0
for i := 0; i < 3; i++ {
workers.Add(1)
go func() {
defer workers.Done()
once.Do(func() { value = 7 })
}()
}
workers.Wait()
fmt.Println(value)
}
7
All workers finish before the initialized value is read.
Choose a failure policy
Once.Do does not provide automatic retries. If the initialization function records an error, later callers need access to that result; if it panics, Do considers the call complete and later calls do not rerun it. Use a different, explicitly synchronized state machine when retries or reset are required. Document whether an initialization failure is permanent for the lifetime of the owner.
Test initialization paths
Test repeated calls and concurrent calls, then wait for all goroutines before asserting the initialized result. Include an injected initialization error and verify that callers receive the documented outcome. Run the race detector on the relevant workload. Avoid testing which goroutine initializes first, and do not mistake one clean detector run for proof of correctness under every schedule.
Define one owner and one initialization
A sync.Once value coordinates at most one invocation of the function supplied to its Do calls. The first call invokes its function; later calls on the same Once return only after that invocation has returned, without executing their own functions. Concurrent callers cannot rely on which caller wins. Decide what the shared owner initializes and ensure all callers use the same Once value; separate Once values represent separate initialization domains. A Once must not be copied after first use.
Do has no result or error return of its own. When initialization can fail, store the value and error in state owned by the same component, then have every caller inspect the published result after Do returns. A permanent cached failure may be appropriate for immutable configuration, but it is a policy choice. If retries, reset or changing inputs are required, design a separately synchronized state machine rather than expecting Once to rerun automatically. Test the exact failure and success contract with controlled dependencies.
Use the publication guarantee precisely
The return from the function passed to Do synchronizes before the return of any call to Do on that same Once value, as documented by the memory model. A caller that returns from Do may therefore observe the initialization writes under that relationship. Do not infer that arbitrary later mutations are protected: if a published map or struct is changed concurrently after initialization, those accesses need a separate lock, channel ownership or immutability policy.
Waiting for all worker goroutines is a different responsibility from Once’s initialization ordering. A worker can return from Do and continue doing work; an owner that needs all of that work completed should join those workers before releasing shared state. Add WaitGroup work before launch, or use explicit completion channels. Test concurrent callers by checking one initializer invocation and a published result after completion, without asserting which goroutine executed the function.
Make error and panic policies explicit
If an initializer stores a non-nil error and returns, Once considers the invocation complete. Later Do calls do not retry, so every caller needs the same documented stored failure or another explicitly designed outcome. Avoid returning a zero value as a valid resource when initialization failed. Clean up resources acquired before failure according to their owner, and test both the returned error category and partial state.
If the function passed to Once.Do panics, Do considers it to have returned; future Do calls do not invoke that function again. This differs from Go 1.22 OnceFunc, OnceValue and OnceValues, whose returned functions repeat the same panic value on every call when their function panics. These helpers can cache return values, including an error returned as one of the values, but they do not create a retry policy. Do not turn panic recovery into an undocumented retry mechanism.
Avoid recursion and hidden ownership
An initializer must not call Do recursively on the same Once: the inner call waits for the outer function to return while that function waits for the inner call. Map initialization dependencies and remove cycles instead of relying on a timeout or launching an unowned goroutine around the deadlock. Avoid placing a used Once in a value that is copied by assignment or a value-receiver method; keep one stable owner and use pointer access where appropriate.
If initialization opens a file, creates a client or starts a worker, state who owns the resource and how it is closed after successful use. On failure release only what was actually acquired. Context can bound a dependency that honors it, but a Once value still cannot be reset merely because a caller timed out. If initialization should retry after a transient failure, coordinate attempt state, waiting callers, cancellation and cleanup explicitly under a mutex or another proven protocol.
Test outcomes, not the winning schedule
Test sequential and concurrent calls against one Once, using a controlled counter and an explicit join to verify one invocation and consistent published data. Include injected error and panic behavior, nil-success handling where relevant, and later mutations under their own synchronization policy. Do not assert which goroutine wins. A race detector on a supported Go 1.22 execution can detect observed races, but a clean run does not prove every possible schedule or failure path safe.
For retry state machines, test failed attempts, concurrent waiters, successful retry, cancellation and cleanup separately, and define whether one attempt is active at a time. Use channels or barriers for readiness and completion, with a generous outer timeout as a hang guard rather than an exact sleep. The cases below are synthetic, unexecuted synchronization traces; they do not claim a runtime, race-detector or timing result.
20 worked examples
1. Sequential Do
Problem: Call Do twice on the same Once with one initializer.
- The first call invokes init.
- The second call sees the same Once already completed.
once.Do(init); once.Do(init); init increments calls
The fixture specifies call ordering and expected outcome without claiming execution.
Expected result: The initializer call count is one.
Why this result follows: One Once value permits at most one invocation.
2. Different functions
Problem: Call Do with f then g sequentially on one Once.
- The first call executes f.
- The later call does not execute g on that Once.
once.Do(f); once.Do(g)
The fixture specifies call ordering and expected outcome without claiming execution.
Expected result: Only f runs in this ordering.
Why this result follows: The first Do call uses its function for the Once value.
3. Concurrent winner
Problem: Two concurrent callers offer different initialization functions to one Once.
- Only one invocation can execute for this Once.
- The fixture does not order which caller arrives first.
concurrent once.Do(f), once.Do(g); same Once
The fixture specifies call ordering and expected outcome without claiming execution.
Expected result: Either f or g may be the single executed function.
Why this result follows: Once does not promise a particular concurrent winner.
4. Separate Once values
Problem: Two independent objects each own a Once and call Do once.
- The Once values are distinct initialization domains.
- Each value has its own first call.
object A.once.Do(initA); object B.once.Do(initB)
The fixture specifies call ordering and expected outcome without claiming execution.
Expected result: Both initializers can execute once.
Why this result follows: The at-most-once guarantee applies separately to each Once value.
5. Published value
Problem: An initializer sets value=7; a caller reads it after Do returns.
- The initialization write occurs before the function returns.
- That return synchronizes before the return of the caller’s Do.
once.Do(func(){value=7}); read value after Do
The fixture specifies call ordering and expected outcome without claiming execution.
Expected result: The caller observes the initialized value under the stated policy.
Why this result follows: Once publishes initialization through its documented ordering.
6. Later mutation
Problem: A map is initialized by Once then written concurrently without a lock.
- Once orders the initialization invocation and returning Do calls.
- It does not synchronize arbitrary later conflicting writes.
once.Do(init map); later concurrent map writes
The fixture specifies call ordering and expected outcome without claiming execution.
Expected result: The later accesses need a separate policy and can race.
Why this result follows: Initialization safety is not ongoing mutation safety.
7. Worker join
Problem: Two workers call Do and then perform additional work; the owner needs both finished.
- Returning from Do establishes initialization completion.
- The later worker work still requires its own completion signal.
workers: once.Do(init); extra work; Done; owner Wait
The fixture specifies call ordering and expected outcome without claiming execution.
Expected result: The owner waits for both workers before release.
Why this result follows: Once does not join arbitrary work after initialization.
8. Stored failure
Problem: An initializer records ErrConfig and returns; a later caller invokes Do.
- The first invocation completes even though it records an error.
- The later Do does not rerun initialization.
once.Do(init stores ErrConfig); once.Do(init); read stored error
The fixture specifies call ordering and expected outcome without claiming execution.
Expected result: The caller observes the stored ErrConfig under the API policy.
Why this result follows: Once does not retry a returned initialization failure.
9. Panic in Do
Problem: The function passed to Once.Do panics and a caller recovers externally.
- Do considers the panicking invocation to have returned.
- The later Do does not invoke f again.
once.Do(f panics); recover outside; once.Do(f)
The fixture specifies call ordering and expected outcome without claiming execution.
Expected result: The initializer is not retried by that Once.
Why this result follows: A panic completes Once.Do’s at-most-once decision.
10. OnceFunc panic
Problem: A Go 1.22 OnceFunc wrapper calls a function that panics with value X.
- The wrapped function is invoked only once.
- The returned function repeats the same panic value on each call.
g=sync.OnceFunc(f panics X); call g twice with recovery
The fixture specifies call ordering and expected outcome without claiming execution.
Expected result: Both calls panic with X under the documented helper contract.
Why this result follows: OnceFunc has an explicit repeated-panic behavior.
11. OnceValues failure
Problem: OnceValues wraps a function returning a zero value and ErrInit.
- The wrapped function executes only once.
- Its returned pair is reused by subsequent calls.
get=sync.OnceValues(func()(Value,error){return zero,ErrInit}); call twice
The fixture specifies call ordering and expected outcome without claiming execution.
Expected result: Both calls return the stored zero value and ErrInit.
Why this result follows: Caching an error result is not an automatic retry policy.
12. Recursive Do
Problem: An initializer calls Do recursively on the same Once.
- The inner Do waits for the outer invocation to finish.
- The outer function cannot finish while waiting for the inner call.
once.Do(func(){ once.Do(other) })
The fixture specifies call ordering and expected outcome without claiming execution.
Expected result: The calls deadlock in this dependency cycle.
Why this result follows: Do must not recursively invoke itself on the same Once.
13. Copied Once
Problem: A struct containing a used Once is copied and both copies are used.
- The synchronization value was used before being copied.
- The sync contract says Once must not be copied after first use.
owner.once used; copied=owner; both call Do
The fixture specifies call ordering and expected outcome without claiming execution.
Expected result: The design violates the usage contract.
Why this result follows: One stable owner must retain its synchronization value.
14. Different input
Problem: First caller initializes with configuration A; later caller supplies B to the same Once.
- The first invocation completes the Once.
- The later function using B is not run.
once.Do(init A); once.Do(init B)
The fixture specifies call ordering and expected outcome without claiming execution.
Expected result: The shared state remains the result of A under this ordering.
Why this result follows: Once does not reinitialize for a later input.
15. Retry state machine
Problem: A transient initialization error must be retried after backoff.
- A completed Once would not rerun the failed function.
- A separate synchronized state machine can coordinate later attempts.
state={idle,running,ready}; mutex coordinates attempts; retry policy bounded
The fixture specifies call ordering and expected outcome without claiming execution.
Expected result: Use an explicit bounded retry design, not reset of a used Once.
Why this result follows: Retry semantics require more state than at-most-once invocation.
16. Failure cleanup
Problem: Initialization opens a temporary resource then fails validation.
- The initializer owns the successfully acquired resource.
- Failure cleanup runs before the initializer returns its stored error.
acquire fake resource; validation fails; close acquired resource; store error
The fixture specifies call ordering and expected outcome without claiming execution.
Expected result: The resource is closed and callers observe the documented error.
Why this result follows: At-most-once coordination does not replace resource ownership.
17. OnceValue result
Problem: A Go 1.22 OnceValue function computes the integer 5.
- The supplied function is invoked once.
- The returned function reuses the computed value.
get=sync.OnceValue(func() int { return 5 }); call get twice
The fixture specifies call ordering and expected outcome without claiming execution.
Expected result: Both calls return 5.
Why this result follows: OnceValue coordinates and retains one returned value.
18. Mutable cached result
Problem: OnceValue returns a pointer to a mutable record used concurrently.
- The helper coordinates computing and returning the pointer.
- It does not synchronize later mutations of the pointed-to record.
get returns *Record once; callers mutate record concurrently
The fixture specifies call ordering and expected outcome without claiming execution.
Expected result: Callers need an additional ownership or synchronization policy.
Why this result follows: Cached initialization is not a lock for later data access.
19. Concurrent result test
Problem: Three callers use one Once and join before checking a controlled invocation count.
- All callers share the same Once value.
- The join observes their completion before the assertion.
wg.Add(3); callers Do(init increments protected count); wg.Wait(); inspect
The fixture specifies call ordering and expected outcome without claiming execution.
Expected result: The expected initializer count is one without choosing a winning goroutine.
Why this result follows: The test checks the contract rather than a scheduler order.
20. Scope of a synthetic race receipt
Problem: Evaluate a synthetic receipt for concurrent Once callers with a later mutation path unrun.
- In the hypothetical fixture, the test joined two workers that called Do and read immutable value 7 after return.
- The receipt states no race was observed for that supported path, but it did not exercise the later map mutation.
synthetic receipt (not an actual run):
workers=2; each calls once.Do(init value=7), reads immutable value, then joins
race result=no race observed on this supported fixture
later concurrent map mutation=not run
The fixture specifies call ordering and expected outcome without claiming execution.
Expected result: The synthetic receipt supports only a scoped initialization-path observation and does not establish safety of the unrun mutation.
Why this result follows: Race-detector evidence is limited to paths and schedules actually exercised.
Common errors and fixes
Initialization unexpectedly does not retry
- Why it happens
- Once.Do only executes the function once.
- How to fix it
- Use a synchronized retry design if required.
- Prevent it next time
- Document the failure policy.
Concurrent code races after initialization
- Why it happens
- Later mutations were assumed to be protected by Once.
- How to fix it
- Synchronize subsequent access separately.
- Prevent it next time
- Run race-enabled tests.
Initialization deadlocks
- Why it happens
- The function calls Do recursively on the same Once.
- How to fix it
- Remove the recursive dependency.
- Prevent it next time
- Keep initialization dependencies acyclic.
20 practice exercises
1. How many times does the first example print initialized?
Show hint
Both calls share the same Once value.
Show worked solution
Once. Both calls use the same Once value, and only the first executes the function.
The first call executes the function that prints initialized and the second Do returns without invoking it again. The sequential example therefore prints once; it does not determine which caller might win in a concurrent case.
Check your solution
- initialized is printed once.
- The second Do does not invoke the function again.
2. Does Once protect a later change to the initialized value?
Show hint
Separate publication of initialization from ongoing synchronization.
Show worked solution
No. It coordinates the function passed to Do. Later concurrent mutations need their own synchronization.
Once coordinates the function passed to Do and publishes its writes to callers after return, but does not protect later conflicting mutations. Use a separate lock, ownership or immutability policy and join workers before releasing shared state.
Check your solution
- The initialized value is visible after Do returns under the contract.
- Later concurrent mutations follow an independent synchronization policy.
3. Five callers use one Once to load configuration. Design a test of one invocation and consistent publication without assuming which caller wins.
Show hint
Share the same Once and join all callers before asserting.
Show worked solution
Use a controlled initializer that records its invocation and produces a known immutable configuration. Start and join five callers, then assert one invocation and the same published value for each; do not assert a particular winning goroutine. Synchronize the test’s own counter and result collection as needed.
Check your solution
- The initializer invocation count is one.
- All completed callers observe the documented configuration.
4. Two objects each have their own Once, but the design requires one shared initialization. Explain the mismatch and repair ownership.
Show hint
At-most-once applies per Once value.
Show worked solution
Separate Once fields permit one invocation per object, so both may initialize. Put one stable Once and its result in the shared owner and have both objects use that owner, with an explicit lifetime. Test two objects concurrently and assert the shared initializer runs once.
Check your solution
- Both objects reference the same initialization owner.
- The shared initializer runs once across both callers.
5. A function offers initA and a concurrent caller offers initB to the same Once. The result must not depend on the winner. Redesign the API.
Show hint
Once does not promise which concurrent call wins.
Show worked solution
Bind a single initializer and configuration to the owner before concurrent use, rather than letting callers provide conflicting functions. Test concurrent calls with the same owner and verify the published value and one invocation; reject incompatible configuration at construction.
Check your solution
- Only one agreed initializer is associated with the owner.
- Concurrent callers receive the same documented result.
6. An initializer sets a configuration pointer, and callers read it after Do returns. Explain the ordering and a condition that would invalidate the simple reasoning.
Show hint
Once publishes the initializer’s writes, not arbitrary later writes.
Show worked solution
The initializer’s return synchronizes before each returning Do call on that Once, so the initialization writes are visible to callers after Do. If a caller later mutates the pointed-to object concurrently, that later access needs separate synchronization or immutability. Test publication and later-access policy separately.
Check your solution
- Callers read the initialized value after Do returns.
- Later mutable access follows a separate documented policy.
7. Once initializes a map, after which two workers update it concurrently. Design a safe access policy and test.
Show hint
Initialization ordering is not ongoing mutual exclusion.
Show worked solution
Keep the initialized map immutable, or protect every later read and write with the same mutex or ownership protocol. Coordinate two workers and join them before checking the invariant; a supported race-enabled run is supplementary evidence for exercised paths only.
Check your solution
- Every later mutable map access follows one policy.
- Both workers complete and the invariant holds in the controlled test.
8. An initializer stores ErrConfig and returns. The next caller expects a retry. Explain the actual Once behavior and define a permanent-failure contract.
Show hint
A returned failure still completes the invocation.
Show worked solution
Once.Do does not rerun the function after it returns, even if the function stored an error. Keep the error with the initialized state and return the documented ErrConfig to every caller; test one invocation and consistent failure. Use a different synchronized design if retry is required.
Check your solution
- The initializer runs once despite multiple callers.
- Each caller receives the documented stored failure.
9. Initialization must retry a transient failure, with at most one active attempt and several waiting callers. Sketch state and tests.
Show hint
A used Once cannot be reset into a retry mechanism.
Show worked solution
Use an explicitly synchronized state machine such as idle, running and ready, with a shared completion signal for waiters and a bounded retry policy after failure. Define cancellation and cleanup of each attempt. Test concurrent waiters, first failure, later success and one-active-attempt invariant.
Check your solution
- No more than one initialization attempt is active at a time.
- Waiters receive the documented failure or later successful result.
10. A Once.Do initializer panics; a caller recovers and calls Do again. Compare this with OnceFunc in Go 1.22.
Show hint
The two APIs have different documented panic behavior.
Show worked solution
Once.Do treats the panicking call as completed and does not invoke its function again. OnceFunc invokes its function once but its returned function panics with the same value on every call. Test each behavior in a controlled recovery fixture without presenting recovery as retry.
Check your solution
- A later Do call does not rerun the panicking initializer.
- Each call to the OnceFunc wrapper repeats the documented panic value.
11. OnceValues wraps an initializer that opens a fake resource and fails with ErrUnavailable. Three callers invoke it. Design checks for attempts, cleanup and results.
Show hint
The wrapper caches the result pair, but resource cleanup belongs to the initializer.
Show worked solution
Have the initializer record one open and close the acquired resource once before returning (nil, ErrUnavailable). Coordinate and join three callers; the fake should record one attempt and one close while each caller receives the cached failure. If transient failure needs retry, design a separate state machine instead of resetting OnceValues.
Check your solution
- The fake records one open and one close across three callers.
- Every caller receives ErrUnavailable without an implicit retry.
12. An initializer opens a temporary file then fails to parse configuration. Define cleanup and result publication tests.
Show hint
Once coordinates invocation but does not own the file automatically.
Show worked solution
Close the acquired file on the failure path, store or return the documented initialization error and prevent callers from treating a zero resource as successful. Use a fake or disposable temporary resource to verify one close and consistent error across callers; test successful ownership transfer separately.
Check your solution
- The acquired file is closed once on initialization failure.
- All callers receive the documented failure rather than a valid resource.
13. A used struct containing Once is copied by a value-receiver method. Explain the contract violation and propose an API change.
Show hint
Synchronization values must not be copied after first use.
Show worked solution
Keep the Once in a stable owner and use pointer receivers for methods operating on it. Avoid returning or assigning copies after use, and review nested structures and tests for accidental copies. Verify both callers share the intended owner and initialization count.
Check your solution
- No used Once is copied by the revised API.
- Both callers use the same owner and observe one initialization.
14. An initializer calls the same Once recursively through a helper. Diagnose the wait and redesign its dependencies.
Show hint
The inner Do waits for the outer invocation to return.
Show worked solution
The outer initializer cannot return until the helper returns, while the helper’s inner Do waits for that same outer return, creating a deadlock. Remove the cycle or split initialization into acyclic dependencies with clear ownership; test the dependency order using controlled signals and a hang guard.
Check your solution
- No initializer recursively enters the same Once.
- The controlled initialization completes under the acyclic dependency plan.
15. A caller cancels while waiting for a long initializer inside Once.Do. Can Once itself be reset or forcibly stop the initializer? Design a suitable boundary.
Show hint
Once has no reset or forced cancellation operation.
Show worked solution
The initializer must use a dependency that honors an explicitly passed context or another supported bounded exit; a caller’s cancellation alone does not forcibly stop arbitrary work. If later retry is required, use a separate synchronized state machine rather than resetting a used Once. Test cancellation and worker completion.
Check your solution
- The initializer’s blocking dependency has a documented exit path.
- Cancellation and completion are observed separately.
16. The first caller supplies configuration A and a later caller supplies B to the same Once. The API requires B to take effect. Explain why Once is insufficient and propose an alternative.
Show hint
One completed Once does not reinitialize for new input.
Show worked solution
Once keeps the first initialization decision and ignores the later function, so it cannot implement changing configuration by itself. Use a separately synchronized update or versioned immutable snapshot design with a clear replacement contract. Test A, update to B and concurrent readers under that policy.
Check your solution
- The revised API can publish B according to its update contract.
- Concurrent readers observe a valid synchronized state.
17. A test checks only that all callers return, but never checks initializer count or the stored error. Strengthen the oracle.
Show hint
Completion alone does not prove the initialization contract.
Show worked solution
Use a controlled initializer with a synchronized invocation counter and a chosen failure. Join all callers, assert the count is one and each receives the documented error, and verify acquired resources were cleaned up. Add a success fixture separately.
Check your solution
- The failure fixture observes one invocation and consistent error.
- The owned resource cleanup and success path are checked separately.
18. A race-enabled run covers successful initialization only; the failure and later-mutation paths were skipped. Write the bounded conclusion and next test.
Show hint
The race detector observes exercised executions, not all schedules.
Show worked solution
Report the tested successful path and environment with no observed race, and mark failure and mutation untested. Add controlled concurrent failure callers and a synchronized later-mutation test, then run the supported configuration and record its actual outcome. Do not claim universal race freedom.
Check your solution
- The report identifies both skipped paths.
- The next tests exercise failure and later-access policy.
19. A worker returns from Do and then writes a result; the owner reads the result immediately after its own Do returns. Explain why an additional join is needed.
Show hint
Once orders initializer completion, not all later worker work.
Show worked solution
The owner’s returning Do observes initialization, but it does not wait for another worker’s subsequent write. Use a completion channel or WaitGroup that orders that write before the owner reads, and test the join with a controlled delayed worker. Avoid reading shared state before the join.
Check your solution
- The owner waits for the worker’s post-initialization work.
- The result read occurs after the completion signal.
20. OnceValue returns a pointer to a cache initially jobs=0. Two workers add 2 and 3 to jobs; design an access policy, independent snapshot and test.
Show hint
OnceValue coordinates pointer creation, not later map updates.
Show worked solution
Protect every map read and update with one mutex, join both workers, then copy the integer entries under the lock into an independent snapshot. After completion jobs is 5; mutate the snapshot and verify the cache remains 5. Use OnceValue only for initialization and do not infer it protects the increments.
Check your solution
- After both workers join, the snapshot has jobs=5.
- Mutating the copied snapshot does not change the protected cache.
Key takeaways
- Once coordinates one initialization, not retries.
- Wait for workers and synchronize later mutations.
- Once coordinates one invocation per value and does not automatically retry failure.
- Initializer return publishes its writes but does not protect later mutation.
- Once.Do and OnceFunc/OnceValues have different panic policies.