Workbench / Volume 3 Companion: The Backend
V3·49
Persistence — JDBC, JPA and Spring Data
Companion to Volume 3, chapter 49: how talking to the database, JPA and Hibernate, Spring Data and the nuances that cause incidents connect; new angles (a log as a ledger, a snapshot as a ledger's carried-forward balance, a database as a library with a catalogue); what the chapter takes for granted, measured on TiffinBox's own append-only order log in stage 50: a log that couldn't open past 2 GiB, restarts that grow with every order ever placed (5.2 s and 1.9 GB of heap at 500,000 orders), compaction that cut the files by a third but not the state, and 40 kill -9s during writes, rolls and compactions with no acknowledged order lost; the theory behind them (write-ahead logs and checkpoints, log compaction, write amplification, the durability chain, retention); how Kafka's log cleaner decides what to keep, from its source; four debugging drills; interview questions with how to approach each.
Understanding it better
Concept map
Chapter 49 covers talking to the database (the persistence stack, JDBC, transactions, parameters), JPA and Hibernate (mapping, the entity lifecycle and persistence context, lazy and eager loading, identity), Spring Data (repositories, derived queries, specifications, projections) and the nuances that cause incidents (N+1, fetch joins, pagination with joins, optimistic locking, batching, connection pools), with persistence in other ecosystems.
The links worth remembering:
- A database is a storage engine you didn't have to write. The chapter's tools sit on top of a write-ahead log, checkpoints, pages, indexes and a buffer pool. TiffinBox, which has its own log, has to build each of those itself, and this stage shows what each costs.
- Most persistence incidents are round trips or races. N+1 and unbatched writes are round trips; lost updates and read-modify-write are races. The fixes move work to where the data is: one query, one batch, one atomic update.
- The persistence context is a cache with rules. It holds what you loaded, writes what you changed at flush, and is per transaction. Treat it as memory with a lifetime, and most JPA surprises become predictable.
Explain it differently
1. A log is a ledger. Every change is a new line; nothing is erased. To know a balance you add up every line, which is fine in January and slow in December (Gaps 2).
2. A snapshot is the balance carried forward. At month end an accountant writes "balance brought forward" and starts a new page. The old pages can go to the archive, because the balance says everything they said that still matters, as long as the line was written before the pages were taken away (Gaps 3, 4).
3. A database is a library with a catalogue. A ledger you hold in your head has to be reread after every nap. A library keeps the books on shelves and finds one through the catalogue, so you only fetch what you need. TiffinBox holds every order in memory, which is the ledger in your head (Gaps 3).
Gaps and misconceptions
What the chapter takes for granted
The chapter's code asks a database to keep data and find it again. TiffinBox has kept orders in an append-only log since stage 8, replayed into memory on every start. All outputs are real, from OpenJDK 21.0.12 and the build's stage 49 and 50 code (exp/50), unless stated.
1. A file's size can outgrow an int. Recovery read the whole log into one array: ByteBuffer.allocate(Math.toIntExact(ch.size())). A log just past 2 GiB (a sparse file, so no disk is used):
# stage 49
orders.log: 2,147,487,745 bytes
open failed: java.lang.ArithmeticException: integer overflow
At 360 bytes per order (Gaps 2), 2 GiB is about 6 million orders: eight years at 2,000 orders a day, ten months at 20,000. The server would have refused to start one morning, with nothing wrong except success. Java arrays, ByteBuffers and memory-mapped regions are all limited to 2 GiB; databases read in pages (8 KiB in PostgreSQL). Stage 50 reads every file in 8 MiB windows:
# stage 50, the same file
orders.log: 2,147,487,745 bytes
opened: 0 records
(The file is zeros after its first byte, so recovery treats all of it as a torn tail.)
2. Restart reads all of history. Orders placed and moved through the order service (nine in ten accepted, made ready and handed over), then the directory opened three times:
# stage 49
50,000 orders: log 17,623 KB (360 bytes per order)
restart 1: read the log 603 ms, rebuild the orders 256 ms, peak heap 197 MB, records read 185,000
200,000 orders: log 70,827 KB (362 bytes per order)
restart 1: read the log 1,853 ms, rebuild the orders 527 ms, peak heap 841 MB, records read 740,000
500,000 orders: log 177,593 KB (363 bytes per order)
restart 1: read the log 4,088 ms, rebuild the orders 1,126 ms, peak heap 1,947 MB, records read 1,850,000
Linear in everything ever written: time, records and heap. Chapter 48's readiness waits for this, and a crash at 500,000 orders is five seconds of no orders. A database restarts in time proportional to the work since its last checkpoint, not to the size of its data (Theory 1).
3. Compaction bounds the files, not the state. Stage 50 splits the log into 64 MiB segments and folds closed ones into a snapshot that keeps only what recovery needs: each order's first record, its last, and records whose idempotency key is younger than seven days. With orders spread at 2,000 a day:
# stage 50
200,000 orders: log 41,072 KB (210 bytes per order)
restart 1: read the log 1,277 ms, rebuild the orders 457 ms, peak heap 570 MB, records read 412,072
500,000 orders: log 117,134 KB (239 bytes per order)
restart 1: read the log 3,032 ms, rebuild the orders 1,094 ms, peak heap 1,606 MB, records read 1,187,473
A third less disk, a quarter less restart time, and still linear: every order ever placed is two records and an object in memory. That's the limit of "state in memory, log on disk": the state grows with the business. A database keeps rows on disk in pages and reads the ones a query needs through an index, with a buffer pool holding the hot ones, so memory follows the working set, not the history. That's TiffinBox's next storage decision (Senior and architect lens in the stage), and the reason most services start with a database.
4. Durable means the name too. Compaction writes a new snapshot and deletes the files it replaces. If a crash lands in between, recovery must find either the old files or the new snapshot, never neither and never both counted. Stage 50 writes to a .tmp file, fsyncs it, renames it, fsyncs the directory, and only then deletes; on open, leftovers (a .tmp, an older snapshot, segments the snapshot covers) are removed. A process appending with 32 KiB segments, so that it rolls and compacts constantly, killed with SIGKILL at random moments, checked after every kill:
40 kills; 112,641 orders acknowledged; lost 0; state older than acknowledged 0; at most 61 files in the directory; 16,681 KB on disk
"At most 61 files": with 32 KiB segments, writes outran the compactor, which rewrites the whole snapshot every time (Theory 3).
Common misconceptions
| Misconception | What's actually true | Where it's shown |
|---|---|---|
| "A file is just bytes; read it." | Arrays and buffers stop at 2 GiB; read in windows. | Gaps 1 |
| "An append-only log is simple storage." | Its restart time and memory grow with history until you add checkpoints. | Gaps 2 |
| "Compaction solves growth." | It removes superseded records; live state still grows. | Gaps 3 |
| "fsync makes a file durable." | It makes its contents durable; a new or renamed name needs the directory fsynced. | Gaps 4 |
| "Autocommit is fine for bulk writes." | Each commit waits for a flush: batch them (TiffinBox's group commit). | The chapter's lab, Experiment 2 |
| "The ORM loads what I use." | It loads what you touch, one query at a time, unless you say otherwise. | The chapter's lab, Experiment 1 |
Theoretical gaps: the ideas behind the chapter
1. Write-ahead log and checkpoints. A database writes each change to a sequential log (fsynced at commit) before changing its pages in memory, and writes dirty pages to their places later. A checkpoint records that every change up to a point is in the pages, so recovery replays only the log after it. PostgreSQL's checkpoint_timeout (5 minutes by default) and max_wal_size bound restart time; TiffinBox's snapshot is a checkpoint, and its segment size is max_wal_size's cousin.
2. Log compaction. For a log of updates to keys, older versions of a key can be dropped once a newer one is safe. Kafka does it per topic key (Code walkthrough); TiffinBox per order id, keeping the first version as well because it carries who placed the order and its price. Deletions need their own retention: if a "deleted" marker is dropped too soon, a reader that missed it sees the old value forever.
3. Write amplification. Every byte the application writes may be written again by compaction. TiffinBox rewrites its whole snapshot at each roll, so the cost of a compaction grows with the state; with fast writes and small segments, compaction falls behind (Gaps 4's 61 files). LSM trees (RocksDB, Cassandra) compact in levels so each byte is rewritten a bounded number of times; B-tree databases update pages in place and pay with random writes and a WAL.
4. The durability chain. Data in a write is in the page cache; fsync (or fdatasync) puts it on the device; a new file's name is a directory entry, durable only after the directory is fsynced; a rename is atomic but not durable until then. Ordering matters: never delete the old copy before the new one, and its name, are durable.
5. Retention is a decision. How long an idempotency key lives decides how long a retry is recognised; how long old orders live in hot storage decides memory; how long personal data lives is often decided by law. Each is a setting with an owner, not a side effect of compaction.
Applying it
Code walkthrough
Gaps 3 and Theory 2 are what Kafka's log cleaner does for compacted topics. From apache/kafka, trunk at commit 5b648ca (20 November 2026).
Keep the newest record per key
storage/src/main/java/org/apache/kafka/storage/internals/log/Cleaner.java:
private boolean shouldRetainRecord(OffsetMap map,
boolean retainDeletesForLegacyRecords,
RecordBatch batch,
Record record,
CleanerStats stats,
long currentTime) throws DigestException {
boolean pastLatestOffset = record.offset() > map.latestOffset();
if (pastLatestOffset) {
return true;
}
if (record.hasKey()) {
ByteBuffer key = record.key();
long foundOffset = map.get(key);
...
boolean latestOffsetForKey = record.offset() >= foundOffset;
...
boolean isRetainedValue = record.hasValue() || shouldRetainDeletes;
return latestOffsetForKey && isRetainedValue;
The cleaner works in two passes, like TiffinBox's compaction: first it builds an offset map (key to the offset of its newest record) over the dirty part of the log; then it copies segments, keeping a record only if it's the newest for its key. A record with a key but no value is a tombstone, a deletion; it's kept until its delete horizon (delete.retention.ms after cleaning), so consumers that were behind still see the delete. Records past the map's last offset are kept untouched: the cleaner never decides about what it hasn't indexed.
Swap the files
Later in cleanSegments, the cleaned segments replace the originals:
log.replaceSegments(cleanedSegments, segments);
Underneath, LocalLog.replaceSegments renames the cleaned files from a .cleaned suffix to .swap, schedules the old segments for deletion, then removes the .swap suffix; its comment says it works "in two phases to be crash safe", and a crash in the middle is completed when the log loads its segments. That's Gaps 4's problem with a different set of suffixes.
Debugging drills
D1. Each restart is slower than the last
A service that rebuilds its state from an event store took 3 s to start in January and 40 s in October. Nothing in the code changed.
D2. Fine for a year, then won't open
A tool that processes daily export files suddenly fails on one file with ArithmeticException: integer overflow or NegativeArraySizeException.
D3. Two copies after a crash
After a power cut, a service that rewrites its data file by "write new, delete old" starts with duplicate entries, or with none.
D4. Duplicates after a week
A client that retries failed payments with the same idempotency key creates duplicates when the retry is more than a week later.
Career-oriented
Interview prep
Mid-level 1: what a commit waits for
Question. "Why is inserting 10,000 rows with autocommit so much slower than in one transaction?"
How to get there. What has to happen before a database can say "committed"?
Mid-level 2: the persistence context
Question. "You load an order, change its status, and never call save. Is the change written?"
How to get there. What does a managed entity mean?
Senior 1: snapshots for an event-sourced service
Question. "Design snapshots for a service that rebuilds its state from an event log."
How to get there. What must a snapshot guarantee, and what happens if the process dies while writing one?
Senior 2: when to move to a database
Question. "Our service keeps all its state in memory and an append-only file. When should it move to a database?"
How to get there. What grows with time, and what does each choice cost?
Staff 1: retention across an organisation
Question. "Design data retention for a platform: idempotency keys, logs, orders, personal data."
How to get there. Who decides each period, and how is it enforced and checked?
Staff 2: building storage
Question. "A team wants to write its own storage layer for performance. How do you evaluate the proposal?"
How to get there. List what a database does that they'd have to do.