I am having a problem with my web application that I’ve built.
It takes and processes customer orders through a web service.
Now, it does a check of MySQL to make sure this order hasn’t been processed before, but lately, we have been getting some duplicates. The time between these two orders is 1 millisecond apart.
I know this is my application and I should know this, but it is more of a generic question:
Is it possible that the 1 millisecond difference could be the difference between MySQL writing a record to its database, and my application checking for that record? If MySQL was taking this time to write its record, I can see that it would be possible for 2 duplicate orders to sneak through.
It appears that it is allowing duplicates because it is checking if the order already exists, and determines that it doesnt.
If so- are there any better ways of preventing duplicates from coming into my system?
You need to check whether the order exists and conditionally insert it in a single transaction.
If you first perform a SELECT and separately an INSERT, you leave a window open where the same INSERT can happen.
If you use a unique index on a field that makes your orders unique (e.g. Order ID), the second attempt to insert the same data would fail in a manner that you could gracefully handle.