Writing multithreaded code to generate incremental index

I want to write a code in following scenario : we want to design an invoice generator.this invoice generator also generates an incremental invoice no .Also note that for some reasons we dont use something like sql Auto Increment here and we want to use C# (I wrote the increment logic). since several users can send requests at a time it means that we dont have to give the same invoice no to them (I used lock for it and I wrote it).

Now i have written increment logic. and i take care of multiple users requests with lock . and I wrote CRUD for mongodb database.

My problem is that my increent logic is naive. each time i find maximum and i increment by one which is not scalable. and another problem is that when we delete a record we don't want the invoice no to be repeated and since we find max if the deleted record had the max value then the invoice no would be duplicate and this is something we don't want to have.

I really don't know how to handle the problem. specially in case of deletion should i store max values in a file or should i change increment logic completely?

i appreciate any help

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum