Search code examples
amazon-dynamodb

How to alias IDs in DynamoDB?


I have the following table in my DynamoDB

PK SK name
user#aee97067-b363-495c-9531-f1da15812eee user#aee97067-b363-495c-9531-f1da15812eee John

I also have a user profile feature in my web application. Users can navigate to their profiles using a URL like http://example.com/aee97067-b363-495c-9531-f1da15812eee. However, I find the long ID in the URL cumbersome, so I want to allow users to create aliases for their IDs. This way, instead of using the UUID, they can use a more human-readable alias in the URL, such as http://example.com/johndoe

How should the DynamoDB be structured in order to support this?

I have two solutions for how to do this, but I'm not sure which to choose because each has its own drawbacks

  1. Replace original UUID in PK with an alias
PK SK name
user#johndoe user#johndoe John
  1. Create a GSI (Global Secondary Index) for the alias and query by the GSI.
PK SK name GSI1PK GSI1SK
user#aee97067-b363-495c-9531-f1da15812eee user#aee97067-b363-495c-9531-f1da15812eee John user#johndoe user#aee97067-b363-495c-9531-f1da15812eee

In the first approach, I'm uncertain if it's a good idea to modify the "static" ID, because it might be used in logs and for "relational" references with other items.

In the second approach, there is no issue with editing its ID because it's a regular attribute. This method works well for querying data, but whenever I need to insert data, I have to somehow remap an alias to the ID. I'm not sure if it's efficient to request the "real" user ID by its alias on each write request in the controller before performing the write operation.

Can you suggest which approach I should use and why? Perhaps you have some experience with this and can share it with me

Thanks!


Solution

  • Use option 2 - make a GSI keyed by alias.

    A human-readable alias like "johndoe" is something could have a reason to change. It's also reasonable to expect that you might someday have users with multiple aliases or no alias.

    You shouldn't use something like that a primary key in any kind of database, because when/if it does change, it will break all of the references to the user in all of your systems.

    It's important to ensure that primary keys have no purpose other than to identify the things they identify.