UUIDs

suggest change

A UUID (universally unique identifier) is a 128-bit value, usually written as 32 hex digits in five groups: 550e8400-e29b-41d4-a716-446655440000. You can create one on any machine without asking a central server and it won't collide with anyone else's. That's why UUIDs are used for database keys, request ids, file names of uploads and idempotency keys.

On the JVM there has always been java.util.UUID. Kotlin now has its own multiplatform type, kotlin.uuid.Uuid, in the standard library. It works the same on JVM, JS, Wasm and Native, and kotlinx.serialization supports it out of the box.

Versions:

All the examples below were compiled and run with Kotlin 2.4.21 on JDK 25.

Creating a random UUID

Uuid.random() returns a random (version 4) UUID. On the JVM it uses SecureRandom, so the value is unpredictable and fine to use for session ids or tokens in URLs:

import kotlin.uuid.Uuid

fun main() {
    val id = Uuid.random()
    println(id)                   // same as toHexDashString()
    println(id.toHexDashString())
    println(id.toHexString())     // 32 hex digits, no dashes
    println(id.toString().uppercase())
    println(Uuid.NIL)
    println(Uuid.random() == Uuid.random())
    println("${Uuid.SIZE_BYTES} bytes, ${Uuid.SIZE_BITS} bits")
}

Output (the UUID is different on every run):

e2dfdb21-558d-4d43-bca7-ccd12f13050e
e2dfdb21-558d-4d43-bca7-ccd12f13050e
e2dfdb21558d4d43bca7ccd12f13050e
E2DFDB21-558D-4D43-BCA7-CCD12F13050E
00000000-0000-0000-0000-000000000000
false
16 bytes, 128 bits

A random UUID has 122 random bits (6 bits are taken by the version and variant). You'd have to generate about 2.7 quintillion of them to have a 50% chance of one collision.

There are no public constructors. You create a Uuid with random(), by parsing a string, or from bytes or two Longs.

Parsing

Uuid.parse() accepts both the 36-character hex-and-dash form and the 32-character hex form, in upper or lower case:

import kotlin.uuid.Uuid

fun main() {
    val a = Uuid.parse("550e8400-e29b-41d4-a716-446655440000")
    val b = Uuid.parse("550E8400E29B41D4A716446655440000") // hex form, any case
    println(a)
    println(a == b)

    println(Uuid.parseHexDash("550e8400-e29b-41d4-a716-446655440000"))
    println(Uuid.parseHex("550e8400e29b41d4a716446655440000"))

    println(Uuid.parseOrNull("{550e8400-e29b-41d4-a716-446655440000}"))
    println(Uuid.parseHexDashOrNull("550e8400e29b41d4a716446655440000"))

    for (bad in listOf("nope", "550e8400-e29b-41d4-a716-44665544000g", " 550e8400-e29b-41d4-a716-446655440000")) {
        try {
            Uuid.parse(bad)
        } catch (e: IllegalArgumentException) {
            println(e.message)
        }
    }
}

Output:

550e8400-e29b-41d4-a716-446655440000
true
550e8400-e29b-41d4-a716-446655440000
550e8400-e29b-41d4-a716-446655440000
null
null
Expected either a 36-char string in the standard hex-and-dash UUID format or a 32-char hexadecimal string, but was "nope" of length 4
Expected a hexadecimal digit at index 35, but was 'g'
Expected either a 36-char string in the standard hex-and-dash UUID format or a 32-char hexadecimal string, but was " 550e8400-e29b-41d4-a716-446655440000" of length 37

The parsers:

Function Accepts On bad input
parse(s) hex-and-dash or plain hex throws IllegalArgumentException
parseOrNull(s) hex-and-dash or plain hex returns null
parseHexDash(s) / parseHexDashOrNull(s) only xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx throws / null
parseHex(s) / parseHexOrNull(s) only 32 hex digits throws / null

Parsing is strict: no whitespace, no braces ({...} as used by Microsoft tools), no urn:uuid: prefix. trim() or strip those yourself if your input has them.

java.util.UUID.fromString() is much more lenient. It accepts 1-2-3-4-5 and returns 00000001-0002-0003-0004-000000000005. Uuid.parseOrNull returns null for it, which is what you want for input validation.

Validating ids from requests

Ids in URLs and JSON come from the client, so parse them with parseOrNull and reply with an error instead of throwing:

import kotlin.uuid.Uuid

data class Order(val id: Uuid, val item: String)

val orders = listOf(
    Order(Uuid.parse("0f8fad5b-d9cb-469f-a165-70867728950e"), "book"),
)

