title: long polling and queue to hold requests
body: <p><code>POST /add-request</code> - adds new request</p>
  
  <p><code>POST /get-request</code> - returns first (oldest) request</p>
  
  <p>I have many Java apps which are called "slaves". Their job is to call <code>POST /get-request</code> to get request to process and after processing it save it to database. All requests are stored in mongoDB. <code>/add-request</code> just adds request to db. <code>/get-request</code> uses <code>findAndModify</code> mongo query to get first request from queue and set its status to "processing" (this status is required to avoid situation when same request is taken twice from DB). For now slaves just call api every 2 seconds. But I want to use some long-polling here. It should look like this:</p>
  
  <ol>
  <li>I have to keep slave requests in a queue.</li>
  <li>I have to set timeout foreach slave request to send for example 404 after 4 seconds if there is no new request.</li>
  <li>When new request is added through <code>/add-request</code> I have to take first slave request from queue, remove it from this queue, get request from DB and send it to this slave.</li>
  </ol>
  
  <p>so let's say i have to handlers (i am using express):</p>
  
  <pre><code>function addRequest(req,res,next){ 
      // add request to db and check if there is waiting slave request in queue
      // if there is one remove it from queue, clear timeout on it, get request from db
      // and send it to slave
  }
  
  function getRequest(req,res,next){ 
      // get request from db - if there is no request add this slave request to queue
      // set timeout to send 404 after 4 seconds
  }
  </code></pre>
  
  <p>The problem is with the queue - I tried many qpproaches but there is no any "synchronization" and I can't make it works... Is it possible to ensure consistency in a queue when two express handlers operate on it in the same time? The problem is with removing requests from queue after timeout. I have to search for request in queue using some uid and then removing it...</p>
  
  <p>Maybe there is some library/tool to accomplish my goal?</p>
  
  <hr>
  
  <p>404 is returned when there is no request for slave to process.
  I want to slave get the new request as fast as possible - so if I would return response instantly (new request or 404 when there is no request) then each slave would have to call api all the time non-stop and it would have impact on server performance I think. So I wanted each slave to "hold" on request for 4 seconds on server before returning any data. </p>