Partition Count Limits per Broker in Kafka

Partition Count Limits per Broker in Kafka

Why "just add more partitions" is one of the most expensive habits in Kafka, what each partition really costs a broker, and how to work out a safe number for your own cluster before it turns into an outage.

Picture a warehouse with a fixed number of workers. Each worker can handle a large number of boxes, but every new shelf you add also needs labels, a floor map, a cleaning schedule and a security check. Add ten shelves and nobody notices. Add ten thousand shelves and the workers spend more time walking between shelves and updating lists than actually moving boxes. A Kafka broker is that warehouse worker, and a partition is the shelf.

Partitions are what give Kafka its speed and its ability to grow. They are also its most common source of hidden trouble. Teams often choose a large number “to be safe,” and months later they see slow restarts, long recovery times, strange delays and errors about too many open files. This guide starts from the very beginning, explains exactly what a partition is and what it costs, and then walks through how experienced architects decide how many partitions a broker should carry and how to keep the total under control.

1Why Partition Limits Exist at All

A partition looks free when you create it. The bill arrives later, and it arrives in the form of files, memory, network traffic and recovery time.

A quick picture of Kafka

Apache Kafka stores streams of events. An event is a small record of something that happened, such as “order 5521 was placed.” Events are written into named containers called topics. To spread the work, every topic is cut into pieces called partitions. Each partition is an ordered, append-only list of events. The servers that hold the partitions are called brokers, and a group of brokers working together is a cluster.

Programs that write events are producers, and programs that read events are consumers. Consumers that share the work of one topic form a consumer group, and inside one group each partition is read by only one consumer at a time. That last rule matters a lot: the number of partitions sets the maximum number of consumers that can work in parallel on one topic.

Why more partitions feel like a good idea

There are three real benefits. First, more partitions let more producers write at once, because different partitions can be written in parallel on different disks and brokers. Second, more partitions allow more consumers to read in parallel, which raises the top speed at which a group can process data. Third, a topic with many partitions spreads across many brokers, so no single machine carries all the traffic. Because of these benefits, many engineers assume that more is always better.

Why more partitions are not free

Every partition, no matter how quiet, brings a fixed set of costs to the broker that hosts it. Each partition owns files on disk. Each partition has bookkeeping objects in memory. Each partition with replicas needs copies kept up to date through constant network fetching. Each partition has an entry in the cluster’s metadata, which the controller must load, change and send to every broker. When partitions are few, these costs are invisible. When partitions reach the thousands per broker, the costs start to shape everything the cluster does.

Everyday analogy

Think of a library. Splitting a large book collection into many small rooms lets many readers work at once. But every room needs a door, a lock, a light, a cleaner and a line on the librarian’s master list. If you split the collection into fifty rooms, life is great. If you split it into fifty thousand tiny rooms, the librarian spends the whole day on the master list, and finding a book becomes slower than before.

A short history of the guidance

In the early years, Kafka clusters ran on ZooKeeper, a separate coordination service that stored all cluster metadata. Every partition added data to ZooKeeper, and the elected controller broker had to read all of it whenever it took over. Because of that, the Kafka community offered a rule of thumb that became famous: keep each broker to about 4,000 partition replicas and each cluster to about 200,000 partitions. Since then, Kafka replaced ZooKeeper with its own built-in metadata system called KRaft, and Kafka 4.0 removed ZooKeeper entirely. The new design was built so that clusters can hold far more partitions, but the per-broker costs of files, memory and replication did not disappear. That is why per-broker limits still matter.

4,000
Classic rule-of-thumb ceiling of partition replicas per broker
200,000
Classic ZooKeeper-era ceiling per cluster
4.0
Kafka version that removed ZooKeeper completely
i
Key idea

There is no single magic number that fits every cluster. The real skill is understanding what each partition costs, so you can compute a safe number for your own hardware, your own traffic and your own recovery goals.

Four myths that cause trouble

Myth 1

More partitions always mean more speed

Speed rises only until another limit is reached, such as disk, network or replication. After that, extra partitions add cost and may even reduce speed.

Myth 2

Idle partitions are free

They still own files, memory, metadata and recovery work. Only the traffic-related cost is missing.

Myth 3

The new metadata system removes limits

It raises the whole-cluster ceiling. The costs inside each broker are unchanged.

Myth 4

I can fix it later

Partitions can be added but never removed, and adding them to keyed topics can disturb ordering. Later is harder than now.

Keep these four myths in mind as you read on. Each chapter that follows will show, with numbers and pictures, why they do not hold.

2Partitions, Replicas and Leaders: Counting Correctly

The number that matters for a broker is not the number of partitions in your topics. It is the number of partition copies the broker actually holds.

Replicas: the copies that keep data safe

To survive machine failures, Kafka keeps several copies of every partition. Each copy is called a replica. The number of copies is the replication factor, and production clusters usually use three. One replica is elected leader. All producers write to the leader, and consumers normally read from it. The other replicas are followers. They continuously fetch new events from the leader so that they can take over if the leader dies. The set of followers that are fully caught up is called the in-sync replicas, often shortened to ISR.

The counting rule

Here is the formula that every Kafka architect should remember. The number of replicas that live on an average broker equals the total number of partitions in the cluster, multiplied by the replication factor, divided by the number of brokers. A cluster of nine brokers holding 3,600 partitions with a replication factor of three carries 10,800 replicas in total, which is 1,200 replicas per broker. Many people forget the replication factor when they compare their numbers with published guidance, and they end up three times too optimistic.

ClusterTotal partitionsReplication factorBrokersReplicas per brokerLeaders per broker
Small team60033600200
Growing product3,600391,200400
Busy shared platform10,800393,6001,200
Over-partitioned30,0003127,5002,500

Why leaders and followers cost different things

A leader replica does the most visible work: it accepts writes, serves reads to consumers and answers requests from followers. A follower replica does quieter work: it repeatedly fetches from the leader and writes the data to its own disk. Both kinds own files and memory objects on their broker, so both count toward the broker’s limits. Leaders add request handling load on top, so an uneven spread of leaders can overload one broker even when the total replica counts look equal.

Everyday analogy

Imagine a newsroom with reporters and note-takers. Each story has one lead reporter who answers questions, plus two note-takers who copy everything the lead says so the story survives if the reporter falls ill. A desk that holds 1,000 stories might have 333 as lead and 667 as note-taker. Every story, in either role, needs its own folder on the desk, but only the lead role involves talking to readers all day.

Do not forget Kafka’s own topics

Kafka creates internal topics that also use partitions. The topic that stores consumer group positions, called __consumer_offsets, has 50 partitions by default. If transactions are used, another internal topic called __transaction_state also has 50 by default. Tools such as Kafka Connect and Kafka Streams add more topics of their own. These are usually small next to your business topics, but they belong in your count.

!
Common trap

When you read an article that says “keep partitions under 4,000 per broker,” check whether the number means partition leaders or partition replicas. The classic guidance counts all replicas, leaders and followers together.

Rack awareness and how replicas are placed

When Kafka creates a topic, it decides which brokers will hold each replica. If brokers are tagged with a location label, such as the Availability Zone they run in, Kafka can spread the copies of one partition across different locations. This feature is called rack awareness. With three zones and a replication factor of three, each partition then has one replica in each zone, so the loss of a whole zone still leaves two copies alive.

Rack awareness affects counting in a subtle way. The brokers in each zone should hold similar numbers of replicas. If one zone has more brokers than the others, its brokers carry fewer replicas each, and the smaller zones carry more. Plan broker counts in multiples of the number of zones, such as 6, 9 or 12 brokers for three zones, so the load divides evenly and no zone becomes the weak link.

3What a Partition Looks Like on Disk

To understand the cost of a partition, open the broker’s data folder and look at what is really there.

One partition, one folder

Kafka stores each partition replica as a folder on the broker’s disk. The folder name contains the topic name and the partition number. Inside the folder, the data is not one big file. It is cut into pieces called segments. A segment is simply a chunk of the log that covers a range of offsets. An offset is the sequential number Kafka gives to each event in a partition, like a page number in a book.

Files that belong to every segment

Each segment has a group of files with the same base name. The main file holds the actual events. Next to it sit two small index files. One index helps Kafka jump quickly from an offset to a position in the main file. The other helps it jump from a timestamp to an offset. When transactions are used, a further index tracks aborted transactions. There are also small snapshot files that remember the state of idempotent and transactional producers. The important point is that one segment means several files, and one partition usually means several segments.

flowchart TB
    T["Topic orders"] --> P0["Partition 0 folder"]
    T --> P1["Partition 1 folder"]
    P0 --> S1["Segment A closed"]
    P0 --> S2["Segment B closed"]
    P0 --> S3["Segment C active"]
    S3 --> F1["Data file"]
    S3 --> F2["Offset index"]
    S3 --> F3["Time index"]
    S3 --> F4["Producer state snapshot"]
    P1 --> S4["Segment D active"]
Figure 1. One topic becomes many partition folders, each holding several segments, and each segment holds several files.

When does Kafka start a new segment?

A segment is closed and a new one started when it reaches a size limit, which is one gigabyte by default, or when it reaches an age limit, which is seven days by default. This age rule surprises many people. A quiet partition that receives only a few events a day will still roll to a new segment every week. Across thousands of quiet partitions, this creates many small segments and therefore many small files.

Retention deletes whole segments

Kafka does not delete individual events. When data becomes older than the retention setting, or when a partition grows past its size limit, Kafka removes complete closed segments. This makes deletion cheap and keeps the disk pattern simple. It also means that the number of segments alive at any moment depends on both retention and segment size. A topic that keeps data for thirty days with daily segments has around thirty segments per partition, each with its own set of files.

Setting exampleSegments per partitionFiles per partition (about)Files for 3,000 replicas on a broker
7 days retention, daily segments721 to 2863,000 to 84,000
30 days retention, daily segments3090 to 120270,000 to 360,000
1 day retention, large segments1 to 23 to 89,000 to 24,000

These numbers are only illustrations, but they teach a clear lesson. The number of files grows with partitions multiplied by segments, and long retention makes the count much larger. The file count then decides how many things the operating system must track, which is the subject of Chapter 5.

Everyday analogy

A partition is like a diary. Each week you seal one notebook and start a new one, and each notebook comes with a small table of contents and a small dated index. If you keep 30 weeks of diaries for one person, that is 30 notebooks and 60 small indexes. Now imagine you keep such a diary for three thousand people at the same desk.

i
Design tip

For topics with many partitions but little traffic, choose retention no longer than the business really needs, and avoid very small segment sizes. Fewer live segments mean fewer files for the broker to hold open.

Writes, the page cache and why sequential matters

Kafka is fast partly because it works with the operating system rather than against it. When a broker receives events, it appends them to the end of the active segment. The operating system first keeps that data in a fast area of memory called the page cache and writes it to the disk later in the background. Kafka does not force every message to the disk immediately, because safety comes from having copies on other brokers. Readers who are close to the end of the log are served straight from the page cache, which is why consumers that keep up are so cheap to serve.

This design works best when writes are sequential, which means each write goes right after the previous one on the disk. Appending to a file is sequential. But a broker with thousands of active partitions is appending to thousands of different files at the same time. On a modern solid state disk, this is fine. On a spinning disk, the head has to jump between files, and speed can fall sharply. Even on solid state disks, having thousands of different files receiving writes reduces the benefit of the page cache because the recently written tail of each file competes for the same memory.

Everyday analogy

Writing in a single notebook page after page is quick because your pen just keeps moving. Writing one line each in thousands of different notebooks means you must open, find the last page and close each notebook again and again. The total number of words is the same, but the effort is far greater.

4The Hidden Costs: What Every Partition Consumes

A partition is cheap in isolation and costly in bulk. Here is the full price list.

flowchart LR
    PART["One more partition replica"] --> FD["Open file handles"]
    PART --> MM["Memory-mapped index files"]
    PART --> HEAP["Broker heap objects"]
    PART --> REP["Replication fetch work"]
    PART --> CTL["Controller and metadata entries"]
    PART --> IO["Disk write spreading"]
    PART --> REC["Longer restart and recovery"]
    PART --> CLI["Client buffers and rebalances"]
Figure 2. Every partition replica touches eight different resources on and around the broker.
Operating system

File handles

Each segment’s data and index files are kept open. The operating system limits how many files a process can hold open, and Kafka can hit that limit.

Operating system

Memory maps

Index files are mapped into memory. The system limits how many mappings one process may have, and large partition counts can exhaust it.

JVM

Heap bookkeeping

Every partition has objects that track its segments, its leader epochs and its producer state. Small each, large in total.

Network

Replication fetching

Followers keep asking leaders for new data on every partition. More partitions mean bigger and more numerous fetch requests.

Cluster brain

Metadata

The controller stores state for every partition and pushes changes to every broker, so metadata grows with the partition total.

Disk

Scattered writes

Kafka loves sequential writes. Thousands of active partitions on one disk push the pattern toward random writes, which hurts spinning disks most.

Operations

Recovery time

After a crash, each partition must be checked and each leader re-elected. More partitions mean a longer road back to normal.

Clients

Buffers and rebalances

Producers keep a buffer per partition, and consumer groups take longer to divide partitions among their members.

Cost is not equal for all partitions

A partition that receives constant heavy traffic costs far more than an idle one, because it uses network, disk and processor time as well as the fixed costs. A quiet partition still pays the fixed costs: files, memory, fetch bookkeeping and recovery. This is the reason why “our data volume is small, so we can create as many partitions as we like” is a dangerous belief. The fixed costs do not care how much data you have.

Traffic decides how hard a partition works. Existence alone decides what it costs.

Which limit hits first?

In practice, one of several limits gets reached first, depending on the cluster. On small machines, the memory maps or file handles often run out first, and the broker fails with errors that look unrelated to partitions. On mid-sized machines, replication latency and recovery time become the complaints. On large machines with plenty of memory, the controller and metadata size are more likely to matter. That is why a single published number cannot replace testing on your own hardware.

Everyday analogy

A small restaurant can be limited by the number of tables, the size of the kitchen, the number of waiters or the size of the fridge. Whichever of these runs out first decides how many customers you can serve. A different restaurant has a different weakest link, so copying another restaurant’s seating limit without checking your own kitchen is risky.

A rough cost model you can use on a whiteboard

Nobody can give one exact price for a partition, because it depends on segments, settings and traffic. But a simple model helps you think. Imagine each replica costs a few units of fixed overhead for its files and memory, a few more for replication bookkeeping, and a share of recovery time. Multiply the fixed overhead by the number of replicas on the broker. Then add the variable cost of traffic, which depends on the bytes per second flowing through the busy partitions. The first part grows with the number of partitions. The second part grows with the number of bytes. A cluster runs into trouble when the fixed part alone uses most of the broker, leaving little room for the traffic part.

This is the reason why two clusters with the same traffic can need very different machines. One cluster serves a few hundred heavy partitions. The other serves twenty thousand light ones. The first is limited by bytes, the second by counts. Knowing which kind you run tells you what to buy: faster disks and networks for the first, more memory, processors and careful limits for the second.

Cluster styleTypical shapeMain pressureWhat to improve first
Few heavy partitionsLog shipping, clickstream, large batch feedsNetwork and disk throughputFaster disks, bigger network, balanced leaders
Many light partitionsMicroservice events, per-entity topicsFile handles, memory maps, recovery timeFewer partitions, more brokers, operating system limits
Mixed platformShared company-wide clusterBoth, plus noisy neighborsQuotas, governance and possibly separate clusters

5Operating System Limits: File Handles and Memory Maps

The first wall most teams hit is not in Kafka at all. It is in the operating system underneath.

Open files

Every program on Linux may keep only a limited number of files open at once. This limit is set per process and is often only a few thousand by default on a fresh machine. A Kafka broker keeps the files of its segments open, so its need grows with partitions multiplied by segments. If the limit is too low, the broker fails to open new files and starts throwing errors such as “too many open files,” often in the middle of a busy day when a new segment needs to be created.