// e.g. the {id} part of GET /orders/{id}
fun findOrder(rawId: String): String {
    val id = Uuid.parseOrNull(rawId.trim()) ?: return "400 Bad Request: invalid id"
    val order = orders.find { it.id == id } ?: return "404 Not Found"
    return "200 OK: ${order.item}"
}

fun main() {
    println(findOrder("0F8FAD5B-D9CB-469F-A165-70867728950E"))
    println(findOrder("7c9e6679-7425-40de-944b-e07fc1f90ae7"))
    println(findOrder("42"))
}

Output:

200 OK: book
404 Not Found
400 Bad Request: invalid id

Keep the id as a Uuid in your domain classes, not a String. Two Uuids compare by value, so upper or lower case and the dashed or plain hex form don't matter, and the type system won't let you pass a user name where an id is expected.

Bytes and Longs

A UUID is 16 bytes. Storing it in that binary form takes less than half the space of the 36-character string. toByteArray() returns the bytes big-endian, in the same order as the hex digits, and Uuid.fromByteArray() converts them back. toLongs and toULongs split a UUID into two 64-bit halves:

import java.nio.ByteBuffer
import kotlin.uuid.Uuid
import kotlin.uuid.getUuid
import kotlin.uuid.putUuid

fun main() {
    val id = Uuid.parse("550e8400-e29b-41d4-a716-446655440000")

    // 16 bytes, big-endian, in the same order as the hex string
    val bytes: ByteArray = id.toByteArray()
    println(bytes.toHexString())
    println(Uuid.fromByteArray(bytes) == id)

    // two 64-bit halves
    id.toLongs { msb, lsb -> println("msb=$msb lsb=$lsb") }
    id.toULongs { msb, lsb -> println("msb=${msb.toString(16)} lsb=${lsb.toString(16)}") }
    println(Uuid.fromLongs(6128981282234515924, -6406858213580079104) == id)
    println(Uuid.fromULongs(0x550e8400e29b41d4uL, 0xa716446655440000uL) == id)

    // ByteBuffer: write and read in a binary record
    val buf = ByteBuffer.allocate(20)
    buf.putInt(7).putUuid(id)
    buf.flip()
    println("${buf.getInt()} ${buf.getUuid()}")
}

Output:

550e8400e29b41d4a716446655440000
true
msb=6128981282234515924 lsb=-6406858213580079104
msb=550e8400e29b41d4 lsb=a716446655440000
true
true
7 550e8400-e29b-41d4-a716-446655440000

toLongs and toULongs don't return a pair. They take a lambda that receives both halves and return whatever the lambda returns, so no object is allocated. The ByteBuffer.putUuid() and getUuid() extensions are JVM-only and need explicit imports from kotlin.uuid. They always write big-endian, whatever the buffer's byte order is set to. See Bytes and binary data and Base64 and hex encoding for more on byte arrays.

Reading the version and variant

java.util.UUID has version() and variant(). kotlin.uuid.Uuid doesn't, but they're easy to read from the bits. The version is the first hex digit of the third group, and the RFC 9562 variant has 10 in the top two bits of byte 8:

import kotlin.uuid.Uuid

// the version is the high 4 bits of byte 6 (the first digit of the 3rd group)
val Uuid.version: Int get() = toLongs { msb, _ -> ((msb ushr 12) and 0xF).toInt() }

// RFC 9562 variant: the top bits of byte 8 are 10
val Uuid.isRfcVariant: Boolean get() = toLongs { _, lsb -> (lsb ushr 62) == 2L }

fun main() {
    for (s in listOf(
        "550e8400-e29b-41d4-a716-446655440000",
        "6ba7b810-9dad-11d1-80b4-00c04fd430c8",
        "019a1c3e-7e40-7c2f-9b1a-5f3c2d1e0a9b",
    )) {
        val id = Uuid.parse(s)
        println("$id version=${id.version} rfc=${id.isRfcVariant}")
    }
    println("random: version=${Uuid.random().version}")
    println("NIL: version=${Uuid.NIL.version} rfc=${Uuid.NIL.isRfcVariant}")
}

Output:

550e8400-e29b-41d4-a716-446655440000 version=4 rfc=true
6ba7b810-9dad-11d1-80b4-00c04fd430c8 version=1 rfc=true
019a1c3e-7e40-7c2f-9b1a-5f3c2d1e0a9b version=7 rfc=true
random: version=4
NIL: version=0 rfc=false

Comparing and sorting

Uuid implements Comparable<Uuid>, and equals/hashCode compare the 128-bit value. It compares as an unsigned 128-bit number, which is the same order as the lowercase strings. java.util.UUID compares its two halves as signed Longs, so any UUID starting with 8-f sorts before one starting with 0-7:

