Blog updates: faster, mathier, and more cacheable

By
Posted on
Tags: mathjax, tex, varnish, caching, performance, blog

After much neglect, my poor blog is finally getting some much-needed care.

The first improvement I wanted to make was to add support for TeX mathematics. Last week’s article on how to update your beliefs after observing a coin toss contained enough painstakingly entered mathematical notation to provide the necessary motivation. The solution I preferred was MathJax, a JavaScript library that runs in the browser to render TeX markup into mathematical notation after a page is loaded. But that solution created a new problem.

MathJax, you see, has a rather large footprint. And my blog runs on a decrepit server that is already overtaxed. So, to use MathJax, I first had to put a reasonably tuned cache in front of my blog to offload the byte-slinging duties soon to be imposed.

Varnish

Enter Varnish, an efficient, highly tunable, caching HTTP proxy. I set it up on a front-end server and told it to cache anything mostly static on the blog’s server:

# allow caching of mostly static resources
sub vcl_fetch {
 if (req.url ~ "\.(ico|png|gif|jpg|swf|css|js)$" ||
     req.url ~ "^/xml/.*\.xml$" ||
     req.url ~ "^/$") {
   set obj.ttl = 600s;
 }
 if (req.url ~ "/javascripts/MathJax/") {
   set obj.ttl = 3600s;
 }
 if (req.url ~ "\.(ico|png|gif|jpg|swf|css|js)\?[0-9]+$") {
   set obj.ttl = 1d;
 }
}

Basically, that bit of Varnish Configuration Language says that after the proxy fetches a resource from the back-end blog server, if it’s an image, script, feed, or MathJax resource, it should be given some reasonable amount of time to live in the cache. Once in the cache, Varnish will serve it up until its time to live expires, when Varnish will finally ask the old blog server to fetch another copy.

This little change made a big difference in my blog’s responsiveness. It feels much snappier now. (Let me know if you agree.)

MathJax

The front-end cache done, I moved on to installing MathJax. Basically, I downloaded a couple of Zip archives, decompressed them, and dropped the resulting files onto my blog’s server. Then I tweaked the blog’s default page template to load the root MathJax JavaScript file. That’s it.

Now I can have fun with TeX-markup mathematical formulas on the blog: \[1 + x_1 + x_2 + \cdots\]

The only downside to using a client-side library like MathJax is that it will probably not go so well for readers using Instapaper and e-readers. (If you’re one of them, let me know how it goes for you.)