Jonatan Littke
Jonatan Littke

Reputation: 5663

Get expiration time of a memcache item in php?

I'm caching tweets on my site (with 30 min expiration time). When the cache is empty, the first user to find out will repopulate it.

However, at that time the Twitter API may return a 200. In that case I'd like to prolong the previous data for another 30 mins. But the previous data will already be lost.

So instead I'd like to look into repopulating the cache, say, 5 minutes before expiration time so that I don't lose any date.

So how do I know the expiration time of an item when using php's memcache::get()?

Also, is there a better way of doing this?

Upvotes: 4

Views: 8114

Answers (3)

zerkms
zerkms

Reputation: 254896

don't store critical data in memcached. it guarantees nothing.

if you always need to get "latest good" cache - you need to store data at any persistent storage, such as database or flat file.

in this case if nothing found in cache - you do twitter api request. if it fails - you read data from persistent. and on another http request you will make same iteration one more time.

or you can put data from persistent into memcache with pretty shor lifetime. few minutes for example (1-5) to let twitter servers time to get healthy. and after it expired - repeat the request.

Upvotes: 1

Nobwyn
Nobwyn

Reputation: 8685

When you are putting your data into memcache - you are setting also how long the cache is valid. So theoretically you could also put the time when cache was created and/or when cache will expire. Later after fetching from cache you can always validate how much time left till cache will expire and decide what you want to do.

But letting cache to be repopulated on user visit can be still risky at some point - lets say if you would like to repopulate cache when it reaches ~5 min before expiration time - and suddenly there would be no visitors coming in last 6 minutes before cache expires - then cache will still expire and no one will cause it to be repopulated. If you want to be always sure that cache entry exists - you need to do checks periodically - for example - making a cronjob which does cache checks and fill-ups.

Upvotes: 0

deceze
deceze

Reputation: 522016

In that case, isn't this the better logic?

  • If the cache is older than 30 minutes, attempt to pull from Twitter
  • If new data was successfully retrieved, overwrite the cache
  • Cache data for an indefinite amount of time (or much longer than you intend to cache anyway)
  • Note the last time the cache was updated (current time) in a separate key
  • Rinse, repeat

The point being, only replace the data with something new if you have it, don't let the old data be thrown away automatically.

Upvotes: 5

Related Questions