Geo-Partitioning Strategies in Kafka

Geo-Partitioning Strategies in Kafka

A complete, plain-English guide to placing streaming data close to the people who create it and the laws that govern it — from partition keys and replica placement to stretched clusters, observers, and multi-cluster replication.

Imagine a pizza company with kitchens in Mumbai, Frankfurt, and Chicago. When a customer in Frankfurt orders a pizza, nobody would dream of sending that order slip to Chicago, waiting for a chef there to read it, and then mailing the answer back. The order stays in Frankfurt. Only the daily sales totals travel to head office. Now replace the order slips with millions of events per second, replace the kitchens with data centers, and replace the head office with an analytics team. That is the world of geo-partitioning in Kafka.

Apache Kafka is a system that moves and stores streams of events. It was designed to be fast and durable inside a single data center. But real businesses are global. Their users are spread across continents, their laws differ from country to country, and their data centers can fail. This tutorial explains, from the ground up, how engineers decide where in the world each piece of Kafka data should live, who should be allowed to read it, and how it should travel. You do not need prior knowledge. Every new word is explained the first time it appears.

1What Is Geo-Partitioning and Why Should You Care?

Geo-partitioning means deliberately deciding which geographic location holds which slice of your data.

The Simple Definition

Geo-partitioning is the practice of splitting data by geography and keeping each piece close to where it is produced, consumed, or legally required to stay. The word “partition” simply means “a piece.” The word “geo” means “related to places on Earth.” Put together, geo-partitioning means “cutting your data into pieces based on location and storing each piece in the right place.”

The idea did not start with Kafka. Distributed databases have used it for years to pin customer records to specific regions. Kafka has its own version of the idea, but because Kafka is a streaming platform and not a database, the tools and trade-offs are different. Kafka also happens to use the word “partition” for something specific, which can cause confusion. In Kafka, a partition is one ordered log inside a topic. So when we talk about geo-partitioning in Kafka, we are really talking about how those logs, their copies, and the clusters that hold them are arranged across the map.

Simple Analogy

Think of a national library system. Each city branch keeps the books its own readers borrow most often. Rare books that must not leave the country stay in the national vault. A central catalog lets anyone search across all branches. Geo-partitioning is the librarian’s plan for which books live where, and why.

Why Not Just Use One Big Cluster Somewhere?

A single cluster in a single location is the easiest thing to run. Many companies start that way, and for many companies it is the right answer. But as a business grows, four pressures push engineers toward geo-partitioning. Physics makes far-away users slower. Laws restrict where certain data may be stored. Disasters can knock out a whole region. And cloud providers charge money whenever data crosses regional borders. Chapter 3 explores each pressure in detail.

4
forces that push data to be local
5
main strategies covered in this guide
1
golden rule: never move data further than you must
i
Good to Know

Kafka does not have a single switch called “geo-partition this topic.” Geo-partitioning is a design you build by combining several features: partition keys, replica placement, rack awareness, replication tools, and separate clusters. That is exactly why understanding the building blocks matters.

2Kafka Foundations You Need First

A short, friendly tour of the vocabulary that the rest of this guide depends on.

If you already know Kafka well, skim this chapter. If Kafka is new to you, read it slowly, because every later strategy is built from these pieces.

Term 1

Event (Record)

One fact that happened, such as “order 42 was placed.” It has an optional key, a value, a timestamp, and optional labels called headers.

Term 2

Topic

A named stream of related events, like a folder called “orders.” Producers write to it; consumers read from it.

Term 3

Partition

One ordered, append-only log inside a topic. A topic with six partitions is six logs working side by side to share the load.

Term 4

Broker

A server that stores partitions and serves reads and writes. A group of brokers working together is a cluster.

Term 5

Replica

A copy of a partition kept on another broker so that data survives a broker failure.

Term 6

Leader and Follower

Each partition has one leader replica that handles reads and writes, and follower replicas that copy the leader.

Term 7

In-Sync Replicas (ISR)

The set of replicas that are fully caught up with the leader. Only members of this set can safely take over if the leader fails.

Term 8

Producer

An application that sends events into Kafka.

Term 9

Consumer and Consumer Group

A consumer reads events. A group of consumers shares the work: each partition is read by exactly one member of the group at a time.

Term 10

Offset

The position number of an event inside a partition. Consumers remember their offset like a bookmark.

How the Pieces Fit Together

A producer sends an event to a topic. Kafka picks a partition for that event. The leader broker for that partition appends the event to its log and assigns it the next offset. Follower brokers fetch the new event from the leader and append it to their own copies. When enough followers have confirmed, the producer is told the write is safe. Consumers then read from the leader, one partition at a time, moving their bookmark forward.

Simple Analogy

A topic is a busy highway. Partitions are its lanes. Cars are events. Each lane keeps cars in the order they entered. Replicas are backup lanes on a parallel road, and the leader is the lane that traffic officers actually direct cars through today.

flowchart LR
  P["Producer"] --> L["Partition Leader on Broker 1"]
  L --> F1["Follower Copy on Broker 2"]
  L --> F2["Follower Copy on Broker 3"]
  L --> C["Consumer Group Member"]
        
FIG 1 — The basic write and read path inside one Kafka cluster

The Control Plane

Besides storing data, a Kafka cluster must remember its own facts: which topics exist, which broker leads which partition, and which replicas are in sync. This “brain” is called the control plane or metadata layer. Modern Kafka keeps this information using a built-in agreement protocol called KRaft, run by a small group of nodes called controllers. Older versions used a separate coordination service. What matters for geography is this: the controllers must be able to talk to each other quickly and must always find a majority. If you spread them across the world carelessly, the whole cluster becomes slow or, worse, stuck.

!
Common Misconception

Many beginners think adding more partitions automatically spreads data across countries. It does not. Partitions are spread across brokers, and brokers can sit anywhere. Where a partition physically lives is a separate decision that you must make on purpose.

3The Four Forces Behind Geo-Partitioning

Latency, law, failure, and cost: the reasons every global Kafka design eventually faces geography.

Force One: Latency and the Speed of Light

Latency is the delay between doing something and seeing the result. Signals in optical fiber travel at roughly two-thirds the speed of light, which works out to about one millisecond for every two hundred kilometers, one way. That is a hard physical limit; no software upgrade can beat it. A round trip between two cities on different continents therefore costs many tens of milliseconds at the very least, and real-world networks usually add much more because cables do not run in straight lines and traffic passes through many devices.

Why does this matter for Kafka? Because Kafka’s safest setting for producers waits for follower replicas to confirm each write. If a follower lives on another continent, every single write waits for a trip across the ocean and back. A system that felt instant in one building suddenly feels sluggish.

Simple Analogy

Asking a neighbor to sign a form takes a minute. Asking someone in another country to sign it means posting the form, waiting, and posting it back. If you had to do that for every single form, you would get almost nothing done.

Force Two: Law and Data Residency

Many countries and regions have rules about where personal data may be stored or processed. Europe’s data protection rules, various national data-localization laws, and industry rules for banking and health all influence where a record may physically rest. These rules are usually called data residency or data sovereignty requirements. Breaking them can lead to heavy fines and loss of customer trust.

Kafka is a log that copies data by design. A single careless replication setting can copy a European customer’s record to a data center in another country within milliseconds. Geo-partitioning gives you the controls to prevent that.

Force Three: Failure and Disaster Recovery

Servers fail. Power fails. Network cables get cut. Whole cloud regions occasionally suffer outages. A cluster that lives in one region is only as safe as that region. Spreading data across geographic locations lets the business keep running when one location is lost. The question is how much data you are willing to lose, and how long you are willing to be down. Those two numbers have names: the recovery point objective (how much recent data you can afford to lose) and the recovery time objective (how long you can afford to be offline).

Force Four: Cost

Cloud providers usually charge for data that moves between availability zones, and charge more for data that moves between regions or leaves the cloud. Kafka moves a lot of data: every write is copied to followers, every consumer reads a copy, and replication tools copy entire topics between clusters. Without care, network transfer can become one of the largest lines on the monthly bill.

ForceThe Question It AsksWhat Geo-Partitioning Does About It
LatencyHow fast can users and services get a response?Keeps leaders, producers, and consumers in the same region
LawIs this data allowed to be here?Confines regulated data to approved locations
FailureWhat happens when a location disappears?Keeps recoverable copies elsewhere, on purpose
CostHow much are we paying to move bytes?Avoids unnecessary cross-region transfer
i
Design Tip

Before choosing any strategy, write down which of the four forces matter most for your business. A bank may rank law and failure highest. A gaming company may rank latency and cost highest. The ranking decides the design.

“Geography is not an afterthought in a streaming system; it is a design input, just like throughput.”

4What “Geo-Partitioning” Really Means Inside Kafka

Four different levels at which you can apply geography, from the smallest to the largest.

Because Kafka uses the word partition in its own special way, it helps to separate the ideas cleanly. There are four levels where you can express geography in a Kafka design. Each level offers a different strength of guarantee and a different amount of work.

1

Level 1: Region Inside the Record

The event carries a region label in its key or headers, and applications use it to route or filter. This is the lightest touch and gives no physical guarantee at all.

2

Level 2: Region Per Topic

Each region gets its own topic, such as one for Europe and one for Asia. Access rules and retention can differ per topic, but the topics may still live on the same brokers.

3

Level 3: Region Per Partition Group

Inside one topic, a custom partitioner reserves certain partitions for certain regions, and replicas of those partitions are placed on brokers in that region.

4

Level 4: Region Per Cluster

Each region runs its own independent cluster. Data moves between clusters only through deliberate replication. This is the strongest form of separation.

Two Extra Ideas That Cut Across the Levels

First, there is the stretched cluster, where one single cluster has brokers in several locations, and placement rules decide which replicas sit where. It behaves like Level 3 but with a shared control plane. Second, there is locality of reads, where consumers fetch from the nearest replica instead of always going to the leader. This does not move data; it moves the traffic path.

flowchart TD
  A["Need geographic control"] --> B{"How strong must the guarantee be?"}
  B -->|"Just routing hints"| L1["Level 1: Region in record"]
  B -->|"Separate access and retention"| L2["Level 2: Topic per region"]
  B -->|"Physical placement, one cluster"| L3["Level 3: Partition groups plus placement"]
  B -->|"Hard isolation"| L4["Level 4: Cluster per region"]
        
FIG 2 — Choosing the level of geographic control
!
Watch Out

Levels 1 and 2 are often mistaken for real data residency. They are not. If the brokers that store a European topic are physically in another country, the data is not resident in Europe no matter what the topic is called. Physical placement is what counts.

5How Kafka Decides Where a Record Goes

To bend Kafka’s routing to your geography, you first need to understand its default behavior.

Keyed Records

When a record has a key, the default partitioner runs a fast hashing formula on the key and uses the result to pick a partition number. The same key always produces the same partition, as long as the number of partitions does not change. This is the reason Kafka can promise that all events for one customer, sharing one key, arrive in order: they all land in the same log.

Records Without a Key

When a record has no key, Kafka is free to choose any partition. Modern producers stick to one partition for a short time while filling a batch, then move on to another, so that batches stay large and efficient while the load still spreads out over time. This is called sticky batching. It is excellent for throughput, but it means keyless records carry no location meaning whatsoever.

The Partition Count Trap

You can add partitions to a topic later, but you can never remove them. Adding partitions changes the hashing result for keys, so records with the same key may start landing in a new partition. Ordering per key then breaks across the change. Any geo-partitioning scheme that depends on partition numbers therefore needs a fixed and generous partition count decided early.

Simple Analogy

The hashing formula is like a mail sorter who assigns every street name to one of twelve bins. If you suddenly add three more bins, the sorter’s rule changes, and letters for the same street may start dropping into different bins than before.

Why Hashing Alone Cannot Give You Geography

The default partitioner knows nothing about the world. It spreads keys evenly across partitions. It also does not know which broker each partition sits on. So even if you put a region name inside your key, records from different regions will be mixed together across all partitions, and partitions will be spread across whatever brokers the cluster chose. Geography needs two more ingredients: a rule that connects region to partition, and a placement that connects partition to location.

Ingredient 1

Region-to-Partition Rule

Decides which partitions belong to which region. Usually implemented with a custom partitioner in the producer.

Ingredient 2

Partition-to-Location Placement

Decides which brokers hold the replicas of those partitions. Implemented with rack labels, manual assignment, or vendor placement rules.

Ingredient 3

Consumer Alignment

Makes sure regional consumers read only regional partitions, using manual assignment or a location-aware assignor.

Ingredient 4

Operational Discipline

Ongoing checks that leaders and replicas have not drifted away from their intended homes after failures and rebalances.

i
Design Tip

Ordering in Kafka only exists inside a single partition. The moment you merge data from many regions into one view, you lose a single global order. Design downstream logic around event timestamps and business keys instead of assuming a global sequence.

6Strategy One: A Separate Topic for Each Region

The simplest and most popular first step: give every region its own named stream.

How It Works

Instead of one topic called “orders” that holds everything, you create one topic per region, for example an orders topic for Europe, one for Asia, and one for the Americas. Producers in each region write only to their own regional topic. Consumers subscribe to the topics they are allowed and needed to read. A global analytics job might subscribe to all three, while a Europe-only fraud service subscribes to just one.

This approach works because Kafka lets you set retention time, access rules, quotas, and replication settings separately for each topic. Suddenly the European stream can keep data for thirty days while the Asian stream keeps it for seven, and the security team can grant a different group of people access to each one.

Simple Analogy

Instead of one giant mailbox for the whole company, you install one locked mailbox in each city office. Each office has its own key holders and its own emptying schedule, but the mailboxes may still be bolted to the same wall unless you also move them.

What This Strategy Gives You

Advantages

  • Very easy to understand, explain, and audit
  • Per-region retention, permissions, and quotas without special code
  • Consumers choose exactly which regions they need
  • Works on every Kafka version and every hosting model
  • A problem in one regional stream does not corrupt another

Disadvantages / Trade-offs

  • Does not by itself control where the brokers physically sit
  • Topic count grows quickly with regions and event types
  • Producers must know their region and pick the correct topic
  • Adding a new region means creating new topics and updating consumers
  • Cross-region views require consumers to merge several streams

Naming Matters More Than You Think

With dozens of topics, a naming convention becomes a safety tool. A good convention puts the region, the business domain, and the event type in a predictable order, so that access rules can use name prefixes to cover many topics at once. For example, a rule that grants a European team access to every topic starting with the European prefix instantly protects future topics as well. Poor naming forces engineers to update permissions topic by topic, and forgotten topics become security gaps.

i
Design Tip

Pick the naming convention before you create the first topic. Renaming is not supported in Kafka; changing a name means creating a new topic and migrating everyone, which is painful at scale.

!
Common Mistake

Teams often create region topics inside one cluster whose brokers all sit in a single country and then tell auditors the data is resident in each region. Topic names are labels, not walls. If residency is a legal requirement, combine this strategy with physical placement (Chapters 8 and 9) or separate clusters (Chapter 10).

7Strategy Two: Region-Aware Keys and Custom Partitioners

Keep one topic, but teach the producer to send each region’s events to that region’s own group of partitions.

The Idea in Plain Words

Sometimes you want a single logical topic, because downstream tools expect one name or because you want consistent schemas and settings. Inside that topic you can still separate regions by dividing the partitions into groups. Suppose the topic has twelve partitions. You might reserve the first four for Europe, the next four for Asia, and the last four for the Americas. A custom partitioner, which is a small piece of logic you plug into the producer, reads the region of each record and picks a partition only from that region’s group. Inside the group it still uses the ordinary key hash, so events for the same customer remain in order.

flowchart LR
  E["Event with region label"] --> R{"Custom partitioner"}
  R -->|"Europe"| G1["Partitions 0 to 3"]
  R -->|"Asia"| G2["Partitions 4 to 7"]
  R -->|"Americas"| G3["Partitions 8 to 11"]
  G1 --> B1["Brokers in Europe"]
  G2 --> B2["Brokers in Asia"]
  G3 --> B3["Brokers in the Americas"]
        
FIG 3 — A custom partitioner mapping regions to partition groups, paired with regional broker placement

The Three Pieces You Must Get Right

1

Producer-Side Routing

Every producer must use the same partitioner logic and the same region map. If one producer application forgets to plug it in, its records will scatter across all partitions and quietly break residency.

2

Replica Placement

Reserving partitions is only a label until you also make sure the replicas of those partitions live on brokers in the matching region. Chapter 8 explains how.

3

Consumer Assignment

Regional consumers should read only their region’s partitions. Applications can be told exactly which partitions to read, or a location-aware assignment can be used. Without this, a consumer group may be handed partitions from a faraway region.

Simple Analogy

A large apartment building has twelve mail slots. You decide slots one to four are for the north wing, five to eight for the east wing, and nine to twelve for the west wing. A sorting clerk follows this rule for every letter. The rule works only if the clerk never skips it, and only if the mail carriers for each wing know which slots to check.

Where This Strategy Struggles

The fixed partition count is the biggest limitation. Each region receives a fixed slice, so if Asia suddenly grows tenfold, you cannot simply add partitions for Asia without changing every region’s slice and disturbing key ordering. Planning for growth means reserving extra partitions per region up front, which wastes some resources early on. Another issue is uneven load: a region with heavy daytime traffic may overload its slice while a quiet region’s partitions sit idle. This is called skew, and it appears often in geographic designs.

There is also a control-plane limitation. All partitions, whatever their region, are still managed by the same cluster and the same controllers. Metadata about every topic and partition, including region-named ones, is visible across the entire cluster. For strict legal separation, this shared control plane can be a problem.

Advantages

  • One topic name, one schema, one set of settings
  • Physical placement possible when paired with replica rules
  • Order per key preserved inside each region’s group
  • Fewer topics to manage than the topic-per-region approach

Disadvantages / Trade-offs

  • Requires custom code in every producer
  • Partition count is hard to change safely later
  • Regional skew can create hot partitions
  • Shared control plane means shared metadata and shared failure modes
  • Errors in one producer can silently violate residency
!
Common Mistake

Some teams put the region only inside the record key and assume the default hash will keep regions apart. The hash spreads keys evenly, so it will mix regions everywhere. A region label inside the key is useful for humans and for filtering, but it does not pin anything anywhere.

8Strategy Three: Rack Awareness and Replica Placement

Teaching brokers where they live so that copies of data end up in the right buildings.

What Is a Rack in Kafka?

In Kafka, “rack” is a label you attach to each broker to say where it physically sits. The name comes from server racks in a data center, but the label can mean anything you want: a rack, a data hall, an availability zone, or even a whole region. When brokers are labeled, Kafka tries to spread the replicas of each partition across different labels, so that losing one label does not lose every copy.

Simple Analogy

If you own three copies of an important document, you would not keep all three in the same drawer. Rack awareness is Kafka’s habit of storing each copy in a different drawer, because it knows which drawer each broker sits in.

Two Very Different Uses of the Same Label

Inside one region, labels usually mark availability zones. Kafka spreads replicas across zones so a zone outage does not lose data, and network hops between zones stay short. Across regions, the same label can mark whole regions, which lets a stretched cluster keep copies in different geographies. The mechanism is the same; the latency and cost consequences are very different, which is why Chapter 9 treats stretched clusters separately.

Automatic Spread Versus Deliberate Placement

Automatic rack awareness is about spreading replicas as evenly as possible. It is a safety feature, not a residency feature. It will happily place one replica of a European partition in Asia if that gives better spread. For geo-partitioning you usually need deliberate placement, where you say exactly which brokers may hold which partitions.

Method A

Manual Reassignment

Administrators tell Kafka, partition by partition, which brokers should hold the replicas and which one should lead. Precise, but laborious and easy to drift.

Method B

Vendor Placement Rules

Some commercial distributions let you declare rules such as “two replicas in region one, one observer in region two” once per topic, and the platform enforces them.

Method C

Automation Around Kafka

Cluster-management tools compute a desired layout and continuously repair drift, moving replicas until the real layout matches the plan.

Method D

Topic Creation Guardrails

Policies that reject topic creation unless the placement follows approved rules, so nobody can create an unplaced regional topic by accident.

Leaders Matter as Much as Replicas

Producers and consumers normally talk to the leader of each partition. If a European partition has its replicas in Europe but its leader has moved to a broker in the United States, every European producer now crosses the ocean for each write. Kafka periodically tries to hand leadership back to the preferred replica, the first one in the replica list, but you must make sure the preferred replica is the local one. Otherwise, after a rolling restart or a failure, leadership can wander away from home and stay there.

1

Label Every Broker

Give each broker a rack label that identifies its true physical location, and make labeling part of the standard server build.

2

Plan the Layout

Decide, for each regional partition group, which brokers hold replicas and which broker should be the preferred leader.

3

Apply and Verify

Apply the layout, then verify with the cluster’s own description output that every partition sits where you intended.

4

Watch for Drift

After every broker replacement, expansion, or incident, re-check placement and leadership, and correct anything that wandered.

i
Design Tip

Treat placement as data: keep the intended layout in a version-controlled file, compare it against reality on a schedule, and alert on differences. Human memory is not a reliable place to store where partitions should live.

9Strategy Four: Stretched Clusters and Observers

One cluster, several locations, and careful rules about who must confirm each write.

What Is a Stretched Cluster?

A stretched cluster is a single Kafka cluster whose brokers are placed in more than one location, such as three data centers in the same metropolitan area or a few nearby regions. Because it is one cluster, clients see one set of topics, one set of offsets, and one bootstrap entry point. If a whole location fails, the surviving brokers continue to serve, and in the best case no data is lost and no consumer needs to be repointed.

The Price: Synchronous Replication

Recall that the safest producer setting waits until all in-sync replicas have the record. In a stretched cluster, some of those replicas are in another location, so each write must wait for a cross-location round trip. This is why stretched clusters are only recommended when the locations are close together, typically with round-trip times of a few tens of milliseconds or less. Beyond that, write latency and throughput suffer, and the cluster becomes fragile when links are slow or flaky.

Simple Analogy

A contract needs signatures from three lawyers. If all three sit in the same building, signing takes minutes. If one lawyer sits in another country, everyone waits for a courier. The contract is very safe, but every signing is slow.

The Quorum Problem

The control plane needs a majority of its controller nodes to agree before anything changes. With two locations, one of them must hold the majority, and if that location disappears, the survivors cannot form a majority, so metadata changes stop. Because of this, resilient stretched clusters use three locations, with controllers spread across all three, so that losing any one location still leaves a majority. This is why “two data centers” is a well-known weak design for a self-managed stretched cluster.

flowchart TD
  subgraph S1["Site One"]
    B1["Brokers"]
    C1["Controller"]
  end
  subgraph S2["Site Two"]
    B2["Brokers"]
    C2["Controller"]
  end
  subgraph S3["Site Three"]
    C3["Controller"]
  end
  C1 --- C2
  C2 --- C3
  C1 --- C3
  B1 --- B2
        
FIG 4 — Three-site layout so that any single site can fail and the controllers still keep a majority

Observers: Copies That Do Not Slow You Down

Some Kafka distributions add a special kind of replica, often called an observer. An observer copies the data like a follower but is not counted when Kafka decides whether a write is safe. Producers therefore do not wait for it, so it adds no write latency. If the main location fails, observers can be promoted into the in-sync set so that the survivor site takes over. This gives many of the recovery benefits of a stretched cluster without paying the full cross-distance cost on every write. The trade-off is that observers are asynchronous: a sudden loss of the main location might lose the most recent records that had not yet reached the observer. Observers and automatic promotion are features offered by certain commercial platforms rather than something in every open-source installation, so check what your distribution supports.

AspectSynchronous FollowerObserver
Counts toward write confirmationYes, while in syncNo
Effect on write latencyAdds distance delayNone on the write path
Data loss risk on site failureVery lowSmall window of recent records
Can take over after failureAutomaticallyAfter promotion
Best suited forNearby locationsFarther or higher-latency locations

Safety Settings That Interact With Geography

Two settings deserve special care. The minimum in-sync replicas setting says how many replicas must confirm a write. If you demand confirmations from two locations, a total loss of one location stops writes entirely, which may be exactly what you want for zero data loss or exactly what you do not want for availability. The unclean leader election setting decides whether a replica that is behind may become leader when nothing better is available. Allowing it keeps the service up but can lose data; forbidding it protects data but can leave partitions unavailable. In a geographic design these are business decisions, not just technical ones, and they should be agreed with the people who own the risk.

Advantages

  • One cluster, one set of offsets, no translation after failover
  • Potential for zero data loss between close locations
  • Clients need no special repointing logic
  • Single place to administer topics and permissions

Disadvantages / Trade-offs

  • Needs low latency between locations
  • Three locations recommended for a healthy quorum
  • Shared control plane across all locations
  • Unsuitable for strict residency between countries
  • Network partitions between sites can cause stalls or difficult decisions
!
Common Misconception

A stretched cluster is not a global cluster. It is designed for a handful of nearby locations. Stretching a single cluster across continents is one of the best-known ways to build a slow and unstable system.

10Strategy Five: One Cluster Per Region With Replication

The strongest isolation: independent clusters that share data only through deliberate, controlled copying.

The Core Pattern

In this strategy each region runs a complete, independent Kafka cluster with its own brokers, controllers, topics, and permissions. Local producers and consumers talk only to their local cluster, which gives the best latency and the cleanest residency story. When data needs to travel, a replication tool reads from one cluster and writes to another. The clusters are separate failure domains: a problem in one region cannot corrupt or stall another.

Simple Analogy

Each country has its own post office with its own staff and rules. When a letter must cross a border, a courier service picks it up, checks it, and hands it to the other country’s post office. The two post offices never share a building.

The Replication Tools

Open Source

MirrorMaker 2

Built on Kafka’s own connector framework. It copies topics between clusters, synchronizes topic settings, translates consumer positions, and emits heartbeats so that you can measure lag.

Vendor Feature

Cluster Linking

A commercial capability that creates read-only mirror topics which copy data byte for byte, preserving offsets so that consumers can switch clusters without translation.

Custom

Stream Processing Bridges

Applications that read from one cluster, filter or transform records, and write to another. Useful when you must remove personal fields before data leaves a region.

Managed

Cloud Provider Replicators

Managed services from cloud vendors that offer cross-region topic copying with less operational effort, sometimes at the cost of fewer options.

Three Classic Topologies

Hub and Spoke (Aggregation)

Regional clusters are the spokes; a central cluster is the hub. Each region copies selected topics to the hub, where global analytics and reporting live. Data flows mostly one way, which keeps the design simple and avoids loops. Ideal for “keep raw data local, send summaries to head office.”

Active-Passive (Disaster Recovery)

One region does all the work while another region holds a continuously updated copy, ready to take over. Simple to reason about, but the standby capacity sits mostly idle, and failing over requires a clear, rehearsed procedure.

Active-Active (Multi-Region Serving)

Every region accepts writes and every region receives the others’ data. Users get local speed everywhere and any region can absorb another’s traffic. This is the most powerful and the most difficult topology, because the same business entity must not be updated in two places in conflicting ways.

flowchart LR
  EU["Europe Cluster"] -->|"replicate selected topics"| HUB["Global Hub Cluster"]
  AS["Asia Cluster"] -->|"replicate selected topics"| HUB
  AM["Americas Cluster"] -->|"replicate selected topics"| HUB
  HUB --> AN["Global Analytics"]
        
FIG 5 — Hub and spoke: raw data stays regional, chosen topics flow to a central hub

Preventing Infinite Loops

In an active-active design, a record written in Europe is copied to Asia. If the Asian side then copies everything back to Europe, the record would bounce forever. The common solution is naming: replicated topics receive a prefix that names their source cluster, and replication rules refuse to copy topics that already carry another cluster’s prefix. Consumers who want a global view subscribe to both the local topic and its prefixed remote counterparts. This convention also makes the origin of every record visible from the topic name alone, which helps with audits.

Offsets Do Not Match Across Clusters

Offsets are numbers that only make sense inside one partition of one cluster. A record that sits at position 5,000 in Europe might land at position 4,970 in the copy in Asia, for example because of retries or filtering. Byte-for-byte mirroring preserves offsets, but general-purpose replication does not. To let consumers resume after a failover, replication tools maintain a translation table between the source and target positions of consumer groups. The translation is approximate and usually errs on the side of replaying a few records rather than skipping any, so consumers must be able to handle duplicates safely.

Advantages

  • Strongest data residency and isolation story
  • Best local latency; no cross-region waits on the write path
  • Independent failure domains and independent upgrades
  • Each region can size and tune its own cluster
  • Selective replication lets you filter or strip sensitive fields

Disadvantages / Trade-offs

  • Replication is asynchronous, so recent data can be lost in a disaster
  • More clusters to run, monitor, secure, and upgrade
  • Offsets differ, so failover needs translation or careful replay
  • Active-active demands conflict-free data design
  • Replication itself consumes bandwidth and costs money
i
Design Tip

Design each entity so that only one region owns its writes at any moment, often the region where the customer lives. This “home region” idea removes most active-active conflicts before they can happen.

11Follower Fetching and Consumer Locality

Moving the reading traffic closer to the reader without moving the data itself.

The Default Path Can Be Wasteful

By default, every consumer reads from the leader of each partition. In a cluster that spans several zones or nearby locations, this often means a consumer in one zone pulls all its data across a zone boundary to reach a leader in another zone, even when a perfectly good follower copy sits right next door. That crossing costs time and, in most clouds, money. Multiply it by a large consumer fleet, and the network bill becomes noticeable.

Reading From the Nearest Replica

Since Kafka 2.4, consumers can be allowed to fetch from a follower replica that is closer to them. The consumer announces its own location label, the brokers are configured with a selector that prefers a replica with a matching label, and the consumer reads from that nearby replica. Writes still go to the leader, so ordering and durability guarantees do not change. Only the read path changes.

Simple Analogy

A newspaper is printed in one central plant, but you pick up your copy from the corner shop nearest your home rather than driving to the plant. The paper is identical; your trip is shorter.

Important Details

Detail 1

Small Freshness Delay

A follower is always slightly behind its leader. Reading from a follower may show new records a moment later than reading from the leader.

Detail 2

Committed Data Only

Followers serve only records that are already confirmed as committed, so a consumer never reads data that could later disappear.

Detail 3

Location Labels Must Match

The labels on consumers and on brokers must use the same naming, or the feature quietly falls back to the leader.

Detail 4

Works Best Within a Cluster

It helps consumers inside a stretched or multi-zone cluster. It does nothing for consumers that live in a different cluster entirely.

Consumer Groups Across Regions

A consumer group is a team that shares partitions. When members join or leave, the group pauses briefly and reshuffles, which is called a rebalance. If a group has members in several regions, each reshuffle may hand a partition to a member far from its replicas. The safest habit is to run a separate consumer group per region, each reading its own local partitions or its own local cluster, and to combine results downstream. Cooperative rebalancing, which moves only the partitions that must move, reduces the disruption when membership changes.

i
Design Tip

Measure the cross-zone and cross-region traffic your consumers generate before and after enabling nearby reads. In large fleets this single change can be one of the cheapest and safest cost reductions available.

12Data Residency, Privacy, and Compliance

Turning legal requirements into concrete Kafka design decisions.

Know What Counts as Regulated Data

Before designing anything, classify your events. Some events contain personal data such as names, email addresses, phone numbers, payment details, precise locations, or identifiers that can be linked to a person. Other events are technical or fully anonymous, like temperature readings or aggregated counts. Only the first kind is usually restricted. A common and very effective pattern is to keep the personal data in regional topics and publish only anonymized or aggregated versions to global topics.

1

Classify Every Event Type

Label each topic as personal, sensitive, internal, or public. Record who owns it and which regions may store it.

2

Decide Where Each Class May Live

Turn the legal rules into a simple table: this class may exist in these regions and may travel to those regions only after these transformations.

3

Enforce With Structure, Not Trust

Use separate clusters, placement rules, access controls, and replication filters so that a mistake by one engineer cannot break the rules.

4

Prove It

Keep evidence: placement reports, access logs, and replication rules that auditors can inspect.

Places Where Personal Data Hides in Kafka

Engineers often protect the record value and forget everything around it. Personal data can hide in record keys, in headers, in topic names, in consumer group names, in schema descriptions, in error and dead-letter topics, in monitoring dashboards, and in log files on the brokers. A customer email used as a record key is a classic example: it appears in partition metadata tools, in logs, and in replication traffic. Prefer opaque identifiers as keys, and treat error topics with the same care as main topics, since failed records carry the same personal data.

ANTI-PATTERN-01 Avoid
Problem

Personal data is used directly as the record key, or copied into headers, so it travels wherever metadata and logs travel.

Why It’s Harmful

Keys and headers are visible to more tools and are more widely replicated and logged than teams expect. A regional restriction on the value is meaningless if the key leaks the same information.

Correct Approach

Use opaque, non-identifying keys, keep personal fields inside the protected value, and review keys, headers, and error topics as part of every residency audit.

The Right to Be Forgotten Meets an Append-Only Log

Many privacy laws let people ask for their data to be erased. Kafka logs are append-only and are read by many consumers, which makes erasure awkward. There are three common approaches. Short retention simply lets old data expire on its own. Log compaction keeps only the latest record per key, and a special deletion marker for a key eventually removes the key entirely. And crypto-shredding encrypts each person’s data with their own key; deleting the key makes every copy unreadable, everywhere, at once. Crypto-shredding is powerful for geographic systems because copies may already exist in several regions, and you cannot reliably chase every copy.

Simple Analogy

Imagine photocopies of a letter scattered across many offices, each locked in a safe that opens with the same personal key. Instead of hunting down every photocopy, you destroy the key. All copies become unreadable in one step.

Sovereignty Beyond Storage

Some rules govern not only where data is stored but also who can operate the systems that hold it. If a support engineer in another country can log in to European brokers, the rules may be broken even if the data never moved. Residency design therefore includes access paths: who can administer brokers, which network paths are open, where backups go, and where encryption keys are held. Keep encryption keys in the same region as the data they protect, so that a legal demand in one country cannot reach keys stored in another.

!
Common Misconception

“The data never left the region” is not the same as “the rules were followed.” Backups, monitoring exports, support access, and dead-letter topics are frequent sources of unintended movement. Follow the data in every form, not just the main stream.

13Failure, Failover, and Failback

Planning for the day a region disappears, and for the harder day you return.

Two Numbers That Drive Everything

The recovery point objective states how much recent data you can afford to lose. The recovery time objective states how long you can afford to be down. A stretched cluster with synchronous replication can approach zero on the first number but demands nearby sites. An asynchronous multi-cluster design accepts a small loss window in exchange for distance, cheaper writes, and stronger isolation. There is no free option; the design is a negotiation between these numbers, cost, and complexity.

RPO
how much data can we lose?
RTO
how long can we be down?
Cost
what will we pay to shrink both?

What Happens During a Failover

1

Detect and Decide

Monitoring shows the primary region is unreachable. A human or an automated rule decides whether this is a true outage or a temporary network problem. Rushing this decision is a classic cause of split brain.

2

Stop the Old Writers

Make sure the old primary cannot accept writes anymore, so that two regions do not both believe they are in charge.

3

Promote the Standby

Make the surviving region writable. In a multi-cluster design this may mean turning read-only mirror topics into normal topics.

4

Repoint Clients

Switch producers and consumers to the surviving region, using a naming layer or configuration switch that was prepared in advance.

5

Resume Consumers Safely

Consumers restart from translated positions. Some records may be processed twice, so consumers must tolerate duplicates.

sequenceDiagram
  participant P as Primary Region
  participant S as Standby Region
  participant C as Clients
  P->>S: Continuous asynchronous copy
  Note over P: Outage begins
  C->>S: Switch to standby after decision
  S->>S: Promote mirror topics to writable
  C->>S: Resume from translated positions
  Note over P,S: Later: rebuild primary and plan failback
        
FIG 6 — Sequence of a regional failover in an asynchronous design

Split Brain: The Nightmare Scenario

Split brain happens when two regions both believe they are the primary and both accept writes while unable to talk to each other. When the link heals, you have two different histories for the same business data and no automatic way to merge them. Prevention comes from clear ownership rules, strong fencing that blocks the old primary, and a decision process that does not promote a standby just because a link looks broken for a few seconds.

Simple Analogy

Two branch managers each think head office has closed and each starts approving loans independently. When phone lines return, the bank discovers two conflicting sets of decisions. The cure is to decide beforehand who is in charge when contact is lost.

Failback Is Harder Than Failover

Going back to the original region after it recovers is often more difficult than leaving it. During the outage, the standby accepted new data that the old primary never saw. To return, you must first copy that new data back, verify it, reverse the replication direction, and then move clients again. Many teams choose a simpler path: treat the recovered region as the new standby and stay where they are until a planned, low-traffic window makes moving back safe.

i
Design Tip

Rehearse failover on a schedule. A written plan that has never been exercised is a hope, not a plan. Drills reveal missing permissions, stale client configuration, and surprising dependencies while the stakes are low.

Making Consumers Duplicate-Proof

Because replication and offset translation are approximate, consumers should assume that any record might arrive twice after a failover. The usual defense is idempotent processing: designing the handling of each record so that doing it twice has the same result as doing it once. Typical techniques are using a unique event identifier and remembering which identifiers have been handled, or writing results in a way that overwrites rather than accumulates.

14Security, Monitoring, and Day-to-Day Operations

Keeping a geographically spread Kafka estate safe, observable, and affordable.

Security Across Borders

Traffic between locations should always be encrypted, and both sides of every connection should prove who they are, using certificates or strong credentials. Access rules should follow the naming conventions from Chapter 6, granting each team the smallest set of topics it needs. Replication tools deserve their own limited identities that can read only the topics meant to be copied and write only to the intended destinations. Private network links or dedicated connections between regions reduce exposure compared with sending replication traffic over the open internet. Quotas protect regional clusters from a runaway client or a replication tool that suddenly tries to copy an enormous backlog.

What to Watch

Health

Under-Replicated Partitions

Counts partitions whose followers have fallen behind. In geographic designs a sustained rise often points at a slow or broken inter-site link.

Health

Replica Set Shrinking and Growing

Frequent changes in the in-sync set indicate unstable links or overloaded brokers, and precede write failures when minimum confirmations cannot be met.

Performance

Produce Request Time

The total time to complete a write, split into queueing, local processing, and waiting for followers. The follower-wait portion reveals distance costs.

Replication

Cross-Cluster Lag and Record Age

How far behind the copy is. This number is effectively your live estimate of how much data you would lose in a sudden disaster.

Consumers

Consumer Lag Per Region

How far behind each regional consumer group is. Rising lag in one region only suggests a local problem; in all regions, a global one.

Placement

Leader and Replica Location Drift

A custom check comparing the real layout with the intended layout. It catches leaders that wandered abroad after a restart.

Cost

Cross-Zone and Cross-Region Bytes

Network transfer between locations, tracked per topic and per team, so that expensive habits become visible early.

Control Plane

Controller Availability

Whether a healthy majority of controllers exists and how quickly metadata changes are applied.

Operational Habits That Pay Off

Alert on trends, not only on hard failures. A slowly growing cross-cluster lag is a warning; a lag that has reached the size of your recovery point objective is an emergency. Keep runbooks next to dashboards so that the person on call can act without hunting for documents. Upgrade regions one at a time, starting with the least critical, and always confirm that replication still works after each step. And keep an inventory of which topics are replicated where, because forgotten replication rules are a common cause of both surprise costs and residency violations.

!
Common Mistake

Teams monitor each cluster in isolation and never monitor the links between them. The link is where geographic designs fail most often. Give inter-region lag, throughput, and error rates their own dashboards and alerts.

15Choosing a Strategy and Real-World Scenarios

A practical guide to matching the strategy to the business problem.

Side-by-Side Comparison

StrategyResidency StrengthWrite LatencyFailover Data LossOperational Effort
Topic per regionWeak on its ownSame as usualDepends on cluster designLow
Region-aware partitionerMedium with placementLocal if placed wellDepends on cluster designMedium to high
Rack and replica placementMediumLocal if leaders stay homeLow within the placementMedium
Stretched clusterWeak across countriesAdds inter-site delayNear zero for nearby sitesMedium to high
Cluster per regionStrongestFully localSmall window (asynchronous)High
flowchart TD
  Q1{"Must data legally stay in a country or region?"} -->|"Yes, strictly"| A["Cluster per region with selective replication"]
  Q1 -->|"No"| Q2{"Are sites close together, under a few tens of ms?"}
  Q2 -->|"Yes, and near-zero loss is needed"| B["Stretched cluster across three sites"]
  Q2 -->|"No"| Q3{"Mainly need cost and latency control?"}
  Q3 -->|"Yes"| C["Topic per region plus nearby reads"]
  Q3 -->|"Need disaster recovery only"| D["Active-passive replication"]
        
FIG 7 — A simple decision path for choosing a geo-partitioning strategy

Four Illustrative Scenarios

Ride-Hailing Platform

Trip requests and driver locations must be handled in milliseconds, and riders in one city never need to interact with drivers in another. Each metropolitan region runs its own cluster for trips and locations. Only aggregated demand statistics and anonymized trip summaries are replicated to a central hub for planning and pricing research. Local speed and simple isolation matter more than a global order.

Retail Bank With Legal Residency Rules

Customer transactions must remain inside each country. The bank runs one cluster per legal jurisdiction, with a private standby in the same country for recovery. A stream processing bridge strips or tokenizes personal fields before sending risk indicators to a group-level cluster. Encryption keys stay in-country. Auditors receive placement and access reports on a schedule.

Global Online Game

Players connect to the nearest region for low lag, while friend lists and global leaderboards need worldwide visibility. Gameplay events stay in regional clusters; leaderboard updates are replicated in an active-active pattern using prefixed topics so that each region sees the others’ scores. Player accounts have a home region that owns their writes, which avoids conflicts.

Industrial Sensor Network

Thousands of factory sensors emit readings continuously. Each site runs a small local cluster so that machinery control keeps working during internet outages. Summaries are replicated to headquarters when the connection is available. Bandwidth is expensive, so only compressed, aggregated data crosses the wide-area link.

“Start with the strongest requirement you cannot compromise on, and let it choose the strategy for you.”

Combining Strategies

Real systems rarely use only one strategy. A common blend is a cluster per country for strict residency, a stretched cluster across three availability zones inside each country for local resilience, topic-per-domain naming with region prefixes for access control, nearby reads inside each cluster to save cost, and a small hub cluster for anonymized global analytics. Each layer solves a different force from Chapter 3, and none of them is wasted.

16An End-to-End Walkthrough: One Event Around the World

Following a single order from a customer’s phone to a global report, to see every idea from this guide working together.

Let us follow one event through a typical design that combines a cluster per region with selective replication. A customer in Germany places an order in a shopping app. Here is what happens, step by step.

1

The Order Is Created Locally

The shopping service in the European region builds an order event. The customer is identified by an opaque code, not by an email address. The personal details, such as name and delivery address, sit inside the protected value of the event.

2

The Producer Writes to the Local Cluster

The producer connects to the European cluster only. The write completes after the local replicas confirm, so it takes a few milliseconds. No ocean crossing occurs.

3

Local Consumers React

Payment, inventory, and fraud services in the same region read the event from nearby replicas. Each service has its own consumer group and its own position.

4

A Stream Processor Removes Personal Fields

A regional stream processor reads the order topic and writes a second, anonymized topic that contains only the order value, product category, country, and time. Everything that could identify a person is gone.

5

Replication Carries Only the Anonymized Topic

The replication tool is configured to copy only the anonymized topic to the global hub. The raw order topic is not on its allowed list, and the tool’s identity has no permission to read it.

6

The Hub Combines All Regions

At the hub, topics from all regions appear with source prefixes. Global analytics jobs merge them using event timestamps, since no single global order exists.

7

A Report Is Produced

The daily worldwide sales report is created from anonymized data. The original personal details never left Europe.

flowchart LR
  APP["Customer App in Europe"] --> EUC["European Cluster: raw orders"]
  EUC --> SVC["Local services: payment, inventory, fraud"]
  EUC --> SP["Stream processor removes personal fields"]
  SP --> ANON["Anonymized orders topic"]
  ANON -->|"replicated"| HUB["Global Hub Cluster"]
  HUB --> REP["Worldwide sales report"]
        
FIG 8 — Personal data stays in the region; only anonymized data travels
Simple Analogy

A hospital keeps patient files in its own building. Each night it sends the head office a sheet of numbers: how many patients were treated, how many beds were free. No names ever leave. Head office still gets everything it needs to plan.

17Best Practices and Design Patterns

Habits and reusable shapes that experienced teams rely on.

Proven Practices

Practice 1

Decide Requirements Before Tools

Write down residency, latency, recovery, and cost targets first. Tools should be chosen to meet them, not the other way around.

Practice 2

Keep Writes Local

Let producers write to the nearest cluster or region and let data travel afterwards, asynchronously, only if it must.

Practice 3

Give Every Entity a Home Region

Assign each customer, device, or account a single owning region for writes. This prevents most conflicts in multi-region systems.

Practice 4

Plan Partition Counts Generously

Choose partition counts with growth in mind, since changing them later disturbs ordering and any partition-based geography.

Practice 5

Replicate Selectively

Copy only the topics that another region truly needs, and transform them first when they carry personal data.

Practice 6

Design Idempotent Consumers

Assume duplicates after failovers and replays. Make repeated handling of the same record harmless.

Practice 7

Automate Placement Checks

Continuously compare the real placement of leaders and replicas with the intended plan, and alert on drift.

Practice 8

Rehearse Disasters

Run scheduled failover drills and record what broke. Fix the runbook, not just the incident.

Reusable Design Patterns

Regional Ingest, Global Aggregate

Raw events are stored regionally; summaries and anonymized streams flow to a central place. This pattern serves privacy, cost, and analytics together.

Home-Region Ownership

Each business entity has one region that owns its writes. Other regions may read copies. This removes most multi-writer conflicts.

Source-Prefixed Topics

Replicated topics carry the name of their origin cluster, which prevents loops, clarifies provenance, and lets consumers choose which origins to read.

Sanitizing Gateway

A dedicated stream processor sits at the regional boundary and is the only component allowed to publish data outward, so that every outbound record passes through one well-audited filter.

Tiered Retention by Region

Recent data is kept on fast local storage, older data is moved to cheaper storage, and retention differs per region to satisfy local rules and budgets.

i
Design Tip

Prefer simple, boring topologies. Each extra region, each extra replication link, and each active-active relationship multiplies the number of failure scenarios you must understand and test.

18Anti-Patterns and Common Mistakes

Ways geographic Kafka designs go wrong, and how to avoid each one.

ANTI-PATTERN-02 Avoid
Problem

A single cluster is stretched across continents to get “global resilience” with one setup.

Why It’s Harmful

Each write waits for a very long round trip, throughput collapses, and unstable links cause replicas to drop in and out of sync. The controllers also struggle to keep a healthy majority across long, unreliable distances.

Correct Approach

Use independent clusters per region and replicate asynchronously between them. Reserve stretched clusters for nearby sites with low latency.

ANTI-PATTERN-03 Avoid
Problem

Regional topics are created in one cluster located in a single country, and the team declares regional residency achieved.

Why It’s Harmful

Topic names are labels. The bytes physically live wherever the brokers are. An audit will find the data stored outside the region, which may be a legal violation.

Correct Approach

Combine topic naming with real physical placement or separate clusters, and produce evidence of where the data actually resides.

ANTI-PATTERN-04 Avoid
Problem

The team adds partitions to a live topic to make room for a growing region, when keys and regional slices depend on the current partition count.

Why It’s Harmful

Key-to-partition mapping changes, ordering per key breaks, and regional slices overlap or shift. Records for the same entity may split across partitions and regions.

Correct Approach

Plan generous partition counts up front, or create a new topic with the right layout and migrate producers and consumers deliberately.

ANTI-PATTERN-05 Avoid
Problem

Replication rules copy every topic to every region “just in case,” including topics with personal data.

Why It’s Harmful

Costs rise sharply, residency rules are broken, and the number of copies that must be secured, monitored, and erased grows without anyone deciding it should.

Correct Approach

Replicate on an explicit allow list. Every replicated topic should have a named owner, a purpose, and an approved destination.

ANTI-PATTERN-06 Avoid
Problem

An active-active design lets two regions update the same customer at the same time, with no rule about which one wins.

Why It’s Harmful

Conflicting updates cross in flight and each region ends with a different picture of the same customer. Reconciling this after the fact is expensive and sometimes impossible.

Correct Approach

Give every entity a home region that owns its writes, and let other regions read copies or send requests to the owner.

ANTI-PATTERN-07 Avoid
Problem

Two data centers are used for a self-managed stretched cluster, with the controllers split evenly or unevenly between them.

Why It’s Harmful

Losing the site with the majority stops metadata changes, and splitting them evenly leaves no majority at all when the link fails. The design fails exactly when it is needed.

Correct Approach

Use three sites with controllers spread across all three, or use separate clusters with asynchronous replication.

ANTI-PATTERN-08 Avoid
Problem

Failover has never been tested, and the team believes replication alone equals disaster recovery.

Why It’s Harmful

Data being copied is not the same as a service being recoverable. Real outages expose missing permissions, hard-coded addresses, stale runbooks, and consumers that cannot handle duplicates.

Correct Approach

Schedule regular failover drills, measure actual recovery time and data loss, and fix every surprise found.

Quick Reference: Mistakes and Their Fixes

MistakeSymptom You Will SeeFix
Leaders drifted abroadSudden rise in local write latencyRestore preferred leaders and check placement automatically
Hot regional partitionsOne broker overloaded while others idleRebalance slices or add capacity in the affected region
Replication loopTopic sizes growing without new business activityUse source prefixes and refuse to re-copy prefixed topics
Wrong consumer assignmentRegional consumers pulling data across oceansAssign regional partitions explicitly or use location-aware reading
Personal data in keysIdentifiers appearing in logs and toolsSwitch to opaque keys and audit headers and error topics

19Under the Hood: How Replication and Acknowledgements Behave Across Distance

A closer look at the internal mechanics that make distance expensive, and the settings that shape the bargain.

The Life of a Write, Slowly

When a producer sends a batch of records, the leader broker first places the batch into its own log in memory and on disk. Followers are constantly asking the leader, “do you have anything new for me?” Each follower repeats this question in a tight loop. When new data exists, the leader sends it, the follower appends it to its own log, and the next question includes the follower’s new position. The leader learns how far each follower has progressed from these questions. Once every member of the in-sync set has reached a position, that position becomes the high watermark, and everything at or below it is considered committed and can be read by consumers.

Notice something important: the leader learns about a follower’s progress only when the follower asks again. In a same-building cluster, that loop turns in a fraction of a millisecond. Across a long distance, each turn of the loop takes as long as a full round trip. The commit point therefore advances in slow steps, and every producer waiting on full confirmation waits for those steps.

sequenceDiagram
  participant Prod as Producer
  participant Lead as Leader
  participant Near as Nearby Follower
  participant Far as Distant Follower
  Prod->>Lead: Send batch
  Lead->>Lead: Append to local log
  Near->>Lead: Fetch new data
  Lead-->>Near: Batch
  Far->>Lead: Fetch new data
  Lead-->>Far: Batch after long trip
  Far->>Lead: Next fetch confirms progress
  Lead->>Lead: Advance high watermark
  Lead-->>Prod: Acknowledge
        
FIG 9 — A distant in-sync follower stretches the time until a write can be acknowledged

The Three Acknowledgement Levels

Level Zero

Do Not Wait

The producer sends and moves on. Fastest possible, but the producer never learns whether the write succeeded. Suitable only for data you can afford to lose.

Level One

Wait for the Leader

The producer waits until the leader has written the batch. Fast, but if the leader fails before followers copy it, the record can vanish.

Level All

Wait for the In-Sync Set

The producer waits until every in-sync replica has the batch, subject to the minimum in-sync setting. Safest, and the one that exposes distance costs most.

Guard Rail

Minimum In-Sync Replicas

Refuses writes when too few replicas are in sync, turning a silent safety loss into a visible error.

How Geography Changes the Meaning of “In Sync”

A replica stays in the in-sync set as long as it has kept up with the leader within a configured time window. In a single building, falling behind by that window is rare and usually signals a real problem. Across regions, a brief network wobble can push a distant replica out of the set, and a quick recovery brings it back in. Each shrink and expansion is a change that must be recorded by the control plane. If it happens frequently, the cluster spends effort on bookkeeping, and the producers using full confirmation see erratic write times. This is why distant replicas are better modeled as asynchronous observers or as a separate cluster than as ordinary followers.

Simple Analogy

A teacher will only end the class when every student has written down the homework. If one student is on a video call with a bad connection, the whole class waits each time the connection stutters. Letting that student catch up from the recording afterward keeps everyone else on schedule.

Batching and Compression: Your Distance Shock Absorbers

Producers can group many records into one batch and compress the batch before sending. Larger batches amortize the cost of each long round trip over more records, and compression reduces the bytes that cross expensive links. The same ideas apply to replication tools, which read in large batches and write in large batches. The price is a small waiting time, since a batch has to fill or a timer has to expire. In geographic designs, generous batching and compression are usually one of the highest-value tuning steps, especially for replication between clusters, where bandwidth is the main cost.

i
Design Tip

When you measure write latency in a geographic setup, look at the percentiles, not the average. A handful of slow confirmations caused by a distant link can hide inside a healthy-looking average while the slowest one percent of writes cause real user pain.

!
Common Misconception

Turning down the acknowledgement level to hide distance latency is not tuning; it is trading durability for speed. If you lower it, make that decision explicit and record who accepted the risk.

20Capacity, Skew, and Cost Planning for a Global Footprint

Sizing each region correctly and keeping the bill under control as the business grows.

Regions Are Not Equal, and They Are Not Constant

Traffic in each region follows the local clock. A region in one time zone peaks during its evening while another region sleeps. Marketing campaigns, holidays, and sporting events create spikes in specific places. If you divide partitions equally among regions, some slices will be overloaded while others sit almost idle. This imbalance is called skew, and it is the most common capacity surprise in geo-partitioned designs.

1

Measure Each Region Separately

Collect peak and average write rates, record sizes, and consumer counts for every region. Use the peak, not the average, as your planning number.

2

Add the Cost of Copying

Every write is stored several times through replication, and possibly copied again by cross-cluster tools. Multiply the raw rate by the number of copies to estimate real storage and network needs.

3

Include Failover Headroom

If region B must absorb region A’s traffic during a disaster, region B needs capacity for both. Decide whether to buy that capacity permanently, scale it on demand, or accept degraded service.

4

Plan Growth and Revisit

Review the numbers on a schedule. Regions that grow faster than forecast need partitions, brokers, or a redesign long before they fill up.

Handling a Hot Region

When one region’s partitions run hot, several remedies exist. If regions have separate clusters or separate topics, simply give the hot region more brokers or more partitions without touching anyone else. If regions share a single topic with partition slices, you may need to migrate to a larger topic layout, moving traffic in stages. Inside a region, spreading a very busy key into several sub-keys can relieve one overloaded partition, but it gives up strict ordering for that key, so use it only when ordering across those sub-keys does not matter.

Peak
size for the busiest hour, not the average
Copies
every write is stored and moved several times
Headroom
room for a neighbor’s traffic in a disaster

Where the Money Goes

Cost 1

Brokers and Storage

Compute and disks for every region, multiplied by replica copies and retention length.

Cost 2

Cross-Zone Traffic

Replica copying and consumer reads that cross availability zones inside a region.

Cost 3

Cross-Region Transfer

Replication between clusters, usually the most expensive network category, so selective replication pays off quickly.

Cost 4

People and Complexity

More clusters and links mean more on-call load, more upgrades, and more drills. This hidden cost often exceeds the hardware.

Ways to Reduce the Bill Without Losing Safety

Replicate fewer topics, and replicate summaries instead of raw events wherever the consumer only needs totals. Compress before sending across regions. Use nearby reads so consumers do not cross zone boundaries needlessly. Shorten retention for regional raw data if the business only needs a few days of it, while keeping a compact long-term copy elsewhere. Move old segments to cheaper storage tiers when your platform supports it. And review the list of replication rules every quarter, removing those whose consumers no longer exist.

“The cheapest byte is the one that never crosses a border.”
i
Design Tip

Attribute network cost to the team that causes it. When each team sees its own cross-region bill, unnecessary replication rules and wasteful consumers tend to disappear without a central campaign.

21Frequently Asked Questions

Short, honest answers to the questions people ask most often.

Q1Does Kafka have a built-in geo-partitioning feature?

Not as a single switch. Geo-partitioning in Kafka is a design assembled from partition keys, custom partitioners, replica placement, location labels, replication tools, and separate clusters. Some commercial distributions add convenience features such as placement rules and observers.

Q2Is putting the region inside the record key enough?

No. The key influences which partition a record uses, but the default hashing spreads keys evenly and knows nothing about geography. A region label in the key is useful for filtering, but it does not control where data physically lives.

Q3When should I choose separate clusters over one stretched cluster?

Choose separate clusters when regions are far apart, when legal residency is strict, or when you want independent failure domains. Choose a stretched cluster only when sites are close, latency is low, and you value near-zero data loss and a single set of offsets.

Q4How far apart can sites be in a stretched cluster?

There is no magic number, but practical guidance keeps round trips within a few tens of milliseconds, which usually means the same metropolitan area or neighboring locations. Farther than that, write latency and stability usually suffer.

Q5What is the difference between a follower and an observer?

A follower that is in sync counts toward write confirmation, so producers wait for it. An observer copies data but does not count toward confirmation, so it adds no write delay and can be promoted after a failure. Observers are offered by some commercial platforms.

Q6Will consumers automatically continue from the right place after failover?

Only if positions are preserved or translated. Byte-for-byte mirroring preserves offsets. General replication tools maintain approximate translations. In both cases, plan for a few duplicate records and make consumers idempotent.

Q7Does replication between clusters guarantee no data loss?

No. Cross-cluster replication is asynchronous, so a sudden disaster can lose records that had not yet been copied. The replication lag at that moment is your data loss window.

Q8How do I stop replicated data from bouncing back and forth?

Prefix replicated topics with the name of the source cluster and configure replication to skip topics that already carry another cluster’s prefix. This also documents where each topic came from.

Q9Can I have global ordering across regions?

Kafka guarantees order only within one partition. Merged streams from many regions have no single global order. Use event timestamps and business identifiers for downstream logic, and accept that some events are ordered only relative to others from the same source.

Q10How does the right to erasure work with an append-only log?

Common tools are short retention, compaction with deletion markers, and crypto-shredding, where each person’s data is encrypted with a key that can be destroyed. Crypto-shredding is especially handy when copies exist in several places.

Q11Should each region have its own consumer group?

Usually yes. Regional groups read local data, avoid long-distance reshuffles when members change, and keep problems contained. Combine results downstream where a global view is needed.

Q12What is the cheapest improvement to try first?

Reading from the nearest replica inside a multi-zone cluster is often the easiest cost and latency win, followed by clean regional topic naming with prefix-based access rules. Both are low risk and reversible.

Q13Is geo-partitioning worth it for a small company?

Only if one of the four forces bites you: users far away and unhappy, laws that require local storage, disaster tolerance requirements, or heavy transfer bills. Otherwise a single well-run cluster is simpler and better.

Q14Does the change from older coordination services to KRaft affect geo design?

The core lesson is the same: the control plane needs a reachable majority. With the built-in approach the controllers are part of Kafka itself, so plan their placement across sites as carefully as you plan broker placement.

22Summary and Key Takeaways

Geo-partitioning in Kafka is the art of placing streaming data where it is fast, legal, safe, and affordable. It is not a single feature but a family of strategies, from a labeled topic, through partition groups with careful replica placement, to stretched clusters with observers, to fully independent regional clusters linked by selective replication. Each step up in isolation brings stronger guarantees and more operational responsibility. The best designs start with the four forces of latency, law, failure, and cost, rank them for the business, and choose the simplest strategy that satisfies the top-ranked requirement. They keep writes local, give every entity a home region, replicate only what other regions need, transform personal data before it travels, and rehearse the day a region disappears.

Key Takeaways

  • Geography is a design input — decide where data lives on purpose, because Kafka will not decide it for you.
  • Labels are not walls — topic names and region tags in keys do not guarantee residency; physical placement or separate clusters do.
  • Keep writes local — synchronous cross-region confirmation adds a hard physics-based delay to every write, so reserve it for nearby sites.
  • Three sites for a stretched cluster — a healthy controller majority needs three locations, never two.
  • Independent clusters give the strongest isolation — replicate selectively and asynchronously, use source prefixes to avoid loops, and expect offsets to differ.
  • Plan for duplicates and drills — make consumers idempotent and rehearse failover and failback before you need them.
  • Protect data in every form — keys, headers, error topics, backups, and encryption keys all count when you prove residency.