Programming on the Edge

Delayed Ajax

Published by Matt Hicks under on Wednesday, June 13, 2007
There has long been a problem with getting information from the server to the client real-time in web applications. There are several hacks out there for making this happen, but most of them revolve around some idea of polling or server push.

These have significant flaws and a while back I sat down to come up with a better solution. I believe I've done so, and I've called it "Delayed Ajax". Now, the name might lead you to believe that it's going to be quite the opposite of real-time, but hopefully I can explain this well and you'll see why I chose the name and why it is the best option for server to client communication available without going to a pure socket connection.

This is actually an extremely simple idea and perhaps others have been doing it for years, but after a lot of searching I have yet to find anyone (correct me if my google skills are lacking) that has been pushing this idea. The idea is founded on Ajax polling, but with a slight twist. The draw-back with polling is that you either poll very fast and create a lot of wasted bandwidth, or you poll slowly and messages from the server to the client are very slow to arrive.

Okay, so here's the twist. Instead of the client polling, the server immediately responding with message(s) or nothing, the client processing and then waiting a few seconds and doing it again, I put the wait-state on the server instead. The client essentially sends an Ajax requests and forgets about it. The server accepts the request and if there is anything waiting in the queue to go to the client it immediately returns. However, if there is nothing in the queue there is a timeout period (typically around ten seconds) that it holds onto the connection without returning anything waiting on data to come through. As soon as anything hits the queue it immediately fires it out to the client and returns. This gives perfect real-time Ajax communication from server to client The client has no waiting, it fires and forgets but when the callback gets hit it will process the data from the server and then immediately fire again.

In my case I'm handling the server-side aspect with a Servlet, but this can be handled in practically any server-side language that supports multithreaded requests (since multiple requests have to sit idle in a thread waiting for data into the queue).


Post a Comment