Workbench / Volume 3 Companion: The Backend
V3·41
Memory and Performance
Companion to Volume 3, chapter 41: how the performance workflow, where data lives, hardware effects and measurement connect; new angles (a memo that keeps photocopies, a toll clerk who writes down "every car since my last note", an open-tickets board against the day's ledger); what the chapter simplifies, measured on JDK 21 and the build's stage 42: a retry cache that kept old copies of every order and served them stale, a kitchen page whose cost grew with the whole day's history while allocating the same bytes, allocation profiles of one build that disagreed with each other because ten samples carried 83% of the weight, and a whole-page rewrite that cost a fifth of the page's allocation; the theory behind them (effective sample size, memoisation, secondary indexes); how JFR's allocation sampler weighs its samples, from the JDK source; four debugging drills; interview questions with how to approach each.
Understanding it better
Concept map
Chapter 41 has five parts: method first (the performance workflow), where data lives (stack and heap, object layout, allocation and TLABs, escape analysis, boxing, strings), hardware effects (CPU caches, data layout, branch prediction), measuring (JMH, what to profile, JFR and Mission Control, async-profiler, the jcmd family, finding a leak, other languages' tools) and tuning in practice.
The links worth remembering:
- Measure, then change one thing, then measure the same way. Every fix in this companion has a before and an after from the same harness.
- Memory is what you keep; allocation is what you make. A histogram answers the first, an allocation counter or profiler the second. They find different problems.
- A profiler is a sample; a counter is a count. Use samples to find where, counters to say how much (Gaps 3).
Explain it differently
1. A retry cache is a memo, and it shouldn't keep photocopies. A cashier who keeps a photocopy of every receipt to answer "have I paid already?" ends up with a drawer full of copies that are all out of date. Keep the receipt number and look up the current receipt (Gaps 1).
2. JFR's allocation sampler is a toll clerk who is often busy. When the clerk is free, the clerk writes on the next car: "this one, and every car since my last note". Cars that pass while the clerk is busy are all credited to whichever car comes next. A few cars end up carrying most of the traffic (Gaps 3).
3. An index is the open-tickets board. To know which orders a kitchen still has to cook, you can read the whole day's ledger every time, or keep a board of open tickets and update it whenever a ticket changes. The board costs a little space and discipline, and makes the question cost the same at 9 a.m. and 9 p.m. (Gaps 2).
4. The counter is a meter; the profiler is a survey. A meter on the pipe says how much water went through. A survey of a few taps says roughly which taps use the most. You need both, and you shouldn't quote the survey as the meter reading.
5. Rewriting the whole page to change the letterhead. To put a new logo on a letter you don't retype the letter. Rewriting only the header is both cheaper and safer: the body can't be changed by accident (Gaps 4).
Gaps and misconceptions
What the chapter oversimplifies
All outputs are real, from OpenJDK 21.0.12 and the build's stage 42 (exp/42), unless stated.
1. A cache of answers keeps the answers, and they go stale. The chapter's leak hunt looks for a collection that grows without bound. TiffinBox's retry table grows exactly as fast as orders do, so it doesn't look like a leak. But it kept each order's first Order object. Orders are immutable and every change makes a new object, so the server held two versions of every changed order. GC.class_histogram after 50,000 orders, most of them delivered:
50,000 orders: live heap 35,123 KB, 719 bytes per order
1: 166659 5986728 [B
2: 215230 5165520 java.lang.String
4: 94982 3039424 in.tiffinbox.core.Order
5: 100003 2400072 java.time.Instant
94,982 Order objects for 50,000 orders. The memory was the smaller problem. A retry after the order moved on returned the old version, and a retry after a restart (when the table is rebuilt from the log) returned the current one:
first request: "status":"Placed"
retry after accept: "status":"Placed"
retry after a restart: "status":"Accepted"
Stage 42 keeps the order id under each key, and the key itself as two longs instead of a 32-character hex string:
50,000 orders: live heap 29,264 KB, 599 bytes per order
2: 165040 3960960 java.lang.String
3: 116469 3577288 [B
7: 50000 1600000 in.tiffinbox.core.IdempotencyKey
8: 50000 1600000 in.tiffinbox.core.Order
first request: "status":"Placed"
retry after accept: "status":"Accepted"
retry after a restart: "status":"Accepted"
50,190 fewer strings and byte arrays: about 72 bytes each, replaced by a 32-byte record. 17% less heap per order, and one answer to the same question whether or not the server restarted.
2. Cost that grows with history doesn't show up in an allocation profile. The chapter lists missing indexes among the biggest backend wins, for databases. In memory, the kitchen page found its open orders by scanning every order the server remembered. The kitchen had the same 20 open orders each time; only the rest of the day grew:
2,000 orders: live heap 4,443 KB, 2,275 bytes per order
GET /kitchen/k7 287,640 bytes allocated, 350.6 µs per request
20,000 orders: live heap 15,066 KB, 771 bytes per order
GET /kitchen/k7 287,219 bytes allocated, 1,848.3 µs per request
50,000 orders: live heap 35,123 KB, 719 bytes per order
GET /kitchen/k7 290,322 bytes allocated, 3,836.7 µs per request
Allocation stayed flat and time grew roughly in proportion to the number of orders: walking a map allocates nothing, so an allocation profiler would never point at it. A CPU profile would, and so does measuring at several sizes. With an index of open orders per kitchen, kept up to date on every write and checked by the concurrency test:
50,000 orders: live heap 29,264 KB, 599 bytes per order
GET /kitchen/k7 292,850 bytes allocated, 363.1 µs per request
A test suite with 20 orders would never see the difference. Note the bytes per order, too: 2,275 at 2,000 orders and 719 at 50,000, because fixed costs (the menu, rules, classes' static data) are shared out over fewer orders. Measure footprint at the size you'll run.
3. An allocation profile is a few heavy samples, not hundreds of light ones. The chapter treats JFR's allocation samples as a picture of who allocates. Two recordings of the same build, rendering the same kitchen page 5,000 times:
# after (first recording, same build, same command): allocation samples for GET /kitchen/k7
42.8% Pages.kitchen < Pages.handle < Server.lambda$new$23
27.8% Pages.themed < Server.route < KPage.route
19.3% Pages.page < Pages.kitchen < Pages.handle
# after: allocation samples for GET /kitchen/k7, by TiffinBox frames
51.2% Html.scriptJson < Pages.kitchen < Pages.handle
18.6% Json.str < Json.lambda$order$0
11.0% Server.lambda$openOrders$0
420 samples, 943.8 MB in all; largest 284.6 MB (30%); top 10 carry 81%; median 505 kB
Different winners. The last line says why: of 420 samples, one carried 30% of all the bytes and ten carried 81%. The thread's own allocation counter, read before and after, agreed with itself across three runs:
GET /kitchen/k7 228,964 bytes allocated, 111.5 us per request
GET /kitchen/k7 235,235 bytes allocated, 156.0 us per request
GET /kitchen/k7 228,132 bytes allocated, 119.3 us per request
Where the lumps come from is in the JDK source (Code walkthrough). Use the samples to find candidates, a counter to measure a fix, and more or longer recordings before trusting a ranking.
4. A filter that rewrites the whole response pays for the whole response. The chapter's hidden costs are logging, regex and formatting inside a method. Every HTML response went through a theming step that ran three replacements over the whole page, the first one a replaceFirst (a regex compiled each call), to change text that appears only in the page's header. Rewriting only the part before <main id="main">, plus a fast path in Json.str for strings that need no escaping:
# stage-41 build
kitchen page: 14744 chars, Latin-1 only: true
GET /kitchen/k7 280,033 bytes allocated, 170.2 us per request
GET /menu 48,264 bytes allocated, 86.8 us per request
# stage-42 build
kitchen page: 14744 chars, Latin-1 only: true
GET /kitchen/k7 226,343 bytes allocated, 144.3 us per request
GET /menu 41,576 bytes allocated, 47.5 us per request
A fifth less allocation on the kitchen page, same output byte for byte (the golden master's 47 exchanges are identical). The rewrite had a correctness edge too: a replacement over the whole page also applies to the page's content, so any <option> in the body matching the theme's value would have been marked selected. (The "Latin-1 only" line matters as well: one character outside Latin-1, such as ₹, would make Java store the whole string as UTF-16, two bytes per character; chapter 41 covers compact strings.)
Common misconceptions
| Misconception | What's actually true | Where it's shown |
|---|---|---|
| "A cache that grows with the data isn't a leak." | It can still keep far more than it needs, and serve stale answers. | Gaps 1 |
| "Immutable objects make caching safe." | Safe to share, but a cached version is still an old version. | Gaps 1 |
| "The allocation profile shows what's slow." | It shows what allocates; a scan that allocates nothing is invisible to it. | Gaps 2 |
| "Bytes per object at a small size predict the large size." | Fixed costs dominate small runs. | Gaps 2 |
| "420 samples is a big sample." | Not when ten of them carry 81% of the weight. | Gaps 3, Theory 2 |
| "Two profiles that disagree mean the code changed." | Not necessarily: the same build can rank differently. | Gaps 3 |
| "String replacement is cheap." | On a whole page it copies the page each time, and changes what you didn't mean to. | Gaps 4 |
| "A regex that runs once a request is fine." | It's compiled once a request too. | Exercises P3 |
Theoretical gaps: the ideas behind the chapter
1. Memoisation remembers answers; what it should remember is the key to the answer. Memoising a pure function (Michie, 1968) is safe because the answer never changes. An idempotency table memoises a request, whose correct answer can change (the order moves on). Store a reference to the thing (an id) and decide explicitly whether a retry returns the original response or the current state. Payment APIs such as Stripe's return the original response; TiffinBox returns the current order. Either is defensible, but it should be one rule, not two depending on whether the process restarted.
2. Weighted samples have an effective sample size. With sample weights wᵢ, Kish's effective sample size (1965) is (Σwᵢ)² / Σwᵢ². For Gaps 3's recordings it is 6.3 (of 480 samples) and 5.7 (of 420): the ranking rests on about six independent observations. With the throttle raised (Code walkthrough), 2,372 samples gave an effective size of 1,319, and two runs agreed within two percentage points.
3. Measure at several sizes, and look at the slope. Asymptotic complexity is invisible at one size. 350.6, 1,848.3 and 3,836.7 µs at 2,000, 20,000 and 50,000 orders is a slope of about 73 µs per thousand orders: linear in history. Measuring at three sizes in a benchmark harness (as exp/42/Heap.java does) is the cheapest way to catch it before production's data does.
4. A secondary index trades space and write work for read time. The open-order index adds about 5,000 map nodes for 50,000 orders and an update on every write. Its correctness is an invariant (the index equals a scan of the orders), which is why stage 42's concurrency test checks exactly that after concurrent writes. Databases make the same trade with every CREATE INDEX.
5. Records still have headers. IdempotencyKey(long hi, long lo) is 16 bytes of data in a 32-byte object (a 12-byte header, padding to 8-byte alignment). Project Valhalla's value classes (JEP 401) aim to let objects without identity be stored flattened, without a header, inside arrays and other objects.
Applying it
Code walkthrough
Gaps 3's lumpy weights come from how HotSpot decides which allocations to report. From openjdk/jdk21u, src/hotspot/share/jfr/support/jfrObjectAllocationSample.cpp.
When a sample is taken
void JfrObjectAllocationSample::send_event(const Klass* klass, size_t alloc_size, bool outside_tlab, Thread* thread) {
assert(thread != nullptr, "invariant");
JfrThreadLocal* const tl = thread->jfr_thread_local();
assert(tl != nullptr, "invariant");
if (outside_tlab) {
normalize_as_tlab_and_send_allocation_samples(klass, static_cast<int64_t>(alloc_size), tl, thread);
return;
}
const int64_t allocated_bytes = load_allocated_bytes(tl, thread);
if (allocated_bytes == 0) {
return;
}
send_allocation_sample(klass, allocated_bytes, tl);
}
The fast path of allocation (bumping a pointer in the thread's TLAB, chapter 41's "Allocation and TLABs") is never interrupted to record anything. HotSpot calls this from the slow path: when a thread needs a new TLAB, or allocates an object too big for one. So the class and stack trace in a sample are those of the object that happened to need the next buffer, not of whatever filled the previous one.
What a sample weighs
inline bool send_allocation_sample(const Klass* klass, int64_t allocated_bytes, JfrThreadLocal* tl) {
EventObjectAllocationSample event;
if (event.should_commit()) {
const int64_t weight = allocated_bytes - tl->last_allocated_bytes();
assert(weight > 0, "invariant");
event.set_objectClass(klass);
event.set_weight(weight);
event.commit();
tl->set_last_allocated_bytes(allocated_bytes);
return true;
}
return false;
}
The weight is everything the thread allocated since its last committed sample. should_commit() includes the event's throttle: the profile settings allow 300 of these events a second, default 150. When the throttle says no, last_allocated_bytes isn't updated, so the next sample that is committed carries all the bytes since. That's the clerk who writes "every car since my last note" (Explain it differently 2), and the 285 MB sample in Gaps 3.
Large objects
// To avoid large objects from being undersampled compared to the regular TLAB samples,
// the data amount is normalized as if it was a TLAB, giving a number of TLAB sampling attempts to the large object.
An object allocated outside a TLAB gets up to one sampling attempt per TLAB-size of its bytes, so a 10 MB array has many chances to be recorded, as if it had filled several buffers.
Debugging drills
D1. Heap grows twice as fast as the data
A service's heap after a day holds about twice as many Order objects as there are orders, though nothing in the heap dump looks like a leak: no list grows faster than the orders.
D2. A page that slows down through the day
A dashboard page takes 5 ms in the morning and 80 ms by evening, and is fast again after a restart. Allocation per request, GC pauses and heap occupancy are flat all day.
D3. Two profiles, two culprits
Two engineers each take a two-minute JFR recording of the same service on the same version. One says JSON encoding allocates the most; the other says the HTML templates do. Both show screenshots of JMC.
D4. A filter that doubled the allocation, and changed a page
A servlet filter injects a CSP nonce into every HTML response by string replacement. Allocation per request doubled on large pages, and a support ticket says one customer's saved note now contains a nonce attribute.
Career-oriented
Interview prep
Mid-level 1: the size of one order
Question. "How would you find out how much memory one order takes in our running service?"
How to get there. Measure the heap with N orders and with 2N, not one object in isolation.
Mid-level 2: counter or profiler
Question. "What's the difference between measuring allocation with ThreadMXBean and with JFR, and when would you use each?"
How to get there. One counts, one samples.
Senior 1: an idempotency store
Question. "Design the idempotency store for our order API. It must survive restarts, and memory is tight."
How to get there. What to store, what a retry returns, how long to keep it.
Senior 2: slower every day until a restart
Question. "An endpoint's p99 rises steadily through the day and resets on restart. How do you investigate?"
How to get there. List what grows during a day, then measure against each.
Staff 1: continuous profiling across a fleet
Question. "We're turning on continuous profiling for all services. How do we make sure teams draw the right conclusions from it?"
How to get there. What sampled data can and can't say, and how to make comparisons trustworthy.
Staff 2: how many orders per instance
Question. "Business expects ten times the order volume next year. How do we decide whether our in-memory design holds, and when to shard?"
How to get there. Build a capacity model from measurements, then find the first limit.