53

OK, so I've got this totally rare an unique scenario of a load balanced PHP website. The bummer is - it didn't used to be load balanced. Now we're starting to get issues...

Currently the only issue is with PHP sessions. Naturally nobody thought of this issue at first so the PHP session configuration was left at its defaults. Thus both servers have their own little stash of session files, and woe is the user who gets the next request thrown to the other server, because that doesn't have the session he created on the first one.

Now, I've been reading PHP manual on how to solve this situation. There I found the nice function of session_set_save_handler(). (And, coincidentally, this topic on SO) Neat. Except I'll have to call this function in all the pages of the website. And developers of future pages would have to remember to call it all the time as well. Feels kinda clumsy, not to mention probably violating a dozen best coding practices. It would be much nicer if I could just flip some global configuration option and Voilà - the sessions all get magically stored in a DB or a memory cache or something.

Any ideas on how to do this?


Added: To clarify - I expect this to be a standard situation with a standard solution. FYI - I have a MySQL DB available. Surely there must be some ready-to-use code out there that solves this? I can, of course, write my own session saving stuff and auto_prepend option pointed out by Greg seems promising - but that would feel like reinventing the wheel. :P
Added 2: The load balancing is DNS based. I'm not sure how this works, but I guess it should be something like this.
Added 3: OK, I see that one solution is to use auto_prepend option to insert a call to session_set_save_handler() in every script and write my own DB persister, perhaps throwing in calls to memcached for better performance. Fair enough.

Is there also some way that I could avoid coding all this myself? Like some famous and well-tested PHP plugin?

Added much, much later: This is the way I went in the end: How to properly implement a custom session persister in PHP + MySQL?

Also, I simply included the session handler manually in all pages.

Community
  • 1
  • 1
Vilx-
  • 104,512
  • 87
  • 279
  • 422

10 Answers10

36

You could set PHP to handle the sessions in the database, so all your servers share same session information as all servers use the same database for that.

A good tutorial for that can be found here.

Oliver Friedrich
  • 9,018
  • 9
  • 42
  • 48
  • 6
    This is not the correct way. The issue is PHP sessions, forget about Databases, we're talking about PHP. This solution is merely a work around. – Daniel Dec 14 '11 at 13:37
  • 12
    I disagree. Storing PHP sessions in the database is a perfectly good solution to this problem. – Matt Fletcher Feb 12 '15 at 14:05
  • 3
    @MattFletcher its a poor solution to the problem. in memory storage should be used, like redis, memcached, or ramfs etc – r3wt May 02 '16 at 12:09
  • 2
    @r3wt in memory? Are you willing to accept that all sessions will disappear if the session storage (memcache etc) for some reason must be restarted? – sbrattla Nov 22 '16 at 18:18
  • Are you going to change your application design because of physical architecture? That doesn't make any sense to me. – Josh Woodcock Jun 10 '17 at 19:20
  • 2
    You could always use Redis – DOfficial Jul 01 '17 at 00:12
  • you can save and load to database, using push to cache on save and pull on no-session-found. best of both worlds. @DOfficial using Redis is a good way to accomplish this with pub/sub – That Realty Programmer Guy Dec 29 '18 at 00:19
23

The way we handle this is through memcached. All it takes is changing the php.ini similar to the following:

session.save_handler = memcache
session.save_path = "tcp://path.to.memcached.server:11211"

We use AWS ElastiCache, so the server path is a domain, but I'm sure it'd be similar for local memcached as well.

This method doesn't require any application code changes.

Doug Johnson
  • 473
  • 4
  • 11
  • 4
    memcached is a mixed blessing for storing sessions. Its fast, easy to setup but when it runs out of memory it will destroy old sessions, so permanent session storage will not work. Before using this, one should really think about if this data loss is fine or not for his application. – Ivan Hušnjak Feb 23 '13 at 11:13
  • 1
    More info here: http://php.net/manual/en/memcached.sessions.php Note: most of the documentation is actually in the comments there! – Darren Cook Dec 02 '13 at 12:11
10

You don't mentioned what technology you are using for load balancing (software, hardware etc.); but in any case, the solution to your problem is to employ "sticky sessions" on the load balancer.

In summary, this means that when the first request from a "new" visitor comes in, they are assigned a specific server from the cluster: all future requests for the lifetime of their session are then directed to that server. In practice this means that applications written to work on a single server can be up-scaled to a balanced environment with zero/few code changes.

If you are using a hardware balancer, such as a Radware device, then the sticky sessions is configured as part of the cluster setup. Hardware devices usually give you more fine-grained control: such as which server a new user is assigned to (they can check for health status etc. and pick the most healthy / least utilised server), and more control of what happens when a server fails and drops out of the cluster. The drawback of hardware balancers is the cost - but they are worth it imho.

