JMX Metrics in Kafka

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

MBean

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.

Attribute

A single reading

One value inside an MBean, for example a count, a rate or a percentage. This is the actual number you read.

Operation

An action you can trigger

Some MBeans let you do something, such as reset a counter. Kafka mainly uses read-only attributes.

MBean server

The registry

A built-in directory inside each Java program that holds all MBeans and answers questions about them.

Connector

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.

ObjectName

The address

The unique name of each MBean, built from a domain and a list of labels. Chapter 3 shows how to read one.

Everyday Analogy

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.

Hundreds
of metrics available on each broker
Read-only
nearly all Kafka metrics only report
Right now
JMX shows the present moment, not history
i
Tip

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.

Everyday Analogy

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.
i
Note

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)"]
    
FIG 1 — From domain to attribute: the four levels of a JMX metric address.

The common domains

DomainWhat lives there
kafka.serverBroker traffic, replication, request handling and quotas
kafka.networkRequest timing, request queues and network threads
kafka.controllerCluster-wide control: leaders, elections, offline partitions
kafka.logLog storage, flushing and cleaning
kafka.clusterPer-partition replica details
kafka.coordinator.groupConsumer group management on the broker
kafka.producerProducer client metrics
kafka.consumerConsumer client metrics
kafka.streamsKafka Streams application metrics
kafka.connectKafka Connect worker, connector and task metrics
java.langThe Java runtime itself: memory, garbage collection, threads
Everyday Analogy

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.

i
Tip

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.

Gauge

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.

Counter

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.

Meter

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.

Histogram

A spread of values

Records many measurements, such as request times, and reports the median and high percentiles like the 99th.

Everyday Analogy

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.

AttributeMeaningBest used for
CountTotal events since startWorking out rates in an external tool
OneMinuteRateRecent rate, very responsiveLive dashboards
FiveMinuteRateSmoother recent rateAlerts that avoid brief spikes
FifteenMinuteRateLong, calm viewTrend watching
50thPercentileThe typical valueNormal behaviour
99thPercentileThe slow tailLatency alerts
MaxWorst value seenSpotting 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.

!
Watch Out

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
    
FIG 2 — Every Kafka component publishes its own JMX metrics to the monitoring system.
ComponentWhat its metrics tell youTypical question answered
BrokerTraffic, request timing, replication, disk and network healthIs the cluster healthy and keeping up?
ControllerLeader counts, elections, offline partitionsIs anything unavailable or unstable?
ProducerSend rate, retries, errors, batching, latencyIs my application writing successfully and quickly?
ConsumerFetch rate, lag, rebalances, commit timeIs my application reading fast enough?
Kafka StreamsProcessing rate, commit time, state store activity, end-to-end latencyIs my stream processor healthy?
Kafka ConnectTask status, records moved, errors, lagIs data flowing between systems?
Java runtimeMemory, garbage collection, threads, open filesIs the program itself starved for resources?
Cluster coordinationController quorum or ZooKeeper healthIs metadata management stable?
Everyday Analogy

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?”.

i
Tip

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.

1

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.

2

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.

3

Turn on protection

Enable authentication and encryption, or restrict the port to a private network. Chapter 18 covers why this is critical.

4

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

JConsole

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.

VisualVM

A richer viewer

A free tool that adds charts, thread views and memory analysis, with a plugin for browsing MBeans.

Command-line tool

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.

HTTP bridges

JMX over the web

Tools such as Jolokia expose MBeans as JSON over HTTP, which avoids the RMI networking difficulties.

Everyday Analogy

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.

!
Watch Out

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

1

Collect

Something reads the JMX numbers at regular intervals, usually every fifteen to sixty seconds.

2

Store

The readings are saved in a time-series database, which keeps each number together with the time it was read.

3

Show

A dashboard tool draws graphs so people can see trends and compare brokers.

4

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"]
    
FIG 3 — A typical pipeline from JMX numbers to dashboards and alerts.
Everyday Analogy

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

ApproachHow it worksGood atWatch for
Prometheus JMX exporter as a Java agentRuns inside the Kafka process and turns MBeans into a web page of metrics that Prometheus readsSimple, no remote JMX port neededRules must be written to map names cleanly
Jolokia agentExposes MBeans as JSON over HTTPEasy to reach through firewallsNeeds its own security setup
Vendor agents such as DatadogAn agent on the machine connects to JMX and forwards metrics to a hosted serviceReady-made Kafka dashboardsCost grows with the number of metrics
OpenTelemetry Java agentReads chosen MBeans and sends them in a vendor-neutral formatWorks with many backendsMapping rules need care
Metrics reporter pluginA class loaded by Kafka itself that pushes metrics elsewhere, chosen with the metric.reporters settingNo separate reader processRuns 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.

