-1

My script sometimes receives 2 identical requests at the same time (difference in milliseconds) from an external system.

The script, upon incoming request, makes a request to the external system, checks for the existence of an entry there, and if not, creates it.

The problem is that with simultaneous requests, the check for uniqueness fails and as a result 2 records are created.

I tried to do a random sleep but it didn't work. $sleep = rand(1,5); sleep($sleep);

skywind
  • 892
  • 6
  • 22
  • 44
  • 1
    Adding sleep won't help at all. You could check afterwards how many rows there are and delete the latest one if there is more than one. – O'con Jan 09 '23 at 16:40
  • 2
    There are plenty of solutions, you can create a lock file and check if it exists before starting your script, if the script calls a database, take a look at [mutex](https://dev.mysql.com/doc/refman/8.0/en/lock-tables.html), or [transaction](https://dev.mysql.com/doc/refman/8.0/en/commit.html) – Reynadan Jan 09 '23 at 16:46
  • If you can make changes to what you call the 'external system' then I would try to set a unique index on there so only one request succeeds. Otherwise, you could set up something locally to do the same prior to forwarding requests to the other system. – Simon Goater Jan 09 '23 at 18:26

2 Answers2

0

I would suggest using a fast caching system, like memcached or redis.

Have a check if the system is busy

If not busy, make system busy by adding a flag in cache

Process the request.

Unflag the busy flag.

While processing, if another request comes, checks if busy in memcache/redis. If system busy, just don't do anything.

I'm going to try some pseudo code here:

function processData($requestData) 
{

   $isSystemBusy = Cache::get('systemBusy');

   if $isSystemBusy == true {

       exit();

   }

   Cache::set('systemBusy', true);

   //do your logic here


   Cache::set('systemBusy', false);


}
Frederik B.
  • 196
  • 3
  • 11
0

Solution was to write lock file with ID:

$tmp_file = __DIR__.'/tmp/'.$origDealId.'.lock';
        if (file_exists($tmp_file)) {
// duplicate request
            return null;
        } else {
// do something
}
skywind
  • 892
  • 6
  • 22
  • 44