Skip to main content

Programming languages · Intermediate · 20 min

Choose and generate IDs: auto-increment, UUIDv4 and UUIDv7

By Padding · Updated 18 Nov 2026
python:3.15-slim (Debian) · Python 3.15.2

You will generate sequential, UUIDv4, UUIDv7, ULID and short display IDs in Python 3.15, read the creation time out of a UUIDv7, measure what each costs in a 200,000-row SQLite table, and leave with a decision table for your own API.

On this page

Every row and every API resource needs an ID, and the choice is hard to change later: it ends up in URLs, foreign keys, logs, exports and other people's systems. There are five common options. A counter the database hands out (1, 2, 3). A random UUID, version 4. A time-ordered UUID, version 7, defined in RFC 9562. A ULID, which has the same idea as v7 written as shorter text. And a short code for people to read aloud, which should sit beside a real ID rather than replace it.

You will generate each one in Python 3.15, see what it gives away, sort them, pull the creation time out of a UUIDv7, and insert 200,000 rows of each into SQLite to measure the cost instead of guessing. The last steps show the same IDs in Node.js and PostgreSQL 18 and end with a decision table. Everything uses the Python standard library.

Step 1 · Create a demo folder and check Python can make UUIDv7

uuid.uuid7() arrived in Python 3.14, so 3.15 has it. Create a throwaway folder and check:

Bash
mkdir -p ~/ids-demo
cd ~/ids-demo
python3 --version
python3 -c "import uuid; print(uuid.uuid4().version, uuid.uuid7().version)"
python3 -m uuid -u uuid7

The last line uses the module's command-line interface, which is handy for a quick ID in a shell script.

Check it worked

The first line is Python 3.15.2 or a later 3.15 release. The second is 4 7. The third is a UUID whose third group starts with 7, something like 01a218fb-81aa-7395-9adc-f85ced609b2c. An AttributeError on uuid7 means python3 is an older Python; run python3.15 instead.

Step 2 · See what a sequential ID gives away

Auto-increment IDs are small, fast and easy to read in a log. Their problem is what they tell outsiders. Write a script that plays a customer who places one order, waits while 1,243 other people order, and orders again:

Bash
cd ~/ids-demo
cat > counter.py <<'PY'
import sqlite3

db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE orders (id INTEGER PRIMARY KEY, customer TEXT NOT NULL)")


def place_order(customer):
    return db.execute("INSERT INTO orders (customer) VALUES (?)", (customer,)).lastrowid


first = place_order("you")
for n in range(1243):
    place_order(f"someone-{n}")
second = place_order("you")

print("your first order id:", first)
print("your second order id:", second)
print("orders other people placed in between:", second - first - 1)
print("the next id anyone will get:", second + 1)
PY
python3 counter.py

Two receipts are enough to work out your order volume, and a competitor can do the same every week. Worse, the next ID is predictable, so an API that serves /orders/1246 without checking who is asking hands that order to anyone who counts upwards. The real fix for that second problem is an ownership check on every request; an unguessable ID only makes the mistake harder to exploit.

Check it worked

The output ends 1243 and 1246. The difference between your two IDs is the number of orders other customers placed in between.

Step 3 · Generate UUIDv4 and UUIDv7 and sort them

Both kinds are 128 bits, written as 32 hex digits in five groups. The first digit of the third group is the version. A v4 is 122 random bits. A v7 starts with the time in milliseconds since 1970 in its first 48 bits, and the rest is a counter and random bits. Generate a thousand of each and compare sorted order with creation order:

Bash
cd ~/ids-demo
cat > compare.py <<'PY'
import uuid

v4 = [uuid.uuid4() for _ in range(1000)]
v7 = [uuid.uuid7() for _ in range(1000)]

print("uuid4:", v4[0], "version", v4[0].version)
print("uuid7:", v7[0], "version", v7[0].version)
print("three uuid7 in a row:")
for u in v7[:3]:
    print("   ", u)

print("uuid4 sorted == creation order:", sorted(v4) == v4)
print("uuid7 sorted == creation order:", sorted(v7) == v7)
print("uuid7 sorted as text == creation order:", sorted(v7, key=str) == v7)
PY
python3 compare.py

The three v7 values share their first twelve or so hex digits, because they were made in the same millisecond. Python keeps them in order within a millisecond with a 42-bit counter, so sorting by value, by bytes or by the lowercase text all give creation order. That property is what makes v7 friendly to database indexes: each new key lands at the end, not somewhere random.

Check it worked

uuid4 sorted == creation order is False and both uuid7 lines are True. The version numbers match the third-group digit you can see in each UUID.

Step 4 · Read the creation time out of a UUIDv7

Because the time is in the ID, anyone holding a v7 can read when it was made. That is useful for you (rough creation time without a join, debugging, ordering) and is information you hand to every client who sees the ID. Write a small decoder:

Bash
cd ~/ids-demo
cat > decode.py <<'PY'
import datetime as dt
import sys
import uuid

