Search code examples
ruby-on-railsmodelguiduuidspine.js

Should I use UUIDs as primary keys for Rails?


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?


Solution

  • 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.