How to make a UUID in DynamoDB?

Disclaimer: I am the maintainer of the Dynamodb-mapper project

Intuitive workflow of an auto-increment key:

  1. get the last counter position
  2. add 1
  3. use the new number as the index of the object
  4. save the new counter value
  5. save the object

This is just to explain the underlying idea. Never do it this way because it's not atomic. Under certain workload, you may allocate the same ID to 2+ different objects because it's not atomic. This would result in a data loss.

The solution is to use the atomic ADD operation along with ALL_NEW of UpdateItem:

  1. atomically generate an ID
  2. use the new number as the index of the object
  3. save the object

In the worst case scenario, the application crashes before the object is saved but never risk to allocate the same ID twice.

There is one remaining problem: where to store the last ID value ? We chose:

{
    "hash_key"=-1, #0 was judged too risky as it is the default value for integers.
    "__max_hash_key__y"=N
}

Of course, to work reliably, all applications inserting data MUST be aware of this system otherwise you might (again) overwrite data.

the last step is to automate the process. For example:

When hash_key is 0:
    atomically_allocate_ID()
actual_save()

For implementation details (Python, sorry), see https://bitbucket.org/Ludia/dynamodb-mapper/src/8173d0e8b55d/dynamodb_mapper/model.py#cl-67

To tell you the truth, my company does not use it in production because, most of the time it is better to find another key like, for the user, an ID, for a transaction, a datetime, ...

I wrote some examples in dynamodb-mapper's documentation and it can easily be extrapolate to Node.JS

If you have any question, feel free to ask.


Another approach is to use a UUID generator for primary keys, as these are highly unlikely to clash.

IMO you are more likely to experience errors consolidating primary key counters across highly available DynamoDB tables than from clashes in generated UUIDs.

For example, in Node:

npm install uuid

var uuid = require('uuid');

// Generate a v1 (time-based) id
uuid.v1(); // -> '6c84fb90-12c4-11e1-840d-7b25c5ee775a'

// Generate a v4 (random) id
uuid.v4(); // -> '110ec58a-a0f2-4ac4-8393-c866d813b8d1'

Taken from SO answer.