Lazy init of expensive clients with sync.Once

6124
0

Some dependencies are expensive to initialize (TLS-heavy clients, large config loads, SDKs that fetch metadata). I use sync.Once to ensure initialization happens exactly once, even under concurrent access. The important detail is capturing the initialization error and returning it consistently; Once only runs the function once, even if it fails, so you need to decide whether failures should be cached or retried. For most services, caching is correct: if the dependency can’t initialize, the service should fail fast or degrade explicitly. The snippet below implements a lazy client with Client() that either returns the initialized client or the init error. This keeps call sites simple and prevents subtle races where two goroutines try to initialize the same global client simultaneously.