Handling Race Condition

sandeep3791
Tera Contributor

Hello,

I am trying to prevent the race condition issue that we are running into because of the nature of application we have.

System - 

We have a phone number management (inventory) application which is Queried by external system and our application returns the NEXT AVAILABLE phone number. Now since this is a Phone Number that is later on activated on the network this should not be given to multiple requests coming from external systems.

Problem - 

All of this is working fine unless we try to trigger two or more requests at exactly the same time and our application in such cases return the same number to all the concurrent requests which we want to avoid.

Note - At the same time we want our application to be able to handle parallel requests that could be for other operations (other REST API), so not want to resolve this race condition problem by making the system linear in terms of processing API requests one by one.

 

Is there a way to solve this, may be somehow by allowing only one Active thread to access our scripted REST at a time.

 

 

 

 

 

 

2 REPLIES 2

DrewW
Mega Sage
Mega Sage

Sounds like you need to use a GlideMutex to lock out the web service until other requests are fullfilled.  Don't expect any documentation on it thou, ServiceNow does not want people using it.  Here is an old example that you can look at and don't forget to release it.

https://old.wiki/index.php/Serialize_Using_a_Lock_(Mutex)

Some other thoughts/suggestions

- Generate a bunch of phone numbers ahead of time and change your query to get the next available one that is not taged as sent or something. Before updating the record use a GlideMutex to lock it so other requests cannot update it.

- Create a semaphore pool that allows a max concurrency of 1 and is only for the one web service.  I had a script at one point to create one but cannot find it, but the table they are stored in is sys_semaphore.  Its not a good idea to create a lot of these as I understand it.  You are basically allocating slices of pie and by creating more of these you make the slices smaller since you only have 1 pie for all but they do act as a kind of traffic cop queueing up people who go over the set limit.

 

- Add a unique index to the phone number field.  Then in your code use a try catch block and write to the field.  If you get an error then try and get the next number and try again, rinse and repeat.  Make sure that you use a max loop check so you do not accidently loop infinitely for some reason.

 

Ramon Cordova
Tera Contributor

Hi @sandeep3791,

Were you able to implement a solution for your problem?

I am facing a kind of similar issue too.