Filed in by Angela Bartels | July 17, 2009 9:28 am
Coding in the Cloud
By Adrian Otto
This continues my series on Rules for Coding in the Cloud, rules I’ve developed after watching applications encounter problems at scale when deployed on Cloud Sites.
The use of Sessions
The Web was originally designed to be stateless, that is, not to rely on information about users being stored between interactions. Sessions are a way to save the state of the application for the user between requests (shopping carts being the classic example of this). Programmers, feeling that they need to save information about particular users between interactions, find all sorts of ways to use sessions that are not really appropriate. As a result, the concept of sessions gets abused and the scalability of the applications suffers due to requiring sessions. If you can design your application not to use sessions at all and be completely stateless, it can be scaled horizontally much more easily and the application will run much better under high load than if you try to keep track of which user needs to be reconnected with which session settings.
The error that we often see is that the application programmer makes a dependency on sessions central to the design of the software, and later when it becomes identified as a scalability bottleneck, it cannot be removed from the application because it was designed in at such a low level.
The reason why sessions are so evil is that most developers store the session information in the database. To get the information you need out of the session, you need to query the database and read the information. And because sessions change so often, such applications require lots and lots of writing to the database to keep the state of the session. You can end up with a read/write ratio of about 50/50 because of sessions, which kills scalability.
Working with REST
One way to make sure you don’t rely on sessions is to use Representational State Transfer (REST) architectures, which are by definition stateless.
Some types of information are stateful by nature, such as something that requires an open network connection to monitor progress of a remote operation that does not have stateless features. In such cases, using a stateless design may not be practical, or even possible. When you have more clients than servers it makes sense to do as much work on the clients as you reasonably can. If your application must save state, save it on the client rather than on the server. Consider using a browser cookie, or some Ajax. This will greatly improve your scalability. Furthermore, you pay for the server side resources you consume, but client side resources are free!
Source URL: http://www.rackspace.com/blog/coding-in-the-cloud-rule-3-use-a-stateless-design-whenever-possible/
Copyright ©2015 The Official Rackspace Blog unless otherwise noted.