views:

143

answers:

2

Imagine that your web application maintains a hit counter for one or multiple pages and that it also aggressively caches those pages for anonymous visitors. This poses the problem that at least the hitcount would be out of date for those visitors because although the hitcounter is accurately maintained on the server even for those visitors, they would see the old cached page for a while.

What if the server would continue to serve them the cached page but would pass the updated counter in a non-persistent http cookie to be read by a piece of javascript in the page that would inject the updated counter into the DOM.

Opinions?

A: 

you can also get the page programmatically via asp or php out the cache yourself and replace the hitcounter.

Toad
You mean apply some smart (and potentially very flawed) regex magic to the cached content?
Oliver Weichhold
regex seems a bit over the top. If the text which needs replacing is defined as such: %%COUNTER%% then you can just do a simple search and replace.
Toad
But this will still put the burden on the server. Replacing a string should be lightning fast but its still work on the server.
Oliver Weichhold
if you do client side caching (specify in a header to cache the page) then the cookie will also not be updated. If you do server side caching then the overhead of a simple replace is nothing against retransmitting the page anyway.
Toad
Well, the page I'm talking about is pretty costly to render so the savings of just returning a pre-rendered string versus a full rendering pass is pretty significant. The reason I'm not working with cache headers is that I need to be able to invalidate the cache once the content changes.
Oliver Weichhold
+1  A: 

You are never going to keep track of the visitors in this manner. If you are aggressively caching pages, intermediate proxies and browsers are also going to cache your pages. And so the request may not even reach your server for you to track.

The best way to do so would be to use an approach similar to google analytics. When the page is loaded, send an AJAX request to the server. This ajax request would increment the current counter value on the server, and return the latest value. Then the client side could could show the value returned by the server using javascript.

This approach allows you to cache as aggressively as you want without losing the ability to keep track of your visitors.

sri
Yeah I think thats probably the best solution.
Oliver Weichhold