import kotlin.uuid.Uuid
import kotlin.uuid.toJavaUuid

fun main() {
    val ids = listOf(
        "c0a80101-0000-4000-8000-000000000003",
        "00000000-0000-4000-8000-000000000001",
        "7fffffff-ffff-4fff-bfff-ffffffffffff",
        "80000000-0000-4000-8000-000000000002",
    ).map(Uuid::parse)

    println("Kotlin Uuid (unsigned, same as string order):")
    ids.sorted().forEach { println("  $it") }

    println("java.util.UUID (signed halves):")
    ids.map { it.toJavaUuid() }.sorted().forEach { println("  $it") }

    println(ids.sorted() == ids.sortedBy { it.toString() })

    // equals and hashCode work, so Uuid is a fine map key
    val names = ids.associateWith { "user-${it.toString().takeLast(1)}" }
    println(names[Uuid.parse("80000000-0000-4000-8000-000000000002")])
}

Output:

Kotlin Uuid (unsigned, same as string order):
  00000000-0000-4000-8000-000000000001
  7fffffff-ffff-4fff-bfff-ffffffffffff
  80000000-0000-4000-8000-000000000002
  c0a80101-0000-4000-8000-000000000003
java.util.UUID (signed halves):
  80000000-0000-4000-8000-000000000002
  c0a80101-0000-4000-8000-000000000003
  00000000-0000-4000-8000-000000000001
  7fffffff-ffff-4fff-bfff-ffffffffffff
true
user-2

The Kotlin order matches what PostgreSQL does with its uuid type and what you get when you sort the string form. That matters for version 7 UUIDs (see below), which are meant to sort by creation time.

The first releases of kotlin.uuid had no natural order, and you sorted with the experimental Uuid.LEXICAL_ORDER comparator. In Kotlin 2.4 using it is an error ("Use naturalOrder() instead"). Use sorted(), < or naturalOrder<Uuid>().

Converting to and from java.util.UUID

JDBC drivers, Spring, Jackson and most Java libraries use java.util.UUID. The JVM-only extensions toJavaUuid() and toKotlinUuid() convert between the two types without going through a string:

import java.util.UUID
import kotlin.uuid.Uuid
import kotlin.uuid.toJavaUuid
import kotlin.uuid.toKotlinUuid

fun main() {
    val k: Uuid = Uuid.parse("550e8400-e29b-41d4-a716-446655440000")

    val j: UUID = k.toJavaUuid()
    println("${j.javaClass.name} $j version=${j.version()} variant=${j.variant()}")

    val back: Uuid = j.toKotlinUuid()
    println("${back::class.qualifiedName} $back ${back == k}")

    // java.util.UUID can make name-based (version 3, MD5) UUIDs
    val v3 = UUID.nameUUIDFromBytes("alice@example.com".toByteArray()).toKotlinUuid()
    println("$v3 (same input -> same UUID)")
}

Output:

java.util.UUID 550e8400-e29b-41d4-a716-446655440000 version=4 variant=2
kotlin.uuid.Uuid 550e8400-e29b-41d4-a716-446655440000 true
c160f8cc-69a4-30bf-ab03-62752353d060 (same input -> same UUID)

Which one to use:

Name-based UUIDs (version 5)

Random UUIDs are different every time. Sometimes you want the same input to always give the same UUID, for example to get a stable id for a URL or an email address. That's what version 5 is for: SHA-1 of a namespace UUID plus a name. Neither the Kotlin nor the Java standard library has it, but it takes a few lines:

import java.security.MessageDigest
import kotlin.uuid.Uuid

val NAMESPACE_DNS = Uuid.parse("6ba7b810-9dad-11d1-80b4-00c04fd430c8")
val NAMESPACE_URL = Uuid.parse("6ba7b811-9dad-11d1-80b4-00c04fd430c8")

// RFC 9562 version 5: SHA-1 of namespace + name, then set version and variant bits
fun uuidV5(namespace: Uuid, name: String): Uuid {
    val sha1 = MessageDigest.getInstance("SHA-1")
    sha1.update(namespace.toByteArray())
    val hash = sha1.digest(name.encodeToByteArray())
    val bytes = hash.copyOf(16)
    bytes[6] = ((bytes[6].toInt() and 0x0F) or 0x50).toByte() // version 5
    bytes[8] = ((bytes[8].toInt() and 0x3F) or 0x80).toByte() // variant 10
    return Uuid.fromByteArray(bytes)
}

fun main() {
    println(uuidV5(NAMESPACE_DNS, "www.example.com"))
    println(uuidV5(NAMESPACE_URL, "https://example.com/orders/42"))
    println(uuidV5(NAMESPACE_URL, "https://example.com/orders/42"))
}

