title: Design patterns for asynchronous rebuilding of cache entries
body: <p>I have an application which routes requests depending on <code>predefined URLs</code> in the following manners:</p>
  
  <p><strong>1st step: Cache lookup</strong><br>
  All the <code>URLS</code> are aggregated into a single <code>array</code> (which is serialized and stored in cache) which structure is as follows:  </p>
  
  <ul>
  <li>Each <code>array key</code> represents a <code>URL</code>  </li>
  <li>The <code>URL</code> information (i.e. what to do with the <code>URL</code>) is defined as the corresponding <code>array value</code>.</li>
  </ul>
  
  <p>In practice, this gives me (FYI <code>PHP 5.4</code> array syntax):  </p>
  
  <pre><code>&lt;?php
  
  // structure of the cached URLS array
  $cached_urls = [
      '/pageA' =&gt; [
          'controller' =&gt; 'ProductController',
          'content_id' =&gt; 1234
      ],
      '/serviceA' =&gt; [
          'controller' =&gt; 'ServiceController',
          'content_id' =&gt; 45678
      ]
  ];
  
  // working with the array (retrieve $cached_urls from cache, then...)
  if (!isset($cached_urls[$request['url']])) {
      // 404
  } else {
      $url = $cached_urls[$request['url']];
      // further actions based on $url
  }
  </code></pre>
  
  <p><strong>2nd step: DB lookup &amp; cache rebuilding</strong><br>
  if the <code>$cached_urls</code> array could not be retrieved from cache I do 3 things:  </p>
  
  <ul>
  <li>retrieve the <code>URL</code> information from a <code>url</code> table (where each <code>row</code> represents <code>1 URL</code> and the <code>URL</code> itself is the field used to filter the query) and other related tables.</li>
  <li>Process the request the same way I would to it in the cache scenario once I have <code>$url</code></li>
  <li>Rebuild the cache so that next time a request comes in, I don't have to do a DB lookup,</li>
  </ul>
  
  <p>In terms of execution speed, here is what we have (from faster to slower):  </p>
  
  <ol>
  <li>Cache Lookup  ( ~10ms)  </li>
  <li>DB lookup     ( ~100ms) </li>
  <li>Rebuilding the cache ( ~2000ms)</li>
  </ol>
  
  <p>When the cache is available, page are served very fast, however every time the cache gets rebuilt (which is about every minute), pages take a couple of seconds to be served, which is a problem. Therefore I was wondering:</p>
  
  <p><strong>What are the design patterns available in PHP to perform asynchronous processing (which in my case would be used to rebuild the cache) while avoiding the same tasks to be executed several times concurrently (as I only need the cache to be rebuilt once at a time until it is rebuilt, not for every request that hits my application in the meantime)?</strong></p>