Kafka’s own installation guides recommend raising this limit to a very high value, commonly in the range of one hundred thousand or more. Do not guess. Estimate your file count by multiplying replicas per broker by segments per replica by files per segment, add generous headroom for connections and temporary files, and set the limit above that.

Memory maps

Kafka uses a feature called memory mapping for its index files. The operating system lets a program treat a file as if it were part of memory, and this makes lookups very fast. But each mapped file uses one entry in a system-wide table with a limit called the maximum map count, which is 65,530 by default on many Linux versions. Each segment maps at least two index files. Therefore a broker with 20,000 segments would ask for about 40,000 mappings, which is already close to the default limit.

!
Classic failure

When the memory map limit is reached, Kafka cannot map a new index file and reports a “map failed” out-of-memory error, even though the machine has lots of free memory. Engineers waste hours adding heap memory when the real fix is one operating system setting.

A safe tuning routine

1

Count what you have

List replicas per broker and segments per replica. Multiply to estimate the total number of segments on the largest broker.

2

Estimate file handles

Take segments times about three files, then add room for client connections and a healthy safety factor.

3

Estimate memory maps

Take segments times at least two index files. Set the system map limit comfortably above this number.

4

Apply the settings permanently

Put the new limits into the service definition and the system configuration so they survive a restart, and verify them on the running process.

5

Watch usage over time

Track the open file count and the map count as metrics and alert when they pass, say, seventy percent of the limit.

Why sparse index files still matter

Kafka reserves space for an active segment’s index files up front so that they never have to grow while the broker is running. That reserved space is a sparse file, so it does not use real disk until it fills, but the address space and the mapping still count. Thousands of active segments therefore reserve a lot of virtual memory even if the disk stays nearly empty. This is another reason why many idle partitions are not as harmless as they look.

i
Interview angle

If asked why a broker with 8 gigabytes of free memory crashes with an out-of-memory error, a strong answer mentions the operating system’s memory map limit, explains that index files are mapped per segment, and says the fix is to raise the limit and to reduce segment counts by lowering partitions or retention.

Other operating system details worth checking

Open files are not only segments. Every client connection is also a file handle, so a broker that serves thousands of producers and consumers needs additional room. Add the expected number of connections to your estimate. Next, check that the file system suits Kafka. The Kafka documentation recommends modern file systems such as XFS or ext4 and warns against network file systems. A file system that holds hundreds of thousands of tiny files should also have enough inodes, the records the file system keeps for each file, or it may report “no space left” while gigabytes are still free.

Finally, remember the wider machine. The page cache needs memory outside the Java heap, so do not give all memory to the JVM. A common approach is a moderate heap, often a few gigabytes, and leaving the rest for the operating system to use as cache. Thousands of partitions increase the pressure on both, so measure garbage collection pauses as well. Long pauses on a broker can look like a broker failure to the rest of the cluster.

i
Design tip

Newer versions of Kafka can move older data to remote storage such as Amazon S3 through a feature called tiered storage. Because far fewer old segments then stay on the local disk, the local file and mapping counts shrink. It helps with the operating system limits in this chapter, but it does not remove replication, metadata or leader election costs.

6Replication Work and End-to-End Latency

Every follower replica is a small background job that never stops. Thousands of them add up.

How followers stay current

A follower does not wait to be told about new data. It runs a loop: send a fetch request to the leader, receive whatever is new, write it to disk, and ask again. A broker that hosts many follower replicas groups their requests by leader, so one fetch request can ask about many partitions at once. Each broker also runs a limited number of replica fetcher threads to do this work. With few partitions, these threads are mostly idle. With thousands, they can become the busiest threads on the machine.

The commit rule and why it creates delay

Kafka treats a message as safely stored, or committed, only after all in-sync replicas have it. A consumer normally cannot see a message until it is committed. This means the end-to-end time for a message includes the time for followers to copy it. When one broker must replicate hundreds or thousands of partitions to another broker, each round of fetching takes longer, so the message waits longer to become visible. Measurements published by the Kafka community showed this delay staying small for a few hundred partitions and growing to tens of milliseconds and beyond when a single broker pair shared a thousand or more. The exact numbers depend on hardware, but the trend is clear: latency creeps up as partitions per broker go up.

Everyday analogy

A courier picks up parcels from one warehouse and delivers copies to a second warehouse. With ten parcels per trip, each trip is quick. With ten thousand tiny parcels per trip, every parcel needs a label check and a signature, and each trip takes much longer, so the last parcel waits before it can be counted as delivered.

Falling out of sync

If a follower cannot keep up, it may be removed from the in-sync group. In recent Kafka versions the follower must fail to catch up for about 30 seconds by default before it is dropped. A dropped follower means fewer safe copies, and if producers require several copies to acknowledge a write, the producers may start to see errors or slowdowns. A broker overloaded by too many replicas is a common reason for this pattern, often shown as a rise in under-replicated partitions, which is the number of partitions whose followers are behind.

Levers you can pull

Threads

More fetcher threads

Raising the number of replica fetcher threads spreads the copy work, up to the point where extra threads compete for processor time.

Placement

Balanced leaders

Keep leaders spread evenly so no single broker carries a big share of both reads and writes.

Design

Fewer, fuller partitions

The cheapest fix is to hold fewer partitions per broker, because that removes the work instead of speeding it up.

Replication factor

Choose it deliberately

Each extra copy multiplies replication work. Use three for important data and think carefully before using more.

Example: replication on AWS across zones

A team runs a nine-broker cluster across three Availability Zones with a replication factor of three, so each partition has one copy in each zone. Every produced byte is copied to two other zones. This design survives the loss of a whole zone, but it means that all replication traffic crosses zone boundaries and is billed as inter-zone data transfer. More partitions do not change the bytes, but they change how many small fetches carry those bytes, and poorly tuned clusters can waste both time and network capacity.

Acknowledgments and the price of safety

Producers choose how sure they want to be that data is safe. With the strictest setting, the leader answers “done” only after all in-sync replicas have the data. A related broker setting, the minimum in-sync replicas, says how many copies must exist for a write to be accepted at all. A very common production choice is three replicas with a minimum of two in sync, which survives the loss of one broker without losing data or stopping writes. This is a good place to see why partition counts matter: when a broker is overloaded and a follower falls out of sync, the partition may drop below the minimum, and producers start receiving errors.

So the partition limit is also a safety limit. A broker that carries too many replicas is more likely to slow down in a way that removes copies from the safe set. The system then loses the very protection you paid for by keeping three replicas.

Setting choiceSafetySpeedEffect of overloaded followers
Acknowledge from leader onlyLowestFastestData can be lost if the leader fails before followers copy it
Acknowledge from all in-sync replicas, minimum of oneMediumMediumData may sit on a single copy for a while
Acknowledge from all in-sync replicas, minimum of two of threeHighSlower under loadSlow followers can cause write errors when fewer than two copies are in sync

7The Controller and Metadata: ZooKeeper Era and KRaft

The brain of the cluster keeps a record of every partition. How that brain is built decides how many partitions the whole cluster can hold.

What the controller does

One broker in the cluster acts as the controller. It watches which brokers are alive, chooses the leader for each partition, and tells every other broker about changes. All of that information is metadata: the list of topics, their partitions, which brokers hold each replica, and who leads. Metadata must always be correct, because clients use it to find where to send their requests.

The ZooKeeper design

In older clusters, the metadata lived in ZooKeeper, a separate service. The controller was one of the brokers, and when it failed, a new controller had to be elected and then had to read the state of every partition from ZooKeeper before it could work again. With hundreds of thousands of partitions, this reading took long enough to cause noticeable outages. Every change to a partition, such as a leader move, was also a write to ZooKeeper, so a broker failure with thousands of leaders produced thousands of writes in a short burst. These facts are the source of the old cluster-wide ceiling of about 200,000 partitions.

The KRaft design

In the modern design, called KRaft, Kafka stores metadata in an internal log that is replicated among a small group of controller nodes using a Raft-style agreement protocol. One controller is active and the others are hot standbys that already hold the full log. When the active controller fails, a standby takes over in a very short time without reloading everything from an outside system. Brokers follow the metadata log and keep an up-to-date copy in memory. This makes failovers much faster and removes the ZooKeeper bottleneck, so the design target for cluster-wide partition counts moved from hundreds of thousands to the millions.

flowchart TB
    subgraph OLD["ZooKeeper era"]
        ZK[("ZooKeeper ensemble")]
        CO["Active controller broker"]
        BR1["Brokers"]
        ZK --> CO
        CO --> BR1
    end
    subgraph NEW["KRaft era"]
        Q1["Active controller"]
        Q2["Standby controller"]
        Q3["Standby controller"]
        ML[("Replicated metadata log")]
        BR2["Brokers with metadata copy"]
        Q1 --> ML
        Q2 --> ML
        Q3 --> ML
        ML --> BR2
    end
Figure 3. In the older design the controller reads state from ZooKeeper. In KRaft, standby controllers already hold the state.

Does KRaft remove per-broker limits?

No. This is a very common misunderstanding. KRaft raises the ceiling for the whole cluster and speeds up recovery of the cluster’s brain. But files, memory maps, replication fetching, disk behavior and client buffers are broker-level costs, and they are the same as before. Every broker also keeps the full metadata in memory, so a huge cluster-wide total does still cost each broker some heap. A team that reads “KRaft supports millions of partitions” and decides to put ten thousand replicas on one broker will still meet the older walls.

!
Do not mix up the two numbers

The cluster-wide partition ceiling is mostly a controller and metadata question, and KRaft raised it a great deal. The per-broker ceiling is mostly an operating system, disk, network and replication question, and it still applies under KRaft.

AspectZooKeeper eraKRaft era
Where metadata livesZooKeeperReplicated internal metadata log
Controller failoverNew controller loads all state firstStandby controller already has the state
Cluster-wide guidanceAbout 200,000 partitionsDesign aims for millions
Per-broker guidanceAbout 4,000 replicas as a rule of thumbStill governed by the same broker-level costs
Extra system to runYes, ZooKeeperNo

How metadata reaches brokers and clients

Metadata travels in two directions. Inside the cluster, every broker follows the controller’s metadata log and applies each change to its own in-memory view. Outside, clients ask brokers for the current picture of the topics they use: how many partitions each has and which broker leads each one. Clients refresh this information periodically and whenever they hit an error such as “not the leader for this partition.”

Clients normally ask only about the topics they use, so the response is small. But some tools ask for everything: monitoring systems, administrative dashboards, connectors that read topic lists, and some poorly written scripts. A metadata response that covers hundreds of thousands of partitions is large, and a fleet of tools requesting it every few seconds can burn a surprising amount of broker processor time. When partition counts grow, review which tools ask for full metadata and slow them down or narrow their questions.

!
Hidden load

Just after a leader election storm, thousands of clients receive errors at the same moment and all refresh their metadata together. This sudden burst is one more reason why a broker with fewer leaders recovers more gracefully.

8Failures, Restarts and Recovery Time

The number of partitions on a broker decides how long a bad day lasts.

When a broker dies

Suppose a broker holding 3,000 replicas, about 1,000 of them leaders, suddenly loses power. Every partition it led is now without a leader. Producers and consumers of those partitions get errors until a new leader is chosen. The controller must select a new leader from the in-sync followers for each of those 1,000 partitions, record each decision, and tell the other brokers. Clients then must refresh their view of the cluster and reconnect. If the broker held only 300 leaders, all of these steps would finish about three times faster, and fewer applications would notice.

sequenceDiagram
    participant P as Producer App
    participant B1 as Broker 1 failing
    participant C as Active Controller
    participant B2 as Broker 2 follower
    participant B3 as Other Brokers
    P->>B1: Write to partition leader
    B1--xP: No response, broker is down
    C->>C: Detect missing broker
    C->>B2: Promote follower to leader
    C->>B3: Send updated leader metadata
    P->>B3: Refresh metadata
    B3-->>P: New leader is Broker 2
    P->>B2: Write to new leader
    B2-->>P: Acknowledged
Figure 4. Leader election work grows with the number of leaders on the failed broker.

Planned restarts are smoother, but still scale with partitions

For planned maintenance, Kafka offers controlled shutdown. Before stopping, the broker asks the controller to move its leaders elsewhere first, one group at a time, so clients see very little disruption. This gentle process takes time proportional to the number of leaders, which is why rolling upgrades of a broker with many partitions take noticeably longer. After the broker comes back, it must catch up on everything it missed, and later Kafka moves leadership back to the original preferred brokers.

Crashes and log recovery

If a broker stops without a clean shutdown, it cannot trust its files. On start-up it must check the latest segments of every partition and rebuild indexes where needed. A setting called the number of recovery threads per data directory controls how many partitions are checked at once. The default is low, so with thousands of partitions on a busy disk the start-up can take many minutes. Many operators raise this setting on brokers with lots of partitions, keeping in mind that too many threads on one slow disk help little.

Everyday analogy

After a power cut in a large hotel, the manager must walk through every room to check the locks and the safes before opening the doors again. A hotel with 30 rooms is ready in ten minutes. A hotel with 3,000 rooms needs many staff and much longer, even if most rooms were empty.

A recovery budget

Good architects work backward from a goal. Suppose the business says that no data stream may be interrupted for more than one minute after a single broker failure. You then test how long a failure of your busiest broker really takes, with realistic partition counts, and choose a per-broker limit that keeps this time under the goal with room to spare. This turns an abstract number into a promise you can defend.

i
Design tip

Rehearse failures. Run a game day where you stop one broker in a test cluster that has production-like partition counts, and record how long leader election, client recovery and catch-up replication each take. Repeat after every big growth in partitions.

A rolling-restart checklist for brokers with many partitions

1

Confirm the cluster is healthy first

There should be no under-replicated or offline partitions before the first broker is touched.

2

Stop one broker gently

Use the controlled shutdown path so leadership moves away before the process ends.

3

Restart and wait for catch-up

Wait until the returning broker has rejoined every in-sync set, not just until it is running.

4

Let leadership return

Allow preferred leader election to spread leaders back before moving on.

5

Repeat with the next broker

Only continue when the cluster is fully healthy again. Record the time each step took.

If this routine takes hours in a large cluster, it is a sign that the per-broker partition count is high or that catch-up traffic is being throttled too much. The time taken is a direct measure of how much room for growth you have left.

9Effects on Producers, Consumers and Rebalances

Partition counts do not only burden brokers. The applications on the other side of the wire feel them too.

Producers: smaller batches, more memory

A producer does not send each event on its own. It collects events into batches, one batch per partition, and sends a batch when it is full or when a short waiting time has passed. Batching is the secret of Kafka’s high throughput. When a topic has many partitions, the same stream of events is spread over more batches, so each batch fills more slowly and contains fewer events. Smaller batches mean more requests, more overhead and lower efficiency. The producer also needs memory for each partition it is writing to, so a producer touching thousands of partitions may need a larger buffer.

Modern producers reduce the pain for events that have no key. A “sticky” strategy, introduced in Kafka 2.4, keeps sending keyless events to one partition until its batch is full and then switches, which makes batches larger. Events with keys must go to the partition chosen by their key, so this help does not apply to them.

Consumers: the parallelism ceiling and the fetch cost

A consumer group can never use more active consumers than there are partitions in the topic. Extra consumers simply sit idle. This is the true reason many teams want lots of partitions: to leave room for growth in consumer count. But each consumer also fetches from every partition assigned to it, and it holds fetch buffers for each. A consumer assigned hundreds of partitions needs plenty of memory and can spend much of its time managing fetches. Kafka improved this in version 1.1 with incremental fetch sessions: instead of repeating the whole list of partitions in each request, the consumer and broker remember the list and send only the changes.

Rebalances: dividing the work again

