Short answer: a compliant UUIDv4 has 122 random bits, so its ideal sample space contains 2122, or about 5.3 × 1036, values. For n independent uniform UUIDv4 values, the birthday-bound approximation is p ≈ 1 − exp(−n(n−1)/(2·2^122)). At one billion values, that is about 9.4 × 10−20. The probability is tiny, not zero—and generator failures are more plausible than the ideal model suggests. Keep a unique constraint and handle its failure.

Why UUIDv4 has 122 random bits

RFC 9562 Section 5.4 defines UUIDv4 as a random or pseudorandom UUID. The complete value is 128 bits, but six positions are fixed: four bits identify version 4 and two leading variant bits select the layout defined by the RFC. The remaining fields contain 48 + 12 + 62 = 122 random bits.

UUIDv4 text layout
xxxxxxxx-xxxx-4xxx-Nxxx-xxxxxxxxxxxx

4 = fixed version nibble
N = 8, 9, a, or b for the RFC variant
x = random hexadecimal bits, subject to field boundaries

The size of the v4 sample space is therefore:

Number of possible UUIDv4 values
N = 2^122
  = 5,316,911,983,139,663,491,615,228,241,121,378,304
  ≈ 5.3 × 10^36

This is not the space of every 128-bit string, nor the space of every UUID version. The calculation below assumes that each generation independently chooses one of these v4 values with equal probability and replacement.

The birthday-bound collision formula

A collision means that at least two generated values in the same comparison pool are equal. After the first value, the second must avoid one occupied value, the third must avoid two, and so on. Under the ideal independent-uniform model, the exact no-collision probability is a product:

Exact model and useful approximation
P(no collision) = ∏ from k=0 to n−1 of (1 − k / 2^122)

p(collision) = 1 − P(no collision)

p ≈ 1 − exp(−n(n−1) / (2 · 2^122))

The exponential expression is the birthday-bound approximation. It is accurate over the practical counts in this guide and avoids multiplying an enormous series of numbers close to one. When the result is very small, another approximation is useful:

Small-probability shortcut
p ≈ n(n−1) / (2 · 2^122) ≈ n² / 2^123

The square is why “one chance in 2122” is not the collision probability of a collection. Every pair is another opportunity to match. Doubling the number of generated IDs makes the small-probability estimate roughly four times larger.

Worked UUIDv4 orders of magnitude

The following figures use the exponential approximation and count all generated values in one collision domain. They describe ideal UUIDv4 output, not a service-level guarantee.

UUIDv4 values generatedApproximate probability of at least one collisionInterpretation
1 million (106)9.4 × 10−26About 9.4 × 10−24 percent
1 billion (109)9.4 × 10−20About 9.4 × 10−18 percent
1 trillion (1012)9.4 × 10−14Roughly one chance in 10.6 trillion
1 quadrillion (1015)9.4 × 10−8About 0.0000094 percent, or roughly one in 10.6 million
About 3.27 × 10171 percentThe count at which the model reaches approximately 1 in 100
About 2.71 × 101850 percentThe familiar birthday-bound midpoint, not certainty

At a sustained million UUIDs per second, generating one trillion takes about 11.6 days; one quadrillion takes about 31.7 years. That illustrates the size of the ideal space, but it does not justify removing safeguards. A malformed generator can repeat values immediately, while a database constraint is cheap compared with repairing silently misassociated records.

A 50 percent probability does not mean the first collision occurs at exactly 2.71 × 1018 values. It describes repeated hypothetical experiments: about half of equally sized ideal runs would contain at least one collision. No finite count below exhausting the space makes a random collision impossible, and a low probability does not guarantee that a particular run will be collision-free.

Define the collision domain before using the formula

The n in the formula is the number of independent UUIDv4 values that can meet in the same uniqueness domain. If ten services write to one globally unique table, use their combined lifetime count—not the count of one service for one day. If databases later merge during replication, backup restoration, tenant consolidation, or offline synchronization, those previously separate pools may become one domain.

