Friday, November 23rd, 2007

Avoid unnecessary Ajax traffic with session state

Category: Ajax, JavaScript, Tip

<>p>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.

Related Content:

Posted by Dion Almaer at 2:38 am
3 Comments

+++--
3.3 rating from 32 votes

3 Comments »

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: http://bitworking.org/news/201/RESTify-DayTrader

As I understand it the article advocates:
http://myserver.example.com/latest_data/

Seems what they’re advocating might work better as:
http://myserver.example.com/uuid/data/N

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.