i
Tip

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 meansHealthy value
kafka.server:type=ReplicaManager,name=UnderReplicatedPartitionsPartitions whose copies are not all up to date0
kafka.controller:type=KafkaController,name=OfflinePartitionsCountPartitions with no working leader, so nobody can read or write them0
kafka.controller:type=KafkaController,name=ActiveControllerCountWhether this broker is the active controllerExactly 1 across the whole cluster
kafka.controller:type=ControllerStats,name=UncleanLeaderElectionsPerSecElections that chose an out-of-date copy and may lose data0
kafka.server:type=ReplicaManager,name=IsrShrinksPerSec and IsrExpandsPerSecCopies falling out of and returning to syncNear 0, and shrinks followed by expands only briefly
kafka.server:type=KafkaRequestHandlerPool,name=RequestHandlerAvgIdlePercentHow much of the time request threads are freeComfortably above 20 percent
kafka.network:type=SocketServer,name=NetworkProcessorAvgIdlePercentHow much of the time network threads are freeComfortably above 30 percent
kafka.network:type=RequestMetrics,name=TotalTimeMs,request=ProduceEnd-to-end time for write requestsStable, with a low 99th percentile
Everyday Analogy

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.
!
Watch Out

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

MessagesInPerSec

Records arriving

The rate of incoming records. A sudden drop may mean producers are failing. A sudden jump may mean a runaway job.

BytesInPerSec

Data arriving

The rate of incoming bytes. Compare with network capacity to see how close you are to the limit.

BytesOutPerSec

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.

Request rates

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"]
    
FIG 4 — The five stages of a request. The total is the sum of the parts.
StageIf it is high, suspect
Request queue timeNot enough request handler threads, or too many requests at once
Local timeSlow disk writes or reads on the leader
Remote timeSlow followers when acknowledgement of all is required, or long waits for data on fetches
Response queue timeNetwork threads too busy to send replies
Response send timeSlow or congested network to the client
Everyday Analogy

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.

i
Tip

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
    
FIG 5 — A slow follower leaves and rejoins the in-sync set, and the metrics show both moments.
Everyday Analogy

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

UnderReplicatedPartitions

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.

IsrShrinks / IsrExpands

Coming and going

Shrinks followed quickly by expands are a brief hiccup. Shrinks with no expands mean a follower is not coming back.

UnderMinIsr

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.

OfflinePartitions

No leader at all

Nobody can read or write these partitions. This is an outage for the affected topics.

UncleanLeaderElections

Data-loss risk

Counts elections that picked an out-of-date copy because no in-sync copy was available. It should stay at zero.

LeaderCount

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 metricsLikely causeFirst action
Under-replicated partitions constant at a non-zero value on one broker’s topicsA broker is down or unreachableCheck whether the broker process and machine are alive
Under-replicated partitions rising and falling with shrink and expand burstsSlow disk or network on a broker, or long garbage collection pausesCheck disk latency, network and pause times
Offline partitions above zeroAll copies of a partition are unavailableRestore a broker holding a copy urgently
Many leader electionsBrokers restarting or losing their sessionCheck logs for session timeouts and restarts
!
Watch Out

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.

Everyday Analogy

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

RequestQueueSize

Waiting to be handled

Requests received but not yet picked up by a handler thread. A steadily growing queue means handlers cannot keep up.

ResponseQueueSize

Waiting to be sent

Replies ready but not yet sent. A growing queue points to network thread or network trouble.

Purgatory size

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.
i
Tip

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.

MetricWhat it showsWarning sign
Heap memory usedHow full the heap isConstantly near the maximum
Garbage collector collection timeTotal and recent time spent cleaningA large share of each minute
Garbage collector collection countHow often cleaning runsSudden increase
Thread countNumber of threads aliveSteady climb without levelling
Open file descriptorsFiles and network connections held openApproaching the operating system limit
Process CPU loadProcessor time used by KafkaSustained near 100 percent
Everyday Analogy

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.

i
Note

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.

MetricWhat it meansWhat to watch for
record-send-rateRecords sent per secondSudden drops mean the application stopped producing
record-error-rateSends that failed for goodAnything above zero deserves attention
record-retry-rateSends that had to be repeatedRising values signal broker or network stress
request-latency-avg and maxTime from sending a request to receiving its replySustained growth or large maximums
batch-size-avgAverage bytes per batchVery small batches waste capacity
records-per-request-avgRecords in each requestLow values mean batching is not working
compression-rate-avgCompressed size divided by original sizeValues near 1 mean compression barely helps
buffer-available-bytesFree memory in the send bufferApproaching zero means the producer will block
bufferpool-wait-ratioFraction of time spent waiting for buffer spaceAny sustained value means the application is being slowed
produce-throttle-time-avgTime the broker asked the client to wait because of quotasNon-zero means the client hit a limit
Everyday Analogy

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.