Conversely, a composite key such as (tenant_id, uuid) can make each tenant a local uniqueness domain if the application contract never treats the UUID alone as global. RFC 9562 recognizes practical local uniqueness, while noting that true global uniqueness cannot be guaranteed without shared knowledge. State the scope in the schema and API instead of relying on the word “universally.”

Do not apply the 122-bit figure after truncating or transforming an identifier. Keeping only the first 12 hexadecimal digits leaves at most 48 bits before other restrictions, radically increasing the birthday risk. Case normalization and hyphen removal preserve all bits when done correctly; substring IDs, decimal rounding, lossy database columns, and case-insensitive encodings that discard information do not.

The ideal calculation has strict assumptions

  • Uniformity: every one of the 2122 possible v4 payloads is equally likely.
  • Independence: one output does not make another output more or less likely, across calls, processes, hosts, containers, and restarts.
  • Correct fixed bits: the generator sets the version and variant without accidentally overwriting or freezing additional random positions.
  • Full preservation: serialization, transport, database storage, and normalization retain the complete 128-bit UUID value.
  • One defined pool: the count includes every value that must be mutually unique for the application.

The formula cannot inspect any of these properties from a UUID string. A validator can confirm the text form and fixed fields, but it cannot prove that the payload came from a secure source or was sampled independently. Generator provenance and operational tests are separate evidence.

Random-generator failures dominate practical concern

RFC 9562 recommends a cryptographically secure pseudorandom number generator and specifically warns about reseeding when generator state changes, such as after process forks. Real collisions can become much more likely than the birthday model when an implementation violates its assumptions:

  • Predictable or repeated seeds: instances initialized from a low-resolution clock, process ID, or fixed configuration can replay the same sequence.
  • Cloned state: virtual-machine snapshots, container images, forked workers, or restored checkpoints can duplicate pseudorandom state unless the platform handles reseeding correctly.
  • Non-cryptographic APIs: a homemade generator or a function such as Math.random() may have a much smaller internal state and weaker independence than the UUID field suggests.
  • Test doubles in production: deterministic mocks, fixtures, or patched entropy functions can escape a test boundary and repeat known values.
  • Error-handling bugs: code may reuse a previous buffer when the random source fails, ignore partial reads, or initialize bytes to zero.
  • Lossy storage: a short column, prefix index treated as unique, incorrect byte conversion, or application truncation can collapse different UUIDs into the same stored key.

Use the operating system or runtime's reviewed UUID/CSPRNG primitive, keep dependencies current, and test across concurrency, forks, snapshots, and restarts appropriate to the deployment. The UUID v4 Generator is useful for local ad hoc values; production code should use its platform's direct secure API rather than scrape or call a web page.

Use a unique constraint as the final authority

If two rows must never share an identifier, express that rule in the database with a primary key or UNIQUE constraint. The constraint protects against both a genuine random collision and more ordinary causes such as duplicate messages, buggy retries, stale imports, or a broken generator.

Example relational schema
CREATE TABLE events (
  id uuid PRIMARY KEY,
  payload jsonb NOT NULL
);

An application-level “does this ID exist?” query followed by an insert is not an equivalent substitute. Another transaction can insert the same key after the check and before the write. Let the database decide atomically, then map its specific duplicate-key result to controlled retry logic.

The scope of the constraint must match the data model. Use a global unique key when UUIDs identify records across all tenants, or an intentional composite constraint when uniqueness is tenant-local. Replication and offline merge systems need conflict policy at the point where independently accepted writes converge.

Retry collisions carefully and observably

  1. Attempt the insert with a newly generated UUID. Avoid a separate existence pre-check.
  2. Recognize only the expected unique-key violation. Do not turn network errors, schema errors, or unrelated constraints into silent retries.
  3. Generate a completely new UUID. Do not increment, edit one digit, or recycle the rejected value.
  4. Retry a small bounded number of times. A second collision under an ideal generator is extraordinarily suspicious.
  5. Record a safe diagnostic signal. Alert on repeated collisions and inspect the entropy source, cloned state, import path, idempotency logic, and storage width.

