0

I am trying to understand how memcache works when (if) you fill up the allocated memory buffer. In particular I want to understand the lifecycle of a key value pair in cache. I am talking about low level cache operations in rails where I am directly creating the key/value pairs. e.g. commands like

Rails.cache.write key, cached_data

Rails.cache.fetch key 

Assume for the sake of argument I have an infinite loop that was just generating random UUIDs as keys and storing random data. What happens when the cache fills up? Do older items just get bumped off or is there some specific algorithm behind the scenes that handles this eventuality? I have read elsewhere "Cache Invalidation is a Hard Problem".

Just trying to understand how it actually works.

Maybe some simple code examples that illustrate the best way to create and destroy cached data? Do you have to explicitly define when entries should expire?

Gordon Potter
  • 5,802
  • 9
  • 42
  • 60

1 Answers1

1

MemcacheD handles this behind the scenes. Check out this question -

Memcache and expired items

You can define expiration parameters, check out this wiki page -

http://code.google.com/p/memcached/wiki/NewProgramming#Cache_Invalidation

For cache invalidation specific to you application logic (and not just exhaustion of memory behind the scenes), the delete function will simply remove the data. As far when to delete cached data in your app, thats harder to say - hence the quote you referenced about cache invalidation being hard. I might suggest you start by thinking about ActiveRecord callbacks like after_commit - http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html, to let you easily invalidate cached data whenever your database changes.

But this is only a suggestion, there are many different cache invalidation schemes out there.

Community
  • 1
  • 1
Scott S
  • 2,696
  • 16
  • 20