负载均衡会话保持(session persistence, session stickiness, session affinity)

来源:互联网 发布:nginx lvs 负载均衡 编辑:程序博客网 时间:2024/05/21 06:39

问题的产生

An important issue when operating a load-balanced service is how to handle information that must be kept across the multiple requests in a user’s session. If this information is stored locally on one backend server, then subsequent requests going to different backend servers would not be able to find it. This might be cached information that can be recomputed, in which case load-balancing a request to a different backend server just introduces a performance issue.

解决方案


  1. ip 相同则转发到相同的 backend server(nginx: ip_hash)
    问题1:ISP 的 ip 可能是动态变化的。
    问题2:同一局域网下出口 ip 都是同一个,如果该 ip 访问量巨大,会导致负载均衡失效。
  2. session 数据相同则转发到相同的 backend server(nginx: hash)

One basic solution to the session data issue is to send all requests in a user session consistently to the same backend server. This is known as persistence or stickiness. A significant downside to this technique is its lack of automatic failover: if a backend server goes down, its per-session information becomes inaccessible, and any sessions depending on it are lost.
问题:如果 backend server 崩掉,则会导致服务不可用。
  • 保存 session 数据
    腾讯云-产品文档-会话保持原理
    1) 数据库存放
    Session信息存储到数据库表以实现不同应用服务器间Session信息的共享。此种方式适合数据库访问量不大的网站。
    优点:实现简单
    缺点:由于数据库服务器相对于应用服务器更难扩展且资源更为宝贵,在高并发的Web应用中,最大的性能瓶颈通常出现在数据库服务器。因此如果将 Session存储到数据库表,频繁的数据库操作会影响业务。
    2) 文件系统存放
    通过文件系统(比如NFS)来实现各台服务器间的Session共享。此种方式适合并发量不大的网站。
    优点:各台服务器只需要mount存储Session的磁盘即可,实现较为简单。
    缺点:NFS对高并发读写的性能并不高,在硬盘I/O性能和网络带宽上存在较大瓶颈,尤其是对于Session这样的小文件的频繁读写操作。
    3) Memcached 存放
    利用Memcached来保存Session数据,直接通过内存的方式读取。
    优点:效率高,在读写速度上会比存放在文件系统时快很多,而且多个服务器共用Session也更加方便,将这些服务器都配置成使用同一组memcached服务器就可以,减少了额外的工作量。
    缺点:一旦宕机内存中的数据将会丢失,但对Session数据来说并不是严重的问题。如果网站访问量太大、Session太多的时候memcached会将不常用的部分删除,但是如果用户隔离了一段时间之后继续使用,将会发生读取失败的问题。
  • session 数据存放在客户端——cookie
    腾讯云-产品文档-会话保持原理
    Security Enhanced NGINX - HTTP Persistence
  • References

    NGINX Plus - Session Persistence/Sticky Session Load Balancing
    Load balancing - Session persistence
    load balancing, affinity, persistence, sticky sessions: what you need to know