Standards

Public short ids

On this page
  1. Rule
  2. Why a stored alias, not an encoding
  3. Not a secret
  4. Public is the only public identifier
    1. Where each id lives
  5. Which entities get one
  6. Alphabet & length
    1. Collision headroom
  7. Type-safety
    1. Optional entity prefix
  8. Persistence & resolution
  9. Minting & collisions
  10. Ordering & pagination
  11. Logging
  12. Checklist

Rule#

Entities exposed in user-facing URLs carry a public short id alongside their internal Id<T> (UUIDv7). The short id is a stored opaque alias — an 11-character Crockford Base32 code with a UNIQUE index — not an encoding of the UUID. URLs and public API surfaces use the short id; the database primary key and all internal code stay on Id<T> (data-persistence.md). Resolution is a single indexed lookup at the HTTP boundary.

/subscriptions/019e61e2-0a78-7540-b060-0e6e01d171e0   internal / DB
/subscriptions/9TXK4P2RQ8M                            public

Why a stored alias, not an encoding#

A UUIDv7 is 128 bits; an 11-char code holds 55. You cannot reversibly shrink one into the other, so the short id must be a separate value with its own column and unique index. Encoding schemes (Sqids/Hashids, Feistel) need a small sequential integer key — our entities have none, they're UUIDv7 by standard. The short id is minted at insert, immutable, and 1:1 with the entity for its lifetime.

Not a secret#

The short id is a handle, not a capability. Authorization is enforced server-side on every request exactly as before (auth-integration.md); knowing a short id grants nothing. Never gate access on the short id alone. If a resource is protected only by an unguessable URL, use a full-entropy token — not this mechanism.

Public is the only public identifier#

The public id is the only identifier that crosses the public boundary. Anywhere an id is exposed — URL path, query param, JSON body, real-time event envelope — it is the public id, never the UUID. A DTO's id field carries the public id; the UUID is never serialized to a client.

Where each id lives#

The public id is a stored attribute of the entity, not a view-layer invention: db mints it at insert and owns the resolve_* lookup. So the layers split like this:

  • core / db may carry it. A domain model or row struct can hold a public_id: PublicId<T> field alongside its Id<T>, the same way it holds any other column. An event/audit row that is itself exposed to clients may cite the public ids of the entities it references, so replaying it needs no translation.
  • Relationships and internal calls stay on Id<T>. Foreign keys, repo method arguments, engine operations, joins, cursors and ordering all use Id<T>. Nothing inside the server looks an entity up by its public id except the resolver.
  • Resolution and choice of wire id live in the exposer. The poem API (or any other outward-facing surface) parses the inbound PublicId<T>, resolves it to Id<T> once via db, and passes only Id<T> inward. On the way out it decides which id goes on the wire: always the public id.

Which entities get one#

A judgement call: any entity a user might land on, link to, or reference by URL. Internal-only entities (never addressed from outside the exposer layer) keep just their Id<T> and need no public id.

Alphabet & length#

  • Crockford Base32, uppercase: 0-9 A-Z minus I L O U. Case-insensitive, URL-safe, no ambiguous characters, survives being read aloud or transcribed into a support ticket.
  • Fixed 11 chars = 55 bits (~3.6e16 codes). Generate 7 random bytes (56 bits), Crockford-encode, take 11 chars. Insert against the UNIQUE index; on conflict, regenerate. A collision is a transparent retry, not a failure.
  • Normalize on input before lookup: uppercase, then map Crockford's confusables (I/i/L/l → 1, O/o → 0).

Collision headroom#

At 55 bits a collision is a non-event until table sizes far beyond fleet scale. The UNIQUE index + regenerate-on-conflict means a collision only ever costs one extra insert attempt:

Rows in tablePer-insert collision probabilityLifetime chance of any collision
1M2.8e-11~0.001%
10M2.8e-10~0.14%
100M2.8e-9~13% (≈ one transparent retry)

The ~50% point for a single lifetime collision is ~224M rows. Treat 11 as fixed; if an entity ever genuinely approaches that scale, widen its column rather than shorten anything.

Type-safety#