Retries are a resilience mechanism, not proof that the random source is healthy. An unbounded loop can conceal a constant-output generator and consume resources indefinitely. High-impact systems may need stronger coordination or a different allocation design in addition to UUIDs; RFC 9562 recommends choosing collision resistance according to the consequence of failure.

Do not reuse the v4 formula for every UUID version

The 2122 calculation applies to v4 only when all non-fixed bits are independently uniform. Other versions allocate their payload differently:

  • UUIDv1 and UUIDv6 combine timestamp, clock sequence, and node state. Analyze clock behavior, node allocation, rollback, and shared state—not a 122-bit random pool.
  • UUIDv3 and UUIDv5 deterministically map namespace and name through a truncated hash layout. Their collision analysis involves both duplicate canonical inputs and hash collisions.
  • UUIDv7 has a 48-bit millisecond timestamp and 74 remaining bits that may be random or partly stateful. Analyze values per millisecond, generator policy, counters, nodes, and clock rollback.
  • UUIDv8 is scheme-specific. RFC 9562 explicitly says its uniqueness must not be assumed.

Use the UUID Decoder or UUID Validator to identify the variant and version before choosing a risk model. The UUID versions guide compares all layouts, and the v4 vs v7 guide covers the random-versus-time-ordered decision in depth.

Collision resistance does not make a UUID a secret

A low collision probability answers “how likely are two generated identifiers to match?” It does not answer “can an attacker guess a valid identifier?”, “does possession authorize access?”, or “has this value been modified?” Those are different security properties.

RFC 9562 says implementations must not assume UUIDs are hard to guess and must not use them as security capabilities. Even a well-generated v4 UUID has no signature, expiry, audience, revocation, or authorization context. Protect every object lookup with authentication and authorization. Use a purpose-built, high-entropy bearer token when secrecy is part of the protocol, and store or transmit it according to that threat model.

UUID text also has no error-detection code. A one-character change can produce another structurally valid UUID, so visual inspection and regex validation cannot establish integrity. Use an authenticated message, digital signature, or trusted database relationship when tamper detection matters.

Need fresh random identifiers? Generate standards-shaped UUIDv4 values locally, then enforce the real uniqueness rule in your application database.

Open the UUID v4 Generator

Frequently asked questions

How likely is a duplicate UUIDv4?

For independent, uniformly distributed UUIDv4 values, one billion generated values have an approximate collision probability of 9.4 × 10^-20. The risk grows with the square of the count, and real systems can have a much higher risk when the random generator, state handling, or storage pipeline is defective.

Why does UUIDv4 have 122 random bits instead of 128?

A UUID is 128 bits, but UUIDv4 fixes four bits to the version value 4 and two bits to the RFC 9562 variant. The other 122 bits carry random or pseudorandom data, giving 2^122 possible UUIDv4 values.

Should a UUID column still have a unique constraint?

Yes when duplicate identifiers would violate the data model. A primary-key or unique constraint turns a rare collision or generator defect into a detectable write failure. It also handles concurrent inserts atomically, which an application-level check before insertion cannot do by itself.

What should an application do after a UUID collision?

Catch the specific unique-constraint failure, generate a completely new UUID from the trusted source, and retry a small bounded number of times. Repeated collisions are evidence of a generator, deployment, or data-flow defect and should stop the operation and trigger investigation rather than an endless retry loop.

Can a UUIDv4 be used as a secret access token?

No. RFC 9562 says implementations must not assume UUIDs are hard to guess and must not use them as security capabilities whose possession grants access. Use authentication and authorization, and use a purpose-built high-entropy token when a secret bearer credential is required.

Does the UUIDv4 collision formula apply to UUIDv7?

Not directly. UUIDv7 divides its payload between a millisecond timestamp and 74 remaining bits that may contain randomness, a sub-millisecond fraction, a counter, or a combination. Collision analysis must use the actual generator policy, generation rate per timestamp bucket, node coordination, and rollback behavior.

Primary reference