I'm working on a billing system (C# code, MySQL Galera Cluster backend, InnoDB storage engine) and have a doubt about how to generate a truly unique sequence number for invoices.
Usually in other systems I created a unique service to get the invoice numbers, whenever an invoice where generated I asked to that service for a number and as that service guaranteed the exclusive access to a table which held the counter there would be no problem at all.
But this new system is clustered for high availability, so this approach is not acceptable as there needs to be multiple of these services running.
So the logic I'm aplying here is this:
- start transaction
- create invoice with no serial number
- retrieve serial counter
- write new counter to table
- update invoice
- commit
If i'm not wrong, if some other transaction updates the counter before the current transaction is finished then the commit will throw an exception and I can then retry the operation, that will ensure the sequentiality of invoice numbers.
So my question is, which one is the correct isolation level to achieve this? is READ_COMMITED enough or may yield to duplicates? Or there's a better approach to this?