Django and memcached Interface

January 25, 2009

I've had memcached running on my server for a while now, but I haven't really been keeping track of what it is doing. Other than monitoring its memory and CPU usage, I didn't know of anything fun to look at. I did some looking around and found this post showing how to view the cache stats. It is fairly simple using netcat.

  1. Connect to the your memcache using netcat: nc 127.0.0.1 11211
  2. Simply type stats over the netcat connection

The result:

jon@joncraton.org:~# nc 127.0.0.1 11211
stats
STAT pid 31608
STAT uptime 68
STAT time 1232941648
STAT version 1.2.2
STAT pointer_size 32
STAT rusage_user 0.012000
STAT rusage_system 0.008000
STAT curr_items 15
STAT total_items 34
STAT bytes 75306
STAT curr_connections 2
STAT total_connections 146
STAT connection_structures 3
STAT cmd_get 76
STAT cmd_set 34
STAT get_hits 32
STAT get_misses 44
STAT evictions 0
STAT bytes_read 156923
STAT bytes_written 165530
STAT limit_maxbytes 4194304
STAT threads 1
END

I also found out that the TCP interface for memcached is very simple from the protocol documentation. Getting values out of the cache is especially simple. The syntax is simply 'get <key>'. Memcached returns the value it has stored followed by END.

I had to do a pit of poking around to figure out how Django creates it's cache keys, but I eventually found it in the code. The key looks like this for Django 1.0:

views.decorators.cache.cache_page.<prefix>.<path>.<hash>

So, to check that Django was caching my root url, I sent memcached the following request:

get views.decorators.cache.cache_page../.62966c281246fb85ab5b59688b708d9d

This should return all the HTML for the page along with the response headers if caching is working properly.

Check out my other pages tagged "blog".