Below is a “menu” of memory-cutting ideas that have worked for most Spring Boot projects I’ve tuned.
Pick the ones that fit your situation, measure again, and iterate. 🚀
0. Measure first (or you’ll tune the wrong thing)
| Tool | What you learn | Quick start |
|---|
| Spring Boot Actuator | Live heap / metaspace / threads | ./actuator/metrics/jvm.memory.used |
| JDK 17+ GC logging | GC pauses & heap pressure | -Xlog:gc*:file=gc.log:time,level,tags |
| VisualVM / JMC | Heap dump, allocation hot spots | jcmd <pid> GC.heap_dump heap.hprof |
| Eclipse MAT “Leak Suspect” | Memory leaks, class-loader bloat | Import heap.hprof |
| Container stats (Docker/K8s) | RSS vs JVM heap vs native | docker stats, kubectl top pod |
Write down a baseline (RSS, heap %, GC pause) before touching anything.
1. Trim what you ship
| Thing to check | Why it saves RAM | How |
|---|
| Starters | Every starter drags transitive deps | Replace spring-boot-starter-web with spring-boot-starter-webflux or spring-boot-starter-undertow if you don’t need Tomcat/Servlets |
| Unused autoconfig | Classes get loaded even if unused | spring.autoconfigure.exclude=... |
| Dev tools in prod? | They keep classes hot-loaded | Exclude spring-boot-devtools from prod build |
| Lombok at runtime | Remove; code is already compiled | provided scope |
| Beans created eagerly | They allocate on startup | spring.main.lazy-initialization=true |
| Reflection-heavy libraries | More metaspace & parsing | Favour plain Java APIs or JSON-B over Jackson for microservices |
2. JVM flags that usually pay off
| Flag | Typical micro-service value |
|---|
-Xms / -Xmx | Start==Max avoids resizes: -Xms256m -Xmx512m |
-XX:MaxMetaspaceSize | Cap class metadata: -XX:MaxMetaspaceSize=128m |
-XX:+UseG1GC | Default in 11+, good balance |
-XX:+UseStringDeduplication | 2-5 % RSS win if many repeated strings |
-XX:+HeapDumpOnOutOfMemoryError | Debugging, not perf—still recommended |
-XX:MaxRAMPercentage=70 (container) | Heap = % of cgroup limit (JDK 10+) |
Put them in JAVA_TOOL_OPTIONS (Docker/K8s) or a jvm.args file for Heroku/Cloud Foundry.
3. Tune Boot itself
| Property | Default | Memory-friendly value |
|---|
server.tomcat.max-threads | 200 | 20–50 (async I/O & WebFlux need fewer) |
spring.datasource.hikari.maximum-pool-size | 10 | ~ (#cpu × 2) or less for light DB use |
management.endpoints.web.exposure.include | * | Only what you need (health, prometheus) |
logging.level.* | INFO | Drop to WARN/ERROR in prod (log buffers) |
4. Code-level knobs
• Prefer @Configuration(proxyBeanMethods=false) to skip CGLIB proxies.
• Reuse RestTemplateBuilder / WebClient; don’t create new ones per call.
• Cache expensive immutable objects (compiled regex, ObjectMapper).
• Don’t keep large DTOs in session; prefer stateless requests.
• Watch out for unbounded collections (Guava cache w/o maximumSize, LinkedBlockingQueue without capacity, etc.).
5. Container / Cloud layer
| Scenario | Tip |
|---|
| Docker | docker run -m 512m … then rely on MaxRAMPercentage |
| Kubernetes | resources: limits: memory: 600Mi; add liveness probe to restart on leak |
| JLink | Create a 35-40 MB custom JRE: jlink --add-modules java.base,java.logging,… |
| AWS Lambda | Native image (below) |
| Heroku / CloudFoundry | Set JAVA_OPTS or SPRING_JPA_OPEN_IN_VIEW=false, scale dynos down |
6. Go further: AOT & Native
| Approach | Effect | Status |
|---|
| Spring AOT (3.x) | Generates static bytecode, ~30 % faster start, a bit less heap | GA |
| Spring Native w/ GraalVM | Binaries start <100 ms, 50–70 MB RSS | Still cutting-edge, worth for FaaS/micro apps |
| CRaC checkpoints | Snapshot warm JVM, near-instant cold start | Early adopters |
7. A repeatable optimization loop
- Baseline: collect
RSS, heap, GC stats under prod-like load.
- Apply ONE change (e.g., lower
Hikari pool to 5).
- Run the same load, capture metrics.
- Keep the change if p99 latency & GC improve, rollback if not.
Automate #1-#3 with JMeter/Gatling + a Grafana dashboard so you see wins and regressions.
Quick win checklist (copy-paste into your PR)
Nail those and most Spring Boot services happily run in 300-600 MB instead of 1-2 GB. 🎉
Need deeper help (heap dump analysis, GC tuning, or going native)? Let me know what environment and workload you’re on and we can dive further.