The JVM Immune System: Debugging Distributed Servers at Scale
Learn how your system should allow you to debug large distributed systems running the JVM.
Join the DZone community and get the full member experience.Join For Free
today more than ever, speed plays a larger role in the software development lifecycle. we see r&d teams who want to push code faster to production environments with rising complexity, and this amplifies a vulnerability that must be addressed.
those few hours after a new deployment set the tone for its success. every once in a while, things go wrong, no matter how strict your tests are. when your code is out in production and it meets the real-world architecture and scale of your system, with real data flowing through the application, things can go south pretty quickly. in order to be resilient and stay on top of things, a strategy needs to be implemented that allows you to:
- identify when there’s an error happening
- assess the error’s severity to prioritize it
- draw out the state that caused the error
- trace back and solve the root cause
- deploy a hotfix
in this post we’ll cover some of the most useful practices to allow you to assemble a time-critical response and “weaponize” your application.
the case for distributed logging
with production environments spread across multiple nodes and clusters, it’s easy for a transaction that starts on one machine or service to cause an error someplace else. when an exception happens, there’s a need to be able to trace back this type of distributed transaction, and the logs are often the first place to look for clues.
this is why, for every log line printed out, we need to be able to extract the full context to understand exactly what happened there. some data might come from the logger itself and the location the log is created in; other data needs to be extracted at the moment of the event. a good way to trace such errors to their origin would be generating uuids at every thread’s application entry point.
a useful yet underutilized feature here is using thread names to provide a window for this precious context, right before the stack collapses and the data is lost. you can format your thread name to something like:
thread.currentthread().setname(prettyformat(threadname, getuuid(), message.getmsgtype(), message.getmsgid(), getcurrenttime()));
so instead of an anonymous name like ”pool-1-thread-17” your application now produces smart stack traces that start this way:
“threadname: pool-1-thread-17, uuid: ab5cad, msgtype: analyzegraph, msgid: 5678956, 30/08/2015 17:37”
this works well when handling caught exceptions, but what if there’s an uncaught exception involved? a good practice is to set a default uncaught exception handler, both to cover for that and to help extract any useful data you need. other than thread names, additional places we can use to store hints about what happened are the tls (thread local storage) and the mdc (mapped diagnostic context, which is provided by your logging framework). all other data gets lost as the stack frames collapse.
leaning on the jvm tool belt
some more complex bugs like deadlocks or heavy performance bottlenecks require a different approach. take jstack , for instance: a powerful tool that ships together with the jdk. most of you are probably already familiar with it in some way. basically, jstack allows you to hook into a running process and output all the threads that are currently running in it. it will print each thread’s stack trace; frames—either java or native; locks they’re holding; and all sorts of other metadata. it can also analyze heap dumps or core dumps of processes that have already ended. it’s a longstanding and super useful toolkit.
the problem here is that jstack is mostly used in retrospect. the condition you’re looking to debug has already happened, and now you’re left searching through the debris. the server isn’t responding, the throughput is dropping, database queries are taking forever: a typical output would be a few threads stuck on some nasty database query, with no clue of how we got there. a nice hack that would allow you to get the jstack output where it matters most is to activate it automatically when things start tumbling down. for example, you can set a certain throughput threshold and get jstack to run at the moment it drops .
combined with using smart thread names, we can now know exactly which messages caused us to get stuck, and we can retrace our steps back, reproduce the error, isolate it, and solve it.
using java agents to skip logging altogether
the next step in this process is gaining visibility into your application during runtime. logs are inspected in retrospect and only include the information that you’ve decided to put there in advance. we’ve seen how we can enrich them with stateful data, but we also need a way to access the exact variable values that caused each error to get down to the real root cause. java agents give us the ability to get to the data we need straight from the source without writing to disk and using huge log files, so we can extract only the data we’ll actually be using.
one interesting approach is using btrace , an open-source java agent that hooks up to a jvm and opens up a scripting language that lets you query it during runtime. for instance, you can get access to things like classloaders and their subclasses, and load up jstack whenever some troubled new class is instantiated. it’s a useful tool for investigating specific issues and requires you to write scripts for each case you want to cover.
you could also write your own custom java agent, just like btrace. one way this helped our team at takipi was when a certain class was instantiating millions of new objects for some reason. we wrote an agent that hooks up to the constructor of that object. anytime the object was allocated an instance, the agent would extract its stack trace. later we analyzed the results and understood where the load was coming from. these kind of problems really pique our team’s interest. on our day-to-day we’re building a production grade agent that knows how to extract the variable values that cause each exception or logged error, all across the stack trace, and across different machines. check out a live demo right here .
java / scala developer? takipi replaces logging in production jvms and lets you see the variable state that caused each log error and exception – try takipi
testing in production: not for the faint hearted
jokes aside, testing in production is a serious practice that many companies are taking part in. they don’t cancel the testing phase completely, but they understand that staging environments are not enough to mimic full blown distributed environments, no matter how much time and effort you put into setting them up. the only real testing takes place in production, with real data flowing through the system and unexpected use cases being thrown at it.
there are several approaches you can adopt for performing controlled production testing, depending on what kind of functionality is it that you’re trying to test. one option is duplicating and routing live traffic both through the current system and through the new version of the component that you’re testing. this way you can see how the new component behaves and compare it directly to the current version without risking the delivery of wrong results back to the user if, for example, it’s some data crunching task.
another option is segmenting your traffic and releasing new features gradually. one way to do this is to use a canary server, which is a single node in your system updated with the new version you’d like to roll out (just like a canary in the coal mine). sometimes it’s also helpful to add more fine-grained monitoring and logging to the canary server. another option is to add more abstraction on top of the canary setup, implementing and making use of gradual rollouts with feature switches, or a/b testing small changes in your application to see how they impact performance.
debugging java applications in production requires a creative and forward-thinking mindset. unless we prepare our applications and environment in advance, there will not be much insight to recover after getting hit by errors and performance issues.
15 tools to use when deploying new code to production – view tool list
java 8 exceptions have never been so beautiful – try takipi for java 8
java / scala developer?
replaces logging in production jvms and lets you see the variable state that caused each log error and exception.
Published at DZone with permission of Alex Zhitnitsky, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.