promise.race – Saves the Day!

Earlier, I discussed how we resolved the problem of connection leaking in an out-of-box thinking. Today I wish to share a different problem.

Our unexpected surge in GeoIP subscription caused a massive connection problem. While we were focusing on auto-sharding, we realized that it was not just too many connections, it was also saving of data as a transaction.

Problem in technical terms:

Connection is stuck somewhere – we don’t know where. Client is expecting a response for PixSpy – it ain’t giving!

Solution:

RACE! – Lets race it down, whosoever wins get the output.


const itemOperation = 1000 * 0.1; //100 ms for our operation

const failedOnTimeout = new Promise((resolve,reject) => {
  return setTimeout(reject, itemOperation); //100 ms is more than enough for the operation
})
const saveMyData = new Promise(async(resolve,reject) => {
  // write your actual work here.
  try{
    return resolve(await Magic());
  }catch(e){
    return reject(e);
  }
})

return Promise.race(failedOnTimeout,saveMyData);

Updated: 2017
PS: You will need babel here to compile code. While es6 native support it at least 2 years away.

promise.race – Saves the Day!

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top