Using stripe like IDs in Ecto (Elixir)

Jan 13, 2022

This week I’ve been slowly learning more about Phoenix and Elixir, after a few false starts things are starting to make more sense.

Part of this has been digging into the world of IDs.

By default (just like in rails), Phoenix supports BIG SERIAL integer IDs for their primary keys + foreign keys.

It works okay… but if you’ve looked around, there are more options out there (IDs vs UUIDs vs ULIDs).

For me, I wanted to support a stripe like ULID. Something that could be generated outside of the app, but also had the convience of prefixing IDs with a short handle.

Luckily for me, Ecto actually supports prefixing out of the box (or at least it was added in 2020).

Now I’m able to support prefixing on primary ids like:

I’ve also opted to go with downcasing the ULIDs (normally they are upcased, but it is fully interchangeable).

Now when my ID for an org is created, it looks something like:

org_01fsab1yp4zh97q2pnj7p6x73x

Here’s the code to do it (it’s still fairly messy in parts):