Using UUIDv7 as a JPA primary key for B-Tree index performance
Adopt RFC 9562 UUIDv7 as a JPA entity primary key with Hibernate 6.2+ to avoid UUIDv4 B-Tree page splits, backed by 1M-row PostgreSQL 17 benchmarks.
Choosing an entity primary key in Spring Data JPA usually forces a trade-off between
BIGINTwrite speed andUUIDv4distributed uniqueness. In this post, I explain why I adopted UUIDv7 (RFC 9562) with Hibernate 6.2+’s built-in@UuidGenerator, and share 1-million-row PostgreSQL 17 benchmarks comparing insert throughput, B-Tree index bloat, and buffer cache hit ratios.
Tested with Spring Boot 3/4, Hibernate 6.2+, Kotlin, and PostgreSQL 17.
The classic primary key trade-off: BIGINT vs. UUIDv4
Every new Spring Boot domain model starts with the same question: what type should the primary key be? Historically, backend teams had to pick between two flawed options:
flowchart TD
A["BIGINT AUTO_INCREMENT\n(Identity / Sequence)"] --> A_PRO["Pros: Right-append B-Tree writes\nCompact 8-byte index"]
A --> A_CON["Cons: Enumeration leaks\nNo pre-insert IDs\nHard to distribute"]
B["UUIDv4\n(Random 128-bit)"] --> B_PRO["Pros: Distributed generation\nUnpredictable global IDs"]
B --> B_CON["Cons: Random B-Tree inserts\nFrequent page splits\nIndex bloat & cache thrashing"]
1. Where BIGINT AUTO_INCREMENT falls short
Sequential 64-bit integers are ideal for database storage engines. Every insert appends to the rightmost leaf page of the B-Tree index, keeping page fill factor above 90% and memory usage low.
The cracks show up at the application and API layers:
- ID enumeration leaks: Sequential URLs like
GET /api/v1/users/1042expose user volume and growth rates to anyone paying attention, and let scrapers iterate through resources in a simple loop. - Centralized sequence bottleneck: In multi-region, microservices, or sharded setups, coordinating a single auto-increment sequence across nodes becomes a bottleneck.
- No pre-insert ID generation in JPA: With
GenerationType.IDENTITY, Hibernate cannot know the primary key until PostgreSQL runs theINSERT. That disables JPA transactional write-behind and JDBC batch inserts (as detailed in my JPA bulk insert guide) and makes publishing domain events before flush awkward.
2. Why UUIDv4 wrecks B-Tree write performance
Switching to UUID.randomUUID() solves distribution and enumeration, but hits a performance wall once a relational table grows large.
Because all 128 bits of UUIDv4 are random, every new row lands in a random leaf page of the sorted B-Tree index:
- Page splits: Inserting into a full 8 KB–16 KB leaf page forces PostgreSQL to split the page in two and copy half the entries to a new page.
- Index bloat: Split pages average ~50% fill factor, nearly doubling physical index size on disk and in RAM.
- Buffer pool thrashing: Writes scatter across the entire index instead of staying hot in the rightmost leaf page, driving down the shared buffer cache hit ratio and spiking random disk I/O.
How UUIDv7 (RFC 9562) fixes B-Tree locality
Standardized in May 2024 as RFC 9562, UUIDv7 keeps the standard 128-bit UUID wire format and global uniqueness while placing a 48-bit Unix epoch millisecond timestamp in the most significant bits.
classDiagram
class UUIDv7_Layout {
+Bits 0..47 : Unix_Epoch_Timestamp_ms (48 bits)
+Bits 48..51 : Version_0111 (4 bits)
+Bits 52..63 : Sub_millisecond_Counter (12 bits)
+Bits 64..65 : Variant_10 (2 bits)
+Bits 66..127 : Cryptographic_Random_Data (62 bits)
}
| Bit range | Field | Size | Purpose |
|---|---|---|---|
| 0–47 | unix_ts_ms | 48 bits | Milliseconds since Unix epoch (monotonic for ~8,900 years) |
| 48–51 | ver | 4 bits | UUID version (0111 = 7) |
| 52–63 | rand_a | 12 bits | Sub-millisecond sequence or counter for same-ms ordering |
| 64–65 | var | 2 bits | RFC variant (10) |
| 66–127 | rand_b | 62 bits | Cryptographically random bits for collision resistance |
This layout gives you three practical wins at once:
- Right-append B-Tree writes: Because the leading 48 bits increase with time, new keys append to the rightmost leaf page just like
BIGINT, avoiding random page splits. - Collision resistance and unpredictability: 74 bits of sequence and random entropy prevent collisions across distributed nodes and stop sequential ID guessing.
- Embedded creation time: You can decode the millisecond timestamp straight from the top 48 bits without an extra lookup.
Mapping UUIDv7 in Kotlin + Hibernate 6.2+
In Hibernate 5, using UUIDv7 required adding a third-party library (uuid-creator) and writing a custom IdentifierGenerator. Since Hibernate 6.2, @UuidGenerator(style = UuidGenerator.Style.VERSION_7) is built right into Hibernate core—no extra dependencies required.
1. Entity mapping (User.kt)
Here is how I mapped User in demo-backend-server:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// src/main/kotlin/com/example/server/user/domain/User.kt
package com.example.server.user.domain
import com.example.server.common.BaseEntity
import jakarta.persistence.CascadeType
import jakarta.persistence.Column
import jakarta.persistence.Entity
import jakarta.persistence.GeneratedValue
import jakarta.persistence.Id
import jakarta.persistence.OneToMany
import jakarta.persistence.Table
import java.util.UUID
import org.hibernate.annotations.UuidGenerator
@Entity
@Table(name = "users")
class User(
@Id
@GeneratedValue
@UuidGenerator(style = UuidGenerator.Style.VERSION_7)
@Column(columnDefinition = "UUID", updatable = false)
var id: UUID? = null,
@Column(unique = true, nullable = true)
var email: String? = null,
@Column(nullable = true)
var password: String? = null,
@Column(nullable = false)
var nickname: String,
var profileImageUrl: String = "https://api.dicebear.com/7.x/lorelei/svg?seed=${email ?: nickname}",
@OneToMany(mappedBy = "user", cascade = [CascadeType.ALL], orphanRemoval = true)
val socialAccounts: MutableSet<SocialAccount> = mutableSetOf()
) : BaseEntity()
Use PostgreSQL’s native
uuidcolumn type: Specifying@Column(columnDefinition = "UUID", updatable = false)stores the key in 16 binary bytes instead of a 36-byteVARCHAR(36)string, cutting index size by more than half.
2. Picking PK types by domain role
You don’t have to force UUIDv7 onto every table. In production, I split primary key types by how the table is exposed:
- UUIDv7: External-facing entities like
User,SocialAccount, andOrderwhere public IDs must resist enumeration and support pre-insert generation. BIGINT IDENTITY: High-volume internal batch tables likeJudgmentandRawJudgmentthat are never exposed directly to enumeration attacks and benefit from 8-byte keys.
Verifying RFC 9562 compliance and monotonic ordering
I wrote two integration tests to verify that Hibernate registers the VERSION_7 generator and that sequential inserts preserve time ordering:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// src/test/kotlin/com/example/server/user/domain/UserUuidV7Test.kt
package com.example.server.user.domain
import com.example.server.support.IntegrationTestSupport
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
class UserUuidV7Test : IntegrationTestSupport() {
@Autowired
private lateinit var userRepository: UserRepository
@Test
@DisplayName("Persisting an entity generates an RFC 9562 UUIDv7 identifier")
fun shouldGenerateUuidV7OnPersist() {
// given
val user = User(nickname = "Namju", email = "dev@namju.kim")
// when
val saved = userRepository.save(user)
// then
assertThat(saved.id).isNotNull
val id = saved.id!!
// RFC 9562 check: 13th hex char is '7', 17th hex char is variant [8, 9, a, b]
val hexString = id.toString().replace("-", "")
val versionNibble = hexString[12].digitToInt(16)
val variantNibble = hexString[16].digitToInt(16)
assertThat(versionNibble).isEqualTo(7)
assertThat(variantNibble in 8..11).isTrue()
}
@Test
@DisplayName("Sequentially created UUIDv7 IDs match createdAt ordering")
fun shouldPreserveMonotonicTimeOrdering() {
// given & when
val users = (1..50).map { i ->
userRepository.save(User(nickname = "user_$i", email = "user$i@namju.kim"))
}
// then: sorting by id must match sorting by createdAt
val sortedById = users.sortedBy { it.id }
val sortedByCreatedAt = users.sortedBy { it.createdAt }
assertThat(sortedById.map { it.id }).isEqualTo(sortedByCreatedAt.map { it.id })
}
}
Running ./gradlew test confirms Hibernate binds UuidGenerator.Style.VERSION_7 to both User#id and SocialAccount#id and passes both assertions in milliseconds:
Figure 1. Spring Boot test run confirming Hibernate 6.2+ VERSION_7 generator registration and monotonic ordering assertions.
Benchmark: 1 million inserts in PostgreSQL 17
To measure the real B-Tree impact, I created three tables (BIGINT IDENTITY, UUIDv7, and UUIDv4) in a local PostgreSQL 17 container (8 GB RAM, Apple Silicon NVMe SSD) and ran a single-threaded bulk insert of 1,000,000 rows into each.
Figure 2. 1M-row bulk insert comparison across total elapsed time (s), PK index size (MB), and buffer cache hit ratio.
| Key strategy | 1M insert time | Throughput | PK index size | Leaf fill factor | Cache hit ratio |
|---|---|---|---|---|---|
BIGINT (Identity) | 12.1 s | 82,644 ops/s | 21.4 MB | 92.8% (dense) | 99.8% |
UUIDv7 (RFC 9562) | 14.2 s | 70,422 ops/s | 26.1 MB | 91.4% (dense) | 99.2% |
UUIDv4 (Random) | 42.8 s | 23,364 ops/s | 43.8 MB | 54.2% (fragmented) | 88.4% (thrashing) |
Three numbers stand out:
- 3x faster writes than UUIDv4: UUIDv7 inserted 1 million rows in 14.2 seconds versus 42.8 seconds for UUIDv4—roughly 301% of UUIDv4’s throughput and 85% of raw
BIGINT. - 40% smaller index than UUIDv4: Random page splits bloated the UUIDv4 PK index to 43.8 MB (54.2% fill factor), whereas UUIDv7 stayed compact at 26.1 MB (91.4% fill factor).
- Hot buffer pool: Because writes stay localized on the rightmost leaf page, UUIDv7 held a 99.2% shared buffer hit ratio, avoiding the cache thrashing seen with UUIDv4 (88.4%).
Inspecting ORDER BY id DESC and index scans in PostgreSQL 17
Querying the live PostgreSQL 17 table confirms how UUIDv7 behaves during reads as well:
Figure 3. PostgreSQL 17 ORDER BY id DESC output and EXPLAIN (ANALYZE, BUFFERS) showing an index scan on users_pkey.
- Time-ordered pagination on the PK: The leading hex digits (
0193e24b-...→0193e24a-...→0193e249-...) sort in exact reverse chronological order, matchingcreated_at DESC. You can run keyset pagination (ORDER BY id DESC LIMIT 20) straight off the primary key index without adding a secondarycreated_atindex. - Sub-millisecond point lookups: Even at 1 million rows,
EXPLAIN (ANALYZE, BUFFERS)completes a single-row lookup viausers_pkeyin0.038 ms.
When not to use UUIDv7 and production caveats
UUIDv7 isn’t a blanket replacement for every primary key. Watch for two trade-offs before adopting it:
- Timestamp visibility: The top 48 bits directly encode the millisecond creation time. In domains where record creation timestamps themselves are sensitive (anonymous whistleblower reports, sealed-bid auctions), exposing a raw UUIDv7 leaks timing metadata. Keep
UUIDv4or add a separate opaque public token for those cases. - Cross-node clock drift: When multiple servers generate UUIDv7 independently, millisecond-level NTP drift can slightly invert ordering across nodes. If you require strict global ordering for event sourcing, rely on a single-writer broker (such as Kafka partitions) or a consensus sequence instead.
Quick adoption checklist
- Use
@UuidGenerator(style = UuidGenerator.Style.VERSION_7)on Hibernate 6.2+ instead of third-party generators. - Map the column to PostgreSQL’s native
UUIDtype (16bytes), neverVARCHAR(36). - Reserve UUIDv7 for externally exposed or distributed entities; keep
BIGINTfor internal high-volume batch tables where 8-byte compactness matters more. - Verify RFC 9562 version/variant nibbles in a unit test when introducing a new generator configuration.