Sub topic 12
Predictable IDs and what they reveal
This chapter assumes you have read the earlier chapters on UUID v4, UUID v7, and Snowflake IDs. It also assumes you know how a web API usually exposes a record by ID, for example GET /orders/1042. The earlier chapters judged ID schemes on uniqueness, ordering, size, and coordination. This chapter adds one more property: what an outsider can learn from an ID, and what they can guess from it.
Two separate problems
An ID can cause two kinds of security trouble.
- Information leakage. The ID itself carries facts, such as how many records exist, when one was created, or which machine made it.
- Guessability. An attacker who has seen some IDs can produce other valid IDs, then probe your system with them.
These problems are related but not identical. A sequential ID is both guessable and leaky. A Snowflake ID leaks a lot but is hard to guess in full. A UUID v4 leaks almost nothing and is practically unguessable, provided it came from a proper random source.
What sequential IDs reveal
Auto-increment IDs and counter-based IDs expose business facts to anyone who can create a record and see its ID.
- Volume. If your order number is 1042 today and 1090 tomorrow, you sold 48 orders in a day (counting only orders placed between those two observations). A competitor can sign up, place two orders a week apart, and read your growth from the difference.
- Total size. A new user who gets ID 5,000,000 learns the platform has about five million users. During the Second World War, the Allies used the same idea on German tank serial numbers. This is known as the German tank problem.
- Enumeration. If IDs are consecutive, an attacker can request
/invoices/1,/invoices/2, and so on. Each request that succeeds without an ownership check is a data leak.
def estimate_daily_volume(id_day_1, id_day_2, days=1):
# Works only when IDs are consecutive and every ID corresponds to one event.
return (id_day_2 - id_day_1) / days
print(estimate_daily_volume(1042, 1090)) # 48.0The calculation is trivial, which is the point. Nothing here needs special skill or access.
What time-ordered IDs reveal
Time-ordered schemes trade some privacy for index locality. The timestamp sits in plain sight in the high bits.
- UUID v7 starts with a 48-bit Unix millisecond timestamp. Anyone can read the creation time of a record from its ID.
- ULID has the same property in its first 10 characters.
- Snowflake IDs embed the timestamp, the worker ID, and the sequence number. These expose creation time, which machine or process handled the request, and how busy that machine was in that millisecond.
Decoding is a few bit operations. This uses the layout from the Snowflake chapter (41-bit timestamp, 10-bit worker, 12-bit sequence):
from datetime import datetime, timezone
EPOCH_MS = 1_700_000_000_000
def decode_snowflake(snowflake_id, epoch_ms=EPOCH_MS):
sequence = snowflake_id & 0xFFF
worker = (snowflake_id >> 12) & 0x3FF
ts_ms = (snowflake_id >> 22) + epoch_ms
created = datetime.fromtimestamp(ts_ms / 1000, tz=timezone.utc)
return created, worker, sequence
def uuid7_created(u):
# The top 48 bits of a UUID v7 are the Unix timestamp in milliseconds.
return datetime.fromtimestamp((u.int >> 80) / 1000, tz=timezone.utc)
# Build an example ID: one day after the custom epoch, worker 7, sequence 3.
example = (86_400_000 << 22) | (7 << 12) | 3
print(decode_snowflake(example))
# (datetime.datetime(2023, 11, 15, 22, 13, 20, tzinfo=datetime.timezone.utc), 7, 3)Is this a problem? It depends on what the timestamp means in your system.
- For a chat message, the creation time is already shown to users, so nothing new leaks.
- For a user account, the creation time can reveal when someone joined a service. That can be sensitive.
- For a record whose existence is itself private (a medical appointment, a legal case), the ID can confirm that the record existed at a certain moment.
The worker field leaks infrastructure details. Knowing that IDs come from workers 0 to 9, and which worker handled a given request, helps an attacker map your deployment. A sequence number near its maximum (4095) tells them a single worker was handling more than 4,000 IDs in one millisecond, which is a load signal.
Randomness quality decides guessability
UUID v4 is unguessable only if its 122 random bits come from a cryptographically secure random number generator (CSPRNG). Python's uuid.uuid4() reads from os.urandom, which is a CSPRNG. A hand-rolled generator may not be.
import random
import secrets
import uuid
# Safe: uses the operating system's CSPRNG.
safe_id = uuid.uuid4()
# Unsafe for anything an attacker must not guess.
# The Mersenne Twister behind `random` is fully predictable once an
# attacker has seen enough output (624 consecutive 32-bit values).
weak_id = uuid.UUID(int=random.getrandbits(128), version=4)
# Right tool for unguessable tokens: 128 bits from the CSPRNG.
reset_token = secrets.token_urlsafe(16)
print(safe_id, weak_id, reset_token, sep="\n")Two mistakes recur in real systems.
- Seeding a general-purpose generator with the clock, such as
random.seed(time.time()). An attacker who knows roughly when the server started can try a small number of seeds. - Using the same ID type for a record name and for a secret. A UUID v7 has only 74 random bits (the other bits are timestamp and fixed fields), and the timestamp part is often known to the attacker. Even if 74 bits is hard to brute-force, it is not what you want guarding a password reset link. Use a dedicated random token.
ULID's "monotonic" mode makes this concrete. To keep IDs in order within one millisecond, it increments the previous random part by one instead of drawing a new one. If an attacker sees one ULID created in a given millisecond, the next ULID from that generator in the same millisecond is easy to predict.
An unguessable ID is not access control
The most common security error with IDs is relying on obscurity. Switching from /orders/1042 to /orders/9f1c... makes enumeration impractical, but it does not make the endpoint secure.
- IDs appear in logs, browser history, referrer headers, shared screenshots, and support emails. Once an ID leaks, anyone holding it can use it if the server checks nothing else.
- A user can legitimately learn another user's ID in many ways, such as a shared link or a comment mentioning someone.
- The vulnerability class is called insecure direct object reference (IDOR). Random IDs reduce its exploitability, but the actual fix is an authorization check on every request.
The rule: every request that takes an ID must check that the caller may access that record. Treat unguessable IDs as a second layer.
Notice that both "does not exist" and "not yours" return the same 404. A 403 for the second case confirms to an attacker that the ID is valid, which is itself a small leak.
Mitigation options
You rarely need to give up an ID scheme you chose for good reasons. You can separate internal IDs from the identifiers you show outside.
| Approach | What it does | Limits |
|---|---|---|
| Authorization checks | Verify ownership or permission on every request | Required in all cases; does not hide metadata |
| Separate public ID | Keep a Snowflake or bigint as the primary key and add a random UUID v4 column for URLs and APIs | Extra column and index; two lookups paths to keep consistent |
| Opaque random tokens | Use `secrets.token_urlsafe` for links that grant access | Must be stored and compared; should expire |
| Reversible encoding (for example, Hashids-style) | Makes sequential IDs look random | Obfuscation, not encryption; patterns are often recoverable. Do not rely on it |
| Encrypting the ID | Encrypt the internal ID with a key and expose the ciphertext | Needs key management and rotation; ciphertext length grows |
| Coarser timestamps | Zero out low timestamp bits or use a custom epoch | Weakens ordering; the epoch offset is easy to guess |
| Rate limiting and monitoring | Slows enumeration and flags scans | Detects abuse; does not prevent leaks |
The separate-public-ID approach is the most common. You keep the compact, ordered key inside the database, where it helps index locality, and you give clients a random identifier that reveals nothing. The cost is one extra unique index on the public column.
Matching schemes to exposure
How much any of this matters depends on where the ID is visible.
| Scheme | Reveals | Guessable? | Typical guidance |
|---|---|---|---|
| Auto-increment | Volume, total count, order | Yes, trivially | Keep internal; never expose directly |
| Block allocation | Approximate volume, which block range a node used | Mostly yes | Keep internal |
| UUID v4 (CSPRNG) | Nothing useful | No, with a good random source | Safe to expose; still check authorization |
| UUID v7 / ULID | Creation time to the millisecond | Partly; 74 random bits remain | Fine if creation time is public; avoid as a secret |
| Snowflake | Creation time, worker, load | Partly; fields are structured | Keep internal or accept the metadata leak |
Internal IDs, such as those used between services or in a database you never expose, face a much smaller attacker pool. The risk grows when IDs cross a trust boundary: URLs, public APIs, mobile apps, exported files, and error messages.
Common mistakes
- Exposing auto-increment keys in URLs and then relying on the front end to hide links the user should not see.
- Returning different errors for "not found" and "forbidden", which lets an attacker test which IDs exist.
- Using
randominstead ofsecretsfor tokens. - Assuming a UUID is a secret. Standards define UUIDs as identifiers. UUID v1 even embeds a timestamp and, in many implementations, a MAC address.
- Forgetting that IDs also leak through side channels such as sort order, pagination cursors, and API response ordering.
Exercise
Your service uses Snowflake IDs as primary keys and shows them in public URLs like /posts/6958302241390723. Name two things an outside observer can learn from the ID alone, and give one change that addresses them without losing the index benefits of time-ordered keys.
Show answer
An observer can decode the creation time of the post (from the high 41 bits plus the custom epoch, which is easy to estimate) and the worker ID and sequence number (which show which machine handled the write and roughly how busy it was). Two IDs from the same worker also reveal how many IDs that worker produced between them. To fix this, keep the Snowflake ID as the internal primary key and add a separate random public identifier, such as a UUID v4 or a 128-bit token from secrets.token_urlsafe, with a unique index. Expose only the public ID in URLs and look up by it. Authorization checks are still required on every request.
Exercise
A developer generates password reset tokens with str(uuid.uuid7()) from a library, reasoning that "UUIDs are unguessable". Explain what is wrong and what to use instead.
Show answer
A UUID v7 starts with a 48-bit millisecond timestamp, which an attacker can estimate from when the reset was requested, and it has only 74 random bits left. It was designed to be a unique, sortable identifier and not a secret, so a reset token built from it is weaker than it looks. Use secrets.token_urlsafe(16) or longer (at least 128 bits from a CSPRNG), store only a hash of the token, set a short expiry, and invalidate it after use.