AJAX: what’s a session?

As I mentioned here, my concern about the buzz surrounding AJAX is not what’s being said but what isn’t being said.

One question I’ve got nagging me, which I’ve yet to see serious discussion of, is the that of AJAX and sessions / state. I guess either no one is thinking about it or it’s got brushed under the carpet of “implementation detail”. The furthest I’ve seen seen the discussion go in this direction is Diego blogging on ajax. That said Joshua Eichorn did a great job of hinting at the issues with his memento demo – move the pictures around then hit your browser’s “reload”.

From where I stand AJAX redefines the notion of state in web applications – the “new session” exists for a user for as long as they keep the current web page running. Session data is being “persisted” locally on the client, in memory in Javascript variables.

Of course it’s not that simple and Diego hits the right term, in talking about the “the thin-fat client”.


The web is inherently stateless. That is HTTP is stateless – once a web server has delivered it’s response to you, the connection is closed and it no longer cares you exist.

Of course that’s not great if you want your web app to recognize returning users, either for the purpose of displaying a “Welcome back Joe Bloggs” message or implementing functionality like a shopping cart. To get round this inherent statelessness, you need to build things on top of HTTP, which Netscape did somewhere around 1997 with their cookie spec.

With cookies it is possible to store data “permanently” on a given client, tied to the domain that issued the cookie. The cookie data is then exposed to the domain that issued it, for all future requests, until the cookie expires.

Of course cookies aren’t suitable for all data. If it’s sensitive information such as a credit card number or a password, that data is at risk to anyone with access to the client filesystem or anyone able to listen in on the conversation between the client and the server (i.e. when using HTTP not HTTPS). It’s also a bad idea to store large quanties of data in cookies, as it’s going to eat bandwidth and resources on the client and server. And these days users often work with many different client computers, from their home PC, their desktop at work, from an Internet cafe or even mobile devices. Unfortunately cookies don’t travel as well as users do.

So some of this data you want to keep on the server and the natural next step was using cookies to implement the notion of “sessions” – send a cookie containing a unique identifier for a given user during a given “visit” to a web site and the server can retrieve data specific to that user without exposing it to the world. Cookies aren’t the only way to implement sessions. Another approach is attaching an ID to all “internal” URLs but this introduces greater security risks. It’s also common to use hidden form fields in POST requests, sometimes for short-term “state” for a multi page form or “wizard” (see Application Controller) or, in more extreme form, ASP.NET’s view state. And there are more obscure ways to track sessions. But cookies remain the most popular compromise for solving this problem in general, most web based solutions, from PHP to J2EE implementations, providing default solutions based on cookies.

Persistance on the Server

While not directly related to AJAX, thinking about what happens on the server is also important, at least when it comes to implementation time. I’ve already had questions along this line regarding JPSpan and it’s clear what’s obvious to me isn’t obvious to everyone.

This is an itchy subject in web applications. Once you’ve started using sessions, you need to live with the consequences. When you’ve only got one web server, storing user session data is no problem. But crank up the traffic volume and you start wanting to add more servers to cope with it, balancing requests between them, scaling horizontally. Suddenly you have a problem in providing all servers access to the session data.

The solution to this depends on who you ask and the arguments are often conflicting.

The J2EE crowd, for example, bought the notion that databases == evil (or perhaps database vendors == evil – independence baby!). Somehow that’s extended to database == bottleneck == can’t scale.

Meanwhile Rasmus describes shared nothing and PHP;

PHP encourages you to push scalability issues to the layers that require it. If you need a shared datastore, use a database that supports replication and can scale to the levels you need. If you need to load balance requests or distribute certain requests to certain servers, use a front end load balancer that supports this. By avoiding a central controlling process, PHP avoids being the bottleneck in the system. This is the defining characteristic that separates PHP from what people commonly refer to as application servers.

Which could be read as “pick a decent db vendor and use the features you paid for”.

The two key issues, as I see them, for scaling horizontally are efficiency and transparency. If replication traffic floods the local network your servers run on, grinding it to a halt that’s clearly bad news – now the network has to scale vertically. Meanwhile it should be possible to tap into a back end “farm” from your web application without having to significantly modify code, or even spend vast effort in design the code to scale in the first place.

