JMX Metrics in Kafka
Every healthy Kafka cluster is quietly talking about itself: how many messages it handles, how long requests take, whether copies are in step. JMX is the window through which you listen. This guide explains what JMX is, which Kafka metrics matter, how to read them and how to turn them into calm, useful alerts.
Picture the dashboard of a car. The speedometer shows how fast you travel, the fuel gauge shows how far you can still go, and a small red light warns you before the engine overheats. You do not open the bonnet to learn any of this. The car reports on itself through simple dials, and the driver only has to glance and understand.
A Kafka cluster needs the same kind of dashboard. It may run on dozens of machines, move millions of messages every minute, and keep copies of data on several servers at once. Nobody can watch that with their eyes. Instead, every Kafka program publishes hundreds of small numbers about its own health, and those numbers are exposed through a standard Java technology called JMX.
Learning JMX metrics is one of the most valuable skills for anyone who runs Kafka. It lets you spot a slow disk before users complain, notice a lagging consumer before data goes stale, and prove that a change made things better. This guide starts with the very basics, defines every term the first time it appears, and builds up to the metrics and alerts used by real production teams.
1What Is JMX?
The three letters hide a simple idea: a standard way for a running Java program to describe itself and let others look inside.
JMX stands for Java Management Extensions. It is a part of the Java platform that lets a running program publish information about itself, such as counters and settings, and sometimes accept commands. Because Kafka’s servers and clients are written in Java or Scala and run on the Java Virtual Machine, they can use JMX without any extra software.
The key words
A managed bean
A small object that exposes a group of related numbers or actions. Think of it as one dial cluster on the dashboard, such as everything about incoming traffic.
A single reading
One value inside an MBean, for example a count, a rate or a percentage. This is the actual number you read.
An action you can trigger
Some MBeans let you do something, such as reset a counter. Kafka mainly uses read-only attributes.
The registry
A built-in directory inside each Java program that holds all MBeans and answers questions about them.
The door to the outside
A network entrance that lets tools from other machines talk to the MBean server, normally over a Java technology called RMI.
The address
The unique name of each MBean, built from a domain and a list of labels. Chapter 3 shows how to read one.
Imagine a large hotel with a front desk. Every department, from the kitchen to the laundry, gives the desk a short daily report. The desk keeps all reports in labelled folders. A visitor can ask the desk “how many meals did the kitchen serve today?” and get an answer without walking into the kitchen. The desk is the MBean server, the folders are MBeans and the numbers inside are attributes.
What JMX is not
JMX is only the window. It does not store history, draw charts or send alerts. It shows what a number is right now, and nothing more. To see how a number changed over an hour, or to be woken up when it crosses a limit, you connect JMX to a monitoring system that reads it regularly and records the results. Later chapters show how.
If the vocabulary feels heavy, remember one sentence: JMX is a directory of live numbers inside a Java program, and Kafka fills that directory with numbers about its own health.
2Why Kafka Uses JMX
Kafka could have invented its own reporting system. It chose JMX for practical reasons that still hold today.
Built into the platform
Every Java program already has an MBean server waiting to be used. Kafka only has to place its numbers into it. No extra service has to be installed, no extra port has to be built into Kafka’s own code, and no new protocol has to be invented. Any tool that understands JMX can read Kafka, and almost every monitoring product does.
A common language for all components
Brokers, producers, consumers, Kafka Streams applications and Kafka Connect workers all publish metrics in the same way. A person who learns to read one learns to read them all. The same monitoring tool, the same naming style and the same habits work across the whole ecosystem.
Live, low-cost, always on
Kafka updates its counters as it works, often with a single tiny in-memory step per event. Reading them later costs almost nothing, because the numbers are already sitting in memory. The cost of collecting metrics is therefore small compared with the work Kafka does.
A shop till counts every sale as it happens, so at closing time the owner just reads the total. Nobody needs to recount every receipt. Kafka’s counters work like the till: they tick up during the day, and reading them is quick.
Two families of metric code
Under the surface, Kafka has two metric systems. The brokers mostly use a library called Yammer Metrics, which offers meters, histograms and timers with familiar names such as one-minute rate and 99th percentile. The clients, meaning producers, consumers, Streams and Connect, use Kafka’s own metrics library, which is simpler and reports plain values like averages, maximums and rates. Both publish through JMX, but their naming styles differ a little, which is why you will see two flavours of names in this guide.
Why JMX works well
- Universal: nearly every monitoring product can read it.
- Rich: hundreds of metrics for brokers alone.
- Cheap: reading a number is a memory lookup.
- Consistent across brokers and clients.
Where JMX is awkward
- Remote access needs careful network and security setup.
- Names are long and hard to read at first.
- Nothing is stored, so you need another tool for history.
- Very many per-partition metrics can overwhelm a collector.
Newer Kafka versions are also adding ways for clients to report metrics to the cluster in an OpenTelemetry style. JMX remains the everyday standard, and it is the skill you need first.
3Reading an MBean Name
The names look scary, but they follow a strict pattern. Learn the pattern once, and every metric becomes readable.
The pattern
An MBean’s ObjectName has two parts separated by a colon. The part before the colon is the domain, which groups metrics by area. The part after the colon is a list of key=value labels separated by commas, which pin down exactly which metric is meant. Here is a real example from a broker:
kafka.server:type=BrokerTopicMetrics,name=MessagesInPerSec
flowchart LR
A["Domain: kafka.server (which area)"] --> B["type=BrokerTopicMetrics (which group)"]
B --> C["name=MessagesInPerSec (which metric)"]
C --> D["Attribute: OneMinuteRate (which reading)"]
The common domains
| Domain | What lives there |
|---|---|
| kafka.server | Broker traffic, replication, request handling and quotas |
| kafka.network | Request timing, request queues and network threads |
| kafka.controller | Cluster-wide control: leaders, elections, offline partitions |
| kafka.log | Log storage, flushing and cleaning |
| kafka.cluster | Per-partition replica details |
| kafka.coordinator.group | Consumer group management on the broker |
| kafka.producer | Producer client metrics |
| kafka.consumer | Consumer client metrics |
| kafka.streams | Kafka Streams application metrics |
| kafka.connect | Kafka Connect worker, connector and task metrics |
| java.lang | The Java runtime itself: memory, garbage collection, threads |
An MBean name works like a postal address. The domain is the city, the type is the street, and the name is the house number. Once you know the layout, you can guess where to find things. If you want the kitchen’s report, you look under the hotel’s kitchen folder, not under laundry.
Extra labels for clients and topics
Client metrics carry an extra label for the client’s identifier, so many applications in the same process or many processes on the same monitoring system do not collide. A producer’s name looks like kafka.producer:type=producer-metrics,client-id=orders-service. Topic-level and partition-level metrics add labels such as topic and partition, which multiplies the number of metrics quickly. A cluster with thousands of partitions publishes tens of thousands of per-partition metrics, which is worth remembering when we discuss overhead in chapter 17.
Give every client a meaningful client identifier. Without one, monitoring tools show automatically generated names, and you cannot tell which application a graph belongs to.
4The Kinds of Metric: Gauges, Counters, Meters and Histograms
Not all numbers behave alike. Knowing which kind you are looking at tells you how to read it and how to graph it.
A current level
A value that goes up and down, such as the number of partitions on a broker or the current queue size. You read it as it is.
A total that only grows
A count of things since the program started, such as total records sent. To make it useful you look at how fast it grows.
A rate over time
Tracks how often something happens. It reports a total count plus average rates over the last one, five and fifteen minutes.
A spread of values
Records many measurements, such as request times, and reports the median and high percentiles like the 99th.
A fuel gauge in a car is a gauge: it shows the level right now. The trip odometer is a counter: it only counts up. Miles per hour is a rate, like a meter. And if you wrote down the time of every journey to work and asked “how long do the slowest five percent take?”, you would be building a histogram.
Reading meters
A broker meter such as messages in per second offers several attributes. Count is the total since startup. MeanRate is the average since startup, which is rarely useful on a long-running broker. OneMinuteRate, FiveMinuteRate and FifteenMinuteRate are smoothed averages that give more weight to recent moments. For alerting on current traffic, the one-minute or five-minute rate is usually the best choice.
Reading histograms and percentiles
Averages hide pain. Suppose ninety-nine requests take one millisecond and one request takes a full second. The average looks fine, yet one user waited a long time. Percentiles reveal this. The 99th percentile means “ninety-nine percent of requests were faster than this”. Broker timing metrics offer the median (50th), 75th, 95th, 98th, 99th and 99.9th percentiles. Alerting on a high percentile catches trouble that averages would miss.
| Attribute | Meaning | Best used for |
|---|---|---|
| Count | Total events since start | Working out rates in an external tool |
| OneMinuteRate | Recent rate, very responsive | Live dashboards |
| FiveMinuteRate | Smoother recent rate | Alerts that avoid brief spikes |
| FifteenMinuteRate | Long, calm view | Trend watching |
| 50thPercentile | The typical value | Normal behaviour |
| 99thPercentile | The slow tail | Latency alerts |
| Max | Worst value seen | Spotting rare extreme cases |
Client metrics use plainer names
Kafka’s own client metrics library reports values such as average, maximum and rate as separate metric names, for instance request-latency-avg and request-latency-max. They are calculated over a short sampling window, which by default is thirty seconds with two samples, so client numbers reflect roughly the last minute of activity.
A counter that never moves might mean nothing is happening, or it might mean the counter reset because the program restarted. Always check the uptime before trusting a total.
5Where JMX Metrics Exist in Kafka
Every Kafka program has its own set of metrics. Knowing whom to ask about what saves a great deal of time.
flowchart TB
subgraph Cluster["Kafka cluster"]
BR["Brokers: traffic, replication, requests"]
CT["Controller: leaders and elections"]
end
PR["Producer applications"] --> BR
BR --> CO["Consumer applications"]
KS["Kafka Streams applications"] --> BR
KC["Kafka Connect workers"] --> BR
BR -. "each publishes JMX metrics" .-> MON["Monitoring system"]
PR -. "JMX" .-> MON
CO -. "JMX" .-> MON
KS -. "JMX" .-> MON
KC -. "JMX" .-> MON
| Component | What its metrics tell you | Typical question answered |
|---|---|---|
| Broker | Traffic, request timing, replication, disk and network health | Is the cluster healthy and keeping up? |
| Controller | Leader counts, elections, offline partitions | Is anything unavailable or unstable? |
| Producer | Send rate, retries, errors, batching, latency | Is my application writing successfully and quickly? |
| Consumer | Fetch rate, lag, rebalances, commit time | Is my application reading fast enough? |
| Kafka Streams | Processing rate, commit time, state store activity, end-to-end latency | Is my stream processor healthy? |
| Kafka Connect | Task status, records moved, errors, lag | Is data flowing between systems? |
| Java runtime | Memory, garbage collection, threads, open files | Is the program itself starved for resources? |
| Cluster coordination | Controller quorum or ZooKeeper health | Is metadata management stable? |
A city has many services, each with its own reports. The traffic department knows about roads, the power company knows about electricity, and the hospital knows about patients. You would not ask the hospital how busy the motorway is. In the same way, ask brokers about storage and replication, and ask consumers about lag and reading speed.
Brokers versus clients
A common mistake is to watch only the brokers. Brokers can look perfectly healthy while an application is failing, because a bad client may simply stop sending or reading. Watching the client side is equally important. Broker metrics answer “is the service up and fast?”, and client metrics answer “is my use of the service working?”.
When users report a problem, compare the same moment on both sides. If broker request times spike while producer latency also rises, the cluster is the cause. If only one application’s numbers are bad, look at that application first.
6Turning JMX On and Looking Around
Reading Kafka’s numbers takes a few small steps: allow access, connect a tool, and browse.
Local access versus remote access
Every Java program has JMX inside, but by default it is only reachable from the same machine, and tools must attach to the running process. To read metrics from another machine, the program has to open a network port for remote JMX. Kafka’s start-up scripts make this easy: setting an environment variable named JMX_PORT before starting a broker or a client tells the script to open remote JMX on that port.
Choose a port
Pick a free port on each broker, and use the same port on all brokers for simplicity. Each machine is contacted separately.
Set the address the program advertises
Remote JMX uses a helper protocol called RMI, which tells the caller which hostname to connect back to. If this hostname is wrong, tools connect once and then hang. Set it to an address the monitoring machine can reach.
Turn on protection
Enable authentication and encryption, or restrict the port to a private network. Chapter 18 covers why this is critical.
Restart and verify
Restart the broker in a rolling fashion, then connect from the monitoring machine to confirm the metrics appear.
Tools for looking around
The classic viewer
A graphical tool shipped with Java. Connect to a host and port, open the MBeans tab, and browse the tree of domains and attributes.
A richer viewer
A free tool that adds charts, thread views and memory analysis, with a plugin for browsing MBeans.
Quick checks in a terminal
Kafka ships a small JMX reader that prints chosen attributes on a repeating timer. Useful for scripts and quick sanity checks.
JMX over the web
Tools such as Jolokia expose MBeans as JSON over HTTP, which avoids the RMI networking difficulties.
Using JConsole is like walking into the hotel’s front desk and flipping through the folders yourself. It is perfect for learning and for a one-time investigation. For running a hotel every day, though, you want the reports typed into a spreadsheet automatically every minute, which is the job of the monitoring pipeline in the next chapter.
A first exploration
A gentle way to begin is to connect JConsole to a test broker and open three MBeans. Look at the messages-in rate under broker topic metrics, the under-replicated partition count under the replica manager, and the heap memory under the Java runtime. Send a few test messages and watch the first number change. In ten minutes you will understand what a JMX metric feels like.
Never leave remote JMX open to the internet without authentication. An exposed, unprotected JMX port has historically been a way for attackers to run their own code on a server. Chapter 18 covers this in detail.
7From JMX to Dashboards: Building the Pipeline
JMX shows numbers for this moment only. To see trends and receive alerts, you need a pipeline that reads them regularly, stores them and draws them.
The four jobs of a monitoring pipeline
Collect
Something reads the JMX numbers at regular intervals, usually every fifteen to sixty seconds.
Store
The readings are saved in a time-series database, which keeps each number together with the time it was read.
Show
A dashboard tool draws graphs so people can see trends and compare brokers.
Alert
Rules watch the stored numbers and notify people when something crosses a limit for long enough.
flowchart LR
K["Kafka broker JVM with MBeans"] --> A["Exporter or agent reads JMX"]
A --> S["Metrics store: time-series database"]
S --> D["Dashboards"]
S --> R["Alert rules"]
R --> N["Notification: pager, chat or email"]
A weather station has a thermometer that shows today’s temperature, which is JMX. A weather service also records the temperature every hour, draws a graph of the week and sends a warning when a frost is coming. The recording, graphing and warning are the pipeline built around the thermometer.
Popular ways to collect
| Approach | How it works | Good at | Watch for |
|---|---|---|---|
| Prometheus JMX exporter as a Java agent | Runs inside the Kafka process and turns MBeans into a web page of metrics that Prometheus reads | Simple, no remote JMX port needed | Rules must be written to map names cleanly |
| Jolokia agent | Exposes MBeans as JSON over HTTP | Easy to reach through firewalls | Needs its own security setup |
| Vendor agents such as Datadog | An agent on the machine connects to JMX and forwards metrics to a hosted service | Ready-made Kafka dashboards | Cost grows with the number of metrics |
| OpenTelemetry Java agent | Reads chosen MBeans and sends them in a vendor-neutral format | Works with many backends | Mapping rules need care |
| Metrics reporter plugin | A class loaded by Kafka itself that pushes metrics elsewhere, chosen with the metric.reporters setting | No separate reader process | Runs inside the broker, so it must be well tested |
Pull and push
In a pull design, the monitoring system visits each Kafka machine and asks for the current numbers. This is how Prometheus works. In a push design, an agent on each machine sends numbers out to a central place. Pull makes it easy to see when a machine has stopped answering, because the visit fails. Push suits environments where the monitoring system cannot reach into the machines.
Making names friendly
Raw MBean names are long and use characters that many databases dislike. Exporters therefore apply rules that translate a name such as the messages-in meter into a short flat name like kafka_server_brokertopicmetrics_messagesin_total, and turn labels such as topic or client identifier into database labels. Well-written rules keep the number of distinct names small and consistent, which makes dashboards reusable across clusters.
Prometheus and the JMX exporter
The JMX exporter is an open-source project from the Prometheus community, widely used for Kafka. Run as a Java agent, it reads MBeans from inside the process and serves them for scraping. Many public Grafana dashboards for Kafka are built on the metric names it produces, so teams can start with a ready-made dashboard and refine it.
Datadog and JMX fetching
The Datadog Agent includes a Kafka integration that reads JMX metrics directly from brokers and clients and sends them to Datadog’s hosted service, together with prepared dashboards and alert suggestions. It shows how commercial products build on the same JMX foundation.
Start with the exporter or agent your team already knows. The best pipeline is the one that people actually look at, and Kafka’s metrics look the same whichever tool carries them.
8The Broker Health Checklist
If you can watch only a few numbers, watch these. They tell you whether the cluster is safe, available and keeping up.
| Metric (MBean name) | What it means | Healthy value |
|---|---|---|
kafka.server:type=ReplicaManager,name=UnderReplicatedPartitions | Partitions whose copies are not all up to date | 0 |
kafka.controller:type=KafkaController,name=OfflinePartitionsCount | Partitions with no working leader, so nobody can read or write them | 0 |
kafka.controller:type=KafkaController,name=ActiveControllerCount | Whether this broker is the active controller | Exactly 1 across the whole cluster |
kafka.controller:type=ControllerStats,name=UncleanLeaderElectionsPerSec | Elections that chose an out-of-date copy and may lose data | 0 |
kafka.server:type=ReplicaManager,name=IsrShrinksPerSec and IsrExpandsPerSec | Copies falling out of and returning to sync | Near 0, and shrinks followed by expands only briefly |
kafka.server:type=KafkaRequestHandlerPool,name=RequestHandlerAvgIdlePercent | How much of the time request threads are free | Comfortably above 20 percent |
kafka.network:type=SocketServer,name=NetworkProcessorAvgIdlePercent | How much of the time network threads are free | Comfortably above 30 percent |
kafka.network:type=RequestMetrics,name=TotalTimeMs,request=Produce | End-to-end time for write requests | Stable, with a low 99th percentile |
A hospital nurse checks a small set of vital signs: pulse, temperature, blood pressure and breathing. Dozens of other tests exist, but these few tell whether the patient is stable. The eight metrics above are Kafka’s vital signs. If they are all normal, you can relax, and if one drifts, you know where to look first.
Reading the checklist together
- Availability: offline partitions and active controller count tell you whether the cluster can serve traffic at all.
- Safety: under-replicated partitions and unclean elections tell you whether data is protected against a broker failure.
- Capacity: the idle percentages tell you whether threads are running out of headroom.
- Speed: total request time tells you whether users feel slowness.
The active controller count must be exactly one when you add it up across all brokers. Zero means the cluster has no control plane. Two or more suggests a split situation, and either case deserves an immediate response.
9Traffic and Request Latency Metrics
Two families answer the question “how busy is the cluster, and how quickly does it respond?”.
Traffic: how much is flowing
Records arriving
The rate of incoming records. A sudden drop may mean producers are failing. A sudden jump may mean a runaway job.
Data arriving
The rate of incoming bytes. Compare with network capacity to see how close you are to the limit.
Data leaving
The rate of bytes sent to consumers and followers. It is often several times higher than bytes in, because each write is read by many.
Produce and fetch calls
Total produce and fetch requests per second. Failed produce and failed fetch counters show rejected calls.
These metrics exist for the whole broker and also for each topic, when you add the topic label. Broker-wide numbers give the big picture, and per-topic numbers show which topic is responsible for a change.
Latency: how long requests take
Every request to a broker passes through five stages, and Kafka measures each one. The stages tell you not only that something is slow, but where the time is spent.
flowchart LR
A["Request arrives"] --> B["RequestQueueTimeMs: waiting in the request queue"]
B --> C["LocalTimeMs: processed on the leader"]
C --> D["RemoteTimeMs: waiting for followers or data"]
D --> E["ResponseQueueTimeMs: waiting in the response queue"]
E --> F["ResponseSendTimeMs: sending the reply"]
F --> G["TotalTimeMs is the sum of all stages"]
| Stage | If it is high, suspect |
|---|---|
| Request queue time | Not enough request handler threads, or too many requests at once |
| Local time | Slow disk writes or reads on the leader |
| Remote time | Slow followers when acknowledgement of all is required, or long waits for data on fetches |
| Response queue time | Network threads too busy to send replies |
| Response send time | Slow or congested network to the client |
Think of ordering food at a restaurant. You wait to place your order (queue), the kitchen cooks it (local time), the chef waits for a missing ingredient from the storeroom (remote time), the plate sits under the warmer until a waiter is free (response queue), and the waiter walks to your table (send time). If dinner is late, knowing which step took too long tells you whom to speak to.
Fetch requests come in two kinds
Requests are also labelled by type. Produce is a write from a producer. FetchConsumer is a read from a consumer. FetchFollower is a read by another broker copying data. Consumer fetches may legitimately wait for new data to arrive, so their remote time is often high and is usually not a problem. Produce requests with acknowledgement of all show remote time as the time waiting for followers, which is a real signal about replication health.
Graph the 99th percentile of total time for produce requests, and stack the five stages underneath. The colours make it obvious which stage grows during an incident.
10Replication, Controller and Leadership Metrics
Kafka keeps several copies of each partition. These metrics tell you whether the copies are keeping up and who is in charge.
The basic idea of replication
Each partition has one leader copy that handles reads and writes, plus follower copies on other brokers that keep themselves up to date by fetching from the leader. The set of followers that are fully caught up, together with the leader, is called the in-sync replica set, or ISR. A follower that falls too far behind, by default for about thirty seconds, is removed from the set.
sequenceDiagram
participant L as Leader broker
participant F1 as Follower 1
participant F2 as Follower 2
L->>F1: Data fetched, in sync
L->>F2: Data fetched, in sync
Note over F2: Slow disk, falls behind
L->>L: Follower 2 removed from ISR
Note over L: IsrShrinksPerSec rises and UnderReplicatedPartitions becomes 1
F2->>L: Catches up again
L->>L: Follower 2 rejoins ISR
Note over L: IsrExpandsPerSec rises and UnderReplicatedPartitions returns to 0
Imagine a teacher dictating notes to several students. The students who keep up write every line and belong to the “up to date” group. One student who falls behind is moved out of that group until they catch up. The number of students outside the group is the under-replicated count. It is normally zero, and any other number deserves a look.
The key metrics explained
The classic alarm
Counts partitions where at least one follower is missing from the in-sync set. A steady non-zero value means a broker is down, slow or overloaded.
Coming and going
Shrinks followed quickly by expands are a brief hiccup. Shrinks with no expands mean a follower is not coming back.
Below the write safety line
Partitions with fewer in-sync copies than the required minimum. Producers using the strongest acknowledgement will get errors for these.
No leader at all
Nobody can read or write these partitions. This is an outage for the affected topics.
Data-loss risk
Counts elections that picked an out-of-date copy because no in-sync copy was available. It should stay at zero.
Balance of work
How many partition leaders each broker holds. Big differences between brokers mean uneven load.
The controller
One broker, or in newer clusters a small group of controller nodes, takes the role of controller. It decides which broker leads each partition and reacts when brokers join or leave. Metrics such as the active controller count, the rate and duration of leader elections, and the preferred replica imbalance count show whether the control plane is stable. Frequent elections point to brokers flapping in and out of the cluster.
| Symptom in metrics | Likely cause | First action |
|---|---|---|
| Under-replicated partitions constant at a non-zero value on one broker’s topics | A broker is down or unreachable | Check whether the broker process and machine are alive |
| Under-replicated partitions rising and falling with shrink and expand bursts | Slow disk or network on a broker, or long garbage collection pauses | Check disk latency, network and pause times |
| Offline partitions above zero | All copies of a partition are unavailable | Restore a broker holding a copy urgently |
| Many leader elections | Brokers restarting or losing their session | Check logs for session timeouts and restarts |
During a planned rolling restart, under-replicated partitions rise briefly and then return to zero. Do not restart the next broker until they have returned to zero, or you may take down two copies of the same partition.
11Request Handling, Queues and Storage Metrics
Behind the scenes, a broker is a small factory of threads and queues. These metrics show when the factory is running out of room.
Two thread pools
A broker uses network threads to read requests from and write replies to the network, and request handler threads to do the actual work such as writing to disk. Each pool reports an average idle percentage between zero and one. Near one means the threads are mostly waiting for work, which is healthy. Near zero means they are always busy, and requests will start to queue.
In a bank, receptionists welcome customers and tellers do the transactions. If receptionists are idle most of the time, there is plenty of room. If the tellers are never idle and the waiting line is growing, the bank needs more tellers or a faster process. Idle percentage is the bank’s measure of how much slack is left.
Queues
Waiting to be handled
Requests received but not yet picked up by a handler thread. A steadily growing queue means handlers cannot keep up.
Waiting to be sent
Replies ready but not yet sent. A growing queue points to network thread or network trouble.
Requests waiting on a condition
Some requests, such as produce with full acknowledgement, must wait for followers. Purgatory counts these waiting requests.
Storage and disk behaviour
Kafka stores data in log files divided into segments. Metrics under the log domain report on flush time, segment counts and cleaning for compacted topics. Kafka leans heavily on the operating system’s page cache for speed, so many of the most useful storage numbers, such as disk utilization, read and write latency and network throughput, come from the operating system rather than JMX. A complete picture uses both.
Comes from JMX
- Thread idle percentages and queue sizes.
- Request timing broken into stages.
- Log flush and cleaner statistics.
- Per-topic and per-partition traffic.
Comes from the machine
- Disk usage, throughput and latency.
- Network interface throughput and errors.
- Page cache behaviour and memory pressure.
- Operating system limits and health.
Alert on disk space well before it fills. A full disk stops a broker completely, and JMX cannot warn you about something it does not measure. Include machine-level disk metrics in the same dashboard.
12Java Runtime Metrics: Memory, Garbage Collection and Files
Kafka is a Java program, so the health of the Java runtime is part of the health of Kafka. JMX exposes it under the java.lang domain.
Memory and garbage collection
A Java program keeps most of its objects on the heap. From time to time, a component called the garbage collector cleans up objects that are no longer needed. During some cleaning steps, the program pauses briefly. Long pauses are dangerous for Kafka, because a paused broker cannot answer followers, and it may be removed from the in-sync set or lose its session with the cluster.
| Metric | What it shows | Warning sign |
|---|---|---|
| Heap memory used | How full the heap is | Constantly near the maximum |
| Garbage collector collection time | Total and recent time spent cleaning | A large share of each minute |
| Garbage collector collection count | How often cleaning runs | Sudden increase |
| Thread count | Number of threads alive | Steady climb without levelling |
| Open file descriptors | Files and network connections held open | Approaching the operating system limit |
| Process CPU load | Processor time used by Kafka | Sustained near 100 percent |
A garbage collector is like the cleaning crew in a busy kitchen. If the crew works quietly in the background, service runs smoothly. If they must stop the whole kitchen for a long clean, orders pile up and the waiters get anxious. Kafka’s followers are the waiters, and a long pause makes them think the kitchen has closed.
Why file descriptors matter for Kafka
A broker keeps open files for every log segment it manages, plus a network connection for every client and follower. A cluster with thousands of partitions and many clients can hold tens or hundreds of thousands of open handles. If the count reaches the operating system limit, the broker can no longer open files or accept connections, and it fails in confusing ways. Watching the open count against the maximum, both available under the operating system MBean, prevents this.
Cruise Control and balancing by metrics
LinkedIn, where Kafka was created, open-sourced a tool called Cruise Control that watches broker metrics such as traffic, disk use and leader counts, then proposes and carries out moves of partitions to balance the load. It gathers the numbers through a metrics reporter running in the brokers, showing how JMX-style metrics are used not only to alert humans but also to drive automation.
Modern Kafka versions run well on recent Java releases with a moderately sized heap, since Kafka relies on the operating system page cache for most data. A huge heap is rarely the answer. Watch collection times before you decide the heap is too small.
13Producer Client Metrics
A producer reports on its own writing. These numbers tell you whether your application is sending quickly, reliably and efficiently.
Producer metrics live under the kafka.producer domain, in groups labelled with the client identifier. The most important group is producer-metrics, which describes the whole producer. Other groups cover each topic and each connection to a broker.
| Metric | What it means | What to watch for |
|---|---|---|
| record-send-rate | Records sent per second | Sudden drops mean the application stopped producing |
| record-error-rate | Sends that failed for good | Anything above zero deserves attention |
| record-retry-rate | Sends that had to be repeated | Rising values signal broker or network stress |
| request-latency-avg and max | Time from sending a request to receiving its reply | Sustained growth or large maximums |
| batch-size-avg | Average bytes per batch | Very small batches waste capacity |
| records-per-request-avg | Records in each request | Low values mean batching is not working |
| compression-rate-avg | Compressed size divided by original size | Values near 1 mean compression barely helps |
| buffer-available-bytes | Free memory in the send buffer | Approaching zero means the producer will block |
| bufferpool-wait-ratio | Fraction of time spent waiting for buffer space | Any sustained value means the application is being slowed |
| produce-throttle-time-avg | Time the broker asked the client to wait because of quotas | Non-zero means the client hit a limit |
A courier company measures how many parcels it hands over per hour (send rate), how many come back undelivered (errors), how many need a second attempt (retries), how long a delivery takes (latency) and how full its vans are (batch size). A manager who sees full vans, few retries and short delivery times knows the operation is healthy.
Reading retries and errors
A small, steady retry rate is normal on a busy cluster, because networks have hiccups. A retry rate that suddenly grows is an early warning that brokers are slow or leaders are changing. Retries that finally fail appear as errors, and errors mean data your application believed it was sending did not arrive. If you use idempotent producers, retries are safe from duplicates, yet they still cost time, so a high retry rate is still worth investigating.
Reading batch size and compression
Small batches mean many small requests, which use more processor time and more network overhead per record. If the average batch is only a few hundred bytes, the producer is probably sending as soon as any record arrives. Allowing a short wait time and larger batch size often improves throughput dramatically. Compression rate tells you whether compression is worthwhile: a value of 0.3 means the compressed batch is 30 percent of the original size, a big saving.
The three producer graphs worth pinning to every application dashboard are send rate, error plus retry rate, and average request latency. They answer the questions people ask first.
When the send buffer fills, the producer’s send call may block or fail. An application that suddenly seems frozen may simply be waiting for buffer space because the brokers are slow. Buffer wait metrics reveal this immediately.
14Consumer Client Metrics and Lag
Consumers face a different question from producers: are they keeping up? One number, called lag, answers it.
What lag means
Every message in a partition has a position number called an offset. The newest message sits at the log end offset. A consumer saves how far it has read, the committed offset. The gap between the two is the lag: how many messages are waiting to be read. Small, steady lag is normal. Lag that keeps growing means the consumer is slower than the producers.
flowchart LR
A["Oldest message"] --> B["Committed offset: consumer has read up to here"]
B --> C["Messages waiting: this gap is the lag"]
C --> D["Log end offset: newest message"]
Imagine a reader working through a stack of letters on a desk while the postman keeps adding new ones on top. The number of unread letters is the lag. If the reader clears ten letters an hour and the postman adds nine, the pile slowly shrinks. If the postman adds fifteen, the pile grows, and reading faster or hiring another reader becomes urgent.
The important consumer metrics
| Metric | Group | Meaning |
|---|---|---|
| records-lag-max | consumer-fetch-manager-metrics | Largest lag among the partitions this consumer reads |
| records-consumed-rate | consumer-fetch-manager-metrics | Records read per second |
| fetch-rate and fetch-latency-avg | consumer-fetch-manager-metrics | How often and how quickly it asks for data |
| commit-latency-avg | consumer-coordinator-metrics | Time to save the read position |
| rebalance-total and rebalance-latency-avg | consumer-coordinator-metrics | How often, and how long, partitions were reshuffled |
| last-heartbeat-seconds-ago | consumer-coordinator-metrics | Time since the group was last told this consumer is alive |
| assigned-partitions | consumer-coordinator-metrics | How many partitions this consumer owns |
| time-between-poll-max | consumer-metrics | Longest gap between reads; too large gets the consumer removed |
Two kinds of trouble
Lag grows steadily
The consumer is healthy but too slow. Processing per message takes too long, or there are too few consumers for the partitions. Add consumers, up to the number of partitions, or speed up the work.
Lag jumps and reads stop
The consumer stopped polling or was removed from the group, often because processing took longer than allowed between reads. Look at poll gaps and rebalance counts.
Constant rebalances
Consumers keep joining and leaving, so partitions keep moving and little work gets done. Look at heartbeat and session timeouts, and at frequent restarts.
Measuring lag from outside
The consumer’s own lag metric only exists while the consumer is running. If it crashes, the metric disappears at exactly the moment you most need it. For this reason, many teams also measure lag from outside, comparing each group’s committed offsets with the log end offsets. Kafka ships a command-line tool for this, and LinkedIn open-sourced a service called Burrow that watches groups over time and classifies them as healthy, warning or in error, rather than relying on a fixed lag threshold.
Lag in messages depends on message rate. A lag of one thousand is nothing at a million messages a second and a disaster at ten a day. Where possible, express lag as time: how many seconds behind is this consumer?
15Kafka Streams and Kafka Connect Metrics
Two higher-level Kafka tools publish their own sets of metrics, layered on top of the producer and consumer ones.
Kafka Streams
A Streams application is built from threads, and each thread runs tasks. The metrics follow that structure and sit under the kafka.streams domain. Metrics are grouped by level of detail through the metrics.recording.level setting: the default INFO level records the most useful numbers cheaply, while DEBUG and TRACE add detail that costs more processing time and should be turned on only when investigating.
Is it alive?
Counts of alive and failed stream threads show whether the application is running with its full set of workers.
How busy is each worker?
Process rate, poll rate and commit latency show throughput and how long saving progress takes.
Per-partition health
Process rate and dropped records for each task. Dropped records often mean late events discarded by a closed time window.
Memory of the application
Read and write rates, latencies and sizes of the local stores that hold counts and joins.
End-to-end delay
Record end-to-end latency shows how long it takes from a record being created to being processed.
A Streams application is like a factory with production lines. The application-level metrics tell you how many lines are running. Thread metrics show how busy each line is. Task metrics reveal a jammed station, and state store metrics show how the warehouse next to each line is coping.
Kafka Connect
Connect metrics are grouped under kafka.connect and follow its structure of workers, connectors and tasks. A worker reports how many connectors and tasks it runs and how often they start or fail. Each task reports its status, how often it commits progress, and how many records it reads or writes.
| Level | Useful metrics | Question answered |
|---|---|---|
| Worker | Connector count, task count, startup failures, rebalance activity | Is the Connect cluster stable? |
| Connector | Status, connector type, task counts by state | Is this connector running? |
| Task | Status, running ratio, offset commit success percentage, batch size | Is this task healthy and saving progress? |
| Source task | Records polled and written per second | Is data flowing into Kafka? |
| Sink task | Records read and sent per second, sink record lag | Is data flowing out and is the sink keeping up? |
| Task errors | Total record errors, skipped records, retries, dead letter topic writes | Are transforms or converters rejecting records? |
A Connect task can be in a failed state while the worker itself looks perfectly fine. Alert on task status and error counts, not only on worker liveness, or a stalled data pipeline can go unnoticed for days.
16Turning Metrics into Alerts
A metric nobody watches is only decoration. Good alerts turn numbers into timely, actionable messages, without waking people for nothing.
Four questions for every service
Site reliability teams often describe the health of a service using four signals. They map neatly onto Kafka.
| Signal | In plain words | Kafka examples |
|---|---|---|
| Latency | How long things take | Produce request 99th percentile time, consumer fetch latency |
| Traffic | How much work is happening | Bytes in, bytes out, messages in per second |
| Errors | How often things fail | Producer error rate, failed produce requests, connector task errors |
| Saturation | How close resources are to their limit | Thread idle percentages, disk usage, file descriptors, heap |
Choosing what to alert on
| Condition | Suggested urgency | Why |
|---|---|---|
| Offline partitions above zero | Page now | Some data is unavailable |
| Active controller count not equal to one across the cluster | Page now | The control plane is missing or split |
| Under-replicated partitions above zero for more than a few minutes | Page during working hours, or now if combined with other signs | Data is less safe than intended |
| Unclean leader elections above zero | Page now | Data loss may have occurred |
| Disk usage above about 80 percent | Ticket, then page if rising fast | A full disk stops a broker |
| Consumer lag growing for a sustained period | Ticket or page depending on the business | Consumers are falling behind |
| Producer error rate above zero for a sustained period | Ticket, or page for critical writers | Data is not being written |
| Connect task in failed state | Ticket, or page for critical pipelines | A pipeline has stopped |
flowchart TB
M["Metric crosses a limit"] --> D{"Does it last longer than the wait time?"}
D -- "no" --> I["Ignore: brief spike"]
D -- "yes" --> S{"Does it hurt users or data now?"}
S -- "yes" --> P["Page the on-call person"]
S -- "no" --> T["Open a ticket for working hours"]
P --> R["Link to a runbook"]
T --> R
A smoke alarm that beeps whenever you make toast soon gets its battery removed. A useful alarm sounds only for real fire, and only after the smoke lingers. Good alert rules use the same idea: wait a few minutes before reacting, and reserve loud alarms for problems that truly need a person.
Habits of good alerts
- Alert on symptoms first: a user-facing problem such as high latency matters more than a cause such as a busy thread, though causes help diagnosis.
- Add a waiting period: require the condition to hold for several minutes to ignore brief blips.
- Attach a runbook: each alert should link to a page explaining what it means and what to try first.
- Review regularly: delete alerts that never lead to action, and tighten those that fire too late.
After every incident, ask two questions: which alert should have fired earlier, and which alert fired but did not help? Adjusting both after each incident steadily improves your monitoring.
17Performance and Scalability of Monitoring Itself
Monitoring has a cost. Done carelessly, it can slow the very brokers it watches or flood your metrics database.
Why reading JMX is usually cheap
Kafka updates its counters as part of normal work with tiny in-memory steps. Reading a handful of MBean attributes every thirty seconds costs very little. Problems appear when a collector asks for far more than it needs, or asks too often.
The cardinality problem
Cardinality means the number of distinct time series a system must track. Each combination of metric name and labels is one series. Per-partition metrics on a large cluster multiply quickly. A cluster with two thousand partitions, ten metrics per partition and three copies of each can produce tens of thousands of series from one metric family alone. Storing and drawing that many series slows dashboards, raises storage costs and, in hosted services, raises the bill.
A school could record every pupil’s attendance every minute of the day, and it would soon drown in paper. Recording class attendance once each morning captures what matters at a fraction of the effort. Collecting only the metrics and labels you use is the same kind of sensible choice.
Practical ways to keep it light
Collect only what you use
Configure the exporter or agent with an explicit list of MBeans instead of scraping everything.
Do not scrape too often
Fifteen to sixty seconds suits most dashboards. Every second is rarely useful and multiplies storage.
Drop what you do not need
Remove labels with very many values, such as per-partition or per-client identifiers, unless you actively chart them.
Summarize at write time
Pre-compute cluster-wide and per-topic totals so dashboards read a few series instead of thousands.
Keep detail briefly
Keep raw numbers for days or weeks, and keep summarized versions for months.
Use in-process agents wisely
An in-process exporter shares the broker’s memory and processor. Keep its rules light and its output small.
A lean setup
- Fast dashboards that open in seconds.
- Low storage and hosting costs.
- Little effect on broker performance.
- Easy to understand which metric feeds which chart.
A collect-everything setup
- Slow, cluttered dashboards.
- High storage and vendor bills.
- Collector queries that add load to brokers.
- Important signals hidden among thousands of graphs.
A poorly tuned collector that queries all MBeans over remote JMX every few seconds can occupy broker threads and slow real traffic. Test collector settings on a staging cluster, and watch broker latency when you change them.
18Security and Logging
A metrics port is a door into a running server. It deserves the same care as any other door.
The danger of an open JMX port
Remote JMX is powerful. Beyond reading numbers, it can let a connected client load code or change settings inside the program. An unprotected JMX port reachable from an untrusted network has a long history of being abused to take over servers. Treat any open JMX port as a potential entrance for attackers.
Limit who can reach it
Bind to an internal network address and allow only the monitoring machines through the firewall. Never expose it to the internet.
Require authentication
Turn on password-based sign-in, using a file of users and a file of access levels. Give the monitoring user a read-only role, so it can look but not change.
Encrypt the connection
Enable TLS for JMX so passwords and metrics cannot be read on the network.
Prefer safer designs
An in-process exporter that serves a read-only web page avoids opening remote JMX at all. Protect that page with network rules or sign-in.
Audit and rotate
Record who has access, rotate passwords and review firewall rules regularly.
The hotel front desk is happy to tell guests how many rooms are free. It should not let a stranger walk behind the desk, open the safe or change the room keys. Read-only access to reports is the visitor window, and full JMX control is the door behind the counter. Leave only the window open.
What metrics can reveal
Metrics are not secrets, but they are informative. Topic names, client identifiers, consumer group names and connector names can reveal business structure. Traffic patterns can hint at customer activity. Give dashboards and metric stores the same access rules you give other operational data, and avoid putting sensitive words into client identifiers.
Metrics and logs work together
Metrics say that something is wrong and roughly when. Logs say why. When under-replicated partitions rise at 02:14, the broker log around 02:14 might show a long garbage collection pause, a disk error or a session timeout. Keep clocks synchronized on all machines, so timestamps line up, and keep logs long enough to look back after an incident. Turn on garbage collection logging, since JMX shows totals while the log shows each pause.
Annotate dashboards with deployments, restarts and configuration changes. When a graph changes shape, a marker showing “broker 3 restarted” saves an hour of guessing.
19Patterns and Anti-Patterns
Teams that run Kafka for years tend to converge on the same handful of good habits, and to trip over the same handful of bad ones.
Patterns worth copying
Layered dashboards
Build one overview page for the whole cluster showing a few health signals, then deeper pages for brokers, topics, producers, consumers and connectors. People start at the overview and drill down only when something looks odd.
Why it works
A single crowded page of hundreds of graphs hides problems. A short overview with red and green indicators lets an on-call engineer judge health in seconds, and the deeper pages explain causes.
Everyday picture
A hospital ward has one board showing whether each patient is stable, and detailed charts by each bed. Nobody reads every chart to learn whether the ward is calm.
Measure from both sides
Watch the same flow from the broker side and from the client side. Compare the broker’s bytes-in figure with the producers’ send rates, and compare consumer lag from inside the consumer with lag measured from outside.
Why it works
A broker cannot see a client that failed to connect, and a client cannot see a broker that silently dropped out. Two viewpoints reveal disagreements that one viewpoint would miss.
Everyday picture
A delivery company tracks parcels when they leave the warehouse and again when customers confirm arrival. A gap between the two numbers exposes lost parcels.
Canary and synthetic checks
Run a tiny producer and consumer that send a marker message through the cluster every minute and measure how long the round trip takes. Publish the result as its own metric.
Why it works
Internal metrics can all look fine while an end-to-end path is broken, for example by a network rule. A synthetic probe experiences the cluster like a real user would.
Everyday picture
A restaurant owner occasionally orders a meal as a customer, to see the real experience rather than trusting the kitchen’s report.
Version-aware, shared dashboard templates
Keep dashboards and alert rules in version control and apply them to every cluster from one template. Use the cluster name as a variable so the same page works for all environments.
Why it works
Hand-made dashboards drift, break silently and vanish when the person who built them leaves. Templates make new clusters observable from the first day.
Everyday picture
A franchise uses the same kitchen layout in every branch, so any cook can work in any branch without relearning where things are.
Anti-patterns to avoid
What people do
They expose an unauthenticated JMX port to a wide network so that any monitoring tool can connect easily.
Why it hurts
Anyone who reaches the port may read internal details or even run management actions, and unprotected JMX ports have a long record of being used to take over servers.
What to do instead
Keep JMX on a private network, require authentication and encryption, or use a read-only exporter that serves plain metrics.
What people do
They alert on every metric that has ever been interesting: every partition’s size, every thread’s idle percentage, every retry.
Why it hurts
The on-call engineer receives a flood of messages, learns to ignore them, and eventually misses the one that matters. This is often called alert fatigue.
What to do instead
Alert on a small number of symptoms that need human action. Keep everything else on dashboards for investigation.
What people do
They watch only averages, such as average request time, and ignore percentiles and maximums.
Why it hurts
An average hides the slowest requests. If ninety-nine requests take one millisecond and one takes ten seconds, the average looks acceptable, yet one customer waited ten seconds.
What to do instead
Chart the 95th and 99th percentiles beside the average, and alert on the percentile that matches your service goals.
What people do
They monitor brokers only, and assume that if brokers are healthy then applications must be fine.
Why it hurts
A broker can be perfectly healthy while a consumer group is hours behind or a connector task has stopped. Business damage often begins at the client, not the broker.
What to do instead
Include producer, consumer, Streams and Connect metrics in the monitoring plan from the start, with clear ownership of each application’s dashboard.
What people do
They keep no history and look only at the current value, or they retain data for just a few hours.
Why it hurts
Many problems are slow trends, such as disks filling over weeks or traffic growing each month. Without history, nobody can plan capacity or compare this week with last week.
What to do instead
Store detailed data for a short period and summarized data for many months.
20Best Practices and Common Mistakes
A compact list of habits to adopt and traps to avoid when you monitor Kafka through JMX.
Do
- Start with a small, well-chosen set of broker health metrics and grow only when needed.
- Watch offline partitions, active controller count, under-replicated partitions and unclean elections first.
- Chart request time percentiles, not only averages.
- Monitor producers, consumers, Streams applications and connectors, not only brokers.
- Give every client a meaningful client identifier so metrics can be traced to an application.
- Use thread idle percentages and disk usage to plan capacity before it becomes urgent.
- Secure JMX with network limits, authentication and encryption.
- Store dashboards and alert rules in version control.
- Write a runbook for every alert.
Do not
- Open remote JMX to the internet or to untrusted networks.
- Scrape every MBean every few seconds.
- Alert on metrics that nobody knows how to act on.
- Judge health only by averages.
- Treat a briefly non-zero value as an emergency without a waiting period.
- Forget that some metrics reset when the process restarts.
- Rely only on client-side lag, which vanishes when the client dies.
- Leave default client identifiers, so that dozens of applications appear as the same anonymous client.
- Ignore garbage collection and file descriptor metrics on brokers.
Mistakes beginners meet first
The connection works locally but not from another machine
The broker advertises the wrong host name to remote JMX clients, so the second connection step fails. Setting the RMI host name to an address reachable by the monitoring server fixes it.
Reading a counter as a rate
A total count rises forever. Charting it directly gives a line that only goes up. Convert counts to per-second rates before drawing or alerting.
Looking at one broker and assuming it represents the cluster
Some values, such as the active controller count, are only meaningful when summed across brokers. Others, such as request rates, must be viewed per broker to spot an unbalanced cluster.
Confusing “no data” with “zero”
If a producer crashes, its metrics disappear rather than dropping to zero. Alerts must treat missing data as a possible failure, not as calm.
Ignoring the meaning of the window
Client rates are averaged over a sample window, about thirty seconds by default, so short bursts are smoothed away. A spike shorter than the window may barely show.
Alerting on causes instead of symptoms
A busy request thread pool is interesting, but it only matters if users feel slowness. Alert first on latency and errors, and use causes to diagnose.
Restarting all brokers together during an alert
Restarting many brokers at once can turn a small problem into an outage. Restart one at a time and wait for replicas to catch up between restarts.
Learning to read a dashboard is like learning to read a doctor’s chart. At first every number is confusing. Soon you know your handful of vital signs by heart, you recognize your system’s normal pattern, and you notice quickly when something departs from it.
A starter routine for a new cluster
Enable metrics safely
Turn on JMX or an exporter with network limits, authentication and encryption in place.
Collect a short allow-list
Begin with the broker health checklist, traffic, request time and Java runtime metrics.
Build the overview page
Show a few red and green signals, and link each to a detail page.
Add client metrics
Bring in producer, consumer and connector metrics for the applications that matter most to the business.
Write alerts with waiting periods
Cover offline partitions, controller count, lag, disk space and errors. Attach a runbook to each.
Rehearse
Stop a test broker on purpose and check that the dashboard and alerts react the way you expect.
21Real-World Stories
Public talks, open-source projects and vendor documentation show how well-known organizations turn Kafka’s metrics into daily practice.
LinkedIn and Kafka monitoring
Kafka began at LinkedIn, and LinkedIn engineers have described in public talks how they watch huge clusters with automated checks. They also open-sourced Burrow, which follows consumer group progress over time and judges health by trends instead of a fixed lag number, and Cruise Control, which uses broker metrics to detect imbalance and suggest moving partitions.
Confluent and the metrics reporter
Confluent, the company founded by Kafka’s creators, has published guidance on monitoring Kafka, including which broker and client metrics to watch. Its platform includes a metrics reporter that sends broker metrics into a Kafka topic, showing that Kafka can transport its own health data.
Datadog and integrations
Datadog offers a Kafka integration whose agent reads JMX metrics from brokers and clients and sends them to hosted dashboards. Its public documentation lists the MBeans it collects, which is a helpful reference for what a large vendor considers worth watching by default.
Prometheus and the JMX exporter
The Prometheus project publishes a JMX exporter that runs inside the Java process or beside it and converts MBeans to a plain web page of numbers. Many organizations pair it with Grafana dashboards shared by the community, and it is one of the most common ways to monitor Kafka on Kubernetes.
Strimzi on Kubernetes
Strimzi, an open-source project that runs Kafka on Kubernetes, includes ready-made metrics configuration and example dashboards. Teams starting on Kubernetes often adopt these examples and adjust them, saving weeks of guessing which metrics matter.
Uber and large-scale operations
Uber has described in engineering posts how it runs very large Kafka deployments, with tooling to watch health, balance partitions and detect stuck consumers. The general lesson is that at large scale, metrics feed automation, and people look at summaries rather than individual machines.
Amazon MSK and managed Kafka
Managed services such as Amazon MSK publish Kafka metrics to their cloud monitoring service and offer open monitoring through Prometheus-compatible endpoints. The provider looks after the machines, but the customer still needs to watch topic traffic, consumer lag and client errors, because those depend on the application.
22Frequently Asked Questions
Short answers to questions that beginners and experienced engineers ask most often about JMX and Kafka metrics.
kafka.server, followed by key and value pairs like the type and name of the metric.23Summary and Key Takeaways
If you keep only one page of this guide, keep this one.
JMX is the window through which a Kafka cluster tells you how it is doing. Brokers, producers, consumers, Kafka Streams applications and Kafka Connect workers all publish measurements as named MBeans. By reading a small, well-chosen set of them, and turning those readings into dashboards and thoughtful alerts, you can notice trouble before customers do and understand it quickly when it happens.
Key Takeaways
- JMX is Java’s built-in way to publish metrics. Kafka exposes measurements as MBeans, each addressed by an ObjectName made of a domain and key-value pairs.
- Read the name to understand the metric. Domains such as
kafka.server,kafka.network,kafka.controller,kafka.producerandkafka.consumertell you where a metric comes from. - Know the metric types. Gauges show current values, counters only rise, meters give rates and histograms give percentiles.
- Watch the broker health essentials. Offline partitions, active controller count, under-replicated partitions, unclean elections, thread idle percentages, request time and disk space form a strong core.
- Do not forget the clients. Producer error and retry rates, consumer lag, Streams task health and Connect task status often reveal business impact first.
- Get metrics out safely and cheaply. Use an exporter or agent, collect an allow-list at sensible intervals, and watch cardinality.
- Alert on symptoms with a waiting period. Page for problems that need people now, ticket the rest, and attach a runbook to every alert.
- Secure the door. Limit network access, require authentication, encrypt traffic and prefer read-only access.
- Use metrics and logs together. Metrics show that and when, logs show why, and both need synchronized clocks and enough history.