3

I created a new application and I am thinking where is the best place to generate a UUID.

  1. Generate a UUID in application level and persist it
  2. Generate a UUID in Database level

I have a feeling that is a better approach to generate the UUID in Database level.

What do you think and why?

Many thanks in advance

pik4
  • 365
  • 3
  • 13
  • 3
    One of the reasons why you might want to use a UUID is because you *want* to generate it in the application. Other kinds of primary keys, like consecutive integers, cannot be generated in the application without an extra round trip to the database, making generating them in the database a more favorable approach. – Robert Harvey Jun 06 '18 at 15:00
  • 1
    Beyond that, there are several other pros and cons. Which approach is "better" for you depends on what your specific requirements are. – Robert Harvey Jun 06 '18 at 15:01

2 Answers2

3

You may want to go with "both".

Generating the UUIDs in the application usually makes it easier to run tests as mocking DB logic can be quite fragile.

On the other side of things, if you're developing and need to quickly populate fake data, it's easiest if the UUID can be generated as part of a simple insert statement.

TL;DR: it depends on the context

Morgen
  • 1,071
  • 7
  • 10
0

For most applications IDs should be generated in the DB as this will prevent duplicates if you have multiple client instances, for example load balanced web servers. There are database systems which have different consistency models from SQL RDBMSs which can have the same problem but then you are making an active choice to use an inconsistent DB.

Inverted Llama
  • 413
  • 2
  • 9
  • 3
    Note that this doesn't really apply for UUIDs, as the entire point is that they are "unique" purely through probability. – Turksarama Jul 09 '18 at 01:34