I am running a queue of more than 7000 async tasks in parallel using an async queue with a max concurrency of 18.
In each async task I need to create a webserver, do some work and close the web server. I am using get-port to get an available port but I still get into race conditions where two or more different tasks will try to use the exact same port number.
My idea is to create these webservers once and reuse them accross tasks. This way I won't run into issues where multiple web servers can try to reuse the same port.
How can I make sure I am NOT reusing the same webserver between parallel async tasks?
Here is some code, some irrelevant parts are missing:
const asyncTask = async (task) => {
const port = await getPort()
// static files server
const server = http.createServer((request, response) => {
// You pass two more arguments for config and middleware
// More details here: https://github.com/zeit/serve-handler#options
return serveHandler(request, response, {
public: 'dist'
})
})
// start listening
server.listen(port, () => {
console.log(`worker running for task ${task} at port ${port}`)
})
// do the async work
server.close()
return 0
}
const q = queue(asyncTask, 18)
q.drain(function() {
console.log('all items have been processed')
})
q.error(function(err, task) {
console.error(`task ${JSON.stringify(task)} experienced an error`, err)
})
q.push(tasks)