Skip to content

Instantly share code, notes, and snippets.

@goooooouwa
Last active April 2, 2016 11:25
Show Gist options
  • Save goooooouwa/2df61c44484f131ff3438b3a4502d26d to your computer and use it in GitHub Desktop.
Save goooooouwa/2df61c44484f131ff3438b3a4502d26d to your computer and use it in GitHub Desktop.
a draft implementation of key-based cache expiration model proposed in DHH's article "How key-based cache expiration works" https://signalvnoise.com/posts/3113-how-key-based-cache-expiration-works

Implementation

  1. implement a #cache_key method for every model, as this:
def cache_key
  "#{self.class.model_name.cache_key}/#{id}-#{self[:updated_at].utc.to_s(:number)}"
end
  1. update update_at field whenever the model or it's related models (through method such as touch) are changed.

Conclusion

So whenever the model's content is updated, #cache_key update as well, e.g. from 'Event/5-2016033110450' to 'Event/5-2016040125545'. When you ask for the cache, you do:

Rails.cache.find(@event.cache_key)

This will give you the newest copy of event.

Notes

  • the #cache_key method is inspired by ActiveRecord's #cache_key method
@hyjk2000
Copy link

hyjk2000 commented Apr 2, 2016

FE will have to provide the key with timestamp in the request.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment