Skip to content

Stateful vs Stateless Backends

Course: Singleton Pattern, Backend State management and Pub Subs - chapter 2

Common interview question

Usually when you write HTTP servers, they dont hold any state

This means, they don’t have any in memory variables that they use

They usually rely on the database for state

  1. Users can connect to a random server, there is no need of stickiness
  2. Can autoscale up and down easily and simply decide where to route traffic based on CPU usage.

A lot of times, you make servers hold state Good examples of this are

  1. Creating an in memory cache - https://github.com/code100x/cms/blob/e905c71eacf9d99f68db802b24b7b3a924ae27f1/src/db/Cache.ts#L3
  2. Storing the state of a Game in case of a realtime game - https://github.com/code100x/chess/blob/main/apps/ws/src/Game.ts#L41-L47
  3. Storing a list of 10 most latest chats in memory for a chat application

In case 1, there is no need of stickiness

In case of 2 and 3, there is need of stickiness

Making sure that the user who is interested in a specific room, gets connected to a specific server.

Good question to ask at this point is - How to store state in a JS project?