Sunday, December 22, 2013

Decentralise id generation

It seems to be a common practice nowadays to rely on the database-generated, incremental id.

In one of our projects, we let the client-side (JS) generate the id (using guid/uuid). It leads to interesting consequences. We no longer need to send the form data to the backend immediately. If we want, we can create the object on the client-side, give it a guid, keep editing it and then send it back to the server, with the guid. The server stores the guid and uses it for identification. The same can happen at the same time from another Ruby client that connects to the same API.

This is how an example guid looks like:

f81d4fae-7dec-11d0-a765-00a0c91e6bf6


"A UUID is 128 bits long, and can guarantee uniqueness across space and time."

RFC: http://www.rfc-archive.org/getrfc.php?rfc=4122

"A UUID is an identifier that is unique across both space and time, with respect to the space of all UUIDs. Since a UUID is a fixed size and contains a time field, it is possible for values to rollover (around A.D. 3400, depending on the specific algorithm used)."

"Unless you're accepting IDs on, say, an Internet-wide scale, or with an untrusted environment where malicious individuals might be able to do something bad in the case of an ID collision, it's just not something you should worry about."

My opinion on UUIDs

For years, I have been thinking that centralised id generation is the natural way. Seems obvious. After I learnt mote about UUID, I start seeing more and more good things about it. It allows for less coupling between components/services.  You no longer need to 'ask' for the id. In case of JavaScript frontends it solves the problem of whether to block the UI, when we create a new resource.

The area, that I haven't researched much is having distributed database which you sync between the services. From what I know, it's already possible with http://www.datomic.com/.

Ruby 

Ruby has a built-in method:

http://www.ruby-doc.org/stdlib-1.9.3/libdoc/securerandom/rdoc/SecureRandom.html#method-c-uuid

p SecureRandom.uuid
# "2d931510-d99f-494a-8c67-87feb05e1594”

JavaScript

JS library
https://github.com/pnegri/uuid-js

var uuid4 = UUID.create();
console.log(uuid4.toString());
// Prints: 896b677f-fb14-11e0-b14d-d11ca798dbac


Python

>>> import uuid
>>> # make a UUID based on the host ID and current time
>>> uuid.uuid1()

UUID('a8098c1a-f86e-11da-bd1a-00112444be1e’)


Java

UUID uuid = UUID.randomUUID();



Also worth reading: http://stackoverflow.com/questions/703035/when-are-you-truly-forced-to-use-uuid-as-part-of-the-design/786541#786541

No comments: