How to have string IDs with a prefix like Stripe has?

When working with Stripe API (and dashboard), I got so used to their style of IDs.

For customer, it is something like cus_sd9f87gds987, for subscription it is sub_df987gds98fg, for invoice it is in_d98fg7d987fg, and so on. You got the idea.

The UX is so much better, especially when logging, debugging, etc. I can even imagine when doing something like MySystem.Customer.find("sub_asd8f987sdfg908") I can reject it immediately without even asking the DB, because I am sure this ID doesn’t belong to a customer but to a subscription.

I am really curious how it works internally. If those “hashes” are just numerical DB IDs transformed on-the-fly to a string and prefixed with cus_, sub_, … for better readability or if those exact values are stored in their databases. If those IDs are generated by some central service like a Snowflake, or if they are using a PostgreSQL function or something similar.

What do you think would be the best approach to have something like that in a Phoenix + Ecto app?

3 Likes

Look at this package hashids | Hex it will give you hashed ids that you can reverse back.

2 Likes

Custom implementation(s) of Phoenix.Param can handle url generation using those user facing ids.

4 Likes