I have got an http server written in Node.js that works fine, basically.
What it does is relay incoming requests to a web service. If the web service reacts, my web server transforms the answer and sends it back to the client. So far, so good.
Now what I want is some kind of timeout: If the web service takes too long to react (let's say, more than 5 seconds), I don't want to wait any longer and send back a 500 to the client.
I know that I could do this by using a call to setTimeout in the begin of the request, and cancelling it lateron, but that means that I am creating hundreds or thousands of concurrent timers - and most of them are completely irrelevant, as the result will be there in less than 5 seconds.
My fear is that this might be a bad idea due to memory usage and / or performance. Is this correct, or is it no problem to solve this requirement like this?
If it is a bad idea, what might be a solution? I already thought of a global timer that ticks every second, and each request subscribes to this timer, and has an internal counter, and sends a 500 when its internal counter is above 5. This would reduce the number of required timers to 1, but means that each request must correctly subscribe and (more important) unsubscribe to the global timer.
What other options are there?