Java Memory Leaks: Why a Cart Update Keeps Loading
Asha changes quantity from 1 to 2, but her cart keeps loading. Learn how abandoned cached copies can pressure the shared Java heap, and how a bounded cache protects current requests.
Architecture in Motion · Episode 018 · at a glance
Asha changes quantity from 1 to 2. She expects the quantity and total to refresh, but the cart keeps loading and she cannot confirm the result.
Find the map retaining old shoppers’ cart copies, limit how long those copies stay, and reload the original saved cart when a copy is missing.
Illustrative customer journey. Entry counts are not measurements of heap bytes or response times.
See the problem.
Understand the rule.
Java Memory Leaks: Why a Cart Update Keeps Loading
Follow one quantity change: expected quantity and total, the normal saved-cart/cache flow, abandoned copies competing for shared memory, evidence of retention, and Caffeine limits with safe database reload.
Use the player controls to pause, seek, or enter fullscreen. The written explanation below is available at your own pace.
Open video separately ↗Explain the loading cart, one step at a time
Start with Asha changing quantity from 1 to 2. Learn what the API and database should do, why old copies can accumulate, and how a size limit, idle expiry and database reload protect the cart. Then test the failure and healthy scenarios.
Open the cart-cache incident simulator ↗Original comparison lab and controls
The previous unbounded-retention and healthy-growth comparison remains available with its original controls.
Open original comparison lab ↗1. What the shopper is trying to do
Asha has a small shopping cart. She changes the quantity of one product from 1 to 2. She expects the quantity and basket total to refresh so she can check that the cart is correct and continue shopping.
Instead, the page keeps showing Loading…. The displayed total does not update promptly. She cannot confidently confirm the change and may retry or leave. Earlier in the day the same action worked normally; after the service has handled many shoppers, cart updates may slow down.
That is the customer problem: a simple cart change stops giving a timely, clear result. The customer does not see a memory graph or care which collector is running. She needs a responsive cart showing the saved values.
This is an illustrative incident, not a reported production result. The article, video and simulator follow the same quantity-change story. The simulator counts cached copies across shoppers; it does not calculate product quantities, prices or response times.
2. First understand the normal successful flow
- The server endpoint—the Spring Boot cart API—checks who owns the cart and validates the quantity change.
- The application saves the change in the database, which holds the original cart record.
- After the database save completes successfully (commits), it removes any known-old temporary memory copy from the cache. This removal is called invalidation.
- A cart read uses a valid temporary copy, or loads the saved cart from the database when the copy is missing. The response gives the UI the confirmed quantity and total.
A cache is temporary storage for reusable data. Here it keeps a small copy of a cart in server memory so repeat reads can avoid another database call. A missing copy is called a cache miss. Removing a cached copy is called eviction; it does not delete the database record.
The normal flow is useful. The bug is letting those temporary copies live indefinitely.
| Part of this example | Its responsibility |
|---|---|
| Java application memory, called the heap | Holds objects used by the running service, including cached cart copies |
| Spring Boot | Runs the cart API and application services |
| Database / authoritative store | Holds the original saved cart; this lesson does not require a particular database product |
| Caffeine | Provides the proposed cache size limit and idle-expiry policy |
| JFR and heap-analysis tools | Help identify which objects and references are retaining memory |
This is not a new Java 21 collector feature fixing the application. The practical change is the cache lifecycle. Java 21 supports the diagnosis tools; the standalone teaching lab runs on Java 17+.
3. Why other shoppers' old carts can affect Asha
The service stores cart copies in a map: a lookup table keyed by cart ID. The map belongs to a long-lived application service. When another shopper visits, another distinct cart ID can add another cached copy.
The shopper leaves, but the application never removes the old entry. The service continues holding links to all those copies. A link from one live object to another is a reference.
Running application service → cart map → abandoned cart copiesAsha's cart did not become large. Old copies from many shoppers are using the same Java heap that serves her current request. Retaining more objects leaves less space for new request work and can increase garbage-collection work and memory pressure. That can contribute to delays or failures; the effect must be established with evidence, not inferred from a spinner alone.
Garbage collection, or GC, reclaims objects the application can no longer reach. It cannot decide that a shopper has lost interest. If the live map still holds a reference to the copy, Java correctly treats it as reachable and keeps it.
The shelf analogy is useful here: keeping a few recent photocopies near the counter saves trips to the records room. Keeping every abandoned copy forever fills the shared shelf. The original saved records still belong in the records room.
private final Map<String, CartSnapshot> snapshots = new ConcurrentHashMap<>();
void remember(String cartId, CartSnapshot snapshot) {
snapshots.put(cartId, snapshot);
}ConcurrentHashMap coordinates concurrent access; it does not automatically impose a maximum number of entries or expire idle entries. Repeated updates to one key do not by themselves increase the number of keys. The retention problem here comes from accumulating distinct cart IDs without a lifecycle policy.
What we change and why it helps
- Limit cached copies. A Caffeine size policy replaces keeping every distinct cart indefinitely.
- Expire idle copies. Copies that have not been accessed for the chosen interval can leave the cache.
- Save first, invalidate after commit. A committed cart update must not intentionally leave a known-old local copy in use.
- Reload a missing copy. Fetch the saved cart from the database. If the database is unavailable, return a controlled retryable error rather than a fabricated empty cart.
This removes the indefinite-retention path for these cached copies. It does not by itself prove that every slow cart request was caused by memory or that response times improved. We verify both memory behaviour and the customer-facing request outcome under the same workload. The sections below cover the evidence, integration caveats and trade-offs.
4. Diagnose with evidence
The senior engineering decision is to prove the retaining owner before selecting the fix. A slow database, a busy CPU or another memory consumer could also delay the same cart update.
Compare the same workload over time
The post-GC live set is the objects still occupying the Java heap after collection. Compare that retained population during similar workload phases. Also record allocation rate, GC pauses and CPU, errors, and endpoint p95/p99: response-time percentiles that expose slow requests hidden by an average. RSS is process memory resident in physical RAM; it includes more than the Java heap.
Check alternative causes such as database waits, direct buffers, native allocations and thread stacks. If heap retention stabilizes but RSS keeps rising, a heap cache may not explain the growth.
Record runtime evidence
Java Flight Recorder (JFR) records JVM events. In an approved environment, a controlled recording can support an allocation and GC investigation:
jcmd <pid> JFR.start name=cart settings=profile duration=60s filename=/secure/cart.jfrjcmd <pid> GC.class_histogram can identify object types worth investigating; counts do not identify the owner holding the references.
Find the reference chain
A heap dump is a snapshot of Java objects and their references. When appropriate, capture one with jcmd <pid> GC.heap_dump /secure/cart.hprof, accounting for disk capacity and operational impact. In Eclipse Memory Analyzer (MAT), inspect the dominator tree and paths to GC roots to find the long-lived owner. Retained size includes exclusively dominated objects, unlike the shallow size of just one object.
Dumps can contain sensitive customer data. Restrict access, encrypt them and apply retention/deletion policy; never publish production dumps.
5. Implement the fix
Replace the unbounded map with a cache whose lifecycle is explicit. Caffeine provides maximumSize (entry-count policy) and expireAfterAccess (expiry after an idle period). Each access can extend that idle lifetime. The Spring/Caffeine fragment shows a 10,000-entry cap and 20-minute idle expiry as illustrative starting values, not recommended universal defaults. Add the Caffeine dependency using your Spring Boot dependency management. Authorize before fetching cache entries; keys include tenant and cart identity. Cache only small read-only data objects (immutable DTOs), never entire session graphs, payment secrets or mutable entities. Size is a count, not a byte limit; consider maximumWeight and a defensible weight estimator when values vary widely. Expiry and eviction maintenance may be asynchronous in Caffeine, so do not treat the configured count as a strict instantaneous physical heap bound. TTL alone allows large bursts, and repeatedly accessed entries can remain live. A size cap complements expiry.
Cache eviction is not cart deletion. On a miss, reload from persistent storage. If storage fails, return a controlled retryable error rather than inventing an empty cart. Updates must invalidate after commit; a concurrent stale load can race invalidation. For strong consistency, use version checks or bypass cache for critical reads; across pods (separate application instances) use durable invalidation/versioning and define acceptable staleness. Do not rely on local cache for distributed session truth. Payment retries require durable idempotency separately.
6. Runnable lab
Download RetentionLab.java, run javac --release 17 -d out RetentionLab.java, then java -cp out RetentionLab. This demonstration uses a synchronized LRU map and explicit fake time, not Caffeine. The mock authoritative store is deliberately in memory; it is not a production storage implementation or an isolated heap benchmark. It inserts 20,000 unique cart IDs, checks the unbounded map retains 20,000 entries while the teaching cache retains 100, advances time, reloads an evicted cart and validates update invalidation. The integration reruns this Java lab locally; see the verification note below for its scope. For production tests use separate JVMs, realistic bounded payloads, persistent storage and the same load profile before/after.
Why the examples use different capacities
| Example | Capacity | Purpose |
|---|---|---|
| Visual story and simulator | 8 cached copies | Show thirty reachable copies becoming a bounded population |
| Runnable Java teaching map | 100 cached copies | Check 20,000 distinct keys, expiry and reload without a framework |
| Spring/Caffeine fragment | 10,000 entries, 20-minute idle expiry | Illustrate configuration to size and validate for a real workload |
These are distinct teaching scales, not interchangeable heap or performance measurements. The mock authoritative store in the Java lab also retains records; it deliberately prevents this exercise from being an isolated heap-memory benchmark. The Java checks include exact-TTL reload, repeated writes to one key and missing-cart handling. The Caffeine integration fragment is not compiled or integration-tested here.
7. Validate and roll out
Use JMeter in staging to exercise unique cart IDs, repeat visits, writes and cache misses. Ramp traffic, hold steady, stop arrivals and observe recovery; compare post-GC live set, GC overhead, p95/p99, success rate, hit ratio, eviction count, DB load and RSS. Verify logout/revisit, two pods, store failure, tenant isolation and stale-load races. Avoid cart-ID metric labels. Choose heap/container limits with native headroom. Canary rollout; monitor miss storms and revert safely if backend load rises. Larger heaps or a different collector may buy time but do not repair a retention root. Restart is mitigation, not resolution.
8. Trade-offs
Local cache avoids network round trips but duplicates entries per pod. A shared Redis cache supports cross-pod access but introduces network and availability dependencies and still needs memory/TTL policies. No cache is preferable for low reuse or strict freshness when store capacity permits. Bounded caches can increase misses; protect storage with bounded concurrency and request coalescing where appropriate. Do not promise latency improvements until measured.
9. Exercises
- Run the lab with 200 unique IDs and capacity 10. Predict retained entries.
- Add an expiry test at exactly TTL and verify reload from the store.
- Design a multi-pod stale-load race test and a version-aware invalidation strategy.
Solutions: 1: 200 versus 10. 2: advance fake time to last access + TTL, assert expiry and reload. 3: pause a load of version 1, commit version 2, invalidate, release old load; reject or bypass stale version using authoritative version semantics. Test missed invalidation and recovery.
10. Interview questions and answers
Why can Java leak memory with GC? Reachable but obsolete objects remain live. Is a thread-safe map a cache? Not necessarily; concurrency safety is separate from lifecycle. Does TTL bound peak memory? No. Does eviction delete a cart? Not if cache and authoritative storage are separated. Is retained size the same as shallow size? No; retained size includes exclusively dominated objects. Can increasing heap fix this leak? It can delay failure but leaves retention unchanged. How do you distinguish heap and native leaks? Compare heap live set with RSS and native-memory evidence.
Takeaway: A cache should remember useful data, not every customer forever. Bound retention, preserve durable cart state, and validate the customer outcome.
Additional pitfalls and primary references
Do not call every rising heap a leak, use System.gc() as a production repair, or assume a thread-safe collection manages business expiry. Larger heaps and restarts can temporarily mitigate symptoms without releasing the retaining root.
Keep exploring
Questions about these trade-offs or a topic for the next article?
Start a conversation ↗Share on LinkedIn ↗Join the conversation
Was this lesson helpful? Leave a like or share a question.
Comments
Related articles
Java 21 Generational ZGC: Diagnosing Slow Product Search
Why do search results sometimes take two seconds? Understand temporary objects, GC pauses and Java 21 Generational ZGC, then investigate the real bottleneck.
Java 21Java Deadlocks and Thread Dumps: Diagnosing Checkout That Stops Making Progress
The checkout spinner never finishes while CPU stays low; two workers may hold locks that each other needs.
Java 21Payment Idempotency in Spring Boot: Handling Timeouts and Retries
The gateway authorizes a payment but checkout never receives the response. Explore how stable keys, database uniqueness and reconciliation make retries safer.