Skip to content
Advertisement

How to generate low character primary keys for NoSQL/DynamoDB?

I need to generate room codes for a Flask project, in a similar style to how https://jackbox.tv/ does it.

These room codes will serve as the primary key in a DynamoDB table, and as such will need to be unique.

One option is to use UUIDs, however these are very large and are not user-friendly to type in. Is there a way to generate short (~4-8 character), unique-ish codes without repeatedly querying the DB?

Advertisement

Answer

You can use base36 representation of current timestamp which will be 8 characters long and probability of repeated will be very low. in practice this works good.

import base36
from datetime import datetime

key = base36.dumps(int(datetime.utcnow().timestamp() * 1000))
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement