Race condition with a variable changing in time

I have an array in memory (nodejs server side) that I am updating every 10s and a client that do a request every 10s also. The request parses the array to get it in a specific string format. Also, the update process is in a setInterval function.

I want to run a stress test to that endpoint. I thought that if I move the process of parsing the array to string to the place where I am updating the array, then service only will return a string (like a cache) and stress test will not be a problem to pass.

Here, my problem is: if the time required to update my array and parsing is so long until reach the assignation of a new value for the string cached, then client will receive a non correct value from the service because it continues updating. So my question is how can I be sure client will receive the correct value always. That is, how can I avoid race condition in this context.

Upvotes: 0

Views: 409

Answers (1)

Michael Sorensen
Michael Sorensen

Reputation: 2124

The good news is; unless you have spawned a worker or another process Node is single threaded. So it is quite impossible for Node (under normal circumstances) to encounter race conditions.

However, from your description it sounds like your are concerned about the asynchronous nature of your http requests.

  1. Client makes a request to the server

  2. Server begins work

  3. 10 seconds pass (server is still working)

  4. Client makes another request to the server using outdated information since server isn't done working.

  5. Server returns old data but, at this point it is too late.

Fortunately, there is more good news. Javascript has a TON of built in support for asynchronous programming. Usually you would wrap your requests in a promise to avoid such pitfalls. Resulting in a process that looks like this:

  1. Client makes a request to the server

  2. Server begins work

  3. Client waits until server comes back before continuing

  4. Server finishes work and returns data to client

  5. Client send another request to the server (ad-infinitum)

You can also make your Promises look like synchronous programming that you're used to via the new(-ish) async functions. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

Upvotes: 1

Related Questions