i
Tip

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.

!
Watch Out

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"]
    
FIG 6 — Lag is the distance between what the consumer has read and what has been written.
Everyday Analogy

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

MetricGroupMeaning
records-lag-maxconsumer-fetch-manager-metricsLargest lag among the partitions this consumer reads
records-consumed-rateconsumer-fetch-manager-metricsRecords read per second
fetch-rate and fetch-latency-avgconsumer-fetch-manager-metricsHow often and how quickly it asks for data
commit-latency-avgconsumer-coordinator-metricsTime to save the read position
rebalance-total and rebalance-latency-avgconsumer-coordinator-metricsHow often, and how long, partitions were reshuffled
last-heartbeat-seconds-agoconsumer-coordinator-metricsTime since the group was last told this consumer is alive
assigned-partitionsconsumer-coordinator-metricsHow many partitions this consumer owns
time-between-poll-maxconsumer-metricsLongest gap between reads; too large gets the consumer removed

Two kinds of trouble

Slow

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.

Stuck

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.

Churning

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.

i
Tip

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.

Application

Is it alive?

Counts of alive and failed stream threads show whether the application is running with its full set of workers.

Thread

How busy is each worker?

Process rate, poll rate and commit latency show throughput and how long saving progress takes.

Task

Per-partition health

Process rate and dropped records for each task. Dropped records often mean late events discarded by a closed time window.

State store

Memory of the application

Read and write rates, latencies and sizes of the local stores that hold counts and joins.

Latency

End-to-end delay

Record end-to-end latency shows how long it takes from a record being created to being processed.

Everyday Analogy

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.

LevelUseful metricsQuestion answered
WorkerConnector count, task count, startup failures, rebalance activityIs the Connect cluster stable?
ConnectorStatus, connector type, task counts by stateIs this connector running?
TaskStatus, running ratio, offset commit success percentage, batch sizeIs this task healthy and saving progress?
Source taskRecords polled and written per secondIs data flowing into Kafka?
Sink taskRecords read and sent per second, sink record lagIs data flowing out and is the sink keeping up?
Task errorsTotal record errors, skipped records, retries, dead letter topic writesAre transforms or converters rejecting records?
!
Watch Out

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.

SignalIn plain wordsKafka examples
LatencyHow long things takeProduce request 99th percentile time, consumer fetch latency
TrafficHow much work is happeningBytes in, bytes out, messages in per second
ErrorsHow often things failProducer error rate, failed produce requests, connector task errors
SaturationHow close resources are to their limitThread idle percentages, disk usage, file descriptors, heap

Choosing what to alert on

ConditionSuggested urgencyWhy
Offline partitions above zeroPage nowSome data is unavailable
Active controller count not equal to one across the clusterPage nowThe control plane is missing or split
Under-replicated partitions above zero for more than a few minutesPage during working hours, or now if combined with other signsData is less safe than intended
Unclean leader elections above zeroPage nowData loss may have occurred
Disk usage above about 80 percentTicket, then page if rising fastA full disk stops a broker
Consumer lag growing for a sustained periodTicket or page depending on the businessConsumers are falling behind
Producer error rate above zero for a sustained periodTicket, or page for critical writersData is not being written
Connect task in failed stateTicket, or page for critical pipelinesA 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
    
FIG 7 — A simple alert routing decision that avoids waking people for harmless spikes.
Everyday Analogy

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.
i
Tip

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.

1 series
for each metric and label combination
×
partitions and topics multiply the count
15-60 s
typical collection interval
Everyday Analogy

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

Allow-list

Collect only what you use

Configure the exporter or agent with an explicit list of MBeans instead of scraping everything.

Interval

Do not scrape too often

Fifteen to sixty seconds suits most dashboards. Every second is rarely useful and multiplies storage.

Labels

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.

Aggregate

Summarize at write time

Pre-compute cluster-wide and per-topic totals so dashboards read a few series instead of thousands.

Retention

Keep detail briefly

Keep raw numbers for days or weeks, and keep summarized versions for months.

Placement

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.
!
Watch Out

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.

1

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.

2

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.

3

Encrypt the connection

Enable TLS for JMX so passwords and metrics cannot be read on the network.

4

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.

5

Audit and rotate

Record who has access, rotate passwords and review firewall rules regularly.

Everyday Analogy

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.

i
Tip

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

PATTERN 01 Recommended
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.

PATTERN 02 Recommended
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.

PATTERN 03 Recommended
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.

PATTERN 04 Recommended
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

ANTI-PATTERN 01 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.

