Time-based HTTP Caching in Sinatra

It's always a pleasant surprise to come across a library that behaves exactly the right way in the first place rather than forcing you to build helpers from its primitives. Sinatra's last_modified response helper is a great example of this.

Time-based HTTP caching is a simple technique to give smart clients a significant performance boost when accessing content. After receiving a single Last-Modified header, they can pass the pass the same timestamp back to the server on the next response via the If-Modified-Since header, giving the server the opportunity to respond with a 304 Not Modified if the content is still fresh. When responding with a 304, no body is transferred in the response, curbing bandwidth use, and perhaps more importantly, saving the end user from having to re-render the content.

Sinatra's last_modified does all the right things:

  1. Sets Last-Modified.
  2. If the client sent a If-Modified-Since, halts the executing block if the timestamp matches.
  3. Otherwise, allows execution to continue normally.

Most importantly, its usage results in simple and readable code:

get "/:id" do |id|
  @article = Article.first(slug: id) || raise(Sinatra::NotFound)
  last_modified(@article.updated_at)
  slim :show
end

Posted on December 2, 2012 from Caffe Greco in North Beach, San Francisco

Newest Articles

About

My name is Brandur. I'm a polyglot software engineer and part-time designer working at Heroku in San Francisco, California. I'm a Canadian expat. My name is Icelandic. Drop me a line at brandur@mutelight.org.

Aside from technology, I'm interested in energy and how it relates to our society, travel, longboarding, muay thai, symphonic metal, and the guitar.

If you liked this article, consider finding me on Twitter.