Singleton pattern in JS


Before diving deep into singleton pattern we need to know what are State full and Stateless node.js application/server.
Stateless Server
Usually when we write HTTP servers, they don’t hold any state
. This means, they don’t have any in memory variables that they use. They usually rely on the database
for state/data
to read and write data.
Advantages
Independence - Users can connect to a random server, there is no need of stickiness
Scalability - Can auto-scale up and down easily and simply decide where to route traffic based on CPU usage.
Simplicity - They are simpler to design and implement, making them suitable for various use cases.
State full Servers
A lot of times, we make servers hold state/data
, for which we need to create in memory variable/object to store data under application itself.
Advantages
Persistence - They maintain context between client interactions, allowing for persistent sessions and personalized experiences, (we need to apply stickiness if user needs to connect same server).
Complex Logic - State management can add complexity to the server-side design and potentially impact scalability.
Use Cases - State full servers are suitable for applications requiring user sessions, real-time collaboration(real-time game), or applications with persistent data across requests
Stickiness (session persistence)
Stickiness refers to the load balancer (server) routing all requests from a client to the same server for the duration of a session.
Example - Making sure that the user who is interested in a specific
room, gets connected to a specific
server. (online chess game, )
Drawbacks of using stickiness:
Reduced Scalability:
If a server that's handling a sticky session goes down, all the associated users will be affected.
Increased Complexity:
Managing sticky sessions requires additional configuration on the load balancer and potentially adds complexity to the application's architecture.
Singleton pattern
The Singleton pattern is usable under State full servers, singleton pattern in JavaScript ensures that only one instance of a class is created and provides a global point of access to it. This pattern is useful when exactly one object is needed to coordinate actions across the system.
Benefits :
No one can create other instance of the class, from anywhere under that application.
It is usefull when we are creating an state-full application/server where we need to use single place for our data to store in-memory.
Syntax
class Singleton {
private static instance: Singleton;
private data = [];
private constructor() {
// Private constructor ensures that a new instance cannot be created from outside
}
public static getInstance(): Singleton {
if (!Singleton.instance) {
Singleton.instance = new Singleton();
}
return Singleton.instance;
}
// ...other methods
}
const instance1 = new Singleton();
const instance2 = new Singleton();
console.log(instance1 === instance2); // true
instance1.add('item1');
console.log(instance2.get()); // ['item1']
Explanation
- We have created a class Singleton,
class Singleton {
}
- Below line of code, create a static instance of the class, and next line creates a state under the same class
private static instance: Singleton;
private data = [];
- Here we have written private constructor ensures that a new instance cannot be created from outside.
private constructor() {}
public static getInstance():Singleton{...}
- we can call using class, and the condition says if instance already created return it, if not create and return new instance.
public static getInstance(): Singleton {
if (!Singleton.instance) {
Singleton.instance = new Singleton();
}
return Singleton.instance;
}
- We can create 2 different instances and check they are same or not, and also try to update state using one instance and can check using other instance we will see both are using same instance
const instance1 = new Singleton();
const instance2 = new Singleton();
console.log(instance1 === instance2); // true
instance1.add('item1');
console.log(instance2.get()); // ['item1']
By this article we learned - stateless and state full servers, stickiness, singleton pattern in JS
Thank you for reading,
if any suggestion please give me.
Subscribe to my newsletter
Read articles from Ajay Dewangan directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
