This is Magento 1.9.x CE.

I have created some modules that implement a helper to pull data from various APIs and save the output in Magento's cache using the _saveCache method in Mage_Core_Helper_Abstract. The idea here is that if the cache item already exists and is not expired then it is loaded from cache, otherwise an API call is made.

This works well but has the potential to delay page load for the visitor if they hit a page when the item cache is expired and therefore the remote API needs calling.

To workaround this I figured I'd implement a cron task to call the API instead.

Can anyone think of a way to do this which still keeps API calls to a minimum (i.e. only call the API when the cache is nearly expired) but ensures that the cached item is always available?

For reference I am thinking of caching results for around 6 hours but this would be configurable.

I was thinking some kind of logic like this:

  • Run the cron every minute:
  • Check whether the item exists in cache
    • if not: make API call, store result as cache item, exit
    • if so: continue
  • Check whether the cache lifetime is approaching (how to do this bit??)
    • if so: make API call, store result as cache item, exit
    • if not, exit

So really, the question boils down to how can I check whether the cache lifetime is approaching? And/or can anyone think of a better way to do this?

Many thanks!

  • your approach sounds good to me, whether the cache "lifetime is approaching" is irrelevant because as soon as the cache has expired your logic will fetch and cache the data again. – paj Sep 18 '17 at 12:36
  • @paj it is not irrelevant because if a page requests the cache item after the cache has expired but before the cron task has re-saved the cache item then the page will not be able to load the cached data (because it will have expired). – BlueC Sep 18 '17 at 12:41
  • The page request should also refresh the cache if it has expired? if that 60 second window is a problem run the cron job more often, every 10 seconds? – paj Sep 18 '17 at 12:46
  • @paj I would prefer a more robust approach – BlueC Sep 18 '17 at 12:49
  • Hmm looks like I can use getMetadatas() method in Zend_Cache_Core as this will return the expire timestamp amongst other things. – BlueC Sep 18 '17 at 12:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.