Skip to content

Identities

Integer PKs for internal use, UUID and prefixed external identifiers, and encoding choices.

Every table needs two kinds of identity: an internal identifier for joins and foreign keys, and an external identifier safe to expose in APIs and URLs. Integer primary keys are efficient internally; a UUID or prefixed ID column handles external exposure without sacrificing join performance.

Internal identity

Postgres

Prefer GENERATED ALWAYS AS IDENTITY over SERIAL. SERIAL creates a sequence and sets a column default; the sequence is loosely coupled and can be reassigned or dropped independently. GENERATED ALWAYS AS IDENTITY is part of the SQL standard (Postgres 10+), attaches the sequence directly to the column, and makes accidental INSERT ... id = 42 a hard error rather than a silent sequence skip.

-- avoid
id SERIAL PRIMARY KEY
id BIGSERIAL PRIMARY KEY

-- prefer
id INT    GENERATED ALWAYS AS IDENTITY PRIMARY KEY  -- up to ~2 billion rows
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY  -- no practical limit

Use BIGINT by default. The storage difference is 4 bytes per row, negligible against the cost of a migration when an INT table approaches 2 billion rows.

SQLite

INTEGER NOT NULL PRIMARY KEY is an alias for the built-in rowid; SQLite assigns it automatically on insert, no sequence or trigger needed.

id INTEGER NOT NULL PRIMARY KEY

Avoid AUTOINCREMENT. It prevents ID reuse after deletes by tracking the highest ever-used ID in a separate system table, adding overhead to every insert. With proper foreign key constraints, references to deleted rows are cleaned up before those IDs can be reused. For stable external identifiers, add an application-generated identifier column as described below; AUTOINCREMENT is not a substitute.

External identity

Integer primary keys expose too much when used as external identifiers. Sequential IDs reveal insertion order and approximate count, and let anyone enumerate resources by incrementing: GET /users/1, GET /users/2. An application-generated identifier as the public-facing column decouples the API surface from the storage layer.

Two common formats: UUIDs (broad tooling support, standard format) and prefixed IDs (human-readable, type-annotated). Both work with the same two-column pattern.

Keep the integer PK for internal joins. Add the external identifier column that the API exposes.

CREATE TABLE users (
  id        BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  public_id TEXT   NOT NULL UNIQUE, -- e.g. 'usr_9vD8MuBJ3k5TqRnX' or UUID
  email     TEXT   NOT NULL,
  ...
);
CREATE TABLE users (
  id        INTEGER NOT NULL PRIMARY KEY,
  public_id TEXT    NOT NULL UNIQUE, -- e.g. 'usr_9vD8MuBJ3k5TqRnX' or UUID
  email     TEXT    NOT NULL,
  ...
);

The integer id never appears in API responses, URLs, or logs. All external references use public_id. Internal queries join on id.

UUIDs

UUIDv4 is 122 bits of random data. UUIDv7 is a 48-bit millisecond timestamp prefix followed by 74 bits of randomness.

The practical difference is index behavior. Random UUIDv4 values scatter inserts across the entire B-tree index; every insert risks a page split and degrades cache locality at high volume. UUIDv7’s monotonically increasing prefix means new rows append to the end of the index, the same access pattern as a sequential integer.

Use UUIDv7 by default. The timestamp embedded in the ID is millisecond-precision, which is rarely sensitive. Use UUIDv4 only when hiding creation time from the identifier is a concrete security requirement.

Postgres

uuidv7() is built in since Postgres 18. On earlier versions, use gen_random_uuid() (UUIDv4, available since Postgres 13) or add the pg_uuidv7 extension.

-- Postgres 18+
public_id UUID NOT NULL DEFAULT uuidv7() UNIQUE

-- Postgres 13–17
public_id UUID NOT NULL DEFAULT gen_random_uuid() UNIQUE

SQLite

Generate UUIDs in the application layer and pass them on insert. Store as TEXT (36 characters with hyphens); it reads correctly in tooling and sorts correctly as a string for UUIDv7.

public_id TEXT NOT NULL UNIQUE  -- set by application on insert

Prefixed IDs

Stripe-style IDs embed the resource type in the identifier: inv_9vD8MuBJ3k5TqRnX, cus_3Rq7wHNmPxY2, sk_live_abc123. The prefix makes the resource type immediately obvious in logs and error messages, prevents IDs from different tables being silently swapped, and produces strings that are shorter and easier to read than a UUID when someone needs to copy or type one.

Generation is application-side: pick a prefix, generate random bytes, encode them.

Common prefixes

