Once

Once is an Ecto type for locally unique (unique within your domain or application) 64-bit IDs generated by multiple Elixir nodes. Locally unique IDs make it easier to keep things separated, simplify caching and simplify inserting related things (because you don't have to wait for the database to return the ID).

Because a Once fits into an SQL bigint, they use little space and keep indexes small and fast. Because of their structure they have counter-like data locality, which helps your indexes perform well, unlike UUIDv4s.

Once IDs are based on counter, time-sortable or encrypted nonces. These underlying values can then be encoded in several formats, can be prefixed and can be masked. And you can combine all of these options, providing great flexibility.

The library has only Ecto and its sibling NoNoncense as dependencies. NoNoncense generates the actual values and performs incredibly well, hitting rates of tens of millions of nonces per second, and it also helps you to safeguard the uniqueness guarantees.

Read the migration guide {: .warning}

If you're upgrading from v0.x.x and you use encrypted IDs, please read the Migration Guide carefully - there are breaking changes that require attention to preserve uniqueness guarantees.

Features

ID Generation Types

Once supports three types of ID generation:

Flexible Formats

IDs can be represented in multiple formats, both in your Elixir application (:ex_format) and in your database (:db_format). By default, IDs are url64-encoded 11-character strings in Elixir and signed bigints in the database. You can choose from :url64, :hex, :hex32, :raw, :signed, or :unsigned formats and use to_format/3 to transform between them.

Prefixed IDs

Add Stripe-style prefixes to IDs (e.g., "usr_AV7m9gAAAAU") for better debugging, API clarity and type safety. Prefixes can exist only in Elixir or be persisted to the database.

Masked IDs

Masked IDs provide a middle ground between plaintext and encrypted IDs. They're stored as plaintext in the database (preserving performance) but encrypted when retrieved by the Ecto type, so your application only sees encrypted values.

Installation

The package is hosted on hex.pm and can be installed by adding :once to your list of dependencies in mix.exs:

def deps do
  [
    {:once, "~> 2.1.0"}
  ]
end

Docs

Documentation can be found on hexdocs.pm.

Testing

Usage

To get going, you need to set up a NoNoncense instance to generate the base unique values. Follow its documentation to do so. Once expects an instance with its own module name by default:

# application.ex (read the NoNoncense docs!)
children = [
  MyApp.Repo,
  {NoNoncense.MachineId,
    # see NoNoncense.MachineId for different strategies
    strategy: NoNoncense.MachineId.Strategy.SqlLease,
    strategy_opts: [repo: MyApp.Repo],
    # if you want to use encrypted/masked IDs, also pass a 256-bits key
    instances: [[name: Once, base_key: System.fetch_env!("ONCE_SECRET_KEY")]]}
]

Supervisor.start_link(children, strategy: :one_for_one, name: MyApp.Supervisor)

In your Ecto schemas, you can then use the type:

schema "things" do
  field :id, Once, autogenerate: true
end

And that's it! Be sure to look at hexdocs.pm for options and additional info.

Querying sortable IDs

For fields configured with nonce_type: :sortable, import Once.Query to filter by ID generation time:

import Ecto.Query
import Once.Query

from p in MyApp.Post, where: later_or_at(p.id, ^start_time) and earlier_than(p.id, ^end_time)
from p in MyApp.Post, where: at(p.id, ^timestamp)

The epoch defaults to 2025-01-01 00:00:00 UTC. If the generator uses a different epoch, define a module with use Once.Query, epoch: ... and import it instead. The epoch and timestamps can be DateTimes or integer Unix milliseconds. See Once.Query for the available predicates and their requirements.

Reading ID generation time

To read a sortable ID's generation timestamp as a DateTime, map a read-only Once.CreatedAt field to the same database column:

schema "posts" do
  field :event_id, Once, nonce_type: :sortable
  field :event_created_at, Once.CreatedAt,
    source: :event_id,
    nonce_type: :sortable,
    writable: :never
end

See Once.CreatedAt for configuration and limitations.

Compatibility

Elixir 1.18+ and OTP 27+ are fully supported and tested in CI.

Elixir 1.16–1.17 (with OTP 26+) are supported on a best-effort basis and tested in CI. Issues will be considered but may not be fixed if they require significant workarounds.

Older versions are not supported.