4

I want to use the Spine.js client-side framework, and it generates UUIDs as IDs for models, which can then be persisted to the server. It would be easiest if I just used the client-generated UUIDs for the models, and saved them on the server.

What are the drawbacks of using client-generated UUIDs as primary keys in Rails?

skaffman
  • 398,947
  • 96
  • 818
  • 769
Chetan
  • 46,743
  • 31
  • 106
  • 145

2 Answers2

11

I dislike UUIDs for "primary keys" in general, however, a distributed model is one in which they fit rather well, assuming the UUID is generated appropriately ;-) Depending upon other issues, it still might not be the primary key, but rather another candidate key (think of "an alternate PK" that is backed by a unique index).

The two "issues" I am aware of are:

  1. UUIDs are like IPv6. They are long and are thus not the most human-friendly values about. On the other hand, they are very consistent in formatting and are easy to spot. Have your copy'n'paste skills about.

  2. Completely random UUIDs tend to fragment indices; if used as PK, which is normally clustered (vs. an index which may just a pointer to the record), this can lead to terrible fragmentation. However;

    1. A good database maintenance plan should solve this: re-index fragmented indices on a schedule.

    2. Special UUID generation schemes, such as NEWSEQUENTIALID in SQL Server, while "more predictable", can also generate monotonically increasing values and thus mitigate index/cluster fragmentation.

Happy coding.

  • Considering all this, are there any Rails-specific gotchas I should know about? – Chetan Jul 30 '11 at 06:16
  • 2
    "None That I've Run Into" (TM) (C) (R) –  Jul 30 '11 at 06:18
  • I just found one. `rails_admin` doesn't work with non-integer primary keys. Looks like many plugins assume an integer `id` field, and they would be broken :/ – Chetan Jul 31 '11 at 01:31
  • well, id's shouldn't have to be used or written by humans in the first place, you should never hard code an id in code, and for testing you should use your own code to manage it, not typing it. – kisai Jun 07 '18 at 23:35
3

Assuming you're using a relational database to store these values, one thing to watch out for is that UUIDs generally perform poorly as primary table keys when the table is large.

Check out the informative discussion in this blog post written by our fearless leader: Primary Keys: IDs versus GUIDs

Kevin Pullin
  • 13,122
  • 3
  • 24
  • 33