Generate Random Numbers ID: How to Do It Right

Formulas & functions · Updated November 23, 2026

To generate random numbers for an ID, use a cryptographically secure random generator, not a simple rand() function, and ensure uniqueness by checking against existing IDs or using a UUID v4. For most applications, a UUID (Universally Unique Identifier) is the safest and simplest choice because it makes collisions practically impossible without a central check.

Why Random IDs Are Harder Than They Look

The core problem with random IDs is balancing three competing goals: uniqueness, unpredictability, and usability. A simple random number like 123456 is easy to guess and likely to collide with another user’s ID. A long random string like a3f9c2d8-4b7e-4f1a-9c3d-5e6f7a8b9c0d is nearly impossible to guess but is awkward to type or read aloud. The right choice depends on your use case: internal database keys, public-facing order numbers, or security tokens each need a different approach.

How Random Number Generation Works

Computers cannot generate true randomness on their own; they rely on algorithms. There are two main types:

  • Pseudo-random number generators (PRNGs): These use a mathematical formula to produce a sequence that looks random. Examples include the Mersenne Twister and the rand() function in C. They are fast but deterministic—if you know the seed, you can predict the entire sequence.
  • Cryptographically secure PRNGs (CSPRNGs): These draw entropy from system sources like mouse movements, network traffic, or dedicated hardware. Examples include /dev/urandom on Linux, secrets in Python, and crypto.getRandomValues() in JavaScript. They are slower but unpredictable to outsiders.

For IDs that protect user data or authorize actions, always use a CSPRNG. A PRNG might be fine for a lottery simulation, but it is a security risk if the ID grants access to private information.

Choosing the Right ID Format

Here are common formats, with their trade-offs:

  • UUID v4: A 128-bit random number formatted as 36 characters (e.g., f47ac10b-58cc-4372-a567-0e02b2c3d479). Collision probability is negligible (about 1 in 10^38). Best for database primary keys or distributed systems.
  • Short random alphanumeric: For public-facing codes like coupon codes or invite links. Use a base-62 alphabet (A-Z, a-z, 0-9) and generate enough characters. For example, 8 characters gives 62^8 ≈ 218 trillion possibilities.
  • Sequential with random suffix: Some systems use a timestamp plus a random part (e.g., 20250321-8472). This helps with sorting but leaks creation time.
  • ULID or KSUID: These are sorted by time but contain randomness. Useful when you need both chronological ordering and uniqueness.

For most web applications, a UUID v4 is the default answer because it requires no coordination between servers—each server can generate IDs independently without checking a central database.

How to Generate Random IDs in Code

Here are concrete examples in popular languages:

  • Python: import secrets; secrets.token_hex(16) gives a 32-character hex string. Or import uuid; str(uuid.uuid4()) for a UUID.
  • JavaScript (Node.js): crypto.randomUUID() returns a UUID v4. For custom strings, use crypto.randomBytes(8).toString('hex').
  • Java: UUID.randomUUID().toString().
  • SQL (PostgreSQL): gen_random_uuid() (available in Postgres 13+). In MySQL, use UUID() but note it is not v4—it contains time and MAC address.

If you need a short ID, generate a random integer and convert it to base-62. For example, in Python: import secrets; alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; ''.join(secrets.choice(alphabet) for _ in range(8)).

Common Problems and Misconceptions

Misconception: Random IDs are always unique. They are not—collisions happen, especially with short lengths. The birthday paradox shows that with 8-character base-62 IDs, you have a 50% chance of a collision after roughly 16 million IDs. Always add a uniqueness constraint in your database and retry on collision.

Problem: Using rand() for security. Many developers use Math.random() or rand() for password reset tokens. These are predictable. An attacker who knows the seed can guess the token. Always use a CSPRNG for anything security-related.

Problem: IDs are too long for URLs. A UUID is 36 characters, which is fine for a URL but ugly. Consider using a shorter format if the ID appears in user-facing URLs. You can also convert a UUID to base-64 to shorten it, but that adds complexity.

Problem: Readability vs. security. If humans need to read or type the ID (e.g., a conference badge code), avoid ambiguous characters like 0 and O, or 1 and l. Use a restricted alphabet like 23456789ABCDEFGHJKMNPQRSTUVWXYZ (removing 0, 1, I, O, L).

Database and Performance Considerations

Random IDs as primary keys can hurt database performance. In clustered indexes (like InnoDB in MySQL), inserting rows with random primary keys causes page splits and index fragmentation because the new key is unlikely to be the largest value. This slows down inserts. Alternatives:

  • Use an auto-increment integer as the primary key, and store the random ID as a separate unique column for external use.
  • Use a ULID or KSUID, which are time-sortable, so inserts are mostly sequential while still being random-looking.
  • If you must use random keys, consider a non-clustered index or a database that handles random keys well (like PostgreSQL’s default heap storage).

For distributed systems, UUIDs avoid the need for a central sequence generator, but they are larger than integers (16 bytes vs. 4-8 bytes). This increases index size and memory usage.

Security Best Practices for ID Generation

When IDs protect sensitive data, follow these rules:

  • Never use sequential IDs for user-facing resources (e.g., /user/12345). They allow enumeration—attackers can iterate through all IDs to scrape data.
  • Use at least 128 bits of entropy for security tokens. A 64-bit random number is too small—an attacker with moderate resources can brute-force it.
  • Do not embed sensitive information in the ID. For example, don’t encode the user ID and timestamp together in a reversible way.
  • If you generate IDs client-side, ensure the client is trusted, or better, generate them server-side to prevent tampering.
  • Rate-limit endpoints that accept IDs to prevent brute-force guessing.

For password reset tokens, use a separate, high-entropy token (e.g., 32 random bytes) that is hashed in the database, not the ID itself.

Frequently Asked Questions

Can I just use Math.random() for a unique ID? No. Math.random() is not cryptographically secure and does not guarantee uniqueness. You could get the same value twice. Use crypto.getRandomValues() or a UUID library instead.

What is the difference between UUID v4 and v1? UUID v4 is entirely random (122 bits of randomness). UUID v1 contains the current timestamp and the MAC address of the generating machine. v4 is preferred for security because it does not leak information about the time or hardware.

How long should a random ID be? It depends on the number of IDs you expect and the risk of collision. If you expect under a million IDs, 8 characters of base-62 is fine. For security tokens, use at least 16 bytes (32 hex characters). For database keys, a UUID (128 bits) is standard.

Is it safe to use a random ID in a URL? Yes, if it is generated securely and has enough entropy. But be aware that URLs are logged in browser history, server logs, and proxies. For highly sensitive data, consider using POST requests or adding an expiration time.

What happens if two servers generate the same random ID? With a UUID v4, the probability is so low it is effectively impossible. But if you use a shorter format, collisions are possible. Always add a unique constraint in your database and handle the error by regenerating the ID.

Can I make a random ID that is also sortable by time? Yes, use a ULID (Universally Unique Lexicographically Sortable Identifier) or a KSUID. These prefix the random part with a timestamp, so they sort chronologically while still being random enough to prevent enumeration.

Related

Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.

More in Formulas & functions

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.