Output:

2ed6657d-e927-568b-95e1-2665a8aea6a2
e28af53e-3ca6-5bf0-9d0a-e41ae43f323a
e28af53e-3ca6-5bf0-9d0a-e41ae43f323a

These match Python's uuid.uuid5(), so other services can compute the same ids. Name-based UUIDs can be guessed by anyone who knows the name, so don't use them as secrets.

JSON with kotlinx.serialization

kotlinx.serialization has a built-in serializer for kotlin.uuid.Uuid, so a Uuid property in a @Serializable class needs no extra code. It's encoded as the hex-and-dash string. For java.util.UUID you'd have to write a custom KSerializer (see JSON):

import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import kotlin.uuid.Uuid

@Serializable
data class User(val id: Uuid, val name: String, val teamIds: List<Uuid> = emptyList())

fun main() {
    val user = User(
        id = Uuid.parse("550e8400-e29b-41d4-a716-446655440000"),
        name = "Ana",
        teamIds = listOf(Uuid.parse("0f8fad5b-d9cb-469f-a165-70867728950e")),
    )
    val json = Json.encodeToString(user)
    println(json)
    println(Json.decodeFromString<User>(json) == user)

    try {
        Json.decodeFromString<User>("""{"id": "not-a-uuid", "name": "Bob"}""")
    } catch (e: IllegalArgumentException) {
        println("${e::class.simpleName}: ${e.message?.lineSequence()?.first()}")
    }
}

Output:

{"id":"550e8400-e29b-41d4-a716-446655440000","name":"Ana","teamIds":["0f8fad5b-d9cb-469f-a165-70867728950e"]}
true
IllegalArgumentException: Expected either a 36-char string in the standard hex-and-dash UUID format or a 32-char hexadecimal string, but was "not-a-uuid" of length 10

Compiled with the serialization compiler plugin (kotlin("plugin.serialization") in Gradle) and org.jetbrains.kotlinx:kotlinx-serialization-json:1.11.0. Decoding uses Uuid.parse, so an invalid id in a request body fails with an IllegalArgumentException. Catch it and return a 400 response.

Uuid also implements java.io.Serializable, for code that still uses Java serialization.

Version 7 UUIDs (experimental)

Random (version 4) UUIDs have one problem as database primary keys: each new key goes to a random place in the index. In a B-tree index that means inserts touch pages all over the index, pages split often and the cache works poorly. Auto-increment integers don't have this problem because each new key goes at the end.

Version 7 (RFC 9562) fixes that. The first 48 bits are a Unix timestamp in milliseconds and most of the rest is random. In 01a14c04-8a25-71b1-9bcb-c83c5dd359cf:

So new ids sort after older ones, inserts go to the end of the index, and you can see roughly when a row was created from its id. Ids from different machines still don't collide.

Kotlin 2.4 has Uuid.generateV7(), and Uuid.generateV4() as an explicit alias for random(). Both are still experimental. Without an opt-in you get an error:

s7b.kt:4:18: error: this declaration needs opt-in. Its usage must be marked with '@kotlin.uuid.ExperimentalUuidApi' or '@OptIn(kotlin.uuid.ExperimentalUuidApi::class)'
    println(Uuid.generateV7())
                 ^^^^^^^^^^

With @OptIn:

import kotlin.time.Instant
import kotlin.uuid.ExperimentalUuidApi
import kotlin.uuid.Uuid

// the first 48 bits of a version 7 UUID are a Unix timestamp in milliseconds
fun Uuid.v7Timestamp(): Instant =
    toLongs { msb, _ -> Instant.fromEpochMilliseconds(msb ushr 16) }

@OptIn(ExperimentalUuidApi::class)
fun main() {
    println("v4: ${Uuid.generateV4()}")   // same as Uuid.random()

    val ids = List(5) { Uuid.generateV7() }
    ids.forEach { println("v7: $it  ${it.v7Timestamp()}") }
    println("already sorted: ${ids == ids.sorted()}")

    val at = Instant.parse("2025-01-01T00:00:00Z")
    val old = Uuid.generateV7NonMonotonicAt(at)
    println("$old ${old.v7Timestamp()}")
}

Output (the values change on every run):