So my personal bias is leaving this to filesystem or database vendors to get right. The technology is mature, it’s alot easier to tap into scalability in these layers without massive effort in code design and, perhaps most of all, the future of people like these guys depends on solving this one.

Alternatively you can take a gut level view. If you want to build something that works, talk to techies with a solid understanding of networks and, better yet, those who happen fluent in Perl and just coincidentally play a part in defining the spec we rely on and keep returning to bite later on.

Obscure side note: is HTTP subversive by design? Perhaps the design concerns were simply “This must scale” but HTTP keeps dropping reminders that the web is not there to be centralized. Attended a keynote by Roy Fielding where he remarked that he knew the work he was doing on Apache would help protect the HTTP spec. from vendors. Whether that’s in retrospect I don’t know (should have asked) but if you like the word “Open”, Roy is one person to thank.

AJAX and State

Back on track after rambling, so what’s the impact of AJAX on sessions and state in web application? Personally don’t have answers, only more thoughts and questions.

As already said, as I see it, AJAX redefines the notion of what a session is in web applications. The state of a given user’s session can be maintained client side in Javascript and will remain there so long as they don’t click reload.

Data that you “check out” from the server via AJAX resides locally and can be changed locally without the servers awareness, until you “commit” it back to the server.

A user may change their “personal preferences” in your application but this information is finally only transmitted to the server, via AJAX, on Unload and recalled on the next reload.

Technically that means we can now ditch cookies and server-side session implementations and the server side can be just as stateless as HTTP. In practice, common sense suggests it’s not so simple and this is more a matter of drawing lines in the right places, of which data should be preserved where.

Implementation Detail

Resorting finally to bullet points;

Data Loss?
User has locally modified data

  • User’s browser crashes – session data is lost. Seems like a good reason to keep those server-side sessions
  • The network / server is down and updates can be no longer sent. Use cookies as backup until data can be sent? Security implications of that?
  • Can we send data reliably? Are we sure it got there? HTTLR?

When to transmit changes?

  • Do we want fine grained updates? Transmit the change as the user makes it. What’s the network cost? Or should we send a bunch of changes together, e.g. onUnload? See Point 9.
  • Do we transmit changes automatically, without bothering the user? Or do we give them a “Save” button, like Word, and warn them of potential data loss onUnload? Ever thought how 1990’s that Save button is?

Difficient Runtimes
Are we heading for nightmares with Javascript garbage collection? Certainly keeping 100,000 records on the client is going to be a bad idea.


Users A and B are both modifying record X. User B “saves” then User A “saves”, overwriting User B’s changes.

Technically this is already problem with todays web apps but think the “immediacy” data exchange with AJAX compounds the problem. It’s notiously difficult to implement “locking” mechanisms effectively over the web, given statelessness and inherent “brokeness”. Best attempt I’ve seen is Dokuwiki, which users timed locks to prevent multiple users editing together.


Somehow HTTP Basic Authentication appeals most to me as something you can implement transparently, vs. “inline” authentication based on something like cookies / server sessions or POST data.

Problem is there’s pretty much no access to the browsers HTTP basuc auth APIs with XMLHttpRequest, other than two arguments to the open method;

[code lang=”javascript”]
void open ( AUTF8String method , AUTF8String url , boolean async , AString user , AString password )

My own experiments with them suggest they’re better left unused – farm this problem off to the browser and rely on the HTTP status codes.

What else?

