SingletonVSStatic / DI Singleton
The Problem
Scenario A β Classic Singleton territory: You're writing a library that will be used by other teams. It needs a connection pool that is lazily initialized on first use, globally accessible, and guaranteed to be one instance regardless of how many modules import it. You don't control the consuming application's DI container.
Scenario B β DI-managed singleton territory:
Your NestJS app has a ConfigService that loads env vars once and is injected into 30 services. It must be one instance (to avoid re-parsing), but each test must be able to swap it with a mock. You use NestJS's default scope β the container manages the lifecycle.
Why They Look Alike
All three provide "one instance, used everywhere." From the caller's perspective the behavior is identical: you call a method, you get the same state every time.
All three give you "one thing, used many places." The difference is who controls the lifecycle and what you can replace in tests.
The Core Difference
| Aspect | Classic Singleton | Static Class | DI Singleton |
|---|---|---|---|
| Instance | One, self-managed via getInstance() | No instance β just a namespace for static methods | One, managed by the DI container |
| Lifecycle control | The class itself (lazy init in getInstance) | None (loaded when module is imported) | The container (created on first inject) |
| Testability | Hard β must reset static state between tests | Hardest β can't swap or mock without hacks | Easy β inject a mock via overrideProvider |
| State | Can hold mutable instance state | Can hold static mutable state (dangerous) | Instance state, scoped by container |
| Inheritance | Possible but awkward | Not possible (no instance to override) | Natural β inject an interface, swap impl |
| When destroyed | Never (lives until process exits) | Never | Container controls (module dispose) |
One sentence: Classic Singleton owns its lifecycle (hard to test); static class has no lifecycle (impossible to swap); DI singleton lets the container own the lifecycle (testable).
Side-by-Side Code
Classic Singleton β Self-managed
| 1 | class ConnectionPool { |
| 2 | private static instance: ConnectionPool | null = null; |
| 3 | private connections: Connection[] = []; |
| 4 | |
| 5 | private constructor() { |
| 6 | this.connections = this.createPool(10); |
| 7 | } |
| 8 | |
| 9 | static getInstance(): ConnectionPool { |
| 10 | if (!ConnectionPool.instance) { |
| 11 | ConnectionPool.instance = new ConnectionPool(); |
| 12 | } |
| 13 | return ConnectionPool.instance; |
| 14 | } |
| 15 | |
| 16 | query(sql: string): Promise<Result> { |
| 17 | const conn = this.connections[0]; |
| 18 | return conn.execute(sql); |
| 19 | } |
| 20 | |
| 21 | // Testing pain: must add this or tests leak state |
| 22 | static resetForTesting(): void { |
| 23 | ConnectionPool.instance = null; |
| 24 | } |
| 25 | } |
| 26 | |
| 27 | // Usage β tight coupling to the class |
| 28 | const pool = ConnectionPool.getInstance(); |
Static Class β No instance at all
| 1 | class MathUtils { |
| 2 | static clamp(value: number, min: number, max: number): number { |
| 3 | return Math.min(Math.max(value, min), max); |
| 4 | } |
| 5 | |
| 6 | static roundToDecimals(value: number, decimals: number): number { |
| 7 | const factor = 10 ** decimals; |
| 8 | return Math.round(value * factor) / factor; |
| 9 | } |
| 10 | } |
| 11 | |
| 12 | // Fine for pure stateless utilities. Terrible for anything with state. |
DI Singleton β Container-managed (NestJS)
| 1 | @Injectable() // default scope = singleton |
| 2 | class ConnectionPool { |
| 3 | private connections: Connection[]; |
| 4 | |
| 5 | constructor(private config: ConfigService) { |
| 6 | this.connections = this.createPool(config.get('POOL_SIZE')); |
| 7 | } |
| 8 | |
| 9 | query(sql: string): Promise<Result> { |
| 10 | const conn = this.connections[0]; |
| 11 | return conn.execute(sql); |
| 12 | } |
| 13 | } |
| 14 | |
| 15 | // Testing β easy mock |
| 16 | const module = await Test.createTestingModule({ |
| 17 | providers: [ |
| 18 | ConnectionPool, |
| 19 | { provide: ConfigService, useValue: { get: () => 2 } }, |
| 20 | ], |
| 21 | }).compile(); |
| 22 | |
| 23 | const pool = module.get(ConnectionPool); // testable instance |
Decision Rules
| Signal | Choose | Why |
|---|---|---|
| Pure utility functions with no state (math, formatting) | Static class | No instance needed; just a namespace |
| You're writing a library with no DI container available | Classic Singleton | Self-contained lifecycle |
| You're in a NestJS/Angular/Spring app | DI Singleton | Container manages it; testable |
| Tests need to swap the implementation | DI Singleton | overrideProvider is trivial |
| Global mutable state (config, cache, pool) | DI Singleton > Classic Singleton > Static | DI is easiest to test and replace |
| You need to guarantee exactly one instance across dynamic imports | Classic Singleton | Module cache handles it; DI can too |
The Trick Question
"Your NestJS service is
@Injectable()with default scope. Is it a Singleton pattern?"
It is a singleton in behavior (one instance per container), but it is not the GoF Singleton pattern. The GoF pattern means the class itself enforces single-instance via a private constructor and static getInstance(). In NestJS, the class is a normal class β the container decides to create one instance. The distinction matters: GoF Singleton is hard to test because the class controls its own lifecycle. DI singleton is easy to test because the container controls it.
Interview Angles
Q: Why is classic Singleton considered an anti-pattern by many?
It creates hidden global state. Any code can call getInstance() and mutate shared state. Tests can't isolate it without a resetForTesting() hack. It violates DIP β callers depend on the concrete class, not an abstraction.
Q: When is classic Singleton still the right choice?
When you don't have a DI container (browser libraries, CLI tools, standalone utilities) and need lazy initialization of expensive shared resources. Even then, consider a module-scoped let variable with an init function.
Q: What's the difference between module-scope and Singleton in Node.js?
A module-scope variable (let pool: Pool | null = null; export function getPool()) behaves like a Singleton because Node caches modules. But it's simpler β no class ceremony, no getInstance(). It's the pragmatic Node.js alternative to GoF Singleton.
Q: Can you have multiple singletons in NestJS?
Yes β if you use REQUEST or TRANSIENT scope on some providers while others stay default (singleton). Each scope is per-container, so multiple containers (e.g., in microservices) each have their own "singleton."