ANTI-PATTERN 02 Avoid
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.

ANTI-PATTERN 03 Avoid
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.

ANTI-PATTERN 04 Avoid
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.

ANTI-PATTERN 05 Avoid
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

1

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.

2

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.

3

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.

4

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.

5

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.

6

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.

7

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.

Everyday Analogy

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

1

Enable metrics safely

Turn on JMX or an exporter with network limits, authentication and encryption in place.

2

Collect a short allow-list

Begin with the broker health checklist, traffic, request time and Java runtime metrics.

3

Build the overview page

Show a few red and green signals, and link each to a detail page.

4

Add client metrics

Bring in producer, consumer and connector metrics for the applications that matter most to the business.

5

Write alerts with waiting periods

Cover offline partitions, controller count, lag, disk space and errors. Attach a runbook to each.

6

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.

The same few signals appear in every large operation: are partitions online, are copies in step, are requests fast, and are consumers keeping up?

22Frequently Asked Questions

Short answers to questions that beginners and experienced engineers ask most often about JMX and Kafka metrics.

Q1What is JMX in one sentence?
JMX, short for Java Management Extensions, is the standard Java way for a running program to publish named measurements and controls that tools can read locally or over a network.
Q2Why does Kafka use JMX instead of a special metrics format?
JMX comes with Java, works with many existing tools and needs no extra service. Kafka publishes its metrics as MBeans, and exporters and agents can translate them into whatever format your monitoring system prefers.
Q3What is an MBean and what is an ObjectName?
An MBean is a managed object that exposes attributes, which are values you can read, and sometimes operations. An ObjectName is its unique address, made of a domain, such as kafka.server, followed by key and value pairs like the type and name of the metric.
Q4Do I need to enable JMX in Kafka?
The metrics always exist inside the process. Making them reachable from outside requires setting a JMX port or attaching an exporter or agent. Many start scripts read a port setting from an environment variable.
Q5Which metrics should I watch first on a broker?
Offline partitions, active controller count, under-replicated partitions, unclean leader elections, request handler idle percentage, network processor idle percentage, request time percentiles, disk usage and garbage collection time. These give a rounded picture of availability, safety and capacity.
Q6What does a non-zero under-replicated partitions value mean?
Some partitions have fewer in-sync copies than intended, so their data is less protected. It may be brief during restarts, but sustained values point to a slow, stopped or overloaded broker, or a network problem.
Q7What is consumer lag and how do I measure it?
Lag is the number of messages written to a partition that a consumer group has not yet processed. You can read it from the consumer’s own metrics while it runs, or measure it from outside by comparing committed offsets to log end offsets, which also works when the consumer is down.
Q8What is the difference between a meter, a counter, a gauge and a histogram?
A gauge is a current value, like disk usage. A counter is a total that only goes up. A meter counts events and also reports rates over recent windows. A histogram records a spread of values and reports percentiles, such as the time below which ninety-nine percent of requests finished.
Q9Why are there two different metric systems in Kafka?
Brokers were built with the Yammer metrics library, while the newer Java clients use Kafka’s own metrics library. Both end up as MBeans, but the naming styles differ, which is why broker and client names look a little different.
Q10How often should I collect metrics?
Every fifteen to sixty seconds suits most setups. Collecting faster increases cost and load without much benefit, and client rates are averaged over a window of about thirty seconds anyway.
Q11Does monitoring with JMX slow Kafka down?
Updating metrics is cheap, and reading a modest list of attributes at sensible intervals has little effect. Trouble comes from collecting far too many attributes very often, so use an allow-list and test on a staging cluster.
Q12Is JMX secure?
Only when configured that way. Remote JMX without authentication can allow dangerous actions. Restrict network access, require sign-in, use TLS and grant read-only roles, or use an in-process exporter that publishes read-only numbers.
Q13Can I monitor Kafka without JMX?
Partly. Command-line tools, admin client calls and log analysis show some information, and managed services provide their own metrics. Still, JMX-based metrics are the richest source of detail, and even other tools usually read them behind the scenes.
Q14How do I monitor Kafka Streams and Kafka Connect?
Both publish MBeans in their own domains. For Streams, watch thread and task health, process rates, latency and dropped records. For Connect, watch task status, error counts, offset commit success and sink lag. Alert on task status, not only worker liveness.
Q15What if my metrics suddenly disappear?
Treat missing data as a signal. The application may have crashed, the exporter may have failed, the network may have broken or a firewall rule may have changed. Alerts should fire when expected data stops arriving.
Q16Do managed Kafka services still need me to watch metrics?
Yes. The provider handles machines and many broker concerns, but topic traffic, consumer lag, client errors and connector health belong to your applications and remain your responsibility.

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.producer and kafka.consumer tell 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.