Whenever a consumer joins or leaves a group, the group must decide again which consumer reads which partition. This process is called a rebalance. With more partitions, computing and communicating the new assignment takes longer. Older rebalances paused every consumer in the group during the change. Newer approaches reduce the pain: cooperative rebalancing lets consumers keep partitions that are not moving, and the newer consumer group protocol that became generally available in Kafka 4.0 moves the assignment work to the broker so that large groups settle faster.

Client sideWhat grows with partitionsWhat helps
ProducerBuffer memory and number of small batchesLarger buffer, sensible waiting time, sticky partitioning for keyless events
ConsumerFetch buffers and per-partition bookkeepingIncremental fetch sessions, right-sized fetch settings, more consumers
Consumer groupRebalance durationCooperative rebalancing, static membership, newer group protocol
Stream applicationsState stores and tasks, one per partitionFewer partitions on intermediate topics, careful scaling

Example: the slow-starting consumer

An analytics team created a topic with 2,000 partitions “for the future,” but only ten consumers ever read it. Each consumer now owns 200 partitions, needs large fetch buffers, and takes a long time to rebalance whenever one instance restarts during a deployment. Cutting the topic to 120 partitions and giving it room to grow later would have made deployments faster and used less memory.

i
Remember

Stream processing applications create one processing task per partition of their input topics. Too many partitions therefore multiply the internal state and threads the application has to manage.

Client quotas and noisy neighbors

Partition counts also interact with fair sharing. In a shared cluster, one application that reads or writes too hard can slow down everyone whose partitions live on the same brokers. Kafka provides client quotas that cap the bytes per second, and the share of request processing time, that a given user or client identifier may consume. A broker that hosts thousands of partitions serves many applications at once, so quotas are the seat belts that stop one busy application from starving others. Set quotas per service account and review them along with partition budgets.

Another subtle effect is connection count. Each producer or consumer opens connections to every broker that leads one of its partitions. A topic spread over many partitions and brokers therefore makes each client connect to many brokers. With thousands of clients this becomes a large number of connections, each using a file handle and some memory. Very large fleets sometimes reduce this by consolidating producers behind a small number of proxy services.

10How Many Partitions Does One Topic Need?

Before asking what a broker can hold, decide what each topic truly needs.

The throughput formula

A simple method comes from the early Kafka designers. First, measure how fast one partition can accept data from a producer, and how fast one consumer can process data from one partition. Call the target throughput of the topic T, the producer speed per partition p and the consumer speed per partition c. The number of partitions you need is at least T divided by p, and at least T divided by c. Take the larger of these two numbers.

Worked example

A topic must handle 300 megabytes per second. A test shows that a single partition accepts about 10 megabytes per second from producers and that a single consumer processes about 15 megabytes per second from one partition. Producers need 300 divided by 10, which is 30 partitions. Consumers need 300 divided by 15, which is 20 partitions. The larger number is 30. Adding about fifty percent headroom for growth gives 45. Rounding to a friendly number such as 48, which divides evenly among 4, 6, 8, 12 or 16 consumers, gives a sensible answer.

Ordering and keys

Kafka guarantees order only inside one partition, not across a whole topic. When events carry a key, such as a customer id, Kafka uses the key to pick the partition, so all events for one customer stay in order in one partition. The choice is made by a formula that divides a number derived from the key by the count of partitions. Therefore changing the partition count changes where each key goes. New events for a customer may land in a different partition from their old events, and order for that customer can break during the change.

!
One-way door

Kafka lets you increase the number of partitions of a topic but never decrease it. Once a topic has 1,000 partitions, the only way back to 100 is to create a new topic, move all producers and consumers, and delete the old one. Choose the first number with the same care you would give any irreversible decision.

How much headroom is reasonable?

A common practice is to plan for growth over one or two years and allow perhaps two to three times today’s need, not ten or a hundred times. Bigger cushions cost real resources every day. If traffic really does outgrow the topic, there are safe paths: add partitions during a quiet time when the loss of strict key order for a moment is acceptable, or create a new topic with more partitions and migrate. For topics where key order is sacred, plan the migration approach in advance instead of hoping to avoid it.

Questions to ask before choosing a number

Traffic

What is the peak, not the average?

Design for the busiest hour of the busiest season, then add a modest margin.

Consumers

How many will read in parallel?

The partition count must be at least the largest consumer count you will ever need.

Ordering

Do keys matter?

If order per key matters, avoid changing the count later, and pick a number that will last.

Retention

How long will data stay?

Long retention multiplies files per partition, so heavy topics with long retention deserve extra care.

Everyday analogy

Choosing partitions is like choosing the number of checkout lanes for a new supermarket. Too few, and customers queue. Too many, and you pay for idle staff and equipment and the manager must supervise them all. You pick a number that fits the busiest day, and you can open extra lanes later, but tearing out lanes is far harder than adding them.

Special kinds of topics

Not every topic follows the plain rules. Compacted topics keep only the latest value for each key, and they are common for holding current state such as a customer profile. Background threads called log cleaners rewrite their segments from time to time, so many compacted partitions add to the cleaning workload. Kafka’s own offsets topic is compacted for this reason. Dead-letter topics, which collect messages that failed processing, are usually low volume and rarely need more than a few partitions. Change-data-capture topics that mirror database tables often deserve one partition per table when strict order of changes matters, and this can multiply topic counts in a big database.

Stream processing adds internal topics for repartitioning and state backup. Their partition count is usually copied from the input topic, so an oversized input topic makes every internal topic oversized too. This is another quiet way that one decision spreads through the platform.

i
Design tip

Keep a short table of standard sizes for each kind of topic in your company, such as “small event topic, 6 partitions” and “state topic, 12 partitions.” Teams pick from the table, and exceptions require a short explanation.

11How Many Partitions Can One Broker Hold?

Now we reach the main question. The honest answer is “it depends,” but there is a good way to work it out.

The starting point

The classic rule of thumb is to keep the number of partition replicas per broker at or below about 4,000, and many production clusters run well under that. This figure was created for ZooKeeper-era clusters running on reasonably large machines, and it is a ceiling for well-provisioned brokers, not a target. Smaller machines need lower numbers. Some cloud providers publish their own guidance by machine size. Amazon MSK, for example, lists recommended maximum partition counts per broker that rise with instance size, from a few hundred on the smallest test-sized brokers up to about 4,000 on the largest, and it may adjust these numbers over time. Always read the current documentation for the service and version you use.

Broker size (illustrative)Comfortable replicas per brokerUpper caution zoneUsually limited by
Small (2 to 4 virtual CPUs, up to 16 GB memory)Up to about 300 to 1,000Above about 1,000Memory, file limits, small disks
Medium (8 virtual CPUs, 32 GB memory)Up to about 1,000 to 2,000Above about 2,000Replication threads and recovery time
Large (16 or more virtual CPUs, 64 GB or more)Up to about 2,000 to 4,000Above about 4,000Recovery time, network, controller metadata

These ranges are teaching examples, not official limits. Use them only to shape your first estimate, then confirm by testing on your own hardware with your own settings.

The factors that move the number

Hardware

CPU, memory, disk type

Solid state disks tolerate many active partitions much better than spinning disks. More memory leaves more room for the page cache.

Workload

How many partitions are busy

A broker with 3,000 replicas of which 100 are busy is far calmer than one where 2,000 are busy.

Retention

Segments per partition

Long retention means more files and mappings per partition and a higher operating system load.

Recovery goal

How fast you must heal

Strict recovery targets force a lower limit, because recovery time grows with the partition count.

Replication

Factor and fetch settings

More copies and more threads shift the balance between safety and load.

Clients

Producer and consumer behavior

Many small connections and heavy rebalances add to the broker’s daily work.

Leaders matter more than followers for load

A useful refinement is to watch leader counts separately. The busy work of taking writes and serving reads lands on leaders. If your cluster has three replicas per partition, a broker with 3,000 replicas normally has about 1,000 leaders. Limiting leaders per broker, in addition to total replicas, prevents a case where a few brokers have become overloaded leaders while others hold mostly quiet followers.

i
Design tip

Give every cluster two written numbers: a soft limit at which the platform team starts planning to add brokers, and a hard limit at which new topics are refused. A common pair is sixty percent and eighty percent of the value proved in testing.

How to prove your own limit with a load test

Kafka ships with performance test tools for producers and consumers. Use them, or your own load generator, to answer the question for your hardware. The exercise below takes a few hours and is worth far more than any number from a blog post.

1

Build a matching test cluster

Use the same machine type, disk type, Kafka version, operating system settings and replication factor as production.

2

Create partitions in stages

Start with 500 replicas per broker, then 1,000, 2,000, 3,000 and so on, with realistic retention.

3

Run realistic traffic at each stage

Send your expected mix of busy and quiet partitions and measure latency, request handler idle time and replica lag.

4

Break something on purpose

Stop one broker abruptly, then a planned restart, and time the election of leaders, client recovery and catch-up.

5

Find the knee of the curve

Choose the stage just before latency or recovery time begins to rise sharply. That is your proven limit.

Apply a safety factor to the result. Many teams keep production at sixty to eighty percent of the proven limit, so that a broker failure or a burst of new topics does not push the cluster over the edge.

12A Step-by-Step Capacity Planning Method

Follow this routine whenever you design a new cluster or check an old one.

flowchart TD
    A["List topics with target throughput and consumer counts"] --> B["Compute partitions per topic with the formula"]
    B --> C["Add headroom of two to three times at most"]
    C --> D["Multiply by replication factor"]
    D --> E["Divide by number of brokers"]
    E --> F{"Replicas per broker under the tested limit?"}
    F -->|Yes| G["Approve design and set alerts"]
    F -->|No| H{"Can partitions be reduced?"}
    H -->|Yes| B
    H -->|No| I["Add brokers or split into more clusters"]
    I --> E
Figure 5. Capacity planning loops until the per-broker replica count fits the limit proved by testing.
1

Collect requirements

For each topic, gather peak throughput, retention, key ordering needs and the maximum number of consumers.

2

Size each topic

Use the formula from Chapter 10, add modest headroom and round to a helpful number.

3

Total the cluster

Add up all partitions, including internal topics, multiply by the replication factor, and divide by the broker count.

4

Test the limit

On a test cluster with the same machine type, load realistic partition counts and traffic, then measure start-up time, failure recovery, latency and operating system counters.

5

Set thresholds

Declare the soft and hard limits, wire them into dashboards and alerts, and write down who acts when each is crossed.

6

Review every quarter

Compare the plan with reality. Remove unused topics, correct oversized topics and update the numbers.

A complete worked example

A company plans a cluster for 900 topics. On average each topic gets 12 partitions, so the business topics use 10,800 partitions. Internal and connector topics add about 200, giving 11,000. With a replication factor of three, that is 33,000 replicas. The test on the chosen machine type proved that a broker stays healthy up to 3,000 replicas with recovery under the one-minute goal, so the soft limit is 1,800 replicas per broker and the hard limit is 2,400. Dividing 33,000 by 18 brokers gives about 1,833 per broker, right at the soft limit. The team decides to start with 18 brokers, budget for 24 within a year, and to clean up topic sizes before adding hardware.

33,000
Replicas in the worked example
18
Brokers needed to stay near the soft limit
~1,830
Replicas per broker in the plan
!
Never plan for the average day only

Plan for the day when one broker is down. The remaining brokers absorb its leaders temporarily, and during maintenance one more broker may be down. If your cluster runs at its limit on a perfect day, it will break on the first bad day.

Choosing the number of brokers when partitions are the constraint

If the partition count sets your broker count, the calculation is simple. Divide the total number of replicas by the limit you are willing to allow per broker, then round up to a multiple of the number of zones. For the worked example, 33,000 replicas divided by a soft limit of 1,800 gives about 18.3, which rounds up to 21 brokers when using three zones. Comparing this with the traffic-based estimate tells you which factor is really in charge. If traffic needs only 9 brokers but partitions need 21, the extra machines are paying for the partition overhead. That is a strong signal to reduce partitions before buying hardware.

Example: partitions decide the bill

A retail company sizes a cluster on traffic alone and estimates 6 brokers. The topic inventory shows 24,000 partitions with a replication factor of three, so 72,000 replicas. On 6 brokers that is 12,000 replicas per broker, three times the classic ceiling. Trimming oversized topics brings the total to 30,000 replicas, which fits comfortably on 18 brokers at a soft limit of about 1,700. The lesson: the topic inventory, not the traffic graph, decided the hardware.

13Governance: Enforcing Partition Limits

A limit that nobody enforces is only a suggestion. Here is how large platforms keep partition counts under control.

Kafka has no simple built-in cap

Apache Kafka does not ship with one setting that says “refuse partitions beyond this count per broker.” Instead, platform teams put guard rails around the places where partitions are born. There are four main tools.

Policy

Create-topic policy

Kafka can call a small piece of your own code whenever a topic is created or grown. That code can refuse requests that ask for too many partitions or break naming rules.

Defaults

Sensible default count

The default partition count for new topics is one. Keep it low so that a forgotten setting cannot produce a giant topic.

Rate limits

Mutation quotas

Kafka can limit how fast one client may create or delete topics and partitions, protecting the controller from bursts.

Access

Create permissions

Access control rules can allow topic creation only for approved identities and name prefixes, and automatic topic creation can be turned off.

A topic request workflow

Mature platforms treat a new topic as a small design review, done by machine wherever possible. The requester states the expected throughput, retention, key needs and consumer count. A tool applies the formula from Chapter 10, proposes a partition count, checks it against the team’s quota and against the cluster’s remaining room, and either creates the topic or explains what to change. Teams get self-service speed, and the platform team gets numbers it can trust.

ANTI-PATTERN 01Avoid
What people do

They create one topic for every customer, device or user in a multi-tenant product, each with several partitions.

Why it hurts

Ten thousand customers with ten partitions each and three replicas means 300,000 replicas before the product has grown. Files, memory maps, metadata and recovery time all rise together.

What to do instead

Use a small number of shared topics and put the customer identifier in the message key or in the payload. Give heavy customers their own topic only when there is a real reason.

Charge back and clean up

People treat what is free carelessly. Showing each team how many partitions it owns and what share of the cluster that represents changes behavior quickly. Add a monthly report of topics with no producers, no consumers or no traffic for thirty days. Deleting dead topics is often the cheapest way to add capacity, and it also reduces the size of the metadata every broker holds.

i
Design tip

Tie the partition budget to the same naming prefixes you use for ownership and access control. If every team owns a prefix, then counting partitions per prefix is a simple query, and enforcing a team quota is a small extension of the policy that already checks names.

Guard rails for automation and connectors

Partitions are not created only by people. Data integration tools and stream applications often create topics on their own when they start. A connector for each database table, or a stream application with many stages, can create dozens of topics without anyone noticing. Review the defaults of every tool that has topic-creating power. Set the partition and replication values in its configuration to sensible small numbers, and give its service account permission to create topics only under its own prefix. This way, a mistaken configuration can create at most a bounded number of partitions.

Finally, keep a list of the small set of people allowed to override the limits. Exceptions are sometimes right, for example a heavy new pipeline that truly needs 200 partitions. What matters is that exceptions are visible, approved and counted in the same budget as everything else.

14Growing the Cluster: Rebalancing and Moving Partitions

Adding brokers does not automatically lighten the load. The partitions must be moved, and moving has its own costs.

New brokers start empty

When you add a broker to a cluster, Kafka does not shift existing partitions onto it by itself. The new broker holds only new topics created afterwards. To share the existing load, you must run a partition reassignment, which copies chosen replicas to the new broker and then removes them from the old ones. While the copy runs, the moving partition has an extra replica, and the data crosses the network and reads the disks of the source brokers.

The cost of moving

Moving replicas competes with normal traffic. A large reassignment can flood the network, slow producers and consumers, and push followers out of sync. Good practice is to move in small waves, apply a throttle that caps the bandwidth used for moves, and schedule bulk moves in quiet hours. Kafka lets you set such a throttle on replication traffic. Remember that on AWS the traffic between brokers in different Availability Zones is billed, so a giant rebalance has a direct money cost as well as a performance cost.

Everyday analogy

Hiring more staff for a busy office does not fix a queue at once, because new staff have empty desks. Somebody must carry files from the crowded desks to the new ones, and while they are carrying files, the queue moves even more slowly. You move a few boxes at a time and avoid the lunch rush.

Balancing more than counts

An even split of partition counts is not the same as an even split of load. One partition carrying 50 megabytes per second is worth many quiet ones. Balancing tools consider disk use, network in and out, and processor load as well as counts. LinkedIn, the original home of Kafka, built and open-sourced a tool called Cruise Control that watches these numbers and proposes or performs moves. Many managed services now include automatic balancing features as well.

Balance goalWhy it mattersTypical fix
Equal replica countsEven file, memory and recovery burdenReassign partitions across brokers
Equal leader countsEven request loadPreferred leader election
Equal disk usageAvoid one broker running out of spaceMove large partitions
Equal network trafficAvoid hot brokersSpread busy partitions
Zone-aware placementSurvive the loss of a zoneUse rack awareness with one replica per zone

Leader skew after restarts

After a rolling restart, leaders often end up bunched on a few brokers. Kafka can automatically move leadership back to each partition’s preferred replica on a schedule, and this setting is normally left on. If it is off, or if partitions were assigned with poor preferences, one broker can carry far more leaders than others and become the first to fail under load.

i
Interview angle

A good answer to “How do you scale a Kafka cluster that is at its partition limit?” has three parts: add brokers, reassign partitions in throttled waves, and reduce waste by deleting unused topics and shrinking oversized new ones through migration.

Moving a keyed topic to a new partition count safely

When a topic truly must change its partition count and key order matters, the safest route is a migration to a new topic. The steps below keep readers and writers in order.

1

Create the new topic

Choose the new partition count from fresh measurements, with the same settings as the old topic.

2

Copy existing data

Use a copy tool or a small stream job to replay the old topic into the new one so that keys are placed by the new count.

3

Pause producers briefly or dual-write

Either stop writers for a short window or have them write to both topics until the copy is caught up.

4

Switch consumers

Move consumers to the new topic once they have finished the old one, so nothing is skipped or repeated.

5

Retire the old topic

Keep it for a safe period as a fallback, then delete it and its access rules.

15Monitoring and Alerting for Partition Health

You cannot manage a limit that you cannot see. These are the signals worth putting on the main dashboard.

SignalWhat it tells youSuggested alert
Partition count per brokerTotal replicas hosted, leaders and followersWarn at the soft limit, page at the hard limit
Leader count per brokerRequest load balanceWarn when one broker exceeds the average by a large margin
Under-replicated partitionsFollowers that are behindAlert if above zero for several minutes
Offline partitionsPartitions with no leaderPage immediately if above zero
Active controller countWhether exactly one controller is activeAlert if not equal to one across the cluster
Request handler idle percentageHow busy the request threads areWarn when idle time falls low for long periods
Replica lagHow far followers trail leadersAlert on sustained growth
Open file descriptors and memory mapsDistance from operating system limitsWarn at seventy percent of each limit
Broker start-up and recovery timeHow long a restart really takesTrack the trend after each restart
Metadata size and controller latencyHealth of the cluster brainWarn on steady growth

Trends beat snapshots

A single reading of “2,700 replicas on this broker” means little. A chart showing that the number has risen every week for six months tells you when you will run out. Plot the growth rate of partitions per week beside the limit and estimate the date on which the soft limit will be reached. Put that date in the team’s planning calendar and order hardware early.

Measure recovery, not just health

Healthy dashboards on a normal day say nothing about a bad day. Record the time each rolling restart takes, the time to elect leaders after a test failure and the time for a replaced broker to catch up. If these times drift upward as partitions grow, you are approaching a limit even if every other graph is calm.

!
Alert fatigue

A short burst of under-replicated partitions during a planned restart is normal. Alert on sustained problems and use maintenance windows so people are not trained to ignore the page.

Example: the quiet climb

A platform team notices that their nightly restart of a test broker, which used to take about 3 minutes, now takes 11. No alert fired, because nothing was broken. Investigating shows partitions per broker have doubled in a year after several teams created many small topics. The team pauses topic creation, cleans up unused topics and adds two brokers, and restart time returns to normal before production suffers.

A weekly review routine

Dashboards only help if someone looks at them on a schedule. A short weekly review keeps partition growth honest. The platform team opens one page that shows, for every cluster, the replicas per broker against the soft and hard limits, the number of new topics created this week, the largest topics by partition count, and the slowest restart or recovery time recorded. Each week the team asks three simple questions. Which team added the most partitions, and was that justified? Which topics look oversized compared with their traffic? And how many weeks remain until the soft limit is reached at the current pace? Ten minutes on these questions each week prevents most of the emergencies described in this guide.

16Trade-offs, Patterns, Anti-patterns and Best Practices

Every partition decision balances speed today against flexibility and safety tomorrow.

Benefits of more partitions

  • Higher possible producer and consumer parallelism.
  • Load spread across more brokers and disks.
  • More room to add consumers without redesign.
  • Smaller partitions, which are quicker to move one at a time.

Costs of more partitions

  • More open files, memory maps and heap objects per broker.
  • Longer replication cycles and higher end-to-end latency.
  • Slower restarts, failovers and log recovery.
  • Smaller producer batches and heavier consumer fetching.
  • Larger metadata and more work for the controller.
  • Cannot be reduced without creating a new topic.

Patterns that work

Pattern

Size from measured numbers

Test per-partition throughput on real hardware and use the formula, rather than copying a number from a blog or another team.

Pattern

Modest headroom

Plan for two to three times today’s need. Grow later when the data proves it.

Pattern

Shared topics with keys

Put many tenants or entities in one topic, and separate them by key or field.

Pattern

Cells of clusters

Split a giant cluster into several independent clusters by business area to limit blast radius and keep counts manageable.

Pattern

Guard rails at creation

Enforce limits with a create-topic policy, quotas and disabled automatic creation.

Pattern

Regular clean-up

Delete idle topics on a schedule with owner approval.

ANTI-PATTERN 02Avoid
What people do

They create every topic with a large, round number of partitions, such as 100 or 1,000, “to never worry again,” across the entire company.

Why it hurts

Most topics carry small traffic and never need the parallelism. The cluster pays the fixed cost of all these partitions on every broker, and the count can never be lowered without migration.

What to do instead

Start each topic with the number computed from its real requirements plus modest headroom. Let the few truly heavy topics have more.

Common mistakes checklist

  • Counting partitions instead of partition replicas when comparing with guidance.
  • Forgetting internal topics and connector topics in the total.
  • Believing that KRaft removes per-broker limits.
  • Leaving the operating system’s file and map limits at default values.
  • Planning for a perfect day instead of a day with one broker down.
  • Adding partitions to a keyed topic without thinking about broken ordering.
  • Leaving automatic topic creation on in a shared cluster.
  • Never deleting topics that nobody uses.
  • Rebalancing without throttling and swamping the network.

Best practices in one place

Measure before choosing. Count replicas, not partitions. Keep per-topic partition counts close to real need. Prove your per-broker limit on your own hardware. Set soft and hard limits and enforce them at topic creation. Watch the trend and the recovery time, not just today’s health. When the limit is near, add brokers and rebalance gently, and remove waste before buying more machines.

A simple decision guide

SituationRecommended moveReason
Small topic, low traffic, no strict key orderA handful of partitions, for example 3 to 6Enough parallelism for growth without waste
Busy topic with many consumersSize by the throughput formula plus modest headroomParallelism is truly needed here
Many entities, such as customers or devicesShared topic with the entity as keyAvoids a partition explosion
Cluster near its per-broker limitDelete unused topics, then add brokers and rebalanceRemoving waste is cheaper than adding hardware
Giant company-wide clusterSplit into several clusters by domainLimits blast radius and keeps counts manageable
Strict recovery-time goalLower the per-broker limit and rehearse failuresRecovery time grows with partitions per broker