As for software balancers, it comes down to what you are using. For Apache there is the stickysession property on mod_proxy - and plenty of articles via google to get this working with the php session ( for example )


Edit: From other comments posted after the original question, it sounds like your "balancing" is done via Round Robin DNS, so the above probably won't apply. I'll refrain from commenting further and starting a flame against round robin dns.

Ian
  • 4,208
  • 21
  • 33
4

If you have time and you still want to check more solutions, take a look at http://redis4you.com/articles.php?id=01..

Using redis you are fault tolerant. From my point of view, it could be better than memcache solutions because of this robustness.

famousgarkin
  • 13,687
  • 5
  • 58
  • 74
Alex Moleiro
  • 1,166
  • 11
  • 13
4

The easiest thing to do is configure your load balancer to always send the same session to the same server.

If you still want to use session_set_save_handler then maybe take a look at auto_prepend.

Greg
  • 316,276
  • 54
  • 369
  • 333
  • The load balancing is somehow done with DNS entries. The hostname resolves to two different IP addresses and the browser picks one randomly. Or something like that - I don't really know the particulars. But AFAIK there is no load balancer. The "auto_prepend" looks promising. – Vilx- Jun 15 '09 at 08:14
  • +1 use auto_prepend to insert the session_set_save_handler function before every script – Galen Jun 15 '09 at 08:41
  • 2
    Sounds like you've got a "Round Robin DNS" on the go - http://en.wikipedia.org/wiki/Round_robin_DNS . I'll say that the least said about this "solution" to load balancing, the better. – Ian Jun 15 '09 at 08:54
  • Perhaps, but I didn't choose this nor can I change it. – Vilx- Jun 15 '09 at 09:09
3

If you are using php sessions you could share with NFS the /tmp directory, where I think the sessions are stored, between all the servers in the cluster. That way you don't need database.

Edited: You can also use an external service like memcachedb (persistent and fast) and store the session info in the memcachedb index and indentify it with a hash of the content or even the session ID.

Khriz
  • 5,888
  • 6
  • 34
  • 39
  • This is the current "quick workaround", but the admin doesn't like that. Something about security and stuff, I don't know the particulars. – Vilx- Jun 15 '09 at 12:13
  • Mmm, then you could use an external service like memcachedb using a hash of the key as a index for the sessions. The memcachedb service is very fast (especially writing) and easy to use, you can use a special and reduced set of the memcached functions from PHP. – Khriz Jun 15 '09 at 13:24
  • 2
    NFS is not designed for high number of requests... remember, PHP loads session at `session_start()` and saves it when script execution ends (even if no session data changed!), so each PHP request will spawn two NFS requests. – Ivan Hušnjak Feb 23 '13 at 11:20
  • I don't manage sessions that way but it could be an option for people without access to other (better options) key-value storage engines. But yeah is not a very good option... :) – Khriz Feb 25 '13 at 11:43
  • FWIW, we wasted a week trying to figure out why our AWS-hosted Magento setup with two backends and NFS share for cache dir was hopelessly slow. It was NFS. Don't do it, ever! – wkw Apr 04 '17 at 13:53
  • Well it's an answer from 8 years ago, but sorry to hear that. – Khriz Apr 04 '17 at 13:54
2

Might be too late, but check this out: http://www.pureftpd.org/project/sharedance

Sharedance is a high-performance server to centralize ephemeral key/data pairs on remote hosts, without the overhead and the complexity of an SQL database.

It was mainly designed to share caches and sessions between a pool of web servers. Access to a sharedance server is trivial through a simple PHP API and it is compatible with the expectations of PHP 4 and PHP 5 session handlers.

Claudio Bredfeldt
  • 1,423
  • 16
  • 27
2

When we had this situation we implemented some code that lives in a common header.

Essentially for each page we check if we know the session Id. If we dont we check if we're in the situation whehich you describe, by checking if we have stored sesion data in the DB.Otherwise we just start a new session.

Obviously this requires all relevant data to be copied to the DB, but if you encapsulate your session data in a seperate class then it works OK.

pauljwilliams
  • 19,079
  • 3
  • 51
  • 79
2

you could also try using memcache as session handler

1

When it comes to php session handling in the Load Balancing Cluster, it's best to have Sticky Sessions. For that ask the network of datacenter who is maintaining the load balancer to enable the sticky session. Once that is enabled you'll don't need worry about sessions at php end

harigorana
  • 102
  • 1
  • 6
  • Well, without sticky sessions you get failover too. :) However, it the original question there's a different wrinkle - the load balancing is the "DNS round-robin" kind. So sticky sessions are out of the question anyway. :P – Vilx- Jan 13 '17 at 16:54
  • @Vilx- We faced same issue for session in php with load balancer, and that worked for us. Only thing we did was asked our datacenter to enable the sticky session for the configured domain and request routing in round-robin only – harigorana Jan 14 '17 at 08:52