7
← Back to Pattern Arsenal
creational

Singleton

must know

Stage 1: Problem

The Problem

You are building a backend service that connects to a PostgreSQL database. Multiple modules — UserService, OrderService, ProductService — all need database access.

typescript
1class UserService {
2 async getUser(id: string) {
3 const pool = new Pool({ host: 'localhost', port: 5432, database: 'app', max: 20 });
4 const result = await pool.query('SELECT * FROM users WHERE id = $1', [id]);
5 pool.end();
6 return result.rows[0];
7 }
8}
9
10class OrderService {
11 async getOrders(userId: string) {
12 const pool = new Pool({ host: 'localhost', port: 5432, database: 'app', max: 20 });
13 const result = await pool.query('SELECT * FROM orders WHERE user_id = $1', [userId]);
14 pool.end();
15 return result.rows;
16 }
17}

Each service creates its own connection pool, connects, queries, and disconnects. This works for a single request. But now your app handles 500 requests per second.

What happens? Each request creates a new pool → new TCP connections → handshakes → authentication → query → teardown. You hit PostgreSQL's max_connections limit (default 100). The database starts refusing connections. Your app crashes under load.

Think about it: How would you ensure all services share a single connection pool, initialized once, without passing it everywhere manually?


Related Patterns

Confused With a Similar Pattern?

1 / 10 — Problem