I currently use Sequelize'sincrement()
function to increment the column of order number values. For example:.increment("order_no", { by: 1 });
Occasionally a request will arrive at my API simultaneously within the same second, resulting in duplicate order number values.
Is there a way to ensure that the incremental value of the order number is unique? Do I need to wrapincrement
in transaction? After creating an order number, should I randomly and regularly check if there are duplicates? Not sure the correct way to solve this problem.
According to Sequelize’s documentation (https://sequelize.org/docs/v6/core-concepts/model-instances/#incrementing-and-decrementing-integer-values)
In order to avoid concurrency problems, Sequelize provides increment and decrement instance methods to increment/decrement the value of the instance.
However, although it appears that this method works, you will still get duplicate values when used.
I think if there is a duplicate order ID, you can try to catch the error and retry the operation, generating a new order ID.