Rails 3.1 and Http Page Caching
Asked Answered
G

1

7

Given that Heroku Cedar doesn't have http caching provided by Varnish I would like to use Rack::Cache. I have been told that rails 3.1.1 have Rack::Cache active by default, I just need to make sure to have in the configuration:

config.action_controller.perform_caching = true

and I need to pick a cache store, for this experiment I'm using:

config.cache_store = :memory_store

In the action of the page I want to cache I've added the following lines:

response.header['Cache-Control'] = 'public, max-age=300'
response.header['Expires'] = CGI.rfc1123_date(Time.now + 300)

This code used to work fine with Varnish, the first request would return a 200 and the subsequent (for 5 mins) would return a 304.

This doesn't happen with Rails 3.1 and Heroku Cedar Stack. I do get those headers in the response but subsequent requests returns 200 instead of 304.

What am I doing wrong? Thank you.

Gainer answered 18/11, 2011 at 14:47 Comment(0)
D
11

As you noted, the Cedar stack doesn't use Varnish. That means a web request will always hit the ruby server.

With that in mind, Rack::Cache will respect your headers and serve the cached content.

However, since the request is actually going past the http layer into the rails app, the response will always be 200 since the cache doesn't happen at the http layer anymore.

To confirm this is true, insert this in one of your cached actions:

<%= Time.now.to_i %>

Then, reload the page several times and you'll notice the timestamp won't change.

Diu answered 18/11, 2011 at 21:4 Comment(3)
You are right!!!! Is there a way to cache at slightly higher level? Is it worth it? (e.g. what if I setup a rack::cache in config.ru before the rails app?)Gainer
not really... Rack::Cache is your best bet. Just put is as high as you can in your environment and it should give you the performance you need given it avoids the whole Rails http stack.Diu
Oh and I'd appreciate if you could vote up the original answer if it helped you :)Diu

© 2022 - 2024 — McMap. All rights reserved.