My app generates a new order number by retrieving the last sequence number and adding 1. It works fine, except when two users click at exactly the same second, which creates duplicate numbers. How can I prevent this error?
There are a handful of in-depth discussions on the forum proposing various ways to prevent duplicates in situations like this…
but none of them will actually 100% prevent duplicates (as they are all still subject to race conditions) - although there are some ways to significantly reduce the chances.
But the questions is ‘Does it really matter’?
What issue would having 2 Orders with the same order number actually cause?
You Identify things in Bubble by their Unique ID (not by some arbitrary field)… And unless it’s the same order number AND the same User (and the same date, and amount) there won’t be any confusion.
Is it really worth the significant extra work involved to reduce the chances of collisions?
(or, if it really is that important, then consider using an external database so you can lock it as part of a transaction).
There a various ways to deal with this in Bubble (some are discussed in the linked thread)… but you still can’t eliminate the issue of race-conditions, so there’s always still a risk of duplicates.
The best method I’ve every come up with in Bubble is perhaps similar to what you’re suggesting, is to create a queue system, and process each item one by one in sequence.
Every single other method I’ve ever seen mentioned, I’ve been able to ‘break’ and force duplicates to be created… whereas with a queue (when set up correctlY) I’ve never been able to break it (but that doesn’t mean it completely eliminates the possibility of duplicates - it doesn’t, as race conditions are still always a factor in the absence of true database locking).