4

How would you handle this:
You generate an id
You chech the db if it is not taken
If it is taken you generate a new one and check again.
You then save the new item with the generated id.

How do you ensure that between the time you checked and the time you added the item some other call did not try to also add an item with the same id.
Async mvc
C# and dotnet core with ef core

Comments
  • 2
    You let the db handle the id generation
  • 0
    @Kimmax no, because its generated in a special way so that's not an option
  • 1
    I would suggest adding a lock with a synchronisation object... But that is very anti-async 😅
  • 0
    @g-m-f
    No guids and no db id generation. How do you handle it
    😃
  • 0
    @g-m-f you get a string and convert it to int64 that you use for the id.
    Int64 because you can convert it back to the original string. (in the current case a 5 char string).
  • 1
    Use UUIDs in front of your string. The probabiloty of collision is infinitely small (not mathematically speaking).
    You could do
    UUID∅yourString∅
    ∅ being some special char you don't use in the string..
    I'm sure there has to be a simpler way :P
  • 0
    IDENTITY(10000,1) ???
  • 0
    The id(int64) is generated from a string that you need to be able to convert back to the original string. So none of the above work. And my question was not about the id but about the time between the check and the save.
    Also only a-zA-Z0-9
    😀
  • 1
    I know it should be async, but maybe do it as a transaction? You cant have full async and make it work regardless
  • 1
    You have to generate unique ids. That's all. If you can't generate unique id thus you can't ensure that is not already used. End of discussion.
    And you have to accept something: you can't avoid collision. So, play around, and find a way to fix collisions.
  • 1
    @zazapeta i agree its impossible to achieve the goal mentioned in my first post without loosing performance or making other sacrifices.
  • 2
    @SGrigorov it's either going to be the DB generating them, you generating them including locking, UID's or hoping driving a pseudo unique generator never collides with another id
    No other way I could think of.
  • 2
    How about going dirty and check the ID by inserting it? On fail it's taken and you try again, on success it's now reserved and you can go ahead and use it to update...
  • 0
    @Flygger sounds like a major performance hit
    😁
  • 1
    @SGrigorov better than high performance and it doesn't work ;)
Add Comment