u = uuid.UUID(sys.argv[1]) if len(sys.argv) > 1 else uuid.uuid7()
if u.version != 7:
    sys.exit(f"{u} is version {u.version}, which has no timestamp to read")

ms = u.int >> 80          # the top 48 of the 128 bits
assert ms == u.time       # Python 3.14 and later expose the same number as .time
created = dt.datetime.fromtimestamp(ms / 1000, tz=dt.UTC)

print(u)
print("milliseconds since 1970:", ms)
print("created:", created.isoformat(timespec="milliseconds"))
PY
python3 decode.py 01a1edfd-ddc0-7a1c-9e4f-3b2d6c8e1f05
python3 decode.py

Shifting right by 80 bits throws away everything after the timestamp. The shift is worth knowing because it works the same in any language, and in Python it matches the .time attribute.

Check it worked

The first ID decodes to created: 2026-11-18T09:30:00.000+00:00. The second run makes a fresh v7 and prints the current UTC time to the millisecond. Pass a v4, such as one from python3 -m uuid, and the script stops with is version 4, which has no timestamp to read.

Step 5 · Make ULIDs and short display codes

A ULID uses the same layout as a v7, 48 bits of milliseconds then 80 random bits, but writes it as 26 characters of Crockford base32 instead of 36 characters of hex. It is shorter in a URL and still sorts by time. Python has no ULID in its standard library, so write the encoder; libraries exist for most languages if you would rather not.

A display code is different: a short, random code a person can read over the phone or type from a printed receipt, such as K7QM-4TZP. Leave out characters people confuse (0 and O, 1, I and L). Codes like this matter where support happens by phone, SMS or USSD, and where people type on small keypads in a second language.

Bash
cd ~/ids-demo
cat > codes.py <<'PY'
import math
import os
import secrets
import time

CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"   # base32 without I, L, O, U
READABLE = "23456789ABCDEFGHJKMNPQRSTUVWXYZ"     # no 0, 1, I, L or O


def ulid():
    """48-bit millisecond time + 80 random bits, as 26 Crockford base32 characters."""
    ms = time.time_ns() // 1_000_000
    value = (ms << 80) | int.from_bytes(os.urandom(10))
    return "".join(CROCKFORD[(value >> shift) & 31] for shift in range(125, -1, -5))


def display_code(length=8):
    """A short code for people to read out and type, such as K7QM-4TZP."""
    raw = "".join(secrets.choice(READABLE) for _ in range(length))
    return f"{raw[:4]}-{raw[4:]}"


if __name__ == "__main__":
    ulids = []
    for _ in range(3):
        ulids.append(ulid())
        time.sleep(0.002)
    for value in ulids:
        print("ulid:", value, len(value), "characters")
    print("ulids sorted == creation order:", sorted(ulids) == ulids)

    for _ in range(3):
        print("display code:", display_code())

    space = len(READABLE) ** 8
    for issued in (10_000, 1_000_000):
        chance = 1 - math.exp(-issued * (issued - 1) / (2 * space))
        print(f"chance of a repeat after {issued:,} codes: {chance:.1%}")
PY
python3 codes.py

Two details in the code matter. secrets.choice uses the operating system's secure random source; the random module is predictable and wrong for anything an outsider sees. And this simple ULID only sorts across milliseconds: two made in the same millisecond come out in random order, which is why the demo waits two milliseconds between them. Python's uuid7() has a counter that removes that gap.

The last two lines are the birthday problem. Eight characters from a 31-letter alphabet give about 850 billion codes, yet after a million codes the chance of at least one repeat is already about 44%, and it passes 50% at around 1.1 million. Store display codes in a column with a UNIQUE constraint, generate a new one when an insert fails on it, and keep a UUID or integer as the real key.

Check it worked

Three ULIDs of 26 characters that begin with the same characters, ulids sorted == creation order: True, three codes in the form XXXX-XXXX with no 0, 1, I, L or O, and a repeat chance of about 44% after 1,000,000 codes.

Step 6 · Measure insert time and size with 200,000 rows each

Claims about ID performance are easy to repeat and rarely measured. Build four SQLite files, one per scheme, each with 200,000 rows. UUIDs go in as 16-byte BLOBs, the compact form. The ULID goes in as text, the way most apps store it. IDs are made before the clock starts, so the timing covers only the inserts:

Bash
cd ~/ids-demo
cat > bench.py <<'PY'
import os
import sqlite3
import time
import uuid

from codes import ulid

ROWS = 200_000
SCHEMES = {
    "integer": ("INTEGER PRIMARY KEY", lambda: None),
    "uuid4": ("BLOB PRIMARY KEY", lambda: uuid.uuid4().bytes),
    "uuid7": ("BLOB PRIMARY KEY", lambda: uuid.uuid7().bytes),
    "ulid": ("TEXT PRIMARY KEY", ulid),
}


