Rolling Restarts Without Downtime in Kafka
A complete, plain-English guide to restarting, patching, and upgrading a Kafka cluster while producers keep writing and consumers keep reading: how leadership moves, what clients feel, which safety rules matter, and how to automate it with confidence.
Picture a large hospital that never closes. Nurses work in shifts, and every shift change must happen without a single patient being left unattended. Nobody shuts the hospital for an hour so the staff can swap. Instead, one nurse hands over to the next, confirms the handover went well, and only then does the following pair change places. The hospital never stops, yet every person is eventually replaced.
A Kafka cluster is that hospital. Brokers, the servers that hold your data, must be restarted from time to time. Security patches arrive. Settings change. Certificates expire. Versions get upgraded. Yet the applications that depend on Kafka, from payment systems to live dashboards, expect it to be there every second of every day. The skill of doing all this without anybody noticing is called the rolling restart.
This guide starts from zero. Every new word is explained the first time it appears, every big idea comes with an everyday comparison, and every chapter ends with something you can act on. You will learn what happens inside Kafka during a restart, the few rules that keep it safe, how to prepare your applications, how to automate the process, and how to recover when something goes sideways.
1Why Restarts Never Stop
Some people believe a well-run cluster should never need restarting. In reality, restarts are a regular part of life, and the only choice is whether they are painful or boring.
Apache Kafka is a system that stores and moves streams of events between programs. It runs as a cluster of servers called brokers. Like any software running on real machines, brokers need attention over time. Here are the everyday reasons a broker has to stop and start again.
Security patches
Operating system and Java updates fix vulnerabilities. Many only take effect after a restart.
Version upgrades
New Kafka releases bring fixes and features. Upgrading means replacing the software on each broker.
Configuration changes
Some settings can only be read at start-up. Changing them requires a restart.
Certificates and keys
Security certificates expire and must be replaced. Some setups need a restart to load the new ones.
Hardware and cloud maintenance
Cloud providers retire machines and schedule host maintenance. Disks are replaced or grown.
Resource tuning
Changing memory size, file limits, or disk layout often needs the process to start fresh.
Think of a busy train station. Tracks need repairs, signals need updates, and the trains never stop. Engineers close one track at a time, reroute the trains to the others, finish the repair, reopen the track, and only then move to the next. Repairs never stop, and the timetable barely changes. Rolling restarts follow the same idea.
What goes wrong when restarts are done badly
A careless restart can cause real harm. If all brokers are stopped at once, the cluster is simply down. If brokers are stopped too quickly one after another, some data may exist on only one server for a while, which is risky. If clients are not prepared, they may throw errors, lose messages, or trigger long delays while they rediscover where their data lives. Teams that fear restarts postpone patching, and postponed patching turns into a security problem.
The goal is not to avoid restarts. The goal is to make them so routine that a full cluster restart is a quiet task you could run on a Tuesday afternoon.
2What “Without Downtime” Really Means
Before we chase zero downtime, we must agree on what it means. The phrase hides several different promises.
When people say “no downtime”, they usually mean that users and applications do not notice. But there are levels of not noticing, and each needs a different amount of care.
| Level | What it promises | What can still happen |
|---|---|---|
| No outage | The cluster always accepts writes and serves reads | Brief slowdowns and retries |
| No errors seen by applications | Clients retry internally and never surface a failure | Small latency spikes for some requests |
| No data loss | Every acknowledged message survives | Some messages may be delivered twice without safeguards |
| No duplicates | Each message is processed exactly once | Requires idempotent producers and careful consumers |
| No perceptible latency change | Even the slowest requests stay fast | Very hard; needs spare capacity and slow pacing |
Most teams aim for the first three: the cluster stays available, clients do not fail, and no acknowledged data is lost. Tiny latency bumps are accepted as the price. You should decide, before you start, which of these levels your business needs, and write it down. It affects how carefully you pace the work and how much spare capacity you keep.
A restaurant that stays open during a kitchen refit is “open”. But one diner might wait five minutes longer for dessert. That is a very different outcome from a diner who is turned away at the door. Rolling restarts aim for the first kind of experience: a slight wait, never a locked door.
How to measure it
Decide on a few numbers before the maintenance window. For example: producer error rate stays at zero, the slowest one percent of produce requests stay under two seconds, no consumer group falls more than a minute behind, and no partition is ever offline. If any number is crossed, you pause the restart and investigate. Without such numbers, “no downtime” is a feeling, not a fact.
3Kafka Refresher: Leaders, Followers, and the ISR
To restart brokers safely, you must understand who holds what. This short refresher covers exactly the parts that matter.
Topics and partitions
Kafka stores events in named channels called topics. Each topic is split into partitions, which are ordered logs. Partitions let Kafka spread a topic across many brokers, so no single machine has to carry all the traffic.
Replication
To survive machine failures, every partition is copied to several brokers. The number of copies is the replication factor. A common choice is three. Each copy is called a replica. One replica of each partition is the leader. All reads and writes for that partition go through the leader. The other replicas are followers, and they continuously copy data from the leader.
Imagine three notebooks, each holding the same diary. One notebook is the “master” where new entries are first written, and the other two are copied from it a moment later. If the master notebook is lost, one of the copies can be promoted to master, and the diary carries on.
The in-sync replicas
A follower that is keeping up with the leader is called in-sync. The set of in-sync replicas, including the leader, is the ISR. Only members of the ISR can be promoted to leader without risking data loss. A follower that falls too far behind, by default more than about thirty seconds, is dropped from the ISR until it catches up.
Leader
The replica that handles all reads and writes for one partition.
Follower
A replica that copies the leader and stands ready to take over.
ISR
The replicas that are fully caught up. Safe candidates for the next leader.
Under-replicated partition
A partition with fewer in-sync copies than its replication factor. The main warning sign during a restart.
Leaders are spread out
Kafka balances leadership so each broker leads roughly the same number of partitions. That means every broker is the leader for many partitions at once, and a follower for many others. When one broker stops, it takes the leadership of many partitions with it, and those partitions need new leaders. Everything about zero-downtime restarts comes down to moving that leadership smoothly.
A broker restart is really a leadership handover. The data is safe on other brokers. The work is making the handover quick, orderly, and confirmed before touching the next broker.
4The Safety Math: Replication Factor, Minimum ISR, and Acks
Three settings decide how many brokers can be down at once without harm. Get them right before you ever restart anything.
Replication factor
This is the number of copies of each partition. With a replication factor of one, restarting the broker that holds the partition makes it unavailable for the whole restart. That cannot be rolled without downtime. With three copies, two other brokers can take over.
Minimum in-sync replicas
The setting min.insync.replicas is the smallest number of in-sync copies that must exist before Kafka accepts a write from a producer that asks for full safety. If the ISR shrinks below this number, writes are refused instead of risking a single fragile copy.
Acks
A producer chooses how many acknowledgments it wants. With acks=all, the leader waits until every in-sync replica has the message before confirming. That, combined with the minimum ISR rule, gives the strongest promise: an acknowledged message lives on at least the minimum number of brokers.
| Replication factor | Minimum ISR | Brokers that can be down and still accept safe writes | Rolling restart safe? |
|---|---|---|---|
| 1 | 1 | 0 | No. Each restart is an outage for its partitions |
| 2 | 1 | 1 | Works, but a single copy is left during the restart, which is fragile |
| 2 | 2 | 0 | No. Writes stop while one broker is down |
| 3 | 2 | 1 | Yes. The recommended setup |
| 3 | 3 | 0 | No. Writes stop while one broker is down |
| 5 | 3 | 2 | Yes, with room to restart two at once if needed |
A bank vault holds a very important document, and the bank keeps three copies in three buildings. The rule says a new document is only “filed” once two buildings have it. With one building closed for repairs, filing still works, since two remain. Close a second building at the same time, and filing must stop until one reopens.
The golden rule
With a replication factor of three and a minimum ISR of two, you can restart exactly one broker at a time and keep accepting safe writes. The key words are one at a time. The next broker may only go down after the previous one has fully returned and every partition is back to three in-sync copies.
A very common mistake is setting the minimum ISR equal to the replication factor to feel extra safe. That makes every single broker restart block writes. Extra safety on paper becomes an outage in practice.
Check the internal topics too
Kafka keeps its own bookkeeping in internal topics, such as the topic that stores consumer offsets. Their replication factor must also be three. A small test cluster that was created with a replication factor of one for these topics will lose its consumer positions or coordinator service during a restart.
5Architecture: Every Piece a Restart Touches
A restart is not just one broker stopping. Several pieces react. Here is the full picture.
flowchart LR
subgraph Clients["Client Applications"]
P["Producers"]
C["Consumers in groups"]
S["Streams and Connect apps"]
end
subgraph Cluster["Kafka Cluster"]
B1["Broker 1"]
B2["Broker 2"]
B3["Broker 3"]
end
subgraph Control["Controller Quorum"]
K1["Controller 1 active"]
K2["Controller 2"]
K3["Controller 3"]
end
subgraph Ops["Operations"]
ORC["Restart orchestrator"]
MON["Monitoring and alerts"]
end
P -->|"produce to leaders"| B1
P --> B2
C -->|"fetch from leaders"| B2
C --> B3
S --> B1
S --> B3
B1 |"replicate"| B2
B2 |"replicate"| B3
B1 |"replicate"| B3
B1 -.->|"heartbeat and metadata"| K1
B2 -.-> K1
B3 -.-> K1
K1 --- K2
K1 --- K3
ORC -->|"stop, start, wait"| B2
MON -->|"health checks"| ORC
Who does what during a restart
The restarting broker
Hands off its partition leadership, stops cleanly, starts again, catches up, and rejoins the ISR.
The other brokers
Take over leadership, keep serving traffic, and carry extra load for a while.
Controller quorum
Tracks which broker leads which partition, picks new leaders, and tells everyone.
Producers and consumers
Notice leadership moves, refresh their map of the cluster, and retry.
Orchestrator
A script, a tool, or an operator that restarts brokers one at a time and checks health between steps.
Monitoring
Watches replication health and client errors, and stops the process if something looks wrong.
Nothing in this picture is a single point of failure. That is the entire reason a rolling restart is possible. Each piece has a partner that can carry on while it is away.
6Internal Working: Controlled Shutdown, Step by Step
The difference between a clean stop and a crash is the heart of this guide. Kafka has a built-in way to leave gracefully.
When you ask a broker to stop politely, it does not just switch off. It performs a controlled shutdown. That is a short routine in which the broker first tells the cluster “I am leaving, please move my leaders elsewhere”, waits until that is done, and only then closes. This setting is turned on by default in Kafka.
sequenceDiagram
autonumber
participant Op as Operator
participant B as Broker being restarted
participant Ctl as Active Controller
participant F as Other Brokers
participant Cl as Clients
Op->>B: Send polite stop signal
B->>Ctl: Request controlled shutdown
Ctl->>Ctl: Pick new leaders from in-sync replicas
Ctl->>F: New leader assignments
F-->>Ctl: Leadership taken over
Ctl-->>B: All leaders moved, safe to stop
B->>B: Flush data, write clean shutdown marker
B->>Ctl: Deregister and close connections
Cl->>F: Refresh metadata, send requests to new leaders
F-->>Cl: Normal responses
The steps in words
The stop signal
The operator asks the broker process to end, using a normal termination signal that the broker understands. A hard kill is a different thing, and we will see why it hurts.
Ask the controller
The broker tells the controller it is about to shut down. The controller now knows not to choose this broker as a future leader.
Move the leaders
For each partition the broker leads, the controller picks another in-sync replica as the new leader, and announces the change. Because the new leader is already caught up, no data is lost.
Wait for confirmation
The broker waits until the controller says all leadership has moved. If some moves are pending, the broker waits and retries for a while.
Close cleanly
The broker flushes data to disk, records a marker saying it stopped cleanly, and closes its connections.
A pilot handing over a plane in the air is very different from a pilot who suddenly disappears. In a controlled handover, the co-pilot confirms “I have control”, and only then does the first pilot leave the seat. In a crash, the co-pilot must notice the empty seat, work out what happened, and take over from a standing start.
Why the clean marker matters
When a broker starts again, it checks whether it stopped cleanly last time. If the clean marker is present, it can trust its data files and start almost at once. If not, it must scan its log segments to check for damaged data and rebuild indexes. On a broker with terabytes of data, that recovery can take many minutes, and the broker cannot serve during that time. This is the biggest practical reason to avoid hard kills.
| Stop style | Leadership | Restart time | Client impact |
|---|---|---|---|
| Controlled shutdown | Moved first, in an orderly way | Fast, no log recovery | Very small; a brief redirect |
| Crash or hard kill | Moved only after the cluster notices the broker is gone | Slow, log recovery scan | Longer pause and possible errors |
Some process managers, container platforms, and scripts give a program only a few seconds to stop before killing it. If the broker has thousands of partitions to hand off, a short timeout cuts the controlled shutdown short. Always give brokers a generous stop timeout.
7What Clients Feel When a Leader Moves
The brokers do the handover, but the clients are the ones who could get hurt. Here is what they experience, and how they recover.
sequenceDiagram
autonumber
participant P as Producer
participant Old as Old Leader Broker
participant New as New Leader Broker
P->>Old: Send batch for partition 7
Old-->>P: Not the leader anymore
P->>P: Mark metadata stale, wait a short backoff
P->>New: Ask for fresh cluster metadata
New-->>P: Partition 7 leader is now this broker
P->>New: Resend the same batch
New->>New: Write and replicate to followers
New-->>P: Acknowledged
The producer’s experience
A producer keeps a map of which broker leads each partition. When leadership moves, that map goes stale. The next request to the old leader gets a “not the leader” reply. The producer’s client library quietly refreshes its map from any broker and resends the batch to the new leader. If the client is set up well, the application code sees nothing but, at worst, a slightly slower send.
Producers also retry when a connection drops, which happens when a broker closes at the end of its shutdown. Retries are automatic and controlled by a total time limit, called the delivery timeout. As long as the leadership move finishes inside that limit, the send succeeds.
The consumer’s experience
A consumer fetches from partition leaders in the same way, and it refreshes its map in the same way. There is one extra thing. Each consumer group has a group coordinator, a broker that tracks members and their positions. The coordinator for a group is simply the leader of a partition of an internal offsets topic. If the coordinator’s broker restarts, the coordinator role moves too, and consumers must find the new one.
Stale map
Gets a “not the leader” answer, refreshes, and retries. Usually a few hundred milliseconds.
Closed connection
Reconnects to another broker and continues.
Fetch redirect
Learns the new leader and continues reading from its saved position.
Coordinator move
Finds the new coordinator and carries on. If it takes too long, a group rebalance can be triggered.
Imagine you always post letters at the corner mailbox, and one day it is replaced by a new one down the street. The first time, you find a note saying “moved, see next box”. You walk there, post your letter, and next time you go straight to the new spot. That is what a client does.
How long does the blip last?
In a healthy cluster, the leadership handover for a partition takes tens to hundreds of milliseconds. A broker with a huge number of partitions takes longer overall, because each must be moved, but any individual client only cares about the partitions it uses. Most applications see a delay of well under a second, if they see anything at all.
8Start-Up: Recovery, Catch-Up, and Rejoining the ISR
A restart is not finished when the process is running again. The broker is still empty-handed and behind. The next steps are just as important.
flowchart TD
S["Broker process starts"] --> M{"Clean shutdown marker present?"}
M -- "Yes" --> L["Load logs quickly"]
M -- "No" --> R["Log recovery: scan segments and rebuild indexes"]
R --> L
L --> REG["Register with controller"]
REG --> F["Become follower for its partitions"]
F --> CU["Fetch missed data from leaders"]
CU --> ISR{"Fully caught up?"}
ISR -- "No" --> CU
ISR -- "Yes" --> J["Rejoin the ISR"]
J --> PL["Preferred leader election returns leadership"]
PL --> OK["Broker fully back in service"]
Step 1: load or recover the logs
The broker opens its data directories. After a clean stop, it loads the log files quickly. After a crash, it checks the tail of each partition for damaged data and rebuilds indexes. A setting controls how many threads do this work in parallel per disk. More threads shorten recovery on machines with many partitions.
Step 2: register and become a follower
The broker tells the controller it is back. Because other brokers took over leadership, this broker starts out as a follower for all its partitions, not a leader.
Step 3: catch up
While the broker was away, leaders kept receiving new messages. Now it must fetch all those missing messages. The amount depends on how long it was down and how fast data arrives. During this period, the broker is not in the ISR for those partitions, so those partitions are under-replicated. That is normal and expected during a restart, but it is exactly the state that must be fully resolved before touching the next broker.
Step 4: rejoin the ISR
Once a follower has caught up to the leader, it is added back to the ISR. Now each partition again has its full set of in-sync copies.
Step 5: get leadership back
Each partition has a preferred leader, the first replica in its list, chosen when the topic was created to spread leadership evenly. Kafka can check periodically and hand leadership back to preferred leaders when they are in sync. By default this happens automatically every few minutes if the imbalance passes a threshold. You can also trigger it yourself. Restoring balance matters, because otherwise the restarted broker sits nearly idle while others carry extra load.
Whether or not you wait for leadership to return before restarting the next broker is a design choice. Waiting for full balance is the cautious option. Waiting only for the ISR to be complete is faster and still safe. We cover both in the automation chapters.
9The Rolling Loop: One Broker, Then Check, Then Next
Now we combine the pieces into a repeatable loop. The loop is simple, and its discipline is what makes it safe.
flowchart TD
A["Start maintenance window"] --> PRE{"Pre-flight checks pass?"}
PRE -- "No" --> ABORT["Stop and fix first"]
PRE -- "Yes" --> PICK["Pick the next broker"]
PICK --> STOP["Controlled shutdown"]
STOP --> WORK["Apply change: patch, config, upgrade"]
WORK --> START["Start broker"]
START --> W1{"Broker registered with controller?"}
W1 -- "No, timeout" --> HALT["Halt and investigate"]
W1 -- "Yes" --> W2{"Under-replicated partitions equal zero?"}
W2 -- "No, still catching up" --> W2
W2 -- "Stuck too long" --> HALT
W2 -- "Yes" --> W3["Optionally rebalance preferred leaders"]
W3 --> CH{"Client errors and lag within limits?"}
CH -- "No" --> HALT
CH -- "Yes" --> MORE{"More brokers left?"}
MORE -- "Yes" --> PICK
MORE -- "No" --> DONE["Finish and record results"]
The three gates
Registered
The broker is back and known to the controller. If it never registers, something is wrong with its start-up, and you must stop.
No under-replicated partitions
Every partition has its full set of in-sync copies again. This is the most important gate of all.
Clients are happy
Producer errors, latency, and consumer lag are all inside your limits.
It is like relay runners passing a baton. The second runner must have a firm grip before the first lets go, and the third runner does not start until the second is stable and running. Rushing the handoff drops the baton.
Why not restart faster?
Suppose you restart broker two the moment broker one’s process is running, but before broker one has caught up. Now some partitions have one copy that is out of sync, one that is down, and only one healthy. With a minimum ISR of two, those partitions stop accepting writes. Worse, if the lone healthy copy fails, data could be lost. Patience between brokers is the cheapest insurance you will ever buy.
Why not slower?
Waiting for perfection has costs too. The longer the maintenance window, the longer the cluster runs with reduced fault tolerance. If another broker fails unexpectedly during the window, you are exposed. A good loop is thorough between brokers and efficient in everything else.
Decide in advance when you will stop: a broker fails to return within a set time, replication does not settle within a set time, or client errors rise above your limit. A written abort rule beats a judgment call made at two in the morning.
10Pre-Flight Checks: Is the Cluster Ready to Be Touched?
Pilots run through a checklist before every flight, however many times they have flown. Do the same before every restart window.
A rolling restart assumes the cluster starts in good health. If something is already wrong, a restart can turn a small problem into a big one. Spend ten minutes checking before you touch anything.
| Check | What you want to see | If not |
|---|---|---|
| Under-replicated partitions | Zero | Find out why first. Do not start |
| Partitions below minimum ISR | Zero | Writes may already be failing. Stop |
| Offline partitions | Zero | The cluster is already degraded |
| All brokers registered | Every expected broker is present | A missing broker means fewer spare copies |
| Active controller | Exactly one | Investigate controller health |
| Disk space | Comfortable headroom on every broker | Catch-up needs room to grow |
| Leadership balance | Roughly even across brokers | Rebalance first; skew makes each restart harsher |
| Topic settings | Replication factor of three or more; minimum ISR of two | Fix or plan downtime for those topics |
| Current load | Well below peak capacity | Wait for a quieter time |
| Other maintenance | None running: no reassignments, no rebalance jobs | Finish or pause them |
Find the fragile topics
Before the window, list every topic with a replication factor below three, or a minimum ISR that equals the replication factor. These are the topics that will suffer during a rolling restart. Some may be forgotten test topics you can delete. Others may be real, and need a plan: either raise their replication before maintenance, or warn their owners.
Tell people
Announce the window to the teams that use the cluster. Not because you expect trouble, but so that if a team sees a small blip, they know why. Share the time, the expected effect, and a contact. This also gives teams a chance to say “please do not touch us today, we have a launch”.
Have a way back
For a plain restart, going back means simply starting the broker again. For an upgrade or a configuration change, going back means restoring the old version or settings. Keep the old package, the old configuration files, and a written procedure ready.
Automate the pre-flight checks as a script that prints a clear pass or fail. Humans skip steps when tired. Scripts do not.
11Getting Producers Ready
A well-configured producer barely notices a restart. A poorly configured one loses data or fails loudly. These are the settings that decide which you get.
Acks set to all
The leader confirms only after all in-sync copies have the message. With this, a leadership move cannot lose an acknowledged message.
Idempotence on
The producer tags each message so the broker can spot and drop repeats caused by retries. Modern clients turn this on by default.
Generous retries and delivery timeout
Let the client keep trying for a couple of minutes, so a leadership move never turns into an error the application sees.
Several bootstrap servers
List at least three brokers in the connection list, so the client can start even while one is down.
Limited in-flight requests
Keep the number of unconfirmed batches per connection at five or fewer so message order survives retries when idempotence is on.
Sensible request timeout
Long enough for a leader election, short enough to notice real trouble.
A courier who gets a locked door at the first address does not give up. They knock again, ask a neighbor where the family moved, and try the new address. Good producer settings are the courier’s persistence and their sticky notes for avoiding double deliveries.
Why acks matter so much
With acks=1, the leader confirms as soon as it has written the message itself, before any follower has it. If that leader stops before the followers copy the message, and a follower becomes leader, the message is gone, even though the producer was told it succeeded. Controlled shutdown makes this less likely but never impossible. With acks=all and a minimum ISR of two, an acknowledged message is on at least two brokers, so losing any one broker cannot lose it.
Handling errors in code
Even with perfect settings, a send can fail if the outage outlasts the delivery timeout. Application code should handle failure callbacks: log them, retry at a higher level, or park the message in a fallback place. Never ignore the result of a send.
| Producer style | During a restart | Risk |
|---|---|---|
| Acks all, idempotent, long timeout | Slight delay, no errors | Lowest |
| Acks all, short timeout | Occasional send failures | Failures if the move is slow |
| Acks one | Fast, but a leader change can lose messages | Possible silent loss |
| Acks zero | No confirmation at all | Messages lost without any sign |
Very old clients may not handle leadership changes as gracefully as current ones. Check your client library versions before the window. Upgrading clients is a separate project that pays off every time you restart brokers.
12Getting Consumers Ready
Consumers are more delicate than producers, because they work in teams. A restart that shakes the team can cause a pause called a rebalance.
What is a rebalance?
Consumers in a group split up the partitions of a topic. Whenever the membership changes, or the group thinks someone has left, the partitions must be reassigned. This reassignment is called a rebalance. In older styles of rebalance, every consumer stops reading while the new plan is worked out. On a big group, that pause can last many seconds or even minutes.
A team of checkout staff shares out the supermarket tills. Whenever a colleague goes on break, the manager calls everyone off their tills, redraws the roster, and sends them back. During the redraw, no customer is served. A smarter manager only moves the one till that changed.
How a broker restart can trigger a rebalance
Consumers send regular heartbeats to their group coordinator. If the coordinator’s broker restarts, heartbeats fail for a moment while the role moves. If the delay is longer than the session timeout, the group thinks its members are dead and starts a rebalance. So two things matter: making the timeout comfortably longer than a normal coordinator move, and making rebalances cheap when they do happen.
Session timeout
The time a coordinator waits without a heartbeat before declaring a consumer dead. Modern defaults are around forty-five seconds, enough for most handovers.
Heartbeat interval
How often consumers say “I am alive”. Keep it at about a third of the session timeout or less.
Max poll interval
The longest a consumer may go between fetching batches. Slow processing beyond this also triggers a rebalance.
Cooperative rebalancing
Only the partitions that must move are paused. Everyone else keeps reading. Much gentler than the stop-the-world style.
Static membership
Each consumer gets a fixed identity. When it disappears briefly and returns within the timeout, the group does not rebalance at all.
Newer group protocol
Recent Kafka versions add a redesigned rebalance protocol that moves the coordination work to the broker and avoids group-wide pauses. Use it where your versions support it.
Commit offsets carefully
A consumer’s position in each partition is saved as an offset. If a commit fails during a restart, the consumer may re-read a few messages after recovery. This is called at-least-once processing. To be safe, make your processing idempotent, which means applying the same message twice gives the same result. Then a repeated message is harmless.
Test your consumers by deliberately restarting the coordinator broker in a staging environment and watching how long the group is paused. If it pauses for more than a few seconds, tune the settings above before your real window.
13Transactions, Kafka Streams, and Kafka Connect
Higher-level tools have their own behavior when brokers restart. Know it before you begin.
Transactions
Kafka supports transactions, which let a producer write to several partitions and have them appear all together or not at all. Transactions are managed by a transaction coordinator, which, like the group coordinator, lives on a broker and moves when that broker restarts. Producers see temporary errors, such as “coordinator not available”, and retry. A transaction in progress during the move might be aborted if it runs longer than the transaction timeout, so keep transactions short. Consumers that read only committed messages will simply skip aborted ones.
Kafka Streams
Streams applications are built on the ordinary producer and consumer, and they add local state stores. They are designed to ride through broker restarts, retrying for a configured time before giving up. Set that retry window longer than your typical broker restart. If a Streams application’s own instance restarts, it must rebuild its local state from a change log topic, which can take a while for big state. Standby replicas keep a warm copy and shorten this wait.
Kafka Connect
Connect runs connectors as tasks spread over workers. When a broker restarts, Connect’s internal topics briefly move leaders, and connectors retry. When a Connect worker itself restarts, its tasks move to other workers. A delay setting gives a restarted worker time to come back before its tasks are permanently reassigned, so you avoid a reshuffle for a short restart. That delay is a few minutes by default.
| Component | What happens on broker restart | What to check |
|---|---|---|
| Transactional producer | Coordinator moves; brief retry errors | Transaction timeout is longer than the move |
| Streams application | Retries and carries on | Retry window longer than restart time |
| Connect worker | Internal topics briefly unavailable | Retry settings; rebalance delay |
| Source connector | Pauses producing, then resumes | Safe positions saved |
| Sink connector | Pauses consuming, then resumes | Downstream can handle repeats |
Example: the state rebuild surprise
A team restarts application servers and broker machines during the same maintenance window. The Streams application, which has 200 GB of local state and no standby copies, takes forty minutes to rebuild after its restart. During that time its output is late. Splitting the two activities into separate windows, and adding standby replicas, cuts the delay to under a minute.
14The Control Plane: Restarting Controllers Safely
Brokers hold data. Controllers hold the cluster’s brain. Restarting the brain needs its own care.
The controller decides who leads which partition, and remembers the list of topics, settings, and brokers. In modern Kafka, this job is done by a small group of controller nodes running a built-in consensus system called KRaft. The nodes agree on every change by majority vote, so the cluster’s brain survives the loss of a minority of them. Older Kafka versions used a separate service called ZooKeeper for the same purpose. Recent major releases have removed it entirely.
The majority rule
A quorum of three controllers can lose one and keep working. A quorum of five can lose two. Lose the majority and the cluster can no longer change leaders, create topics, or react to broker failures. Existing traffic often keeps flowing for a while, but the cluster is frozen and fragile.
A committee of three makes decisions by majority. If one member is away, the other two can still decide. If two are away, no decision can be made. You would never let two of three committee members go on holiday on the same day.
Rolling controllers
Check quorum health
All controller nodes are present and in sync with the leader of the quorum.
Restart followers first
Restart the non-active controllers one at a time, waiting for each to rejoin and catch up.
Restart the active controller last
Restarting the active one triggers a quick election among the others. This is short, but it is a moment when no changes can be made, so do it when nothing else is in flux.
Verify a single active controller
Confirm exactly one active controller and a full quorum again.
Combined and separate nodes
Some small clusters run controller and broker roles on the same machines. Then a single restart affects both the data plane and the control plane at once. That is workable with three or more nodes, but it makes each step heavier. Larger clusters usually keep controllers on dedicated machines, which makes restarts of each kind independent and easier to reason about.
Never restart a controller and a broker that hold the same data at the same time on a three-node combined cluster. You would lose the quorum and one data copy in a single step.
15Rack and Zone Awareness: Restarting Faster and Safer
If your replicas are spread across failure zones, you can restart a whole zone at once, which turns a long window into a short one.
Every broker can be labeled with the rack or availability zone it lives in, using the setting broker.rack. When this is set, Kafka places the replicas of each partition in different racks whenever it can. With three racks and a replication factor of three, every partition has exactly one copy in each rack.
flowchart LR
subgraph RA["Zone A"]
A1["Broker 1"]
A2["Broker 4"]
end
subgraph RB["Zone B"]
B1["Broker 2"]
B2["Broker 5"]
end
subgraph RC["Zone C"]
C1["Broker 3"]
C2["Broker 6"]
end
P1["Partition 0 replicas"] --> A1
P1 --> B1
P1 --> C1
P2["Partition 1 replicas"] --> A2
P2 --> B2
P2 --> C2
The zone-at-a-time approach
With this layout, restarting all brokers in Zone A at the same time removes exactly one replica of every partition. The minimum ISR of two is still met by Zones B and C, so writes continue. You can restart a whole zone in one step, wait for it to catch up, and then do the next zone. For a large cluster, three zone-sized steps replace dozens of single-broker steps.
Much shorter windows
Restart many brokers together instead of one after another.
Matches real failures
A zone outage is a real thing. Restarting a zone practices for it.
Even rack layout
The same number of brokers per rack, so load spreads evenly.
Rack-aware topics
Only topics created or reassigned with rack awareness are safe this way. Older topics may need a reassignment first.
Verify that for every topic, no two replicas of the same partition sit in one zone. A single partition with two replicas in the restarting zone will lose both at once and stop accepting safe writes.
The catch is that the surviving zones must have the capacity to absorb the load of the missing zone: about one and a half times their normal traffic for a three-zone layout. Confirm you have that headroom before using this approach.
16The Best Restart Is the One You Skip: Dynamic Configuration
Many settings can be changed on a running broker. Learning which ones saves you a surprising number of restarts.
Kafka has three kinds of broker settings. Read-only settings are read once at start-up, so changing them needs a restart. Per-broker settings can be updated on a running broker, one broker at a time. Cluster-wide settings can be updated for all brokers in a single command. Kafka stores dynamic values in its own metadata and applies them without stopping the process.
| Kind of setting | Examples | Needs a restart? |
|---|---|---|
| Identity and layout | Broker ID, data directories, listener addresses, node role | Yes |
| Retention and cleanup | Log retention time and size, cleaner threads | No |
| Quotas | Producer and consumer byte rates per user or client | No |
| Thread pools | Network, I/O, and replica fetcher thread counts | No, within limits |
| Security material | The key store and trust store used by a listener | No, in supported setups |
| Topic-level settings | Retention, minimum ISR, segment size | No |
| Java options and memory | Heap size, garbage collector | Yes |
A house has some things you can change while living in it, like moving furniture or repainting a wall. Other things, like replacing the foundation or the main door frame, need the family to move out for a while. Good operators do the first kind of work whenever possible and save the second kind for planned windows.
Certificates without restarts
Security certificates expire on a schedule, and forgetting one is a classic cause of outages. Kafka can reload a listener’s key store and trust store while running, when they are updated through the dynamic configuration mechanism. That lets you rotate certificates broker by broker, without a restart, and with no interruption to clients. It is worth setting this up long before the first certificate is close to expiring.
Change one broker first
Even with dynamic settings, apply a per-broker change to one broker first, watch it for a few minutes, and only then apply it cluster-wide. A bad value that takes effect everywhere at once can do more harm than any restart.
Keep a short list of settings that need a restart, and settings that do not, for your Kafka version. Before every planned restart, ask whether this change could have been dynamic.
17Rolling Upgrades: A Restart With a Version Change
An upgrade is a rolling restart where each broker comes back running newer software. It adds one careful idea: keep the old and new versions compatible until everyone has moved.
During an upgrade, the cluster runs a mix of old and new brokers for some time. To make this safe, new brokers are told to keep speaking the old dialect of Kafka’s internal protocol until every broker is upgraded. Only then do you switch the whole cluster to the new dialect. In older versions, this was controlled by a setting for the inter-broker protocol version. In current versions, it is controlled by a cluster-wide metadata version that you raise with a special command.
Read the release notes
Find breaking changes, removed settings, and required upgrade order. Test the upgrade in staging first.
Upgrade controllers, then brokers
In current versions, the control plane is upgraded first, then each broker, one at a time using the rolling loop.
Run mixed for a while
Watch the cluster for problems with the new software while you still have the option to roll back.
Raise the cluster-wide version
Once satisfied, raise the metadata or protocol version. After this step, rolling back is harder or impossible.
Upgrade clients on their own schedule
Newer brokers keep working with a wide range of client versions, so clients can follow later.
Why the version step is separate
The step that raises the cluster-wide version is the point of no return. Before it, you can still stop and put the old software back. After it, some data formats or metadata may have changed. Separating the software swap from the version switch gives you a safe soak period in between. Use it.
Never skip more than the supported number of versions in one jump, and never combine a large upgrade with unrelated changes in the same window. When something goes wrong, you want only one suspect.
18Rolling Restarts on Kubernetes
Containers make restarts easy to trigger and easy to get wrong. A few Kubernetes settings decide which.
On Kubernetes, Kafka brokers usually run as a StatefulSet, a kind of workload that gives each pod a stable name and its own persistent disk. When you change the pod definition, Kubernetes replaces pods one at a time, in reverse order. That is a rolling restart already. But by itself, it only waits for each pod to be ready. It does not know whether Kafka’s partitions are fully replicated.
The settings that matter
Readiness probe
Decides when Kubernetes thinks a pod is ready. A probe that only checks “the port is open” says ready far too early. A good probe reflects that the broker is registered and not far behind.
Termination grace period
How long Kubernetes waits after asking the pod to stop before killing it. It must be long enough for a controlled shutdown, which can be minutes on a big broker.
Pod disruption budget
A rule that limits how many pods may be down at once, protecting against other maintenance such as node drains. Set it to allow only one broker to be down.
Persistent volumes
Each broker keeps its own disk across restarts, so it only catches up on recent data, not everything.
Anti-affinity and zones
Spread pods across nodes and zones, so a single node or zone failure never takes down two brokers together.
Update strategy
Choose whether Kubernetes rolls pods automatically or waits for an operator to trigger each step.
Kubernetes on its own is a helpful assistant who replaces staff one by one but only checks that each new person has arrived at the door. It does not check whether they have learned the job. An operator that understands Kafka is a supervisor who asks, “is the new person fully up to speed before the next swap?”
Operators that understand Kafka
Kafka operators, such as those from the Strimzi project and commercial vendors, take over the restart order. A good one restarts brokers one at a time, checks that a restart will not push any partition below its minimum ISR before it acts, waits for replicas to catch up after each restart, and handles controllers before brokers. It can also decide which pods truly need a restart and skip the rest. For most teams running Kafka on Kubernetes, using an operator is the safest path.
Common Kubernetes traps
| Trap | What happens | Fix |
|---|---|---|
| Readiness too optimistic | Next pod restarts while replicas still catch up | Use a readiness check tied to replication health, or an operator |
| Short grace period | Controlled shutdown is cut short; crash recovery on start | Raise the grace period well above typical shutdown time |
| Node drain during a rolling update | Two brokers down at the same time | Pod disruption budget of one |
| Changing pod IP or DNS | Clients hold on to old addresses | Stable network names for each broker |
| Disk lost with pod | Broker restarts empty and must copy everything | Persistent volumes tied to each broker |
| Limits too tight | Out-of-memory kill counts as a crash | Right-size memory and leave room for the page cache |
19Automating Restarts on Servers and Virtual Machines
Outside Kubernetes, the loop is yours to build. The good news is that the logic is short and clear.
Most teams use a configuration or orchestration tool to run the loop across hosts. Whatever tool you use, it should do these things, in this order, for each broker.
Verify the pre-flight state
Ask the cluster whether any partition is under-replicated, under the minimum ISR, or offline. Stop if any is.
Stop the broker with a polite signal
Wait for the process to end on its own, with a long timeout. Do not force it unless the timeout truly runs out, and then treat that as a warning.
Apply the change
Install the patch, swap the software, or write the new configuration.
Start the broker and wait for registration
Poll until the controller lists it as registered, with a time limit.
Wait for replication to settle
Poll until under-replicated partitions reach zero. Set a generous maximum, and halt if it is exceeded.
Restore leadership balance
Trigger or wait for a preferred leader election so the restarted broker takes its fair share of work.
Pause, then check client health
A short settling delay, then look at client-facing metrics before continuing.
Design principles for the automation
Serial by default
One broker at a time, unless you have deliberately designed a zone-wide approach.
Fail closed
If any check errors out or gives a strange answer, stop. Never assume success.
Idempotent steps
Running a step twice must be safe, so a half-finished run can be restarted.
Human in the loop for surprises
The tool pauses and alerts a person rather than improvising.
Log everything
Record each step, time, and result. It builds trust and helps the next run.
Dry run mode
Let engineers preview what the tool would do before it does it.
Do not use fixed sleep timers as a replacement for checks. “Wait five minutes then continue” works on quiet days and fails on busy ones, precisely when the cluster most needs care. Always wait for a condition, with a timeout as the backstop.
20Draining Leadership Ahead of Time
Instead of letting the shutdown move leaders in a rush, you can move them out gently beforehand. It makes the actual stop almost invisible.
Controlled shutdown moves leadership at the moment of stopping. For brokers with a very large number of partitions, that can take a while and produces a burst of leader changes. A gentler approach is to drain the broker first: move leadership away from it in the background, while it is still healthy, in small batches. When you finally stop it, it leads nothing, so nothing has to move.
Before closing a shop for renovation, a manager first moves customers to the neighboring shop over a week, by transferring them gradually. When the shutters finally come down, nobody is inside.
How teams do it
Kafka’s tools can reassign partition leadership by changing the order of replicas or by running a preferred leader election after the order has changed. Cluster management tools such as Cruise Control offer a “demote broker” action that moves all leadership off a chosen broker in a controlled, throttled way, making it a follower only. After maintenance, the same tool can restore the balance.
| Approach | How it feels to clients | Extra effort |
|---|---|---|
| Controlled shutdown only | One burst of leader changes at stop time | None |
| Drain first, then stop | Small changes spread over a longer time | A demote step and a restore step |
| Drain and wait for quiet period | Almost invisible | Longest window |
Draining is most useful on large brokers, on brokers that serve latency-sensitive topics, and on clusters where you want extra caution. For small clusters, controlled shutdown alone is usually enough.
21Timing, Catch-Up Math, and the Page Cache
How long should each step take? A little arithmetic turns guesswork into a schedule.
How long will catch-up take?
When a broker returns, it must fetch everything that was written while it was away. The amount depends on the rate of new data and the length of the outage. Consider a broker that holds copies of partitions receiving 30 MB per second in total. If it is down for 10 minutes, that is 600 seconds times 30 MB, or about 18 GB of data to catch up. If the broker can replicate at 200 MB per second while still handling normal traffic, catching up takes about 90 seconds. If its share is bigger, or the network is slower, the time grows in proportion.
The lesson: the faster the restart itself, the less there is to catch up. Patching that takes 30 minutes means 54 GB to catch up in the same example. Do slow work such as long file operations before stopping the broker, and keep the stopped time short.
The cold cache problem
Kafka leans on the operating system’s page cache, memory that keeps recently used file data. Consumers reading recent messages are served straight from memory, which is very fast. After a restart, or a reboot of the machine, that cache is empty. Reads must go to the disk until the cache warms up. If a restarted broker immediately becomes leader for many partitions, consumers reading through it may see slower responses for a while.
A librarian who keeps the most requested books on the desk can answer instantly. After a night away, the desk is bare, and every request means a walk to the shelves. The first hour is slower, until the desk fills up again.
This is one more reason to avoid rebooting whole machines when a process restart would do, and to give the cache a little time to warm up before you restart the next broker.
Throttling the catch-up
Catch-up traffic competes with client traffic. A broker fetching 18 GB at full speed can saturate the network and slow everyone. Kafka lets you limit replication bandwidth so that catch-up runs at a gentle speed. The trade-off is that the cluster stays in the reduced-safety state for longer. Choose the rate based on how much headroom you have.
| Choice | Effect on clients | Time in reduced-safety state |
|---|---|---|
| No throttle | Possible slowdown during catch-up | Shortest |
| Moderate throttle | Small effect | Moderate |
| Strict throttle | Almost none | Longest |
22Monitoring During the Window
A rolling restart is a live operation. Watch the right dashboards, and you will see trouble before your users do.
Cluster health signals
| Signal | What it tells you | During a restart |
|---|---|---|
| Under-replicated partitions | Partitions missing an in-sync copy | Rises when a broker stops; must fall to zero before the next |
| Under-minimum-ISR partitions | Partitions refusing safe writes | Must stay at zero |
| Offline partitions | Partitions with no leader | Must stay at zero |
| Active controller count | Number of active controllers | Exactly one, except for a moment during controller election |
| ISR shrink and expand rates | Replicas leaving and rejoining | A burst is normal; sustained churn is not |
| Leader count per broker | Balance of leadership | Returns to even after the restart |
| Request handler idle percentage | How busy each broker is | Remaining brokers get busier; watch for saturation |
Client-facing signals
Error and retry rate
A small rise in retries is expected. Errors that reach the application are not.
Send latency
Watch the slowest one percent, not just the average.
Consumer lag
Should rise slightly and drain again quickly.
Rebalance count
Frequent rebalances mean timeouts are too tight.
End-to-end check
A small canary that writes and reads a test message every few seconds, measuring the round trip.
Network, disk, and CPU
Catch-up puts heavy load on all three of the remaining brokers.
Build a single dashboard for maintenance windows that shows only these signals, with your abort thresholds drawn on the charts. During the window, nobody should have to hunt for the right graph.
23Failure Scenarios and Recovery
Sooner or later a restart will not go to plan. Knowing the common failures in advance turns a crisis into a checklist.
The broker does not come back
The process fails to start, or starts and crashes. Common causes: a bad configuration edit, a wrong file permission, a full disk, a missing certificate, or a Java version mismatch. Response: stop the loop immediately. The cluster is now one broker down, which is safe, but you have no more spare. Read the broker log, fix or roll back the change, and start again. Do not touch another broker until this one is back.
Log recovery takes forever
The broker was not stopped cleanly, and now scans terabytes of segments. It may take many minutes with no client service. Response: be patient, and do not kill it again, since that restarts the scan. Next time, give brokers a longer stop timeout, and consider more recovery threads per data directory.
Replication never finishes
Under-replicated partitions do not fall to zero. Possible causes: the network between brokers is saturated, a replication throttle is too strict, the disk is slow, or a single huge partition takes forever to copy. Response: find which partitions are behind, look at network and disk use, and adjust the throttle. Halt further restarts.
A second broker fails mid-window
An unrelated failure hits while one broker is already down. Now two brokers are missing, and some partitions may be below minimum ISR, so writes to them stop. Response: bring back the broker you restarted first, since it is your planned one, or the failed one, whichever returns fastest. Do not restart anything else. This is the scenario that justifies pre-flight checks and a short window.
A partition goes offline
All replicas of a partition are down at the same time, often because it had too few copies. Clients cannot read or write it. Response: restore the broker that holds the last in-sync copy. By default Kafka refuses to promote an out-of-sync replica because that could lose data. Allowing it is a last resort that trades data safety for availability.
Clients keep failing after the restart
Brokers are healthy, yet some clients throw errors. Possible causes: clients pinned to a specific address that no longer works, stale DNS caches, a client library with a bug, or security settings that changed. Response: compare a failing client with a healthy one, check the addresses the brokers advertise, and confirm certificates are valid.
The recovery mindset
Stop making changes
Pause the loop. More changes make problems harder to understand.
Restore redundancy first
Get every broker running and in sync. Redundancy is your safety net.
Find the cause
Read logs and metrics calmly. Compare with a healthy broker.
Decide: fix forward or roll back
If the fix is clear and quick, apply it. If not, restore the previous version or settings.
Write it up
Record what happened, and update the runbook and checks so it cannot surprise you again.
24Troubleshooting by Symptom
A quick lookup table for the situations you will most often meet during a window.
| Symptom | Likely cause | First thing to check |
|---|---|---|
| Producers get “not enough replicas” errors | ISR fell below the minimum: a second broker is down or lagging | Which brokers are missing; under-replicated partitions |
| Producers see timeouts | Leader election taking long, or the delivery timeout is too short | Delivery timeout; number of partitions being moved |
| Consumers stop for a while | Group rebalance triggered by coordinator move | Session timeout; rebalance type |
| Consumer lag keeps growing | Cold cache or heavy catch-up traffic | Disk reads; replication throttle |
| Broker stuck starting | Log recovery after unclean stop | Broker log for recovery progress |
| Under-replicated partitions will not clear | Slow catch-up or a stuck replica | Network, disk, throttle, and specific partitions |
| Leadership stays skewed | Automatic preferred election is off or waiting | Trigger the preferred election manually |
| Some clients cannot connect | Wrong advertised address, expired certificate | Advertised listeners; certificate dates |
| Two controllers appear active | Rare election glitch or misconfiguration | Controller quorum status and logs |
| Disk fills on a peer broker | Extra load from taking over leadership | Retention settings; headroom before next step |
Print this table and your abort thresholds and keep them next to the runbook. In the middle of a window, it is easy to forget what “normal” looked like an hour ago.
25Security During Maintenance
Maintenance windows are also when security slips. Keep the walls up while the brokers come and go.
Limit who can run the restart
Only named people or automation accounts may stop brokers. Log every action with the person and time.
Review changes before applying
Have a second person check configuration changes. A typo in a security setting can open a door or lock everyone out.
Check certificate dates first
A broker that restarts with an expired certificate will not accept clients. Verify dates for every broker before the window.
Do not leave secrets in scripts
Automation should read passwords and keys from a secrets store at run time, not from files kept in shared folders.
Keep firewalls and listeners as they were
Temporary “just to make it work” openings often become permanent.
Keep the trail
Record what changed on each broker, so auditors and future you can reconstruct it.
Security upgrades as restarts
Rolling restarts are often driven by security work, for example moving to a stronger encryption setting or a new login method. Add new options first and let clients adopt them while the old ones still work. Once every client has moved, remove the old option in a later window. This two-step pattern avoids locking out applications that are slower to change.
When a building changes its door locks, the caretaker first installs a second lock, hands out new keys to everyone, and gives residents a few weeks. Only then is the old lock removed. Nobody is locked out on the day of the change.
26When Rolling Is Not Enough: Cluster-Level Fallbacks
Some changes cannot be rolled through a single cluster. For those, you need another cluster to stand in.
Certain big changes, such as moving to a different storage layout, changing the number of controller nodes, or swapping very old infrastructure, are safer or only possible with a second cluster. The idea is simple: build the new cluster next to the old one, copy data across, move applications over gradually, and retire the old one.
Build the new cluster
With the settings and version you want, sized for the load.
Mirror the data
Use a replication tool such as MirrorMaker to copy topics, settings, and consumer positions continuously.
Move consumers, then producers
Move readers first, then writers, group by group, checking after each move.
Retire the old cluster
When nothing uses it, shut it down. Keep backups for a while.
Disaster recovery as a safety net
If your business cannot tolerate even a small risk during a major upgrade, a standby cluster in another place gives you a way out. If the upgrade goes badly, you switch applications to the standby, which is on the old version. It costs more, and it is the strongest insurance available.
| Approach | Best for | Cost | Risk |
|---|---|---|---|
| Rolling restart in place | Patches, most upgrades, most config changes | Low | Low with good practice |
| Blue-green with mirrored cluster | Major changes and infrastructure moves | High while both run | Low, easy rollback |
| Maintenance window with downtime | Rare structural changes; small non-critical clusters | Lowest | Known outage |
27Advantages, Disadvantages, and Trade-offs
Rolling restarts are the standard, and for good reason. Still, an honest look at both sides helps you plan.
Advantages
- The cluster stays available for reads and writes throughout
- No data loss when replication and acks are set correctly
- Patching can happen on a regular schedule, keeping systems secure
- Each step is small and reversible
- Practice makes maintenance routine and boring
- Works with the same tools for restarts, patches, and upgrades
Disadvantages
- Slow: a big cluster takes hours, one broker at a time
- Reduced fault tolerance during each step
- Remaining brokers carry extra load
- Requires healthy pre-conditions and disciplined automation
- Cold caches and catch-up traffic cause small latency bumps
- Not suitable for every kind of change
The core trade-offs
Speed versus safety
Restarting a zone at a time is fast but needs more spare capacity. One broker at a time is slow but gentle.
Drain first versus straight stop
Draining is smoother for clients and adds steps. Straight stop is simple but bursts.
Strict versus relaxed throttle
A strict throttle protects clients and lengthens the risky period.
Automation versus judgment
Automation is consistent and quick, but a person should decide when it meets a surprise.
More replicas versus cost
Higher replication factors give more room for maintenance and cost more disk.
Frequent small windows versus rare large ones
Small, regular changes are safer than infrequent big jumps.
28Design Patterns and Anti-Patterns
Shapes that work, and shapes that look fine until the day you need to restart.
Patterns worth copying
Replication three, minimum ISR two
The standard foundation for rolling maintenance.
Gate on replication health
The next broker starts only when under-replicated partitions equal zero.
Rack-aware placement
Replicas spread across zones, enabling zone-wide restarts and surviving zone loss.
Static membership plus cooperative rebalancing
Consumers ride through restarts of themselves and of brokers.
Canary client
A tiny end-to-end probe measures what real users would feel.
Regular restart schedule
Monthly or weekly rolls keep the process practiced and the cluster patched.
Anti-patterns to avoid
What it looks like
Restarting the next broker on a timer, without checking replication health.
Why it hurts
On a busy day, catch-up is slower than the timer, and two brokers end up out of sync at once. Writes stop or data is put at risk.
Better approach
Wait for a condition, under-replicated partitions equal to zero, and use a timeout only as a backstop.
What it looks like
Killing brokers with a hard stop to save time.
Why it hurts
Leaders vanish suddenly, clients see errors, and the broker needs a slow log recovery on the way back.
Better approach
Use a polite stop with a generous timeout so controlled shutdown completes.
What it looks like
Topics with a replication factor of one, or a minimum ISR equal to the replication factor.
Why it hurts
Every restart is an outage for those topics, whatever you do.
Better approach
Audit topic settings on a schedule, and fix them before maintenance.
What it looks like
Only one bootstrap address in client settings.
Why it hurts
When that broker is down, new clients cannot start at all.
Better approach
List several brokers, or a stable name that reaches any healthy broker.
What it looks like
Doing a restart for the first time during an emergency.
Why it hurts
Unpracticed steps, unknown timings, and no baseline mean small problems grow.
Better approach
Roll the cluster regularly, in calm times, so the process is familiar.
29Best Practices and Common Mistakes
A short list of habits that separate calm maintenance windows from stressful ones.
Best practices
Check the cluster is healthy first
Start only when every broker is up, no partitions are under-replicated, and no other change is in progress.
Audit topic settings
Find topics with a replication factor of one or a minimum ISR equal to the replication factor. Fix them before the window.
Tell the people who depend on you
Application teams should know when a window happens and what small blips to expect.
One failure domain at a time
One broker, or one zone if placement allows it. Never two overlapping.
Wait for a condition, not a clock
The gate is “all partitions fully in sync”, with a timeout only as a backstop.
Use a polite stop
Give the broker time to finish controlled shutdown before any forceful step.
Watch client-side signals
Broker metrics show cause. Client error rates and latency show what people feel.
Restore leadership balance
Run a preferred leader election so load is spread evenly again.
Review and improve
Note the total time, the slowest broker, and any surprises. Update the runbook.
Common mistakes
| Mistake | What goes wrong | Do this instead |
|---|---|---|
| Restarting two brokers at once “to save time” | Some partitions lose two of three copies and stop accepting writes | Serial restarts, or one whole zone with rack-aware placement |
| Changing many things in one window | When something breaks, nobody knows which change caused it | One kind of change per window |
| Ignoring client settings | Producers give up during a normal leader move | Set generous delivery timeouts and retries, with idempotence on |
| Skipping the pre-flight check | Starting with a hidden problem and making it worse | Automate the checks and refuse to start if they fail |
| Using a very short stop timeout | The process is killed halfway through controlled shutdown | Allow several minutes for large brokers |
| Running the window at peak traffic | Less spare capacity, slower catch-up, more visible blips | Pick a quiet period, and know your traffic pattern |
| No rollback plan | A bad version or setting stays on the cluster | Keep the old package and old settings ready, and decide the abort rule ahead of time |
| Forgetting the metadata quorum nodes | Losing a controller majority freezes changes to the cluster | Restart controllers one at a time and confirm quorum in between |
| Never practicing | The first real attempt is during an emergency | Roll the cluster on a regular schedule |
The most expensive mistake is not a technical one. It is rushing. Every serious restart incident starts with someone deciding that waiting five more minutes was not worth it.
30Testing and Game Days
You do not know whether your cluster can survive a restart until you try it, in a place where a mistake costs nothing.
A game day is a planned practice session. The team gathers, chooses a failure or a maintenance step, runs it on a test cluster or, with care, in production, and watches what happens. The goal is not to pass. The goal is to learn what breaks while everyone is calm and ready.
A school holds fire drills so that nobody has to work out the exit route while the alarm is real. A game day is a fire drill for your cluster.
What to test
A clean rolling restart on a staging cluster
Load the cluster with realistic traffic, including a canary client, and run the full loop. Record total time, error rates, latency, and the time for replication to recover after each broker. This gives you a baseline to compare against in production.
A hard kill of one broker
Stop a broker abruptly, as a crash or power loss would. Observe how long clients see errors, how long recovery takes when it returns, and whether alerts fire as expected. This shows the difference between a polite stop and a crash.
A failure during a restart
Restart one broker, and while it is down, stop a second one. Confirm that producers with strict settings stop rather than lose data, and that recovery works once the second broker returns. This tests your abort rules and your pager.
A zone loss
Turn off all brokers in one zone at once. If placement is right, the cluster keeps serving. If not, you find the topics that were not spread properly.
A client-only test
Restart brokers while a set of your real application versions runs against them in a test environment. Old client libraries and unusual settings show up quickly.
How to run a good game day
Write a hypothesis
For example: “Clients will see no errors and the lag will stay under one minute.”
Agree the stop button
Decide in advance which signals end the test, and who has the power to call it.
Run and watch
One person runs the steps. Others watch dashboards and note times.
Compare with the hypothesis
Where reality differed, that is a finding.
Fix and repeat
Change settings or the runbook, then run it again to confirm the fix.
31A Runbook You Can Adapt
A runbook is a checklist that a tired person can follow at night. Here is a shape you can copy and shorten to fit your cluster.
Before the window
Announce
Post the time, expected duration, and contact person to the teams that use the cluster.
Verify health
All brokers up. Under-replicated partitions at zero. Offline partitions at zero. Disk space above your threshold. No reassignment running.
Audit topics
No topic with replication factor of one. Minimum ISR is below the replication factor everywhere.
Stage the change
Packages or configuration files are already on each machine. Previous versions kept for rollback.
Confirm the on-call person
Someone with authority is reachable for the whole window.
For each broker
Gate: healthy
Confirm under-replicated partitions are zero.
Optional: move leaders away
Drain leadership if your clients are sensitive to bursts.
Stop politely
Send a normal stop, and wait for controlled shutdown to finish.
Apply the change
Install the new package or edit the configuration.
Start and watch the log
Look for recovery messages and errors.
Gate: caught up
Wait until the broker rejoins every in-sync list and under-replicated partitions return to zero.
Check the client view
Canary healthy, error rates normal, lag not growing.
After the window
Rebalance leadership
Run a preferred election, and confirm each broker leads roughly its fair share.
Verify versions and settings
Every broker reports the expected version and configuration.
Announce completion
Tell the teams it is done, and mention anything unusual.
Record the results
Duration per broker, alerts fired, surprises, and follow-up tasks.
Write abort rules directly into the runbook, in plain numbers. For example: “If under-replicated partitions are not zero after thirty minutes, stop and call the lead.” A rule written in calm hours is easier to obey in stressful ones.
32A Worked Example from Start to Finish
Let us follow a made-up company through one full window, so the pieces click together.
Imagine an online bookshop called PageTurn. It runs a nine-broker Kafka cluster spread over three zones, with three brokers in each zone. Every important topic has a replication factor of three and a minimum ISR of two. Producers use acknowledgement from all in-sync replicas with idempotence on. Consumers use static membership and cooperative rebalancing. A tiny canary program writes and reads a message every second and reports the delay.
The team needs to apply a security patch to the operating system, which requires a reboot of every machine. They choose a Tuesday morning, when orders are at their daily low.
09:00, announce and check
The lead posts the plan. Pre-flight checks pass: nine brokers up, no under-replicated partitions, disks about half full.
09:10, first broker
Broker 1 in zone A is stopped politely. Controlled shutdown moves its leaders in a few seconds. The canary shows a one-second bump and returns to normal.
09:14, machine returns
The machine reboots and the broker starts. It replays a short piece of its log and begins copying what it missed while it was away.
09:19, gate passes
Under-replicated partitions fall to zero. The automation moves on to broker 2 in the same zone.
10:05, zone A complete
All three brokers in zone A are done. The team pauses, checks the dashboards, and sees a small rise in latency that has already settled.
10:10, a surprise
In zone B, broker 5 takes twenty-five minutes to catch up, much longer than the others. The gate holds, and nothing proceeds. An engineer finds a very large partition with a bursty producer. The team waits it out rather than forcing the next step.
12:30, all done
Zones B and C finish without further trouble. A preferred leader election balances leadership. Version and settings checks pass.
12:45, review
The team writes down the slow broker, decides to split the huge partition’s topic into more partitions later, and adds a “large partition” check to the pre-flight list.
Nothing here was heroic. The safety came from settings chosen months earlier, gates that refused to hurry, and a team that treated a slow broker as a reason to wait rather than a reason to push.
33Real-World Usage Patterns
How different kinds of teams tend to organize this work in practice.
A careful script and a checklist
A handful of brokers, a script that runs the loop with gates, and a person watching. Simple and reliable.
Automation as a service
A pipeline runs weekly patch windows across many clusters. Health checks and abort rules are built in, and humans handle exceptions.
Operators and disruption budgets
An operator restarts pods in a safe order, guarded by budgets and readiness checks that reflect replication health.
Change records and approvals
Every window is scheduled, reviewed, and logged. Rollback steps are rehearsed. A standby cluster covers major changes.
The provider rolls, you prepare clients
The provider restarts brokers. Your job is to make sure clients tolerate leader moves and retries.
Continuous, staggered rolling
Some machines are always being patched. The process is so routine that no one announces it, because the cluster is built to absorb it.
Different as they look, all of these share the same three ideas: keep enough copies, move one failure domain at a time, and let the cluster’s health, not a timer, decide when to continue.
34Quick Glossary
Plain-language reminders of the words used throughout this guide.
| Term | Meaning |
|---|---|
| Broker | One Kafka server that stores partitions and serves clients. |
| Partition | One ordered slice of a topic, stored as a log on disk. |
| Leader | The copy of a partition that handles reads and writes. |
| Follower | A copy that keeps up with the leader and can take over. |
| ISR (in-sync replicas) | The list of copies that are fully caught up. |
| Replication factor | How many copies of each partition exist. |
| Minimum ISR | The smallest number of in-sync copies needed to accept a write. |
| Acks | How many copies must confirm before a producer counts a write as done. |
| Controlled shutdown | A polite stop where the broker hands off its leadership first. |
| Under-replicated partition | A partition with fewer in-sync copies than it should have. |
| Offline partition | A partition with no available leader, so clients cannot use it. |
| Preferred leader | The first replica in a partition’s list, chosen to spread load evenly. |
| Controller | The part of the cluster that tracks metadata and decides leaders. |
| Rack awareness | Placing copies in different zones so one zone loss is survivable. |
| Rebalance | Consumers in a group redistributing partitions among themselves. |
| Static membership | A consumer keeping its identity across a short restart. |
| Log recovery | Checking data files on start-up after an unclean stop. |
| Page cache | Memory the operating system uses to keep recently used disk data. |
| Throttle | A cap on replication speed to protect client traffic. |
| Canary | A tiny test client that measures what real users would feel. |
35Frequently Asked Questions
Short, direct answers to the questions people ask most often.
36Summary and Key Takeaways
Everything above fits on one page in your head.
A rolling restart works because Kafka keeps several copies of every partition. When one broker leaves politely, its leadership moves to a copy on another broker within moments. When it returns, it catches up from those copies and rejoins the in-sync list. Do this for one failure domain at a time, and let the cluster’s own health decide when to take the next step, and the service never stops.
Key Takeaways
- Safety is set months before the window. Replication factor three, minimum ISR two, and acknowledgement from all in-sync copies are the foundation.
- Stop politely. Controlled shutdown hands off leaders first and avoids slow log recovery on the way back.
- Gate on health, not on time. The next broker starts only when under-replicated partitions return to zero.
- Prepare the clients. Idempotent producers with patient timeouts, and consumers with static membership and cooperative rebalancing, make leader moves invisible.
- Use placement and capacity wisely. Rack-aware replicas allow zone-wide steps, and spare capacity keeps the surviving brokers comfortable.
- Skip restarts when you can. Dynamic configuration changes need none, and every avoided restart is an avoided risk.
- Watch, rehearse, and write it down. Client-side canaries, game days, abort rules, and a living runbook turn maintenance into a routine.