Mirror Id<T>: a PublicId<T> newtype tagged with the entity, so a subscription's public id can't be used to look up an order. Runtime representation is 11 ASCII bytes (Copy); it serializes as the canonical code string and parse normalizes confusable spellings on the way in. Internal operations take Id<T> — resolve at the edge.

Both types come from libid (lib-ecosystem.md) — don't hand-roll a copy:

libid = { git = "https://github.com/charliethomson/libid", features = ["sqlx"] }
use libid::{Id, PublicEntity, PublicId};

struct Subscription;
impl PublicEntity for Subscription {}   // canonical form: the bare 11-char code

Feature gates: serde (default) — canonical-string transport, normalizing parse; sqlx — SQLite bindings (Id<T> as BLOB via Uuid, PublicId<T> as TEXT), so the typed values bind directly with no .to_string() at call sites; poem-openapi — both types are opaque strings in the contract.

Optional entity prefix#

An entity may override PublicEntity::PREFIX (default "") with a short lowercase tag:

impl PublicEntity for Order {
    const PREFIX: &'static str = "ord";   // canonical form: ord_9TXK4P2RQ8M
}

The prefix then becomes part of the canonical form — stored, displayed, and required on parse — making a pasted id self-describing in a URL or support ticket. The 11-char code still carries all the entropy; the collision math is unchanged. Pick one style per product and keep it: switching later is a data migration, not a display tweak.

Persistence & resolution#

  • Column public_id TEXT NOT NULL UNIQUE on each public-facing entity. The primary key stays the UUIDv7; the unique index is the only thing the public lookup touches.
  • One repo method per entity: Db::resolve_subscription(&PublicId<Subscription>) -> Result<Id<Subscription>> (or fetch the row directly). Map a miss to the standard not-found error (error-handling.md).

Minting & collisions#

Mint at insert and retry the insert, not the request, on a public_id collision. The catch: the standard write-error classifier maps any UNIQUE violation to a domain Conflict (data-persistence.md), which would surface a code collision to the client as a 409 instead of silently retrying.

Distinguish by the constraint's column. SQLite names it — UNIQUE constraint failed: <table>.public_id — so the insert loop regenerates only on that index and lets every other UNIQUE (a real business conflict) fall through:

for _ in 0..4 {
    let pid = PublicId::<Subscription>::new();
    match self.try_insert(pid, /* … */).await {
        Ok(row) => return Ok(row),
        Err(e) if is_public_id_conflict(&e) => continue,        // regenerate, retry
        Err(e) => return Err(map_write_err(&e, /* … */)),       // real conflict/FK
    }
}
Err(Error::storage("public_id: exhausted retries"))            // ~never; RNG/index bug

Four attempts is plenty — per-insert odds are ~1e-9 even at 100M rows, so exhausting them means something else is wrong (a broken RNG, a duplicated index).

Ordering & pagination#

The public id is random, so never sort, range-scan, or paginate on it. Keep ORDER BY, cursors, and seek keys on the internal Id<T> (UUIDv7, time-ordered) or an explicit timestamp — the same key you'd use without public ids. A cursor handed to a client is an opaque token over that internal key, not the public id; the public id is a point-lookup handle only.

Logging#

Log both: the short id (what appears in user-facing URLs and support tickets) and the internal Id<T> (what joins across services). Short ids aren't secrets, so they're safe as structured fields (observability.md).

Checklist#

  • Public-facing entities have public_id TEXT NOT NULL UNIQUE; PK stays UUIDv7.
  • Short id is a stored alias: 11-char Crockford Base32, minted at insert, regenerated on UNIQUE conflict.
  • Insert retries on a public_id UNIQUE (matched by column); other UNIQUEs still map to domain Conflict, not a swallowed retry.
  • Ordering/pagination keyed on Id<T>/timestamp, never the random public id.
  • libid's PublicId<T> (not a hand-rolled copy); resolved to Id<T> once, at the HTTP boundary. Prefixed and bare canonical forms not mixed within a product.
  • Input normalized (uppercase + Crockford confusables) before lookup.
  • Authz enforced server-side regardless of the short id — it is not a secret.
  • Public id is the only id exposed. Models/rows may carry public_id, and exposed event rows may cite public ids, but internal calls, FKs and cursors use Id<T>; inbound resolution and the choice of wire id live in the exposer layer.