Zhu Wu's Blog

The world is a fine place and worth fighting for.

Display a Latest Content Widget

It is quite common to have a component to display latest contents of the website. Our customer, a local leading online news provider, wanted to have such a feature also. We wrote a simple SQL query to get the contents and displayed them out as part of the page HTML. Everything worked great.

However, we encountered a problem after CDN was deployed. The content page will not be updated frequently after published due to the nature of news industry, so we set up the following CDN cache rules:
1. Set cache TTL of content page to a few days in order to maximize cache hits.
2. Trigger CDN cache invalidation when the content is updated.

The CDN cache also worked fine. However, we noticed that latest content widget displayed old contents in old pages. Because CDN always caches the whole page of the URL, the latest content widget was cached together with the page as well. Thus, if a content page was published yesterday and it was not updated after that, the latest content widget of that page could only show the latest contents of yesterday.

It's not wise to purge all the content page cache when there is new content published. Therefore, our solution is to load latest contents by AJAX instead of loading it as part of the page HTML. In this way, only the JavaScript to load latest contents is cached with content page by CDN. When the content page is loaded, the AJAX is triggered to get the fresh latest contents, so it guarantees that latest content widget in every content page is showing the same contents.

In conclusion, the pattern can be applied to all the scenarios when different parts of the page have different cache TTLs. We can load them separately via AJAX, and set their TTL accordingly in each layer of cache.