Sobes.tech
Senior

How would you organize work and session storage in horizontal scaling?

sobes.tech AI

Answer from AI

When scaling horizontally (multiple servers), storing sessions in a single server's memory becomes a problem because user requests may be directed to different servers.

Solutions:

  • Centralized session storage: use external storage such as Redis or Memcached, where all servers read and write sessions.
  • Sessions in a database: store sessions in a relational or NoSQL database.
  • JWT (JSON Web Tokens): store session state on the client as a token, which the server verifies without needing to store state.
  • Sticky sessions (session affinity): at the load balancer level, direct requests from the same user always to the same server (less scalable).

Example using Redis in PHP:

ini_set('session.save_handler', 'redis');
ini_set('session.save_path', 'tcp://redis-server:6379');
session_start();
// now sessions will be stored in Redis, accessible to all servers

This approach ensures session consistency and allows horizontal scaling of the application.