Friday, November 23rd, 2007

Avoid unnecessary Ajax traffic with session state

Category: Ajax, JavaScript, Tip

David Mertz has written an article on avoiding unnecessary Ajax traffic with session state, which discusses RESTful techniques to minimize traffic, and how you can tweak your XHR code to be watchful. Basically, use 304 please!

This tip presented some server code written in Python, but almost the same design would apply for nearly any language that might be used to program a CGI or other server process. The general idea is simple: Use a client cookie (if available) to identify the cached data, and send a 304 status if no new data has arisen since the last polling event. Whatever your server programming language, your program will look almost the same.

While I have not shown much error catching, the design involved is robust in falling back to correct behavior where cookies are not available. If a client does not have a relevant session cookie — either because it does not accept cookies or because this is a first poll in a new session — old_stuff is simply an empty list, and any data returned will be part of new_stuff. Another capability often worth adding is a special client message that will send any current session state: this is useful both for application debugging and as a way of clearing out inconsistent state should the client detect that something has gone wrong. All you lose in flushing the cache is a little server load and some bandwidth; it does not violate underlying idempotency.

Posted by Dion Almaer at 2:38 am

3.3 rating from 32 votes


Comments feed TrackBack URI

Using cookies is not RESTful. Period.

Comment by Berend de Boer — November 23, 2007

Why? (I genuinely don’t know, and really don’t understand REST.)

Holy spam false positives, Batman!

Comment by Trevor — November 23, 2007

@Trevor the idea with REST is to not re-invent the basic methods (like GET) and instead build on top of them, this simplifies your final product:

As I understand it the article advocates:

Seems what they’re advocating might work better as:

Where N becomes the data since N-1 (or zero).

Comment by Jim — November 23, 2007

Leave a comment

You must be logged in to post a comment.