v4: a05621de-e989-4108-a25a-113528b861ee
v7: 01a14c04-8a24-7014-bf5e-5965a42363d4  2026-10-17T22:38:48.356Z
v7: 01a14c04-8a25-71b1-9bcb-c83c5dd359cf  2026-10-17T22:38:48.357Z
v7: 01a14c04-8a25-71b2-8366-4ebf4a9a5970  2026-10-17T22:38:48.357Z
v7: 01a14c04-8a25-71b3-9885-d723f62024de  2026-10-17T22:38:48.357Z
v7: 01a14c04-8a26-7083-a0c5-cfc5d8b481f1  2026-10-17T22:38:48.358Z
already sorted: true
01941f29-7c00-7347-b32d-fead560c30d4 2025-01-01T00:00:00Z

Notes:

To opt in for a whole module instead of annotating each function, pass -opt-in=kotlin.uuid.ExperimentalUuidApi to kotlinc, or in Gradle:

kotlin {
    compilerOptions {
        optIn.add("kotlin.uuid.ExperimentalUuidApi")
    }
}

Storing UUIDs in a database

JDBC drivers for databases with a UUID type, such as PostgreSQL and H2, map java.util.UUID to it. Convert at the JDBC boundary. This example uses an in-memory H2 database (com.h2database:h2:2.3.232):

import java.sql.DriverManager
import java.util.UUID
import kotlin.uuid.ExperimentalUuidApi
import kotlin.uuid.Uuid
import kotlin.uuid.toJavaUuid
import kotlin.uuid.toKotlinUuid

@OptIn(ExperimentalUuidApi::class)
fun main() {
    DriverManager.getConnection("jdbc:h2:mem:shop").use { conn ->
        conn.createStatement().execute(
            "CREATE TABLE orders (id UUID PRIMARY KEY, item VARCHAR(100))"
        )

        val insert = conn.prepareStatement("INSERT INTO orders (id, item) VALUES (?, ?)")
        for (item in listOf("book", "pen", "lamp")) {
            insert.setObject(1, Uuid.generateV7().toJavaUuid()) // JDBC knows java.util.UUID
            insert.setString(2, item)
            insert.executeUpdate()
        }

        // v7 keys sort by creation time, so ORDER BY id is insertion order
        conn.createStatement().executeQuery("SELECT id, item FROM orders ORDER BY id").use { rs ->
            while (rs.next()) {
                val id: Uuid = rs.getObject("id", UUID::class.java).toKotlinUuid()
                println("$id ${rs.getString("item")}")
            }
        }
    }
}

Output:

01a14c05-11f0-7170-af1e-ae501b39cab6 book
01a14c05-11fb-776c-bd34-3ea20361193b pen
01a14c05-11fb-776d-b66a-cad23b837ed1 lamp

Use the database's native UUID column type (uuid in PostgreSQL, UUID in H2, BINARY(16) in MySQL) rather than a VARCHAR(36). It takes 16 bytes instead of 36 or more and compares faster.

The Exposed ORM supports the Kotlin type directly. In Exposed 1.x uuid() creates a Column<kotlin.uuid.Uuid> and javaUUID() a Column<java.util.UUID> (the PostgreSQL article uses the Java one):

import org.jetbrains.exposed.v1.core.Table
import kotlin.uuid.Uuid

object Tenants : Table("tenants") {
    val id = uuid("id").clientDefault { Uuid.random() }   // Column<kotlin.uuid.Uuid>
    val name = varchar("name", 100)

    override val primaryKey = PrimaryKey(id)
}

Replacing UUID.randomUUID()

Many examples in this book, such as request ids in HTTP middleware and stored file names in File uploads, use java.util.UUID.randomUUID(). On the JVM it's equivalent to Uuid.random(): both produce a version 4 UUID from SecureRandom and format it the same way. Switching is a matter of changing the import, and it lets the code move to common (multiplatform) source sets later.

UUIDs are unique but not short. For short random tokens, or random values that aren't identifiers, see Random numbers.

Summary

Task Code
random UUID Uuid.random()
version 7 (time-ordered) Uuid.generateV7() (needs @OptIn(ExperimentalUuidApi::class))
all zeros Uuid.NIL
to string id.toString() / id.toHexDashString() / id.toHexString()
parse, throwing Uuid.parse(s)
parse untrusted input Uuid.parseOrNull(s)
to and from 16 bytes id.toByteArray() / Uuid.fromByteArray(bytes)
to and from two Longs id.toLongs { msb, lsb -> ... } / Uuid.fromLongs(msb, lsb)
ByteBuffer (JVM) buf.putUuid(id) / buf.getUuid()
sort ids.sorted() (unsigned, same as string order)
Java interop (JVM) id.toJavaUuid() / javaUuid.toKotlinUuid()
JSON works in @Serializable classes, encoded as a string

Use Uuid.random() for ids that must be unguessable, generateV7() for database primary keys, and a name-based UUID when the same input must always give the same id.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents