Rack Awareness in Kafka

Rack Awareness in Kafka

A plain-English deep dive into how Kafka spreads copies of your data across racks, zones, and data centers so one physical failure never takes your data down, how consumers can read from the nearest copy, and how to design, operate, and troubleshoot it in production.

Imagine you run a small chain of libraries and you own one precious book that cannot be replaced. You decide to keep three copies for safety. But you put all three copies on the same shelf, in the same room, in the same building. Then one night a pipe bursts in that room, and all three copies are ruined together. You had three copies, yet you were no safer than with one, because all the copies shared the same weak point. A smarter plan is to place one copy in each of three different buildings across the city. Now a burst pipe, a fire, or a power cut in one building still leaves two healthy copies elsewhere.

That smarter plan is exactly what rack awareness does for Apache Kafka. Kafka keeps several copies of every piece of data, but by default it does not know where the servers physically sit. Rack awareness teaches Kafka about the physical or logical locations of its servers, so it can place the copies far apart from each other and, in addition, let readers pick the nearest copy to save time and money. This guide starts from zero and builds up to production-grade design, operations, and troubleshooting.

1Why Kafka Copies Data and Why Location Matters

Before learning the feature, understand the problem: copies are only useful when they do not fail together.

Apache Kafka is a platform that stores and moves streams of messages. A message is called a record. Records are grouped into named streams called topics. Each topic is split into smaller pieces called partitions, and each partition is an ordered log of records. A server that stores partitions is called a broker, and a group of brokers working together is called a cluster.

Servers break. Disks fail, machines crash, and networks drop. To survive this, Kafka keeps multiple copies of every partition. Each copy is called a replica. The number of copies is the replication factor. If the replication factor is three, then every partition exists on three different brokers. One replica acts as the leader, which handles all writes and, by default, all reads. The others are followers, which continuously copy the leader’s data.

Term 1

Partition

One ordered slice of a topic. Partitions let a topic spread across many brokers so it can grow beyond one machine.

Term 2

Replica

One copy of a partition stored on one broker. A partition with replication factor three has three replicas.

Term 3

Leader

The single replica that accepts writes for a partition. Producers always talk to the leader.

Term 4

Follower

A replica that copies data from the leader and is ready to take over if the leader disappears.

Term 5

In-Sync Replicas

The set of replicas that are fully caught up with the leader. Only members of this set are eligible to become the new leader safely.

Term 6

Failure Domain

A group of machines that can fail together, such as a rack, a power circuit, a room, or a cloud availability zone.

Simple Analogy

Think of a school that keeps three photocopies of every exam paper in case one is lost. If all three sit in the same drawer and the drawer is stolen, the copies were pointless. Copies are only a real safety net when they are stored in different places that will not be lost together.

The central idea is failure domains. Machines do not fail independently in real life. Servers in the same rack share the same power strip and the same network switch. Servers in the same room share cooling. Servers in the same cloud availability zone share the same data center building. If Kafka places all replicas of one partition in the same failure domain, a single event can remove every copy at once, and the partition becomes unavailable or, in the worst case, data is lost. Rack awareness is how you tell Kafka about these failure domains so that it can avoid this trap.

i
Remember

Replication protects you from a machine failing. Rack awareness protects you from a group of machines failing together. You need both to be truly safe.

2What Rack Awareness Actually Is

The word “rack” is a historical name. In practice it means any failure domain you choose to model.

In the early days of big data clusters, machines were literally stacked in metal cabinets called racks. A rack usually had one power feed and one top-of-rack network switch. When either failed, every machine in that rack went dark together. Engineers therefore taught their systems to place copies across different racks. The name stuck, even though modern clusters run in the cloud where there are no racks you can touch.

In Kafka, rack awareness is a feature in which each broker declares a label describing where it lives, and Kafka uses that label in two places. First, when placing replicas, Kafka spreads the copies of each partition across as many different labels as possible. Second, when consumers read data, Kafka can steer them toward a replica that has the same label as the consumer, so data does not have to travel far.

flowchart TB
    subgraph R1["Rack or Zone A"]
        B1["Broker 1"]
        B2["Broker 2"]
    end
    subgraph R2["Rack or Zone B"]
        B3["Broker 3"]
        B4["Broker 4"]
    end
    subgraph R3["Rack or Zone C"]
        B5["Broker 5"]
        B6["Broker 6"]
    end
    P["Partition 0 with replication factor 3"] --> B1
    P --> B3
    P --> B5
        
FIG 1 — One partition with its three replicas placed in three different racks

What a rack can represent

A physical rack in your own data center

The original meaning. Machines sharing one power distribution unit and one switch form one label.

A cloud availability zone

The most common modern meaning. An availability zone is an isolated data center building inside a cloud region. Using the zone name as the rack label protects against a whole building failing.

A room, a floor, or a data center

Organizations with several rooms or sites can label brokers by room or by site to survive larger failures, at the cost of more network distance between replicas.

A power or network group

Even inside one building, machines behind different power feeds or different switches can be labeled separately to survive smaller failures.

Simple Analogy

Rack labels are like the colored stickers a warehouse manager puts on shelves: red for building one, blue for building two, green for building three. When storing three copies of a valuable item, the manager makes sure the copies get three different colors. The stickers themselves do nothing, but they let the manager follow a simple rule.

!
Common Misconception

The rack label is only a name that you provide. Kafka does not check whether it is true. If you label two machines from the same physical rack with different names, Kafka will happily trust you and place replicas on both, defeating the purpose.

3The Two Halves of Rack Awareness

Rack awareness in Kafka has two separate uses that solve two separate problems. Keeping them apart avoids a lot of confusion.

AspectRack-Aware Replica PlacementRack-Aware Consumer Reads
Main goalAvailability and durabilityLower network cost and latency
Who makes the decisionBroker and admin tools, when creating or moving partitionsBroker replica selector, when a consumer fetches
What it needsA rack label on every brokerA rack label on brokers and on the consumer, plus a selector setting
Enabled by default when labels existYesNo, must be turned on deliberately
IntroducedEarly Kafka versionsKafka 2.4 and later
Effect on the write pathReplicas are spread out, so replication may cross rack boundariesNone, producers still write to leaders
1

Placement decides where copies live

When a topic is created or partitions are moved, Kafka looks at the rack labels and spreads the replicas of each partition across different racks.

2

Failure happens

A rack loses power. Because copies were spread out, every affected partition still has replicas alive in other racks, and new leaders are elected there.

3

Reads can use the nearest copy

Separately, consumers can be allowed to read from a follower in their own rack instead of always crossing to the leader in another rack.

i
Key Insight

Placement is about surviving failures and is essentially free. Nearest-replica reading is about saving money and time and comes with a small trade-off in freshness. Many teams adopt the first immediately and the second only after measuring the network bill.

4How Replica Placement Uses Rack Labels

The placement logic is simple to describe: interleave the racks, then deal out replicas round by round.

Every broker can be given a rack label in its configuration. When a new topic is created without an explicit placement, the cluster runs a placement routine. If all brokers have labels, the routine builds an ordered list of brokers in which the racks are alternated. It takes one broker from the first rack, one from the second, one from the third, then goes back to the first rack for the next broker, and continues in this way. The result is a list where neighbors tend to belong to different racks.

The routine then walks through the partitions. For each partition it picks a starting position in the alternating list and selects the required number of consecutive brokers as the replicas. Because neighbors are usually from different racks, the replicas of one partition naturally land in different racks. The starting position moves forward for each new partition, so the load of leaders and followers is spread evenly across brokers as well.

flowchart LR
    A["Brokers grouped by rack label"] --> B["Alternate racks to build an interleaved broker list"]
    B --> C["For each partition pick a starting spot in the list"]
    C --> D["Take the next replication-factor brokers as replicas"]
    D --> E["Replicas land in different racks whenever possible"]
    E --> F["Shift the starting spot for the next partition to balance load"]
        
FIG 2 — The idea behind rack-aware replica assignment

What happens when there are more replicas than racks

Suppose you have three racks and a replication factor of five. Five copies cannot each sit in a unique rack. Kafka then spreads them as evenly as it can, so two racks hold two replicas each and one rack holds one. The rule is best effort: use as many distinct racks as possible, and when racks run out, reuse them as evenly as possible.

What happens when racks are unequal in size

If one rack has ten brokers and another has only two, the alternating pattern still gives each partition a replica in each rack, but the two small-rack brokers must carry a replica of a very large share of all partitions. They become overloaded in storage and traffic, while the big rack brokers are underused. Rack awareness ensures safety, but it can create imbalance when racks are lopsided. The remedy is to keep racks roughly equal in broker count.

Simple Analogy

Imagine dealing playing cards to players sitting at three tables, insisting that each player group gets one card from each table. If one table has only two people and another has ten, those two people end up holding cards from every single deal, while the ten people share very little. The rule is followed, but the workload is uneven.

!
All or Nothing

Rack labels must be set on every broker or on none of them. If only some brokers have labels, the placement routine cannot build a consistent plan and topic creation fails with an error, unless the administrator explicitly tells the tool to ignore rack information. Always label the whole cluster together.

5Setting Up the Broker Rack Label

The whole feature starts with one small configuration value on every broker.

Each broker has a setting that holds its rack label. It is a plain text value, such as the name of an availability zone or a rack identifier. The value is read when the broker starts and is registered with the cluster’s metadata, so every other component can learn it. Changing a rack label requires restarting that broker, because the label is part of its static identity.

Where

Broker configuration file

Each broker’s main properties file carries its rack label. Every broker must have its own correct value.

Format

Plain text label

Any short, stable string. Choose names that clearly map to real failure domains and never change them casually.

Change

Needs a restart

The label cannot be changed on a running broker. Plan a rolling restart, and remember that changing a label does not move existing replicas.

Visibility

Shown in cluster metadata

Administrative tools that describe the cluster can show each broker’s rack, which is the easiest way to verify the setup.

Choosing good labels

Pick labels that correspond exactly to the failure domain you want to survive. In a cloud region with three availability zones, use the zone names. In your own data center, use a label per rack or per power group. Avoid labels that are too fine, such as one label per machine, because then Kafka would believe every machine is its own failure domain and rack awareness would give no benefit beyond ordinary replication. Avoid labels that are too coarse, such as one label for the entire cluster, because then no separation happens at all.

1

List your failure domains

Decide what you want to survive: a rack, a power circuit, a building, or a whole site. This choice sets the meaning of the label.

2

Map every broker to one domain

Produce a simple table of broker identifier against label. Verify it with the infrastructure team, since Kafka will trust it blindly.

3

Apply the labels through automation

Generate the label from a trusted source such as the cloud metadata service or the orchestration platform, rather than typing it by hand.

4

Roll out and verify

Restart brokers one at a time, then describe the cluster and confirm that each broker reports the intended label.

i
Automation Tip

In the cloud, read the zone from the instance’s own metadata at startup instead of hardcoding it. This prevents the classic mistake of copying a configuration file to a machine in another zone and forgetting to edit the label.

6Availability Math: What Rack Awareness Buys You

Numbers make the benefit concrete. The right combination of racks, replication factor, and minimum in-sync replicas decides how much failure you can survive.

Two topic settings interact with rack awareness. The replication factor says how many copies exist. The minimum in-sync replicas setting says how many copies must be up to date and reachable before Kafka accepts a write when the producer requests full acknowledgment. Together they define the balance between availability and durability.

3 copies
typical replication factor for production
2 in sync
typical minimum in-sync replicas
3 racks
one replica in each rack
DesignSurvives one rack lossWrites continue after one rack lossComment
Three copies, three racks, minimum in-sync twoYes, no data lossYes, two copies remainThe standard recommendation
Three copies, two racks, minimum in-sync twoData survives, but one rack holds two copiesDepends on which rack fails; losing the double rack stops writesUneven and risky
Three copies, three racks, minimum in-sync threeYesNo, writes stop until the rack returnsMaximum durability, lower availability
Two copies, two racks, minimum in-sync twoYesNo, writes stopCannot tolerate any loss and keep writing
Three copies, no rack awarenessNot guaranteedNot guaranteedCopies may share one failure domain
Simple Analogy

A bank vault needs two of three keyholders present to open. If the three keyholders live in three different cities, a storm in one city still leaves two who can act. If two of them live in the same city, one storm can lock the vault. Rack awareness makes sure the keyholders are in different cities.

The rule of thumb

Choose a replication factor equal to the number of racks or zones you want to span, commonly three. Set the minimum in-sync replicas to one less than the replication factor, commonly two. With producers that require full acknowledgment, this combination survives the loss of a whole rack without losing acknowledged data and without stopping writes.

!
Dangerous Setting

Allowing an out-of-sync replica to become leader, known as unclean leader election, can restore availability faster but may permanently lose acknowledged records. Rack awareness does not remove this trade-off. Keep it disabled for important data.

7Following a Rack Failure Step by Step

Watching a failure unfold shows why every earlier choice matters.

sequenceDiagram
    participant P as Producer
    participant L as Leader in Rack A
    participant F1 as Follower in Rack B
    participant F2 as Follower in Rack C
    participant C as Cluster Controller
    P->>L: Write record
    L->>F1: Replicate
    L->>F2: Replicate
    F1-->>L: Acknowledged
    F2-->>L: Acknowledged
    L-->>P: Write confirmed
    Note over L: Rack A loses power
    C->>C: Detects leader is gone
    C->>F1: Elected as new leader from in-sync replicas
    P->>F1: Producer retries after metadata refresh
    F1->>F2: Replicate
    F1-->>P: Write confirmed
        
FIG 3 — A leader’s rack fails and a follower in another rack takes over
1

Normal operation

The leader in one rack receives writes and replicates them to followers in two other racks. Everything is in sync.

2

The rack disappears

Power or network fails for the whole rack. Every broker in it stops responding at almost the same moment.

3

Detection

The cluster’s controller notices that those brokers stopped sending heartbeats and marks them as gone after a short timeout.

4

Leader election

For every partition that had its leader in the lost rack, the controller promotes an in-sync follower from a surviving rack.

5

Clients adapt

Producers and consumers refresh their metadata, discover the new leaders, and continue after a brief pause.

6

Recovery

When the rack returns, its brokers catch up from the current leaders, rejoin the in-sync sets, and later leadership can be moved back to balance the load.

i
Practical Lesson

The pause clients see during failover depends on detection timeouts, the number of partitions that need new leaders, and client retry settings. Rack awareness makes failover possible, while tuning makes it fast.

!
Capacity Warning

After losing one of three racks, the two surviving racks must carry the whole load. If your brokers were running above about two thirds of their capacity, the survivors may be overwhelmed. Plan capacity for the failure case, not just for the normal case.

8The Hidden Cost: Cross-Zone Network Traffic

Spreading replicas across zones is safe, but in the cloud it turns internal traffic into billable traffic.

Most cloud providers charge for data that moves between availability zones inside the same region, while data that stays within one zone is free or much cheaper. When Kafka replicates across three zones, every record a producer writes is copied to two other zones. When consumers read from leaders located in other zones, those reads cross zones as well. For a busy cluster moving many megabytes per second, this becomes one of the largest line items in the bill.

flowchart LR
    subgraph ZA["Zone A"]
        PR["Producer"]
        LD["Leader"]
    end
    subgraph ZB["Zone B"]
        FB["Follower"]
        CB["Consumer"]
    end
    subgraph ZC["Zone C"]
        FC["Follower"]
    end
    PR -->|"write, same zone"| LD
    LD -->|"replication, crosses zones"| FB
    LD -->|"replication, crosses zones"| FC
    LD -->|"consumer read, crosses zones"| CB
        
FIG 4 — Where zone-crossing traffic comes from in a three-zone cluster
Traffic TypeCrosses Zones?Can Rack Awareness Reduce It?
Producer writes to a leader in another zoneOften, two out of three times on averageNot directly, since producers must write to leaders
Replication from leader to followersYes, by designNo, this is the price of durability
Consumer reads from a leader in another zoneOftenYes, by reading from a follower in the same zone
Traffic between brokers for rebalancingYesOnly by moving less data
Simple Analogy

Think of three offices in different cities of one company. Sending a courier package between offices costs money, while walking a paper to a colleague’s desk in your own building costs nothing. Keeping backups in other cities is a required expense for safety, but there is no reason to send a courier to fetch a report that a colleague in your own office already has a copy of.

The important insight is that replication traffic is the price of safety and cannot be avoided. Consumer read traffic, however, is often the largest part of the total because many consumer groups may read the same data. Reducing that portion is where nearest-replica reading pays off, and this leads us to the second half of rack awareness.

i
Measure First

Before changing anything, look at your cloud billing breakdown for inter-zone data transfer and estimate how much of it comes from consumer reads. The bigger the number of consumer groups per topic, the bigger the possible saving.

9Reading from the Nearest Replica

Since Kafka 2.4, consumers can fetch from a follower instead of the leader. This is often called follower fetching.

Originally, Kafka had a strict rule: all reads and all writes go to the leader. It kept the design simple and consistent, but it forced consumers to cross zones whenever the leader was elsewhere. A later improvement allowed consumers to read from any replica that has the data, including followers. When combined with rack labels, a consumer can be directed to the replica in its own rack, keeping traffic local.

Piece 1

Broker rack label

Each broker declares where it lives. This is the same label used for replica placement.

Piece 2

Broker replica selector

A pluggable component on the broker that decides which replica a consumer should read from. The default selector always answers with the leader, which means the feature is off until you change it.

Piece 3

Consumer rack label

A client setting that tells the broker where the consumer is running. Without it, the broker cannot pick a nearby replica.

Piece 4

Rack-aware selector

The built-in selector that compares the consumer’s label with the labels of the replicas and prefers a match. If no replica matches, it falls back to the leader.

sequenceDiagram
    participant C as Consumer in Zone B
    participant L as Leader in Zone A
    participant F as Follower in Zone B
    C->>L: Fetch request including my rack label
    L->>L: Selector compares consumer rack with replica racks
    L-->>C: Empty data plus preferred read replica is the follower in Zone B
    C->>F: Fetch request sent to the follower
    F-->>C: Records returned from the local zone
    Note over C,F: Future fetches keep going to the follower until told otherwise
        
FIG 5 — How a consumer is redirected to a replica in its own zone

Reading the flow

1

The first fetch goes to the leader

A consumer always begins by asking the leader, because that is where the cluster’s metadata directs it. The request carries the consumer’s rack label.

2

The leader consults the selector

The rack-aware selector looks at all replicas that are in sync and prefers one with the same label as the consumer.

3

The response names a preferred replica

Instead of data, the leader answers with a hint pointing to the better replica. This costs one small round trip at the start.

4

The consumer switches

It sends its next fetches to the preferred follower, and data now flows within the same zone.

5

The hint is refreshed periodically

The consumer occasionally checks back so that changes, such as a follower falling behind, are respected.

!
Common Mistake

Setting the consumer’s rack label but forgetting to change the broker’s replica selector. The default selector always answers with the leader, so nothing changes and the feature silently does nothing. Both sides must be configured.

10Follower Fetching Trade-offs and Safety

Reading from followers saves money, but it is not free of subtleties. Understanding them lets you decide with confidence.

Followers copy data from the leader with a small delay. A record becomes readable by consumers only after it has been replicated to all in-sync replicas and the leader has advanced a marker called the high watermark. The leader tells followers about the new watermark on their next fetch, so a follower learns that a record is safe to serve slightly after the leader does. As a result, a consumer reading from a follower may see new records a fraction of a second later than one reading from the leader.

Advantages

  • Large reduction in cross-zone consumer traffic and cost
  • Lower read latency when the nearest replica is in the same zone
  • Load is spread across followers, easing pressure on leaders
  • No change to how producers work or to data safety
  • Useful for stretched clusters spanning distant sites

Disadvantages / Trade-offs

  • Slightly higher end-to-end latency, since followers learn the high watermark later
  • Extra initial round trip to learn the preferred replica
  • Requires consistent rack labels on both brokers and consumers
  • Followers must serve reads, adding load to them
  • Harder to reason about which replica served a given read
Simple Analogy

A head office publishes a daily price list, and branch offices keep local copies. Reading the local copy is faster and free, but the branch may receive the newest update a few minutes after the head office publishes it. For most readers a few minutes of delay do not matter, and the savings are large. For a trader who needs the very latest figure the instant it is set, the head office is still the right place to ask.

Is it safe for data consistency?

Yes. Followers only serve data up to the high watermark, which covers records that all in-sync replicas already hold. That means a consumer never sees a record that could later disappear because of a leader change. Kafka also handles the case where a follower does not yet know about a newly committed offset by answering that the offset is out of range temporarily, and the consumer retries.

When to use it and when to skip it

Good fit

High-volume consumers with many consumer groups reading the same topics across several zones, analytics pipelines, and log processing where a fraction of a second of extra delay is invisible.

Think twice

Ultra low latency trading style pipelines where every millisecond counts, and small clusters where the network bill is negligible compared with the added complexity.

Not applicable

Single-zone clusters, where every read is already local and no rack differences exist.

i
Compatibility Note

Follower fetching requires brokers and clients of Kafka 2.4 or newer, and the cluster’s internal protocol version must also be new enough. Consumers on older client libraries simply keep reading from leaders, so mixed environments still work.

11Leaders, Producers, and What Stays the Same

A frequent surprise: rack awareness does not move producer traffic to the nearest broker.

All writes for a partition go to its leader, and only the leader. Rack awareness spreads replicas across racks but does not decide where leaders live in a way that matches any given producer. With three zones and evenly spread leaders, a producer is in the same zone as a given leader only about one time out of three. The remaining two thirds of its writes cross a zone boundary.

flowchart TD
    A["Producer sends a record"] --> B{"Which broker is the leader for this partition?"}
    B -->|"Same zone as the producer"| C["Local write, no cross-zone cost for the first hop"]
    B -->|"Different zone"| D["Cross-zone write, billed as inter-zone traffic"]
    C --> E["Leader replicates to followers in other zones"]
    D --> E
        
FIG 6 — Producer writes always follow the leader, wherever it is

Preferred leaders and balance

Each partition has a preferred leader, which is the first replica in its replica list. Kafka periodically moves leadership back to the preferred replica after failures so that leaders stay spread evenly. Because the replica list is built from the alternating rack order, preferred leaders naturally rotate across racks and across brokers, which keeps the number of leaders in each zone roughly equal.

ComponentRack Awareness Changes It?Explanation
Where replicas are placedYesSpread across racks when labels exist
Where leaders are electedOnly indirectlyAny in-sync replica can become leader, in any rack
Where producers writeNoAlways to the leader
Where consumers readOptionally yesOnly when follower fetching is configured
How writes are acknowledgedNoDepends on acknowledgment and minimum in-sync settings
i
Design Consequence

If your cost problem is mostly producer traffic, rack awareness will not fix it. Options include compressing data on the producer side, batching more, or, for advanced setups, arranging for producers of a topic to be co-located with that topic’s leaders through careful placement of partitions.

12Existing Topics, Reassignment, and Rebalancing

Adding rack labels to a running cluster does not rearrange anything by itself. Existing partitions stay where they were.

Placement decisions are made when a topic is created or when partitions are moved. If you add labels to brokers that already host topics, those topics keep their old replica layout, which may contain several replicas in one rack. Rack awareness only applies to new placements from then on. To fix old topics, you must trigger a reassignment that recomputes the placement using the rack information.

Tool 1

Partition reassignment tool

The command line tool that generates and executes a plan to move replicas. When labels exist, the generated plan is rack aware unless you disable that behavior.

Tool 2

Cruise Control

An open source companion project that continuously balances a cluster. It includes a goal that requires replicas of one partition to be in different racks and can repair violations automatically.

Tool 3

Managed service consoles

Many managed Kafka services handle placement themselves and expose limited controls. Check the provider’s documentation for how zone spreading is guaranteed.

Tool 4

Operator-based deployments

Kubernetes operators for Kafka can map node zone labels to broker rack labels and can integrate with balancing tools.

1

Audit current placement

Describe every topic and list partitions whose replicas share a rack. This is your list of at-risk partitions.

2

Confirm labels are correct

Do this before generating any plan. A plan built on wrong labels moves data for no benefit.

3

Generate a plan

Let the tool propose new replica lists, and review it. Check how much data will move and which brokers receive it.

4

Execute with a throttle

Apply a bandwidth limit on replication so that the copy work does not starve normal traffic.

5

Verify and remove the throttle

Confirm every partition is fully in sync, re-audit placement, and then lift the limit.

!
Heavy Operation

Moving replicas means copying large volumes of data across zones. It consumes network, disk, and money. Do it in stages, off peak, and with throttling. Never reassign the whole cluster at once on a busy production system.

i
Emergency Escape

The command line tools include an option to ignore rack information. It exists for situations such as a temporarily mislabeled cluster, but using it lets replicas land in the same rack again, so treat it as a short-term measure.

13Growing and Shrinking the Cluster Safely

Capacity changes are the moments when rack awareness quietly breaks if nobody is watching.

When you add brokers, new brokers start empty. Kafka does not move existing data onto them automatically. You must reassign partitions to use them. If you add brokers to only one rack, that rack becomes larger, and the alternating pattern will later overload the smaller racks. If you remove brokers, the partitions on them must be moved first, and if the removal empties a rack or reduces racks below the replication factor, some partitions can no longer be spread perfectly.

flowchart LR
    A["Need more capacity"] --> B["Add the same number of brokers to every rack"]
    B --> C["Reassign partitions onto the new brokers"]
    C --> D["Check that every partition still spans distinct racks"]
    D --> E["Verify balance of storage and traffic per rack"]
        
FIG 7 — Scaling out one step at a time while keeping racks balanced

Scale out evenly

Add brokers in multiples of the number of racks. With three zones, add three brokers at a time, one per zone, so that racks stay equal in size.

Scale in carefully

Drain a broker by moving its partitions elsewhere within the same rack first, so the rack balance is preserved, and only then shut it down.

Add a new rack

Assign a new label to the new brokers and run a reassignment so that existing partitions can take advantage of the additional failure domain.

Retire a rack

Move all replicas out before decommissioning. Verify that the replication factor is still achievable across the remaining racks.

!
Common Mistake

Replacing a failed broker in an emergency by starting a new machine in whichever zone has spare capacity, without giving it the correct label. The new broker joins with the wrong or missing label, and placement or balance quietly degrades.

14Rack Awareness on Kubernetes and in the Cloud

Modern deployments rarely have physical racks. The same idea maps neatly onto zones, node labels, and managed services.

On container platforms, each worker node usually carries a label that names its availability zone. A Kafka operator can read that label and inject it as the broker’s rack value, so the rack label comes from the platform instead of a hand-edited file. To make this effective, the platform must also be told to spread broker pods across zones using anti-affinity or topology spread rules. Otherwise the scheduler might place several brokers in the same zone, and the labels would faithfully report a poorly spread cluster.

Layer 1

Node zone labels

The platform records the zone of each node. This is the single source of truth for locality.

Layer 2

Pod spreading rules

Scheduling rules that keep brokers in different zones and prevent all brokers landing on one node.

Layer 3

Broker rack injection

An init step or operator setting copies the node’s zone into the broker’s rack configuration at startup.

Layer 4

Client rack injection

Applications learn their zone the same way, so consumers can set their own rack label for follower fetching.

Layer 5

Storage locality

Disks in the cloud are usually tied to one zone. A broker that restarts must return to the zone of its disk, so pod scheduling and volume placement must agree.

Layer 6

Network paths

Clients must be able to reach brokers in every zone, and any load balancer in front must not hide zone identity or force traffic through one zone.

Managed Kafka services

Most managed Kafka offerings place brokers across several zones for you and set rack labels behind the scenes. Many also support follower fetching, but you may need to enable a broker-level setting through the provider’s configuration and set the rack label on the client yourself. The exact controls differ between providers, so consult their documentation before relying on the behavior.

Simple Analogy

Running Kafka on a container platform is like staffing three warehouses through a staffing agency. The agency must be told to send workers to all three warehouses evenly. Each worker must then wear a badge showing which warehouse they are in. If the agency sends everyone to one warehouse, or the badges are wrong, the safety plan fails silently.

i
Design Tip

Verify the spread from the outside. After every deployment, list broker racks and count brokers per zone. A quick check catches scheduler surprises before they become outages.

15Rack Awareness in Streams, Connect, and Replication

The idea extends beyond plain consumers to the wider Kafka ecosystem.

Kafka Streams

Stream processing applications keep local state and often maintain standby copies of that state on other instances, so a failure does not force a slow rebuild. Newer versions can place standby copies on instances in different racks, and can also assign work to reduce cross-zone reads. This gives stream applications the same resilience and cost benefits.

Kafka Connect

Connect workers act as producers and consumers. Their consumers can set a rack label for follower fetching, which is useful for sink connectors that read large volumes. Worker placement across zones also protects against losing all workers at once.

Consumer groups in general

Group assignment strategies do not automatically match consumers to partitions in the same zone. Rack-aware reading works per partition through the replica selector, regardless of which consumer instance owns the partition.

Cross-cluster replication

Replication tools that copy data between clusters can read from a nearby replica in the source cluster, lowering transfer costs, and each cluster maintains its own rack layout independently.

Balancing and self-healing tools

Balancing tools treat rack placement as a hard requirement, and will move replicas to repair violations before optimizing for evenness of load.

flowchart TD
    L["Rack labels on brokers"] --> A["Replica placement"]
    L --> B["Follower fetching for consumers"]
    L --> C["Standby placement in stream processing"]
    L --> D["Rack goals in balancing tools"]
    L --> E["Monitoring and audits per rack"]
        
FIG 8 — One label, many uses across the ecosystem
i
Insight

Because so many tools reuse the same label, an incorrect label is quietly harmful in many places at once. Treat the rack label as critical configuration, not a decoration.

16Security Considerations

Rack awareness is not a security feature, but it touches security in a few important ways.

Point 1

Labels are metadata, not identity

A client can claim any rack label. The label only influences which replica is suggested and grants no privileges.

Point 2

Authorization still applies to followers

Access rules for reading a topic apply no matter which replica serves the data. Follower fetching does not bypass permission checks.

Point 3

Encryption across zones

Replication and reads that cross zone boundaries travel over the provider’s network. Enabling encryption in transit protects that traffic, and it is a common compliance requirement.

Point 4

Data residency

If regulations require data to stay within a country or region, the racks you define must all be within that boundary. Spreading replicas across regions with different legal rules may be prohibited.

!
Mind the Blast Radius

Spreading replicas across more sites improves availability but also spreads your data to more physical locations. Make sure every location in your rack list satisfies your organization’s security and compliance rules.

Also protect the configuration itself. Anyone who can change broker settings or run reassignment tools can move your data around or defeat your placement. Limit these rights to trusted administrators and audit their use.

17Monitoring, Logging, and Metrics

A rack-aware design only stays rack-aware if you keep checking it.

Check

Brokers per rack

Count brokers under each label. Uneven counts predict uneven load and reduced safety.

Check

Partitions violating rack spread

Scan topic descriptions for partitions with two replicas in one rack, when the number of racks would allow better.

Metric

Under-replicated partitions

A rising count means replicas are falling behind, often the first sign of a struggling rack or a slow cross-zone link.

Metric

Under-minimum in-sync partitions

Partitions below the minimum in-sync count reject writes. Alert immediately, because producers are being affected.

Metric

Leader count per broker and per rack

Imbalanced leadership overloads a rack and increases cross-zone writes.

Metric

Replication lag per follower

Lag drives how stale follower reads can be, so watch it closely if you use nearest-replica reading.

Metric

Bytes in and out per rack

Compare traffic across racks to confirm balance and to verify that follower fetching moved reads locally.

Cost

Inter-zone data transfer billing

The most direct proof that follower fetching works is a drop in this line item after the change.

An alerting ladder

1

Information

Report daily on brokers per rack and partitions with poor rack spread, so drift is visible before it matters.

2

Warning

Notify the team when under-replicated partitions persist or a rack’s load exceeds a planned share.

3

Critical

Page an engineer when partitions fall below the minimum in-sync count or an entire rack stops reporting.

i
Drill Tip

Rehearse a rack failure in a test environment by stopping all brokers in one rack. Measure how long clients pause and whether the surviving racks cope. An untested failover plan is only a hope.

18Design Patterns That Work

These arrangements have been proven again and again in production.

Pattern 1

Three zones, replication factor three

The default choice for cloud clusters. One replica per zone gives the best mix of safety and simplicity.

Pattern 2

Minimum in-sync of two with full acknowledgment

Survives a zone loss without data loss and without halting writes.

Pattern 3

Equal brokers per rack

Scale in multiples of the rack count so that load and storage stay even.

Pattern 4

Labels from a trusted source

Derive labels automatically from platform metadata to avoid human error.

Pattern 5

Follower fetching for heavy readers

Enable it for high-volume, latency-tolerant consumers first, and measure the savings.

Pattern 6

Continuous balancing with a rack goal

Use a balancing tool that treats rack spread as mandatory and repairs violations automatically.

Pattern 7

Headroom for a lost rack

Size each broker so that the remaining racks can absorb the load of a failed one.

Pattern 8

Regular placement audits

Schedule automated checks that report any partition whose replicas share a failure domain.

Simple Analogy

Good patterns are like the habits of a careful traveler: keep copies of your passport in different bags, tell each family member where the spare key is, and check the tickets before leaving. None of it is dramatic, but together these habits mean a single lost bag never ruins the trip.

“Replication makes copies. Rack awareness makes sure the copies do not share a fate.”

19Anti-Patterns to Avoid

These mistakes appear in real incidents. Learn them so you do not repeat them.

ANTI-PATTERN-01 Avoid
Problem

The cluster runs across several zones but no rack labels are configured.

Why It’s Harmful

Kafka has no idea where brokers live and may place all replicas of a partition in the same zone. A single zone outage can then make partitions unavailable, even though the cluster looks well replicated.

Correct Approach

Label every broker with its real zone and rebalance existing topics so that replicas span distinct zones.

ANTI-PATTERN-02 Avoid
Problem

Labels are assigned by hand and copied between machines without checking.

Why It’s Harmful

A wrong label makes Kafka believe two machines are in different domains when they are not, or the reverse. The safety plan is silently broken, and nobody notices until a real failure.

Correct Approach

Generate labels automatically from the platform’s own knowledge of location, and audit them regularly.

ANTI-PATTERN-03 Avoid
Problem

Racks have very different numbers of brokers.

Why It’s Harmful

The small rack must hold a replica of a huge share of partitions and becomes a hot spot for storage and traffic, while larger racks sit underused.

Correct Approach

Keep brokers evenly distributed across racks and grow in multiples of the rack count.

ANTI-PATTERN-04 Avoid
Problem

Replication factor equals the minimum in-sync replicas.

Why It’s Harmful

Losing any one replica, for example during a rack failure or even a routine restart, stops all writes to the affected partitions.

Correct Approach

Set the minimum in-sync count one below the replication factor so that one replica can be missing without halting writes.

ANTI-PATTERN-05 Avoid
Problem

Configuring the consumer rack label without enabling the rack-aware selector on brokers, or the reverse.

Why It’s Harmful

Half a configuration does nothing. The team believes savings are happening, but consumers still read from leaders across zones, and the bill stays high.

Correct Approach

Configure both sides, then verify by comparing inter-zone traffic before and after the change.

ANTI-PATTERN-06 Avoid
Problem

Adding labels to an existing cluster and assuming old topics are now protected.

Why It’s Harmful

Labels affect only new placements. Old partitions keep their original, possibly unsafe, layout until they are reassigned.

Correct Approach

Audit placement after labeling and run a throttled reassignment for topics that violate rack spread.

ANTI-PATTERN-07 Avoid
Problem

Running brokers so close to full capacity that the remaining racks cannot absorb a lost rack’s load.

Why It’s Harmful

Replicas survive, but the surviving brokers collapse under the extra work, turning a partial failure into a full outage.

Correct Approach

Plan for failure-case load. With three racks, normal utilization should stay comfortably below about two thirds of capacity.

20Troubleshooting Common Problems

Most rack awareness problems fall into a handful of families. Recognize the family and the fix is usually short.

SymptomLikely CauseWhat to Check
Topic creation fails with an error about some brokers lacking rack informationOnly some brokers have labelsEvery broker’s rack setting; add missing labels and restart
Two replicas of one partition sit in the same rackOld topic created before labels, or more replicas than racksReplica list against rack labels and the number of distinct racks
One rack’s brokers are far busier than othersRacks have unequal broker countsBrokers per rack and disk usage per broker
Cross-zone traffic did not drop after enabling nearest-replica readingSelector not set on brokers, or consumer label missingBroker selector setting, consumer rack setting, client version
Consumers still read from leaders after configurationBrokers or protocol version too old, or no replica shares the consumer’s labelBroker version, protocol level, matching labels
Consumers see records slightly later than beforeFollower learns the high watermark after the leaderReplication lag; this delay is expected and small
Writes stop when one rack goes downMinimum in-sync setting too high or replicas concentratedReplication factor, minimum in-sync setting, actual replica layout
Reassignment keeps putting replicas in the same rackTool told to ignore rack informationOptions used when generating the plan
After a broker replacement, balance got worseNew broker joined with wrong or missing labelThe new broker’s rack label in cluster metadata

A calm debugging routine

1

Describe the cluster

List every broker with its rack label. Most problems reveal themselves right here.

2

Describe the affected topic

Look at the replica list, leader, and in-sync set of a few partitions, and map each replica to its rack.

3

Compare intended and actual

Decide whether the problem is placement, balance, or reading behavior, since each has different fixes.

4

Fix the cause, not the symptom

Correct the label or the setting first, then move data only if necessary.

5

Verify with measurements

Confirm with metrics and billing data that traffic and balance actually improved.

i
Debugging Tip

Separate three questions: are the copies in different racks, is load balanced across racks, and are consumers reading locally. Each is controlled by a different part of the system, so answering them separately avoids chasing the wrong cause.

21Real-World and Industry Scenarios

The same feature serves different goals depending on the business.

Banking and payments

Payment events must survive the loss of a building without losing a single acknowledged record. Three zones, three replicas, minimum in-sync of two, and unclean leader election disabled give a strong durability story that auditors understand.

Streaming media and analytics

Viewing events flow in huge volumes, and many teams read the same topics for dashboards, recommendations, and reports. Follower fetching cuts the cross-zone read bill dramatically while a fraction of a second of extra delay is invisible to these users.

Retail and e-commerce

Orders and inventory events are business critical during sales peaks. Rack awareness guarantees that a single zone problem during a big sale does not stop order processing, and capacity headroom covers the lost zone’s share of traffic.

Telecommunications

Operators with several data centers label brokers by site. Placement across sites survives a full site outage, and nearest-replica reading keeps regional consumers on local links rather than long-distance lines.

Healthcare and regulated data

Rack labels are limited to sites inside the permitted geography. The cluster gains availability without sending patient related events to locations that violate residency rules.

Internet of Things platforms

Device telemetry arrives constantly from many gateways. Balanced racks spread the constant write load, and consumers in the analytics tier read from local replicas to avoid paying to move the same readings across zones repeatedly.

Survive a zone
replicas spread across failure domains
Read locally
consumers use the nearest replica
Stay balanced
equal brokers per rack
i
Industry Lesson

Across industries the same three habits appear: model failure domains honestly, keep them balanced, and measure the results in both reliability and cost.

22Best Practices and Common Mistakes

A compact checklist you can use before, during, and after rollout.

Best Practices

  • Label every broker with its real failure domain, and do it for the whole cluster at once
  • Use a replication factor equal to the number of zones you span, commonly three
  • Set the minimum in-sync replicas to one below the replication factor
  • Keep the same number of brokers in every rack
  • Generate labels automatically from platform metadata
  • Audit placement regularly and after every scaling event
  • Enable follower fetching for heavy, latency-tolerant readers and measure savings
  • Size for the loss of one full rack
  • Rehearse a rack failure before you need it

Common Mistakes

  • Running multi-zone clusters with no labels at all
  • Labeling only some brokers
  • Assuming labels reshuffle existing topics
  • Growing only one rack when adding capacity
  • Setting only one half of the nearest-replica configuration
  • Expecting rack awareness to reduce producer cross-zone traffic
  • Replacing brokers without restoring their labels
  • Running so hot that the survivors cannot carry a lost rack

A short readiness checklist

1

Define failure domains

Decide what you want to survive and agree on the labels with the infrastructure team.

2

Label and verify

Apply labels through automation, restart brokers in a rolling fashion, and verify the metadata.

3

Fix existing topics

Audit placement and run throttled reassignments for at-risk partitions.

4

Tune durability settings

Confirm replication factor, minimum in-sync count, producer acknowledgment, and leader election rules match your requirements.

5

Optimize reads

Enable the rack-aware selector on brokers and set the rack label on consumers, then measure cross-zone traffic.

6

Monitor and rehearse

Set up alerts, schedule audits, and run a failure drill at least once.

i
Migration Tip

Roll out nearest-replica reading one consumer group at a time. Pick a large, tolerant group first, compare traffic and latency, and then extend to others once you trust the behavior.

23Frequently Asked Questions

Short answers to the questions people ask most often when they start with rack awareness.

Q1Is a rack always a physical rack?

No. It is just a label for a failure domain. In the cloud it usually stands for an availability zone, and in other setups it can mean a room, a power group, or a whole data center.

Q2Does Kafka verify that my rack labels are true?

No. Kafka trusts whatever you configure. Wrong labels quietly weaken your protection, so generate them from a reliable source and audit them.

Q3What happens if I label only some of my brokers?

Placement for new topics fails with an error, unless the administrator tells the tool to ignore rack information. Always label all brokers or none.

Q4Do rack labels move my existing data?

No. Labels influence new placements only. Existing partitions stay where they are until you run a reassignment that uses the rack information.

Q5How many racks should I use?

Three is the most common choice, matching a replication factor of three, so every partition has one replica per rack. More racks give finer spreading but add operational complexity.

Q6What if my replication factor is larger than the number of racks?

Kafka spreads replicas as evenly as it can, so some racks will hold more than one replica of a partition. Safety against a single rack failure is reduced for those partitions.

Q7Does rack awareness make producers write to the nearest broker?

No. Producers always write to the partition leader, wherever it is. Rack awareness affects where replicas live and, optionally, where consumers read.

Q8What is follower fetching in simple words?

It lets a consumer read from a copy of the data that is in its own zone instead of always contacting the leader, which may be in another zone. It saves network cost and can reduce latency.

Q9Is reading from a follower safe?

Yes. Followers only serve records that are already committed, so consumers never see data that could later vanish. The only visible effect is a small extra delay before new records become readable.

Q10Why did my cross-zone traffic not drop after I set the consumer rack?

The brokers also need the rack-aware replica selector enabled, and the client and broker versions must support the feature. Also confirm that some replica actually shares the consumer’s label.

Q11Can I change a broker’s rack label later?

Yes, with a restart of that broker. But existing replicas do not move automatically, so you may need a reassignment afterward to make placement match the new label.

Q12Does rack awareness reduce replication traffic between zones?

No. Replication across zones is the cost of durability and stays the same. Rack awareness reduces only the consumer read portion, and only when follower fetching is enabled.

Q13Do I need rack awareness for a single-zone cluster?

If every broker shares one failure domain, labels add nothing. You may still label by physical rack or power group inside the building to survive smaller failures.

24Summary and Key Takeaways

Rack awareness turns Kafka’s replication from a simple copying mechanism into a real defense against correlated failures. By giving every broker an honest label for its failure domain, you let Kafka place the copies of each partition in different racks, zones, or sites, so a power cut, a switch failure, or a whole building outage still leaves healthy copies elsewhere. The same labels can also steer consumers to the nearest replica, cutting cross-zone network cost with only a small delay in freshness. The feature is simple to enable and easy to break: labels must be correct and complete, racks must stay balanced, existing topics must be reassigned, capacity must allow for a lost rack, and both halves of nearest-replica reading must be configured. Treat the rack label as critical configuration, audit it regularly, and rehearse failures, and this small setting quietly delivers a large amount of resilience.

Key Takeaways

  • Replication is not enough — copies that share a failure domain fail together, so rack awareness spreads replicas across independent domains.
  • A rack is just a label — it can mean a physical rack, a cloud zone, or a site, and Kafka trusts whatever you configure, so labels must be accurate.
  • Label everything and keep racks equal — partial labels break placement, and lopsided racks create hot spots and reduce safety.
  • Pair three copies with minimum in-sync of two — across three zones this survives the loss of a whole zone without data loss or halted writes.
  • Labels only affect new placements — audit existing topics and run throttled reassignments to bring them into line.
  • Nearest-replica reading saves money — configure both the broker selector and the consumer rack label, accept a small freshness delay, and confirm savings in the bill.
  • Plan and rehearse for failure — size for a lost rack, monitor placement and under-replication, and drill a rack outage before it happens for real.