Fix a Race in Lazy Singleton Initialization for a Config Client

Last updated: November 29, 2026

Quick Overview

A shared configuration client is created lazily on first use, but under load the service sometimes builds two instances and one thread reads a half-initialized object. Explain the race and implement thread-safe lazy initialization.

Microsoft
Software Engineering Fundamentals
Software Engineer
Microsoft
November 29, 2026
Software Engineer
Technical Screen
Software Engineering Fundamentals
Easy

0

0

0 solved


A shared configuration client is created lazily on first use, but under load the service sometimes builds two instances and one thread reads a half-initialized object. Explain the race and implement thread-safe lazy initialization.

A common warm-up in Microsoft technical screens for C# and C++ roles, where lazy singletons (and Lazy<T>) appear in many services. The interviewer checks that you can name the check-then-act race, know why double-checked locking needs a re-check and safe publication, and know when a simpler eager or language-provided option is better.

What the Interviewer Expects
  • Identifies the check-then-act race between two threads
  • Implements locking with a re-check inside the lock
  • Explains safe publication and why the object must be fully built before assignment
  • Mentions simpler alternatives like eager init or Lazy<T>
  • Keeps the fast path lock-free after initialization
Key Topics to Cover
race conditions
double-checked locking
memory visibility
singleton pattern
How to Approach This
  1. Apply SOLID principles. Single Responsibility makes code testable, Open/Closed makes it extensible.
  2. Choose data structures based on access patterns, not familiarity.
  3. Prefer immutable data and message passing over shared mutable state for concurrency.
  4. Design APIs with RESTful conventions, versioning, meaningful errors, and pagination from day one.
Possible Follow-up Questions
  • Why is double-checked locking broken in some languages without volatile or memory barriers?
  • How would you handle a constructor that throws on the first attempt?
  • How does C# Lazy<T> with LazyThreadSafetyMode.ExecutionAndPublication behave?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice System Design Problems
Sample Answer
Requirements
  • Exactly one ConfigClient per process, built on first use (construction is slow, it fetches settings).
  • get() is called on every request from many threads, so after the first call it should not ...
High-Level Design

The naive code is if _instance is None: _instance = ConfigClient(). Two threads can both see None and both construct (check-then-act race). Wrapping all of get() in a lock fixes it but seria...


Submit Your Answer
Markdown supported