def index_kib(db):
    try:
        row = db.execute(
            "SELECT SUM(pgsize) FROM dbstat WHERE name LIKE 'sqlite_autoindex_items%'"
        ).fetchone()
    except sqlite3.OperationalError:
        return "n/a"
    return str((row[0] or 0) // 1024)


print(f"{'scheme':<8} {'insert s':>9} {'file KiB':>9} {'index KiB':>10}")
for name, (column, make_id) in SCHEMES.items():
    path = f"{name}.db"
    if os.path.exists(path):
        os.remove(path)
    db = sqlite3.connect(path)
    db.execute(f"CREATE TABLE items (id {column}, label TEXT NOT NULL)")
    rows = [(make_id(), f"item {n}") for n in range(ROWS)]

    started = time.perf_counter()
    with db:
        db.executemany("INSERT INTO items (id, label) VALUES (?, ?)", rows)
    seconds = time.perf_counter() - started

    file_kib = os.path.getsize(path) // 1024
    print(f"{name:<8} {seconds:>9.2f} {file_kib:>9} {index_kib(db):>10}")
    db.close()
PY
python3 bench.py

Inserting None into an INTEGER PRIMARY KEY lets SQLite assign the next number. The index KiB column reads SQLite's dbstat table, which shows n/a if your SQLite was built without it.

One run on a laptop printed this. Your numbers will differ, but the shape should not:

Text
scheme    insert s  file KiB  index KiB
integer       0.18      3816          0
uuid4         0.59     12368       5384
uuid7         0.32     12552       5568
ulid          0.30     16812       7820

Read it in two parts:

  • Size follows key width, not order. An integer key is the row's own address, so there is no separate index. Any other primary key gets an automatic index that stores the key again, so a 16-byte UUID costs room in the table and in the index, and a 26-character text ULID costs more. Storing a UUID as 36 characters of text would be worse still.
  • Time follows order. Random v4 keys land on any page of the index, so every insert can touch a different page and the working set is the whole index. v7 and ULID keys arrive in order and only touch the right-hand edge. Here v4 took nearly twice as long. The gap grows once the index no longer fits in memory.

In PostgreSQL the size story can also change: its B-tree indexes fill pages when keys arrive at the right-hand end and split them half-full when keys land in the middle, so random keys can leave a bigger index there too. Measure on the database you actually run.

Check it worked

Four rows print. integer has the smallest file and an index of 0 (or n/a), ulid has the largest file, and uuid4 has the largest insert time of the three ID types. Run it twice: the numbers move a little, the order stays.

Step 7 · Generate the same IDs in Node.js and PostgreSQL 18

In Node.js, crypto.randomUUID() is built in and makes a v4. For v7, the uuid package on npm has a v7() function:

Bash
node -e "console.log(crypto.randomUUID())"

In PostgreSQL 18, uuidv7() is built in, along with uuidv4() (another name for gen_random_uuid()) and functions that read a UUID's version and timestamp. Use the native uuid type, which stores 16 bytes, never text. This table uses a v7 as its key and a display code for people:

SQL
CREATE TABLE orders (
    id          uuid PRIMARY KEY DEFAULT uuidv7(),
    public_code text NOT NULL UNIQUE,
    placed_at   timestamptz NOT NULL DEFAULT now()
);

INSERT INTO orders (public_code) VALUES ('K7QM-4TZP')
RETURNING id, uuid_extract_version(id), uuid_extract_timestamp(id);

PostgreSQL 19 is out and has the same functions. On PostgreSQL 17 or older there is no uuidv7(), so generate the ID in the application and pass it in.

Generating in the app has a separate benefit. An offline-first Android app on patchy or prepaid data can create orders on the phone, give each a v7 straight away, and sync later with no clash and no round trip to ask the server for the next number.

Check it worked

node prints a UUID whose third group starts with 4. The INSERT returns one row with a UUID starting 01, the version 7, and a timestamp within a second of placed_at. Running the same INSERT again fails with a unique-violation error on public_code, which is the signal to generate a new code and retry.

Step 8 · Choose a scheme for each table

Use this table to pick, then write the choice next to each table in your schema:

Text
Need                                     Pick                     Watch for
---------------------------------------  -----------------------  ------------------------------------
Internal table, never in a URL           bigint identity          Leaks counts if it ever escapes
Public API resource, creation time OK    UUIDv7                   Anyone can read when it was made
Public resource, creation time private   UUIDv4                   Slower inserts on large tables
IDs made offline or in many services     UUIDv7                   Clock skew only affects ordering
Shorter text ID in URLs                  ULID (or v7 in base32)   Stored as text, it is bigger
Something people read out or type        Display code + real key  Needs UNIQUE and a retry on clash

A common hybrid is a bigint identity as the internal primary key, which keeps joins and foreign keys small, plus a v7 or v4 in a unique column that is the only ID the API ever shows. Whatever you pick, an ID is not access control: check on every request that the caller may see the record.

Check it worked

For every table in a schema you are working on, you can name the scheme, say whether its IDs appear outside your system, and say whether revealing the creation time is acceptable. If a public ID is a plain integer, you have found something to change.

Step 9 · Clean up

Delete the demo folder, which holds the scripts and the four SQLite files:

Bash
cd ~
rm -rf ~/ids-demo

Check it worked

ls ~/ids-demo reports No such file or directory.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.