1

I've come up with a fancy issue of synchronization in node.js, which I've not able to find an elegant solution:

I setup a express/node.js web app for retrieving statistics data from a one row database table.

  • If the table is empty, populate it by a long calculation task
  • If the record in table is older than 15 minutes from now, update it by a long calculation task
  • Otherwise, respond with a web page showing the record in DB.

The problem is, when multiple users issue requests simultaneously, in case the record is old, the long calculation task would be executed once per request, instead of just once.

Is there any elegant way that only one request triggers the calculation task, and all others wait for the updated DB record?

1 Answer 1

1

Yes, it is called locks.

Put an additional column in your table say lock which will be of timestamp type. Once a process starts working with that record put a now+timeout time into it (by the rule of thumb I choose timeout to be 2x the average time of processing). When the process stops processing update that column with NULL value.

At the begining of processing check that column. If the value > now condition is satisfied then return some status code to client (don't force client to wait, it's a bad user experience, he doesn't know what's going on unless processing time is really short) like 409 Conflict. Otherwise start processing (also ideally processing takes place in a separate thread/process so that user won't have to wait: respond with an appropriate status code like 202 Accepted).

This now+timeout value is needed in case your processing process crashes (so we avoid deadlocks). Also remember that you have to "check and set" this lock column in transaction because of race conditions (might be quite difficult if you are working with MongoDB-like databases).

Sign up to request clarification or add additional context in comments.

1 Comment

Is there any way that can get rid of the DB table r/w access lock?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.