40 Responses to AJAX: what’s a session?
  1. Nick
    April 22, 2010 | 9:39 am

    Sorry but Javascript is not Robust and making it manage a session is a nightmare.

    Maybe jQuery, but Javascript as a whole is anyone and not productive.

  2. chandan
    December 26, 2009 | 9:11 am

    then how do we track session variables in php with ajax ?

    i have php for simple ajax example like when i click a button it calls [B]ajax.php[/B]

    $_SESSION[‘adpages’] = $_SESSION[‘adpages’]+ 1;
    echo “here”.$_SESSION[‘adpages’] ;
    $_SESSION[‘adpages’] = 0;
    echo “here not “.$_SESSION[‘adpages’] ;

    but it always showing here not 0 :(

  3. battery
    June 24, 2008 | 10:13 pm

    […]The offline scripting tool might add some relief here, but it’s still sort of a pain. I’ve had to separate “build” from “configuration” steps.[…]

  4. John Campbell
    December 12, 2007 | 12:47 pm

    Thank you for this site. I hope it will continue in this vein for a long time to come. Well done! By the way – I found my way here by searching for forex online system trading. When I found your post \”what’s a session? : Ajax Blog\” I was intrigued.

  5. buy bontril
    June 9, 2006 | 2:36 am

    buy bontril…

    buy bontril Phrm889NetW0rkJP …

  6. ativan
    June 8, 2006 | 9:21 pm


    buy ativan Phrm889NetW0rkJP …

  7. Fragrance Reviews
    June 2, 2006 | 1:02 pm

    nice blog keep it up ! good luck

  8. Digital Watches
    June 1, 2006 | 1:44 pm

    Excellent site ive ever seen !!

  9. fast love
    May 29, 2006 | 10:56 am

    thanks for the usefull stuff. we are’ updating oour website and it’s very helpfull info.

  10. Home Fragrance
    May 26, 2006 | 11:43 pm

    Best Blog ive ever seen keep it man

  11. Forex Trading
    May 22, 2006 | 5:42 am

    I read few of you blogs posts and wanted to say you have a good blog . keep it up

  12. ehtel
    May 17, 2006 | 10:49 am

    Nice web page! Very sharp. I also agree, hey I am upside down or even right side up :-). Keep the content flowing.I will return again.

  13. Forex Agent
    May 17, 2006 | 3:26 am

    Superb Blog keep it up

  14. Digital Satellites
    May 10, 2006 | 4:01 pm

    nice one…now even i feel like starting a blog like the one you have now …

  15. Watch Satellite Tv
    May 9, 2006 | 1:39 am

    nice one…now even i feel like starting a blog like the one you have now …

  16. Forex Resource
    May 5, 2006 | 1:14 am

    excellent blog i love this article

  17. laveta
    April 27, 2006 | 3:16 pm

    Nice web page! Very sharp. Very few comments are wrong, if any at all. Glad I stumbled into your site.Keep it real.

  18. discount notebook computers
    April 25, 2006 | 7:11 pm

    This blog is very well put together. Do you have a rss feed also? That would be great although I was able to finish my research on laptop computer parts and the economic changes occuring under the Bush administration. Not to bore you :-_) Back to research!

  19. Cheap Perfumes
    April 23, 2006 | 8:51 am

    Good Blog keep it up… Digital Satellites

  20. massage therapy license
    April 21, 2006 | 6:59 am

    Very nice blog. Very informative. A rss feed would be perfect

  21. work at home
    April 19, 2006 | 6:28 am

    I really appreciate what you are trying to do with this Blog. Congratulations and keep up the good work!


  22. website traffic|free traffic
    April 11, 2006 | 4:05 pm

    This is great system of driving free targeted traffic from the search engine to my site.
    You can duplicate my way of driving free web traffic to your site.
    Go here now: http://websitetraffic-freetraffic-webtraffic.blogspot.com

  23. Digital Watches
    April 8, 2006 | 2:12 pm

    This one is cool article !!! thanks for it. Digital Cameras

  24. free traffic
    April 6, 2006 | 10:02 am

    Unique Traffic generator takes online Advertising to a new Level! Put your ad right to the screens of millions in 15 minutes! Your Sites would receive Quality Traffics in minutes
    Unique Traffic generator automatically diverts 1000s of fresh new visitors in Quality Traffic daily to your web site from google, yahoo, msn and others!
    Go here now : http://www.dejibiz.net/traffic

  25. notebook computers deal
    March 28, 2006 | 10:28 am

    That truly is a valid point. I took that into consideration after reading the above information. I certainly wish all comments had validity. Thanks again. Stu

  26. Use Keyword Here
    March 22, 2006 | 9:19 pm

    Personally, I never use more than a single link in the comment I post because doing so can trigger spam catchers if the user has that plugin activated, whereas a single link will not.

  27. Michael Jouravlev
    March 17, 2006 | 11:49 am

    > We store state in simple temporary tables, simply erased
    > when user’s session expires. (dbf-style table, don’t care
    > about RDBMS for that). This way scalability is total, not
    > a byte of memory more for additionnal users.

    There’s no point of persisting state if it does not propagate beyond session. Memory savings? Depends on your situation of course. In general, adding more memory solves the problem 😉

  28. Bit Design
    March 17, 2006 | 5:15 am

    Great site!

    Bit Design is a Belgrade, Yugoslavia web design agency. Bit Design provides cost-effective corporate branding and Internet solutions for start-up and established businesses.


  29. Bit Design
    March 13, 2006 | 9:58 pm

    Great site!

    Bit Design is a Belgrade, Yugoslavia web design agency. Bit Design provides cost-effective corporate branding and Internet solutions for start-up and established businesses.


  30. […] Ajax: What’s a session?: con la popularización de Ajax el concepto tradicional de sesión (cuando nos loggeamos en una web) se ha quedado un poco obsoleto […]

  31. Sessions in Ajax… at reinventnow
    March 8, 2006 | 10:45 am

    […] Finally, someone is really talking about sessions in the context of  web2.0 apps: AJAX: what’s a session? | Ajax Blog […]

  32. Thierry Nivelet
    March 7, 2006 | 4:27 am

    Very sound article, raises real-world issues.

    Because an event result generally depend on previous events sequence, I’m convinced AJAX application need keep user state on the server during a session.

    We did that quite simply :
    – Server generates a random UID per user, send back to XMLHTTP
    – Each request comes with the UID
    – Server restores state based on the UID

    We store state in simple temporary tables, simply erased when user’s session expires. (dbf-style table, don’t care about RDBMS for that). This way scalability is total, not a byte of memory more for additionnal users.

    Saving – restoring user’s state takes about .2 second, which can proabably be reduced with faster hardware.

    Demo’d here : http://www.abaqueinside.com/IntuiCatAjaxDemo.asp

  33. Michael Jouravlev
    March 7, 2006 | 3:19 am

    > The state of a given user’s session can be maintained client side
    > in Javascript and will remain there so long as they don’t click reload.

    So, what’s the point?

  34. Edvin
    March 6, 2006 | 6:19 pm

    Good article. You raise many good points and I agree these are things that need further attention from the community. As the ASP model gets greater play from developers, and applications like Basecamp, Backpack, Blinksale, etc.. become more prevalent and take on more users, this is going to be a very big concern. At some point, adding hardware is the only way to scale up an application, and there are simply no clean solutions for distributing all the variants of session data.

  35. Ajaxian » AJAX: What’s a Session?
    March 6, 2006 | 3:24 pm

    […] With more and more Ajax usage going on out on the web today (and showing no signs of fading), there are certain topics that aren’t as discussed as others. Certain people pick up those topics and decide to share what they can on the subject, and Harry Fuecks does just that in this post from the Ajax Info blog covering sessions/state storage with Ajax. […]

  36. […] As Bill called it Client / SOA will use the same. SOA may not yet be concept which readily communicates ideas. My angle of understanding this begins with asking AJAX: what’s a session?. An alternative angle comes from Cédric Savarese over at Form Assembly in Ajax: It’s not all about XMLHTTPRequest (and part 2), a train of thought which leads to what he’s done with the freja framework. […]

  37. Intercodes
    January 28, 2006 | 7:43 am

    Thanks for the article. My mind was insane for past two hours when I came upon mod_python tutorial and there were like sessions,cookie crap. I know about cookies but not about sessions. I searched google and it seems this post is the only one closest to explaining sessions and cookies. Now it’s clear. I can go ahead with my tutorial. (didn’t read the ajax part though 😉 )


  38. Jon
    January 9, 2006 | 10:51 am

    One possible way to maintain state is through updating session variables using an XMLHttpRequest.

    How about setSessionVar and getSessionVar() functions in javascript which update server session variables. The server could process the request, then set or return the correct server variables. This will have to be implemented carefully, as you may want to limit what session variables can be set and fetched.

  39. […] robably the right way to go but it raises a whole bunch of new issues, from redefining the notion of a session to whether Javascript is really a robust platform for applicatio […]