How to prevent database from being DDOSed by application when cache expires? How to prevent database from being DDOSed by application when cache expires? codeigniter codeigniter

How to prevent database from being DDOSed by application when cache expires?


If you have control of background tasks, such as cronjobs, you can arrange to have the work done, and data fetched, ahead of the required time, so that recent data never goes out of cache.

You could, for example, have a job run every 20 mins (or every minute for that matter), updating the cached values. While that job runs, no other database queries would be required to fetch the data.


You can use my algorithm from this code: https://github.com/jamm/Memory/blob/master/lib/Jamm/Memory/MemcacheObject.php#L230

  1. Read key and TTL
  2. If TTL is small (less than 5 seconds, forexample), try to lock special key (not that you are reading), like'_update.{name_of_key}'
  3. If lock was successful - calculate (orread) new value and refresh cache
  4. release updating key.

So only 1 process will read new value from DB.


As to clarify my answer i'll write some code to show what i ment ( it might be a solution after all anyway... ):

if ($this->cacheExpired()){    if (!$this->isMarkedAsRegenerating())    {         $this->markAsRegenerating();              //..ing         $this->regenerateCache();         $this->markAsCacheRegenerated();          //..ed    } else {         while ( $this->isMarkedAsRegenerating() )         {               sleep(1); //sleep 1 second to decrease database-queries, we are preventing a DDOS you know...         }    }}$this->output(); //at this point, we always have a cached version of the page

The only risk involved is two pagehits at the very same time which *would make it possible to have the cache regenerated two times. It is very very unlikely but if it happens at least all other requests are still waiting.