Entity Prefix Example
User usr_ usr_9vD8MuBJ3k5TqRnX
Organization org_ org_3Rq7wHNmPxY2KjL4
Session sess_ sess_Kp2mNqRxTvWyZ8
API key key_ key_4FgHjKlMnPqRsT
Token tok_ tok_7BcDeFgHiJkLmN
Post post_ post_2XyZaBcDeFgHi
Comment cmt_ cmt_5JkLmNoPqRsTuV
File file_ file_8WxYzAbCdEfGh
Invoice inv_ inv_1QrStUvWxYzAb
Order ord_ ord_6CdEfGhIjKlMn
Subscription sub_ sub_9NoPqRsTuVwXy
Product prod_ prod_3ZaBcDeFgHiJk
Event evt_ evt_4LmNoPqRsTuVw
Webhook wh_ wh_7XyZaBcDeFgHiJ
Message msg_ msg_2KlMnOpQrStUv

Keep prefixes short and unambiguous. Document them in one place: when a prefix appears in a log, a stack trace, or a support ticket, the mapping to a resource type should be immediately obvious to anyone on the team.

How many random bits

The birthday bound determines when collisions become likely: with b bits of randomness, expect a 50% collision probability after roughly 2^(b/2) IDs.

Bits 50% collision at
64 ~4 billion
80 ~1 trillion
96 ~300 trillion
128 ~18 quintillion

96 bits is the practical sweet spot. 64 bits gets tight at scale; 128 bits (UUID) adds length without a meaningful safety gain at any realistic row count.

Encoding

The encoding determines string length and which characters appear in the output.

Encoding Alphabet Length (96 bits) URL-safe Notes
Hex 0-9, a-f 24 chars Yes Verbose
Base32 A-Z, 2-7 20 chars Yes Case-insensitive
Base58 0-9, a-z, A-Z (no 0OIl) 17 chars Yes No visually ambiguous chars
Base62 0-9, a-z, A-Z 17 chars Yes Includes 0, O, I, l
Base64url 0-9, a-z, A-Z, -, _ 16 chars Yes Compact; - and _ are odd to type

Base58 is the right default: no visually ambiguous characters (0 vs O, I vs l), URL-safe, and compact. Avoid plain base64: the +, /, and = characters require URL encoding.

With a four-character prefix, a 96-bit base58 ID is 21 characters total: inv_ + 17 chars. That compares favorably to a UUID’s 36 characters.

Generating

# Cargo.toml
bs58 = "0.5"
rand = "0.9"
use rand::Rng as _;

fn prefixed(prefix: &str) -> String {
    let bytes: [u8; 12] = rand::rng().random(); // 96 bits
    format!("{prefix}{}", bs58::encode(bytes).into_string())
}

macro_rules! id_type {
    ($name:ident, $prefix:literal) => {
        pub struct $name(String);

        impl $name {
            pub fn new() -> Self { Self(prefixed($prefix)) }
            pub fn as_str(&self) -> &str { &self.0 }
        }

        impl std::fmt::Display for $name {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                f.write_str(&self.0)
            }
        }

        impl std::str::FromStr for $name {
            type Err = String;
            fn from_str(s: &str) -> Result<Self, Self::Err> {
                s.starts_with($prefix)
                    .then(|| Self(s.to_owned()))
                    .ok_or_else(|| format!("not a {}: {s}", stringify!($name)))
            }
        }
    };
}

id_type!(UserId, "usr_");
id_type!(InvoiceId, "inv_");

FromStr is what deserializers and path extractors call; without it the type can be generated but not accepted from the outside world.

go get github.com/mr-tron/base58
package ids

import (
    "crypto/rand"
    "fmt"
    "strings"

    "github.com/mr-tron/base58"
)

type UserID struct{ v string }
type InvoiceID struct{ v string }

func (u UserID) String() string    { return u.v }
func (i InvoiceID) String() string { return i.v }

func newID(prefix string) string {
    b := make([]byte, 12) // 96 bits
    if _, err := rand.Read(b); err != nil {
        panic(err)
    }
    return prefix + base58.Encode(b)
}

func NewUserID() UserID       { return UserID{newID("usr_")} }
func NewInvoiceID() InvoiceID { return InvoiceID{newID("inv_")} }

func ParseUserID(s string) (UserID, error) {
    if !strings.HasPrefix(s, "usr_") {
        return UserID{}, fmt.Errorf("not a user ID: %s", s)
    }
    return UserID{s}, nil
}

func ParseInvoiceID(s string) (InvoiceID, error) {
    if !strings.HasPrefix(s, "inv_") {
        return InvoiceID{}, fmt.Errorf("not an invoice ID: %s", s)
    }
    return InvoiceID{s}, nil
}

Storage

Store the full prefixed ID as TEXT. If the table isn’t heavily referenced by foreign keys, the prefixed ID can serve as the primary key directly:

CREATE TABLE invoices (
  id         TEXT NOT NULL PRIMARY KEY,  -- 'inv_9vD8MuBJ3k5TqRnX'
  created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  ...
);

For tables with many FK references, the two-column pattern keeps foreign key storage compact:

CREATE TABLE invoices (
  id         BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  public_id  TEXT   NOT NULL UNIQUE,  -- 'inv_9vD8MuBJ3k5TqRnX'
  created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  ...
);

Type to search…

↑↓ navigate↵ selectEsc close