---
title: Use AJAX for Cache Invalidation
date: 2010-05-05T15:51:33+00:00
modified: 2012-05-19T16:41:15+00:00
permalink: https://kaspars.net/blog/use-ajax-for-cache-invalidation
post_type: post
author:
  name: Kaspars
  avatar: https://reverse.kaspars.net/gravatar/avatar/92bfcd3a8c3a21a033a6484d32c25a40b113ec6891f674336081513d5c98ef76?s=96&d=mm&r=g
category:
  - Development
  - Web Performance
post_tag:
  - Nginx
---

# Use AJAX for Cache Invalidation

Let’s have a site wide *version number* that is changed every time something is updated and cache needs to be invalidated. This number is stored in a simple text file. Cache keys are made up of Request-URI and this unique key, which is passed around in a cookie `VERSION_NO`.

On every page request javascript calls `version.php?timestamp` (which is never cached because of the timestamp), which using `stat()` reads the *last modified timestamp* of that text file and compares it to the value of `VERSION_NO` cookie. If they are different, a new cookie value is set, which in turn changes the cache key for all future requests, and the cache is invalidated.

The only thing I don’t know is how fast and resource hungry is the `stat()` call?

**Update**: or would it be better to use `<a href="http://php.net/manual/en/function.filemtime.php">filemtime()</a>`? There is [a comment](http://www.php.net/manual/en/function.filemtime.php#96403) which says that 1000 `filemtime()` calls take 0.0049 seconds, which I think is very reasonable.