When two options seem equal, prefer the one that keeps the partition count lower. Fewer partitions are easier to move, recover, monitor and understand, and you can always add more when the data proves that you need them.

17Real-World Usage Patterns

Different businesses meet the partition limit in different ways, and they solve it with the same handful of ideas.

The large shared platform

Companies such as LinkedIn and Uber run Kafka as an internal service for a great many teams. At that size, a single team creating thousands of partitions can affect everyone else. A common answer is a platform group that publishes topic sizing guidelines, enforces limits through automation, provides self-service creation within a team quota and uses tools such as Cruise Control to keep clusters balanced. Many large organizations also run several clusters, partly so that no single cluster carries an unmanageable partition total.

The event pipeline

Netflix uses Kafka as a backbone of its event pipeline, moving huge volumes of messages from applications to processing and storage systems. In pipelines like this, a small number of very high-volume topics carry most of the bytes, so sizing those topics correctly by throughput is far more important than the many small ones, and operators can tune the big ones individually.

The internet-of-things fleet

A company connects millions of sensors. The tempting design is a topic per device, which would create millions of partitions and instantly overwhelm any cluster. The working design uses a few topics keyed by device identifier. Each device’s readings stay in order within one partition, and the cluster holds thousands of partitions rather than millions.

The software-as-a-service company

A business serving thousands of customers starts with a topic per customer for perfect isolation, then hits the wall at a few hundred customers. The fix is shared topics per event type, keys that include the customer id, and access rules or cluster-level separation for the few customers with special needs.

Managed Kafka on AWS

Teams using Amazon MSK receive published guidance for how many partitions each broker size should carry, and they choose broker sizes with those numbers in mind. Many find it cheaper to move to a larger broker class or add brokers than to fight partition overload on small machines. They also spread brokers across three Availability Zones, watch cross-zone data costs and use monitoring in Amazon CloudWatch to track partition counts and lag.

flowchart TB
    TEAMS["Product teams request topics"] --> POL["Topic policy: sizing, naming, team quota"]
    POL -->|approved| CL1["Cluster A: payments domain"]
    POL -->|approved| CL2["Cluster B: logistics domain"]
    POL -->|approved| CL3["Cluster C: analytics domain"]
    POL -->|rejected| TEAMS
    CL1 --> MON["Dashboards: replicas per broker, recovery time, lag"]
    CL2 --> MON
    CL3 --> MON
    MON --> PLAN["Quarterly review: clean up, rebalance, add brokers"]
    PLAN --> POL
Figure 6. A typical mature operating model: policy at the door, several clusters, and monitoring that feeds the next plan.

Lessons that repeat

Every successful platform makes the sensible path the easy path: self-service topic creation that quietly applies good sizing. Every struggling platform lets numbers drift until an outage forces a clean-up. The technology is the same in both. The difference is that the good ones treated partition count as a budget from the very first day.

What to do on day one of a new platform

If you are building a new Kafka platform, you can avoid nearly every problem in this guide with a few early decisions. Write down the naming convention and the sizing formula. Turn off automatic topic creation. Install a create-topic policy with a default team quota. Set the operating system limits before the first broker starts. Choose broker counts in multiples of your zone count. Decide your soft and hard limits from a load test. Put the partition dashboard on the wall. None of these steps is expensive at the start, and each one is painful to add after a hundred teams depend on the cluster.

18Frequently Asked Questions

Q1Is there an official maximum number of partitions per broker in Apache Kafka?
No hard limit is built in. The practical maximum is decided by your operating system limits, hardware, workload and recovery goals. The commonly quoted guide of about 4,000 replicas per broker is a rule of thumb for well-provisioned machines, not a rule enforced by the software.
Q2Do quiet partitions cost anything?
Yes. Even an idle partition owns files, memory-mapped indexes, heap objects and a place in replication and metadata. It also adds to restart and recovery time. Only the traffic-related costs disappear when the partition is quiet.
Q3Does a higher replication factor change the partition limit per broker?
Yes, because each extra copy is another replica that brokers must host and keep updated. With a replication factor of three, a cluster carries three times as many replicas as partitions. Always compute replicas per broker, not partitions per broker.
Q4Does KRaft let me put many more partitions on each broker?
KRaft raises the cluster-wide ceiling and speeds up controller failover, but per-broker costs such as file handles, memory maps, replication and recovery remain. You may be able to run a somewhat larger cluster in total, but you should still test the per-broker level.
Q5Can I reduce the number of partitions of a topic?
No. Kafka only lets you increase the count. To reduce it, create a new topic with fewer partitions, copy or redirect data, move applications and delete the old topic.
Q6What happens to message order if I add partitions?
Order is guaranteed only within a partition. Adding partitions changes how keys map to partitions, so new events for an existing key may go to a different partition than older ones. Plan the change for a moment when this is acceptable, or migrate to a new topic.
Q7Why does my broker report “too many open files” or “map failed”?
These messages usually point to operating system limits on open files or memory mappings being reached, driven by the number of segments, which grows with partitions and retention. Raise the limits and also reduce partitions or retention if the counts are larger than needed.
Q8How do I pick a starting partition count for a new topic?
Measure or estimate the peak throughput and the speed per partition of producers and consumers, apply the formula with the larger result, add two to three times headroom at most, and round to a number that divides evenly among your expected consumer counts.
Q9Should I create one topic per customer?
Usually not. It multiplies partitions quickly. Prefer shared topics with the customer identifier as the key, and use separate topics only for customers with special isolation or volume needs.
Q10How does tiered storage relate to partition limits?
Tiered storage moves older segments to cheaper remote storage, which cuts the number of segments and files kept on local disks and helps with disk-related limits. It does not remove the per-partition costs of replication, metadata and leader election, so it complements sensible partition counts instead of replacing them.
Q11Which metrics warn me first that I have too many partitions?
Rising restart and recovery times, growing replica lag, persistent under-replicated partitions, request handler idle time falling, and file or memory-map usage approaching limits. Trends over weeks are more useful than single readings.
Q12Is it better to have fewer big brokers or more small brokers?
Both work, with trade-offs. Bigger brokers can hold more partitions and need fewer nodes to manage, but a failure removes a larger share of capacity and recovery moves more data. Smaller brokers limit the blast radius of a failure but each holds fewer partitions and adds coordination overhead. Test both shapes with your workload.
Q13Does the number of consumers in a group have to equal the number of partitions?
No. It only needs to be no larger, because extra consumers stay idle. A group with fewer consumers than partitions simply gives some consumers several partitions each. Choosing a partition count that divides evenly by your usual consumer counts keeps the work fair.
Q14How often should I revisit partition counts for existing topics?
Review them at least every quarter, and whenever traffic changes by a large factor. Look for topics that are far larger than their traffic needs, topics that cannot add consumers, and topics that no longer have any users. Fix small problems early, before they become migration projects.
Q15Is splitting into several small clusters better than one big cluster?
It depends on your size and skills. Several clusters keep partition totals lower, limit the effect of a failure and let teams tune settings separately, but they cost more to operate and make cross-team data sharing harder. Many large companies choose a small number of clusters divided by business domain as a middle path.

19Summary and Key Takeaways

What to remember

  • Count replicas, not partitions: replicas per broker equals partitions times replication factor divided by brokers, and the classic ceiling of about 4,000 refers to this number.
  • Every partition has a fixed cost: files, memory maps, heap objects, replication work, metadata and recovery time, whether or not it carries traffic.
  • Watch the operating system: open file and memory map limits are often the first wall, and they are fixed with system settings and by reducing segment counts.
  • KRaft raised the cluster ceiling, not the broker ceiling: the per-broker costs still apply and must be tested on your own hardware.
  • Size topics from real numbers: use the throughput formula, add modest headroom and remember that partitions can never be reduced and that changing them can break key order.
  • Enforce limits where partitions are born: use create-topic policies, quotas, defaults, disabled automatic creation and shared topics with keys instead of topic-per-tenant designs.
  • Plan for the bad day: set soft and hard limits, watch recovery times and trends, rebalance in throttled waves and delete unused topics before buying more brokers.