r/java • u/supremeO11 • Jun 29 '26
How often do you run into JVM heap issues when developing or running microservices?
I'm trying to validate whether this is a real problem that other Java developers face, or whether it's just something specific to my setup.
A while ago I was working on a project where I regularly had around 9 spring boot microservices running locally, along with Activemq and elasticsearch.
Quite a few times I'd hit a point where few services (very often Elasticsearch) simply wouldn't start because the machine was running out of memory. My usual soln was to manually lower the -Xmx of some services, restart them, and keep experimenting until everything fit.
It made me wonder:
- How common is this for people working with multiple JVM services locally?
- Do you just accept it and restart services with different heap sizes?
- Do you have fixed -Xmx values checked into your projects?
- Do you use Docker resource limits or just buy more RAM?
- Have you ever had to stop one service just to start another?
I'm also curious about production.
When services begin running into memory pressure:
- How do you usually detect whether it's a genuine memory leak or just increased load?
- How often do you end up changing heap sizes?
- Is this mostly handled by Kubernetes/VPA/manual tuning, or is it still a fairly manual process?
The reason I'm asking is that I've been experimenting with an idea for a tool that continuously watches JVM heap usage, tries to distinguish memory leak from normal load, and could automatically rebalance heap allocations (or restart a JVM with a better heap size when necessary) instead of requiring manual tuning.
I'm not trying to promote anything I'm still in the research stage and genuinely want to know whether I'm solving a real problem or one that only I experienced.
I'd really appreciate hearing how people currently deal with this in both local development and production.
38
u/-Dargs Jun 29 '26
I do use -Xmx and I also never run into heap issues. You design the code/service well and then you provision the appropriate instance size/type to support it. In production I would never want a service that auto resized and restarted to get a larger heap space. I'd have background monitoring and see that an issue is occurring. I want my services to be reliable and understood.
27
u/repeating_bears Jun 29 '26
It's important to note that JVM memory isn't just the heap. That's just often the biggest thing. In some applications even that is not true (e.g. if using lots of native memory) https://www.youtube.com/watch?v=c755fFv1Rnk
But yes, I ran into into memory issues a lot with Docker. Processes being killed when ideally they wouldn't be. JVM memory is hard/impossible to limit because there's about 20 things with individually configurable limits. Been a while since I watched that talk (it's great though) and maybe things have changed since then but I'm pretty sure there are things you cannot limit though JVM flags.
8
u/_predator_ Jun 29 '26
I don't work with microservices, but even for the monoliths I work on, I set as low of a Xmx as possible for local dev, usually 1gb or less. I'll crank it up as needed, e.g. when I need to test processing of large files.
For production we use containers with MaxRAMPercentage and friends. Available memory managed either via k8s or Docker Compose. The apps are heavily instrumented with Micrometer so we can usually spot memory leaks happening from the heap/GC metrics and can correlate them with other metrics that narrow down what may cause them.
8
u/stubbornKratos Jun 29 '26
We have heap issues but there’s not a single Java program we run (out of hundreds) at work where we don’t specify the min/max in accordance with how much total memory is available on the machine.
12
u/smaratter Jun 29 '26
Never
6
u/Cilph Jun 29 '26
Always. Somerimes 80% of container to heap is fine. Sometimes offheap is so big it can only go up to 50%.
I swear the JVM needs a simpler "Here's 2GB, YOU sort it out" option
5
u/doodo477 Jun 29 '26 edited Jun 29 '26
In low memory environments such as 500MB we routinely ran into issues.
3
u/vips7L Jun 29 '26
9 microservices sounds insane.
3
u/davidalayachew Jun 30 '26
I would never even attempt to try and run more than 1 JVM on a production machine at a time. I would sooner spin up several t3.micro instances than try to run everything on one machine. Just too much headache for no real benefit other than saving costs. And at that point, I would save way more money by making optimizations that limit my horizontal scaling, rather than trying to stuff multiple services on a single JVM/machine.
Absolutely not. An
OutOfMemoryErroris a code red, and a sign that something somewhere went very wrong. It would be all-hands-on-deck if this happened consistently.It actually did happen consistently to me once. That was the first time in my career that I worked over 110 hours in a single week. It was a nightmare, and one I hope to never relive.
More often than not, an
OutOfMemoryErroris due to someone somewhere doing something wrong. But, on the rare chance that our functional needs translate into new memory requirements, then yeah, we'll buy more memory.I don't follow. Our scaling is all automated, no manual inputs unless we desire to.
Run it locally with a debugger. If it is reproducible there, then it is usually easy to solve.
Rarely. We make good estimates of our memory needs, and only adjust when functional requirements change. Changing heap sizes often is usually a sign of a bad design, from my experience.
I don't follow, though I might be biased by not running many applications on a server at once.
When I put a JAR on a service, I'll leave a few GB for Linux to do what it needs to, but the rest I give to the JVM. I expect my jar file to make good use of that RAM -- ALL of that RAM, in order to run as efficiently as possible. It's not like there is anything besides the OS and a couple of vendor security checks running on that machine.
To me, that sounds like you saw an ant crawl into your house, and now you want to build a self-firing turret with motion detection to prevent ants from ever getting back in again.
Most people would, instead, find where the ants are coming in from, and then plug the hole. More often than not, it's just loose floorboards or a gap where the wall and floor meet.
My first advice would be to get a sense of the memory characteristics of the JVM when doing some work. I know it's a moving target, but that usually means that it uses less memory, so this exercise is still useful. For example, assume you have a
record GridLocation(byte row, byte column) []-- Roughly how many of these could you put in aList<GridLocation>before you would be at risk forOutOfMemoryErroron a Linux instance with 16GB of RAM, doing nothing else?2
u/aoeudhtns Jun 29 '26 edited Jun 29 '26
What we are currently doing, and I'm not saying this is best practice, but we are not using -Xmx and instead doing Initial and Max Heap Percent flags. A little futzing around with the max %, especially if you're using libraries that use off-heap/native memory. But, we are trying to keep our deployments simple where the operators can control the Kubernetes requests/limits of the container memory and have the services auto-adjust as much as possible. We've found that for most of our services, going above 70-80% max heap percent is getting you into the danger zone of compromising off-heap usage.
In terms of preventing an OOM situation, the K8s system simply uses more or less nodes as we scale up/down. And then it's up to us to keep an eye on metrics and how much heap we're actually using, and adjust requests/limits accordingly to keep the footprint tight.
A secondary goal for us, with the auto-adjusting system vs. manually setting custom env, is to eventually integrate with VPA and/or HPA like you talk about.
Something that could be interesting IMO/from my perspective would be a tool that sits in that middle ground, that can work with KEDA/HPA/VPA and help "diagonally scale" Java services. Since Java tends to want a minimum size for efficiency, and lots of different circumstances (sometimes specific to the app, like a design that creates a lot of contention on a single monitor) end up affecting the actual top-end of a Java service.
For memory leak detection, for us that's mostly static analysis (e.g. never have an unbounded cache) and profiling. IME that is best handled/prevented earlier than production/runtime. Anything you do in production that could add any significant overhead (like JVM instrumentation) you're going to want to have a capability to do that in a partitioned way (say, 15% of your service pods). Which then is a head-scratcher if you only have 1 or 2.
2
u/Afonso2002 Jun 30 '26
I dont use microservices. One time building a project to read elevation data and creating image huge, around 40GB.
I count use the io.createimage ,because uses int, so max size of image would be 2 GB if I am not wrong. Because of this I switch to array of bytebuffer, because each one has max size of 2 GB. So, I switch from heap memory to off-heap memory. FFM is ready to use, needs a litle improvements ,but if I touch on the project, maybe I will swicth bytebuffer to a memory segment.
I think max heap would be 1/4 of phisical memory, maybe the containers had small amount... If the container is only running the java program, maybe in that case assign more heap to the java program.
2
u/dontcomeback82 Jun 30 '26
We don’t even try to run all the Java apps on a laptop cuz they are too many. But yes they are all absolute hogs, even the ones without memory leaks
2
u/GoodLuckGoodell Jul 01 '26
First things first - you’re running 9 applications locally, so of course memory is going to be a problem if you start dealing with many in-flight objects and any local caches.
In production you’ll always right-size your resources depending on the workload. I have some workloads where the application only needs 128mb of jvm xmx and 256mb of total pod memory. Others that need 1gb xmx and 1.5gb pod memory with over 100 pods. But we definitely always set xmx.
It’s typically easiest to just observe your live usage and tune accordingly if you don’t know where the start. You can start with settings you think are more than what you really need and taper down from there.
3
u/brunocborges Jun 29 '26
We built Jaz exactly to help with configuring the JVM inside dedicated environments and containers so developers don't have to worry about tuning at all.
Default heap size is 25% of available RAM, which inside dedicated environments, it is a big waste of resources.
aka.ms/jaz
1
u/thma_bo Jun 29 '26
We only had heap-related issues with microservices that were sized too large. For example, this affected the service responsible for master data management. Imports and exports were also handled there, and we had problems more often with those.
One reason was that it was difficult for us to determine the actual resource requirements correctly. At the same time, Operations did not want to simply allocate as much memory as possible. ;)
Other than that, not really. I did not observe this with smaller microservices.
1
u/coderemover Jun 29 '26 edited Jun 29 '26
We run into issues constantly. The problem is that it is very hard to know how much memory a java service really needs. Give it not enough memory and the GC will occasionally pause (G1) at the worst moment (usually when there is high load). Give it far too much memory, it will still use it, but then you lose the opportunity to cache (e.g.for page cache).
It's even not possible to look at a running Java app and tell from the logs / metrics how much memory it is currently *using*. Data can live very long on the heap before it is cleaned up.
1
u/herder Jun 29 '26
If you're building docker/OCI images, Cloud Native Buildpacks configure the mem allocation for you automatically: https://paketo.io/docs/reference/java-reference/
1
u/StillAnAss Jun 29 '26
I've been a full time professional Java developer for 25+ years. I think I've had 2 or 3 times in my life where a heap issue arose. There's got to be a pretty fundamental misunderstanding of how memory works in Java to hit this issue frequently.
Stop storing everything in variables.
1
u/ShuredingaNoNeko Jun 30 '26
9 microservicios? Que locura, pero siento que tiene más pinta de un memory leak que de malas especificaciones.
Si ya hiciste las estimaciones de hardware al inicio, con el colchón y lo que necesitabas, si dsps la app te pide cada vez más y más, no es problema de la memoria.
0
u/[deleted] Jun 29 '26
[deleted] — view deleted comment
1
u/[deleted] Jun 29 '26
[removed] — view removed comment