Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Cache Stampede example
<?php
/**
* Cache stampede protection examples
*/
class cache
{
/**
* @var array
*/
protected $items = array();
/**
* @param $key
* @param callable $callback
* @param int $ttlSeconds
* @return mixed
*/
function get($key, callable $callback, $ttlSeconds = 3600)
{
// Item exists
if (isset($this->items[$key])) {
// Cached value is still valid
if ($this->items[$key]['ttl'] > time()) {
return $$this->items[$key]['value'];
}
// Cached value is stale, update the ttl forward so other calls
// get the stale value while regenerating the cache, this is what
// prevents the stampede. 60 sec should be longer than the time that
// $callback takes to run
$this->items[$key]['ttl'] = time() + 60;
}
// Get the value from callback and cache it
$this->items[$key] = array('value' => $callback(), 'ttl' => time() + $ttlSeconds);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.