Page Cache Sizing for Read-Heavy Workloads in Kafka

Page Cache Sizing for Read-Heavy Workloads in Kafka

Kafka is fast because it lets the operating system keep recent messages in memory. This guide explains, in plain words, how much memory to leave for that job, why it matters, and how to keep readers from spoiling it.

Imagine a busy library with one tiny desk near the front door. Every morning the librarian puts the newest books on that desk, because she knows most visitors ask for the newest books. Visitors grab them in seconds. Now imagine the desk is too small. New books fall off, visitors must walk to the far shelves in the basement, and the line grows out the door. Kafka has a desk like that, and it is called the page cache. Making the desk the right size is what this whole guide is about.

1Why Page Cache Sizing Matters

One quiet memory decision can make a Kafka cluster feel lightning fast or painfully slow.

Apache Kafka is a system that stores streams of messages and hands them to programs that want to read them. Many teams notice that Kafka can serve enormous amounts of data using fairly plain machines. The secret is not magic. Kafka keeps its own memory use small and trusts the operating system to keep recently used file data in spare memory. That spare memory is called the page cache.

A workload is called read-heavy when many more bytes leave the brokers than enter them. This happens when one topic feeds many different applications. One producer writes an order event, and then billing, shipping, fraud checks, search indexing, dashboards, and a data lake all read that same event. Every extra reader multiplies the reading work, while the writing work stays the same.

If those reads are answered from memory, the disks stay calm and delivery is quick. If those reads fall through to the disks, every reader waits in line for the disk, and the disk becomes the bottleneck. Sizing the page cache is the act of deciding how much memory you leave free so that the reads land in memory.

Simple Analogy

Think of a pizza shop. Pizzas that were just baked sit under the warming lamp at the counter, and customers get them at once. Pizzas that must be baked from scratch take twenty minutes. The page cache is the warming lamp. If the lamp has room for every pizza people will ask for in the next few minutes, nobody waits. If it holds only three pizzas and thirty people arrive, the oven becomes the problem.

Memory
Answers in microseconds
Disk
Answers in milliseconds
Sizing
Decides which one you get

The gap between memory and disk is enormous. Even fast solid state drives are many times slower than memory when a hundred readers ask at once. So a cluster with a well sized cache can serve the same traffic with fewer machines and fewer surprises, and that is why the topic deserves a full guide.

2Kafka Reads in Five Minutes

Before sizing anything, you need a picture of what a read actually is.

Kafka organizes messages into topics. A topic is a named stream, like a labelled conveyor belt. Each topic is cut into partitions, and each partition is an ordered list of messages that only grows at the end. Every message in a partition has a number called an offset, which is simply its position in line: first, second, third, and so on.

A consumer is a program that reads messages. It remembers the offset it has reached and asks the broker for the next batch starting from there. A broker is one Kafka server. Each partition lives on several brokers as copies, and one copy is the leader. Readers talk to the leader unless the cluster is set up to allow reading from a nearby copy.

On disk, a partition is stored as a series of files called segments. Only the newest segment is being written. Older segments are frozen and read only. Beside each segment sits a small index file that helps Kafka jump quickly to a given offset without scanning everything.

Term 1

Topic

A named stream of messages, like one conveyor belt in a factory.

Term 2

Partition

One ordered slice of a topic. Messages are only added at the end.

Term 3

Offset

The position number of a message inside its partition.

Term 4

Segment

A file that holds a chunk of a partition. Only the newest one grows.

Term 5

Broker

One Kafka server that stores partitions and answers readers.

Term 6

Consumer

A program that reads messages and remembers how far it has read.

Simple Analogy

A partition is like a long roll of receipt paper. New receipts are printed at the end, and nothing in the middle is ever changed. A consumer keeps a finger on the paper at the spot where it stopped reading. Segments are the roll cut into handy sections so that you do not need to carry the whole roll around.

When a consumer asks for messages, the broker finds the right segment, uses the index to find the spot, and sends a batch of bytes back. Notice that the broker does not build the answer. It only copies existing bytes from a file. That simple fact is what lets the page cache do so much of the work.

3What the Page Cache Actually Is

It is not a Kafka feature. It belongs to the operating system.

Computers read files from disks, but disks are slow. To hide this slowness, the operating system keeps copies of recently used file pieces in memory. A piece is called a page, and it is usually four kilobytes. The set of all such pages is the page cache. When a program asks for file data, the system first looks in the page cache. If the page is there, the answer comes back at memory speed. This is called a cache hit. If it is missing, the system reads it from the disk, stores it in the cache for next time, and then answers. This is a cache miss.

You can see the page cache on any Linux machine. Tools that show memory usage report a line for buffers and cached data. Many beginners panic when they see almost no free memory on a healthy Kafka broker. That is normal. The system fills unused memory with cache on purpose, because empty memory is wasted memory. The important number is how much memory is available for programs when they need it, since cache can be given back instantly.

flowchart LR
  A["Consumer asks for data"] --> B["Kafka broker"]
  B --> C{"Page in memory?"}
  C -- "Yes: cache hit" --> D["Send bytes from memory"]
  C -- "No: cache miss" --> E["Read page from disk"]
  E --> F["Keep page in cache"]
  F --> D
        
FIG 1 — A read is answered from memory when the page is cached, and from disk when it is not.

The diagram shows the two roads. Every read takes one of them. The cache hit road is short and cheap. The cache miss road is longer and uses the disk, which is shared by everyone. Your goal as an operator is to make the short road the common road.

Simple Analogy

Your kitchen table is a page cache for the pantry. Things you use every day sit on the table. Things you rarely use stay in the pantry. When the table is full and you bring a new item, something old gets put back. You never decide this consciously, but the table keeps the useful things close.

i
Good to Know

A low free memory number on a Kafka broker is usually a sign of a healthy cache, not a problem. Look at available memory and at the cache hit behavior instead of free memory alone.

4Kafka’s Big Design Bet on the Operating System

Kafka chose to lean on the page cache instead of building its own cache.

Many databases build a large cache inside their own process. Kafka does not. The designers reasoned that the operating system already has an excellent cache, and that a second cache inside the Java process would just store the same bytes twice. Storing them twice wastes memory. Worse, a big cache inside a Java program creates lots of objects, and the garbage collector must sweep them, which can pause the program.

By keeping data in the page cache, Kafka gets several gifts at once. The cache lives outside the Java heap, so it does not add garbage collection work. The cache survives when the Kafka process restarts, because it belongs to the operating system. That means a restarted broker can come back with a warm cache instead of a cold one. And the operating system is very good at deciding which pages to keep.

Advantages

  • No second copy of the data inside the Java heap
  • Small heaps mean short garbage collection pauses
  • The cache stays warm after a broker process restart
  • The operating system tunes the cache automatically
  • Very little Kafka code is needed for caching

Disadvantages / Trade-offs

  • Kafka cannot decide which pages to keep or drop
  • Other programs on the machine can steal cache memory
  • A reboot or new machine starts with an empty cache
  • Sizing needs care because nothing warns you when the cache is too small
Simple Analogy

Instead of hiring a private chef with a private fridge, Kafka eats at a big restaurant that already has a great kitchen. It is cheaper and simpler, but Kafka must accept that the restaurant decides what stays warm on the counter.

This design bet is the reason sizing memory is different for Kafka than for many other systems. You do not hand Kafka a giant heap. You give it a modest heap and leave the rest of the machine’s memory alone so that the operating system can use it as cache.

“Kafka does not cache data. It arranges for the operating system to do so.”

5The Write Path: How Fresh Data Lands in Cache

Reads are fast mostly because writes put the data in the right place first.

When a producer sends messages, the leader broker appends them to the end of the newest segment file. It does this with an ordinary file write. The operating system accepts the bytes into the page cache and answers right away. The bytes are marked dirty, which simply means they have not yet been saved to the disk. Later, a background job of the operating system writes dirty pages to the disk at a convenient time.

Kafka does not force each write to the disk by default. Instead, it relies on copies. Other brokers hold replicas of the same partition, so if one machine loses its memory in a crash, the data still exists elsewhere. This is a deliberate choice that trades a small risk on one machine for far greater speed, protected by replication across machines.

The important consequence for reading is this. Fresh data is already sitting in the page cache the moment it is written. Nobody has to load it. A consumer that reads new messages seconds later finds them in memory. This is why sizing focuses on how long fresh data stays in the cache before newer data pushes it out.

1

Producer sends a batch

The leader broker receives a group of messages over the network.

2

Append to the segment file

The broker writes the bytes to the end of the active segment. They land in the page cache and are marked dirty.

3

Followers copy the data

Follower brokers fetch the new bytes, mostly from the leader’s cache, and write them into their own caches.

4

Consumers read the newest data

Readers ask for the newest offsets and receive bytes straight from memory.

5

The system flushes in the background

The operating system quietly writes dirty pages to disk later, without holding anyone up.

Simple Analogy

A waiter writes your order on a notepad and shouts it to the kitchen at once. Filing the paper order in the big binder can wait until the evening. Everyone who needs the order already heard it, so nothing is lost when the filing is delayed.

!
Common Mistake

Some people force frequent flushing to disk hoping for safety. That usually hurts speed a lot and adds little safety compared with using enough replicas. Safety in Kafka comes from copies on different machines.

6The Read Path and the Zero-Copy Trick

A cache hit gets even cheaper because Kafka can skip most copying.

In an ordinary program, sending a file over a network involves several copies. The data is read from disk into a kernel buffer, then copied into the program’s memory, then copied into another kernel buffer for the network card, and finally sent. Each copy burns processor time and memory bandwidth.

Kafka avoids this with a system feature commonly called zero-copy. The broker asks the operating system to send bytes from a file straight to the network connection. The data moves from the page cache to the network card without visiting the Java program at all. The broker’s own processor barely notices the transfer, and the Java heap stays quiet.

This is why cache hits matter twice. First, they avoid the slow disk. Second, they allow the cheap zero-copy road, where the processor does almost nothing. A single broker can then push out a very large stream of data to many readers, limited mostly by the network card.

flowchart LR
  subgraph Ordinary["Ordinary way: many copies"]
    D1["Disk"] --> K1["Kernel buffer"] --> P1["Program memory"] --> S1["Socket buffer"] --> N1["Network"]
  end
  subgraph ZeroCopy["Kafka zero-copy way"]
    PC["Page cache"] --> N2["Network card"]
  end
        
FIG 2 — Zero-copy skips the trip through the program, so cached data leaves for the network with almost no work.
Simple Analogy

Imagine passing a parcel. In the ordinary way, you hand the parcel to a helper, who carries it to another helper, who carries it to the delivery van. In the zero-copy way, the parcel is already on a conveyor belt that rolls straight into the van. Fewer hands, less effort, and faster delivery.

Later chapters will show that a few common settings quietly turn zero-copy off. Encryption of the connection is the best known one. When that happens, the broker must touch every byte, and the cost of reading rises sharply. Keep this in mind, because it changes how much capacity a read-heavy cluster really has.

7Tail Readers and Catch-Up Readers

Not all readers are equal. Two kinds behave very differently for the cache.

A tail reader is a consumer that keeps up with the newest data. It reads messages moments after they were written. Because fresh messages sit in the page cache, tail readers almost always get cache hits. They are the happy customers of Kafka.

A catch-up reader is a consumer that is behind. Maybe it was switched off for maintenance, maybe it was slow because of a bug, or maybe it is a brand new application that wants to replay yesterday’s history. Such a reader asks for old offsets. Old data may no longer be in the cache, because newer data has pushed it out. So the broker has to read it from disk.

The trouble does not stop at the slow disk read. When the broker loads old pages into the cache for the catch-up reader, those pages take room. That room comes from other pages, which might be the fresh pages that the tail readers need. This is called cache pollution, and it is the main enemy of a read-heavy cluster. One greedy catch-up reader can make everybody else slower.

Reader 1

Tail reader

Reads the newest data. Almost always served from memory. Cheap for the broker.

Reader 2

Lagging reader

Is a little behind. May or may not hit the cache, depending on how far behind and how big the cache is.

Reader 3

Replay reader

Starts from the beginning of retained history. Mostly served from disk and can pollute the cache.

Reader 4

Follower replica

A broker copying data from the leader. Usually a tail reader, but becomes a catch-up reader after an outage.

Simple Analogy

Picture a school library where the front table holds this week’s popular books. Most students take from the front table. One student walks in and asks for twenty old encyclopedias from the basement. The librarian carries them up and puts them on the front table to make the walk shorter, so this week’s popular books are pushed onto the floor. Everybody else now waits.

i
Sizing Idea

A good cache is sized so that tail readers and reasonably lagging readers fit inside it together. You cannot afford to fit deep replays, so those must be handled some other way.

8Anatomy of a Read-Heavy Workload

Before you size a cache, describe the workload in numbers and words.

Read-heavy does not have a single shape. Some clusters have a modest write rate and a huge number of consumer groups. Others have one enormous consumer group with hundreds of members. Some serve mostly tail readers, while others serve batch jobs that scan hours of history. Each shape needs a different answer.

The first idea to grasp is fan-out. Fan-out is the number of separate groups that read the same data. If ten groups read the same topic, the broker sends each message ten times, plus copies to followers. The good news is that all ten reads hit the same cached pages. The cache holds one copy, and ten readers share it. So fan-out raises network and processor work, but it does not raise the amount of cache you need, as long as all groups read at roughly the same position.

The second idea is spread. Spread is how far apart the readers are inside the log. If all ten groups are at the tail, they share one small hot area. If they are scattered across the last six hours, the hot area is six hours wide. Cache need grows with spread, not with the number of readers.

flowchart TD
  W["Producers write new data"] --> L["Partition log in page cache"]
  L --> G1["Billing group at the tail"]
  L --> G2["Search group at the tail"]
  L --> G3["Dashboard group a few minutes behind"]
  L --> G4["Nightly job reads old history"]
  G4 -. "loads old pages" .-> D["Disk"]
        
FIG 3 — Many groups can share the same cached pages, but a group reading old history reaches for the disk.
Simple Analogy

Ten people reading the same newspaper on one table need one newspaper, not ten. But if each person asks for a different day’s newspaper, you need a table big enough for ten different newspapers.

Workload shapeWhat it stressesCache need
Many groups, all at the tailNetwork and processorSmall
Few groups, some minutes behindCache sizeMedium
Batch jobs scanning hours of dataDisk and cache pollutionLarge or impossible
Frequent replays by new appsDisk readsBest handled by isolation

The whole log is huge. The part you must keep in memory is much smaller.

Suppose your brokers store seven days of data. That could be tens of terabytes. Nobody expects the page cache to hold all of that. What matters is the hot set: the slice of data that readers touch again and again within a short time. For a cluster full of tail readers, the hot set is the last few minutes of writes on each broker.

The working set is a slightly larger idea. It is the data that active readers need across a chosen period, such as one busy hour. If the working set fits into the cache, nearly every read is a hit. If the working set is larger than the cache, the system keeps throwing out pages just before they are needed again, and the hit rate falls.

This is why capacity planning for the cache starts with a question about people and programs, not about machines: how far behind is the slowest reader we still want to serve from memory? That answer, converted into a length of time, becomes the width of your hot set.

Simple Analogy

A chef does not keep the whole grocery store on the counter. She keeps the ingredients for tonight’s menu within arm’s reach. The counter size should match tonight’s menu, not the size of the store.

Short hot set: real-time alerting

All readers are at the tail and act on messages within seconds. The hot set is only a minute or two of writes, so a small cache is enough.

Medium hot set: dashboards and micro-batches

Some readers poll every few minutes and may fall behind during spikes. The hot set becomes ten to thirty minutes of writes.

Long hot set: hourly batch consumers

Jobs wake every hour and read everything since last time. Keeping all that in cache is costly, so teams often accept disk reads for these jobs while protecting the tail readers.

i
Practical Tip

Write down the slowest reader you truly want to protect and how far behind it can get during a bad hour. That single sentence is the seed of your whole sizing plan.

10Splitting Memory: Heap Versus Page Cache

A Kafka machine has memory for three things: the operating system, the Java heap, and the cache.

Java programs keep their objects in a region called the heap. Kafka’s heap holds bookkeeping such as partition state, request objects, and buffers. It does not hold message bodies for long. Because of this, a modest heap is usually enough. Many teams run brokers with a heap in the range of a few gigabytes, often around six. Very large heaps bring longer garbage collection pauses and steal memory from the cache for no benefit.

The operating system itself needs some memory for its own work, network buffers, and running other small services such as monitoring agents. Whatever is left is what the page cache can use. So the rule is simple to say: give the heap only what it needs, keep the operating system happy, and let the rest be cache.

flowchart LR
  subgraph Machine["One broker machine, for example 64 GB"]
    H["Java heap: about 6 GB"]
    O["Operating system and agents: about 4 GB"]
    C["Page cache: the remaining memory, about 54 GB"]
  end
        
FIG 4 — A small heap and a lean operating system leave most of the machine’s memory to the page cache.
Simple Analogy

A restaurant has a kitchen, an office, and a dining room. The office is small because paperwork is small. The kitchen is the working core. Most of the building should be the dining room, because that is where customers actually enjoy the service. In Kafka, the dining room is the page cache.

!
Common Mistake

People often raise the heap to fix a problem and accidentally starve the cache. Every extra gigabyte given to the heap is a gigabyte the cache can no longer use. Increase the heap only with evidence, and check cache impact afterwards.

Other services on the same machine also compete. A log shipper, a security scanner, or a co-located application can quietly consume memory. On a machine where the cache is the star, every side program has a cost that appears as extra disk reads.

11A Simple Sizing Method in Words

You can size the cache with a short chain of easy steps and a little arithmetic.

The method turns the question how much cache do I need into a multiplication. The main idea is that the cache must hold the newest data for as long as your slowest protected reader might lag. So you multiply the rate at which new data arrives on one broker by the length of time you want to cover, and then add a safety margin.

1

Measure the write rate per broker

Take the total data rate arriving from producers, multiply by the replication factor because every message is stored on several brokers, and divide by the number of brokers.

2

Choose the time window to protect

Decide how many minutes of lag you want served from memory. Five minutes covers ordinary hiccups. Thirty minutes covers slow batch consumers.

3

Multiply rate by window

That product is the amount of fresh data that must sit in the cache to serve readers inside the window.

4

Add a safety margin

Traffic is bursty, and the cache also holds index pages and other files. A margin of one and a half to two times is a common starting point.

5

Add heap and operating system memory

The total machine memory is the cache need plus the heap plus the memory the system needs for itself.

Simple Analogy

A bakery that sells forty loaves an hour and wants to always have the last thirty minutes of bread on the shelf must fit twenty loaves. Adding a little extra room for busy mornings gives the final shelf size. The method is the same shopkeeper thinking, applied to bytes.

!
Remember

This is an estimate to get you started, not a law of nature. Always confirm with measurements from a real cluster, which later chapters explain.

12A Worked Example with Friendly Numbers

Let us walk through the method once with round numbers.

Imagine a cluster of six brokers. Producers send a combined 200 megabytes per second of new data. The replication factor is three, meaning every message is stored on three brokers. So the cluster as a whole absorbs 600 megabytes per second of writes once copies are counted. Divided across six brokers, each broker takes in about 100 megabytes per second.

The team decides they want to serve any reader that is up to five minutes behind straight from memory. Five minutes is 300 seconds. So each broker needs to keep about 100 times 300, which is 30,000 megabytes, or roughly 30 gigabytes of fresh data. With a safety margin of two times, they aim for about 60 gigabytes of page cache.

Add a heap of about 6 gigabytes and about 4 gigabytes for the operating system. The total is around 70 gigabytes. In practice the team would pick the next standard machine size above this, such as one with 96 or 128 gigabytes, and enjoy extra room for growth.

100 MB/s
Writes per broker with copies
300 s
Five minute protection window
~60 GB
Cache target after 2x margin
StepResult
Producer rate for the cluster200 MB/s
Rate with replication factor of three600 MB/s
Rate per broker over six brokers100 MB/s
Window of five minutes (300 seconds)30 GB of fresh data
Safety margin of two times60 GB of cache
Add heap and operating systemAbout 70 GB of memory per broker
Simple Analogy

It is like packing a suitcase for a five day trip. You count clothes for five days, add a few extra in case it rains, and then pick a suitcase big enough. Nobody packs for the whole year.

i
A Second Check

Look at the read side too. If ten groups read the tail, each broker sends roughly the leader share of 200 megabytes per second times ten, plus follower traffic, so network capacity must also be checked. A perfect cache does not help if the network card is full.

13Replication and Partition Count Multipliers

Copies and partitions change how much data each broker must hold in memory.

The replication factor is the number of copies of each partition. A factor of three is the common choice for important data. Every copy is written by a different broker, so each of those brokers needs to fit its own fresh data in its own cache. This is why the write rate in the sizing method is multiplied by the replication factor before dividing by the number of brokers.

The number of partitions matters in a quieter way. Each partition is a separate set of files with its own active segment. With thousands of partitions on a broker, the fresh writes are spread over thousands of file locations. Total fresh bytes do not change, but the pattern becomes scattered. Scattered access can weaken the benefits of sequential disk writing and read ahead. Extra files also mean extra open file handles and extra index pages.

Spreading load evenly is the last piece. If one broker leads many busy partitions, its cache need is larger than the average you calculated. A cluster with uneven leadership will have one hot machine whose cache is too small while others sit half empty. Balanced leadership is therefore part of cache sizing.

Factor 1

Replication factor

More copies mean more fresh bytes stored across the cluster, so more cache in total.

Factor 2

Broker count

More brokers share the load, so each needs less cache for the same total traffic.

Factor 3

Partition count

More partitions scatter access and add index and file overhead.

Factor 4

Leader balance

Uneven leaders create a hot broker that needs more cache than average.

Simple Analogy

If a school has three copies of every textbook in three different classrooms, each classroom needs a shelf for its copies. Adding more subjects means more shelves. And if one teacher is given all the busiest subjects, her classroom gets crowded while the others stay quiet.

i
Practical Tip

Size for the busiest broker, not the average one. A single overloaded leader can make a whole cluster look slow.

14Eviction and Cache Pollution

When memory is full, something must leave. The choice matters.

The page cache cannot grow without limit. When new pages arrive and memory is short, the operating system removes older pages. Linux roughly keeps two lists. Pages touched only once go on a list of inactive pages. Pages touched more than once move to a list of active pages. When space is needed, the system usually evicts pages from the inactive list first.

This design gives Kafka some natural protection. A page read by many groups becomes active and tends to stay. A page read once by a lonely catch-up reader stays inactive and leaves first. In theory, that already limits pollution from one-time scans.

Theory has limits, though. A very large scan can flood memory faster than pages are promoted, and it can squeeze out pages that would have been used soon. In addition, fresh writes are new pages that are not yet active. If a burst of old reads arrives at the same time as a burst of writes, fresh data can be evicted before consumers reach it. Then the tail readers, who should have been safe, get cache misses.

flowchart LR
  N["New page arrives"] --> I["Inactive list"]
  I -- "touched again" --> A["Active list"]
  I -- "memory is short" --> E["Evicted"]
  A -- "long unused" --> I
        
FIG 5 — Pages touched once tend to leave first, while pages touched repeatedly are protected on the active list.
Simple Analogy

A coat check keeps two hooks. Guests who come once leave their coats on the busy hook near the door. Guests who visit often are given a special hook in the back. When the room is full, the attendant clears the busy hook first. But if a huge tour group arrives all at once, even the special hook can run short.

!
Common Mistake

Assuming that the operating system will always protect hot pages is risky. Heavy replays can still hurt. Plan isolation for them instead of hoping the eviction rules will save you.

15Lagging Consumers: The Silent Cache Killers

A slow reader hurts more than its own speed.

Consumer lag is the number of messages a consumer group still has to read. A small, steady lag is normal. A growing lag means the group is falling behind. Every minute of lag pushes the group’s position farther into the past, and older data is more likely to have left the cache.

The dangerous moment is the turning point. While the group is inside the cached window, its reads are cheap. Once it slips outside, each read costs a disk trip. A disk trip is slower, so the group falls further behind, which means even more disk trips. This is a downward spiral. The reader that needed cache help the most is the one that has lost it.

The spiral spreads. Disk reads from the slow group compete with disk writes and with other readers’ misses. Latency rises for everyone. Producers may see slower acknowledgements, and followers may fall out of sync. A single lagging group can therefore create trouble far from where it started.

1

A group slows down

Maybe a downstream database is slow, so the group reads fewer messages per second than arrive.

2

Lag grows past the cached window

The group asks for offsets that were pushed out of memory.

3

Disk reads begin

Each request now waits for the disk, so the group slows even more.

4

Neighbors suffer

Disk busy time rises and pollution removes hot pages, so other groups miss the cache too.

Simple Analogy

A traffic jam behind a slow truck grows longer the longer it lasts. Once the road is packed, even fast cars far behind cannot pass. One slow vehicle changes the whole highway.

The lesson for sizing is to pick your protection window with the spiral in mind. Extra cache gives slow groups more time to recover before they cross the danger line. It works like a shock absorber.

16Things That Quietly Break Zero-Copy

Some settings look harmless but make every read cost far more.

Chapter 6 described zero-copy, which lets bytes flow from the cache to the network card without touching the Java program. A few common features force the broker to read, transform, and copy data. When that happens, the processor and memory bandwidth become new limits, and the cheap road is closed.

Encrypting client connections with TLS is the most common cause. To encrypt data, the broker must load each byte into user space, scramble it, and send the scrambled result. The page cache still helps by avoiding disk reads, but the cost per byte is higher. Clusters that enable encryption for all traffic often need more processors and sometimes more brokers to move the same volume of data.

Another cause is the conversion of message formats for old clients. If a consumer speaks an old version of the protocol, the broker may have to convert stored messages into the old format before sending. This is called down-conversion, and it defeats zero-copy for those readers. Keeping clients reasonably up to date avoids this hidden tax.

A third cause is when the broker must change how data is compressed. Normally producers compress batches and the broker stores them unchanged, so readers receive the same compressed bytes. If broker settings force recompression, the broker burns processor time on every batch.

FeatureWhat happensEffect on reading
Encrypted client connectionsBroker must process each byteHigher processor use per read
Old client versionsDown-conversion of stored messagesZero-copy lost for those readers
Forced recompressionBroker recompresses batchesProcessor spent on every batch
Plain connections with modern clientsBytes move as storedZero-copy works fully
Simple Analogy

Shipping a sealed box is easy: you lift it and hand it over. If the customer demands that every item be unpacked, wrapped in a new paper, and packed again, the same order needs ten times more workers. Encryption and conversion are the unpacking and repacking.

i
Sizing Idea

When you turn on encryption, do not only size memory. Test the processor headroom too, because a perfect cache cannot fix a tired processor.

17Disk Types and the Price of a Miss

The cost of a cache miss depends on what is under the cache.

A spinning hard disk has a moving arm. Reading data in a straight line is fine, but jumping around is slow. Kafka’s access pattern is mostly sequential, which is why hard disks worked well for it for years. Still, when many readers each ask for different places, the arm must jump between them, and speed falls a lot.

A solid state drive has no moving parts and handles scattered reads much better. An NVMe drive, which connects through a faster path, is better still. On such disks a miss is far less painful, and the cache can be smaller for the same experience. Yet even the fastest drive is slower than memory, and it has limited throughput shared between writes, replication, and reads.

Cloud volumes add another twist. Network attached volumes have limits on operations and throughput per volume, and bursts may be allowed for a short time and then throttled. A cache miss on such a volume competes with these limits. A miss that costs a few milliseconds in a test may cost much more when the volume is throttled.

flowchart TD
  M["Cache miss"] --> Q{"Which storage?"}
  Q --> H["Spinning disk: slow when readers scatter"]
  Q --> S["Solid state: good with scattered reads"]
  Q --> V["Network volume: limited by throughput and operation caps"]
  Q --> L["Local NVMe: fastest, but tied to the machine"]
        
FIG 6 — The same cache miss costs very different amounts depending on the storage underneath.
Simple Analogy

Fetching something from the basement is quick if you have an elevator, slower with stairs, and slowest if the basement door is locked and only opens in bursts. The cache is the drawer next to you, and how much you fear a trip to the basement decides how big that drawer must be.

!
Common Mistake

Choosing fast disks and then skimping on memory is like buying a sports car and putting cheap tires on it. Fast disks make misses gentler. They do not make misses free.

18Read-Ahead and Sequential Patterns

The operating system guesses what you will read next, and Kafka’s pattern makes the guess easy.

When a program reads a file in order, the operating system notices and starts loading the next pieces before they are requested. This is called read-ahead. For a catch-up reader scanning a partition from old to new, read-ahead can hide much of the disk delay, because the next pages are already arriving when the reader asks for them.

Read-ahead has a cost as well. It pulls pages into the cache that may not be needed, and those pages take space. It works best for a few long sequential scans. It works poorly when hundreds of readers each request small pieces from different files, because the system must guess for each and its guesses fill the cache with pages nobody wants.

There is a tuning knob for the size of read-ahead on each disk device. Larger values help long scans and hurt scattered reads. Kafka’s default patterns rarely need extreme values, but teams with many replays sometimes tune it after measuring. As always, measure before changing.

Simple Analogy

A waiter who sees you finish the soup brings the main course early. That is helpful when you are eating in order. If the waiter guesses wrong for a hundred tables at once, the kitchen floods with dishes nobody ordered.

Advantages

  • Hides disk delay for long sequential scans
  • Works automatically without Kafka doing anything
  • Helps followers that are catching up after an outage
  • Suits Kafka because logs are read in order

Disadvantages / Trade-offs

  • Loads pages that may never be used
  • Takes cache space from hot data during heavy replays
  • Can waste disk throughput with many scattered readers
i
Practical Tip

Keep the defaults until measurements show a problem. If you tune it, change one thing at a time and compare disk read rates before and after.

19Index Files and Memory-Mapped Pages

The small helper files also live in the cache, and they need room too.

Each segment has index files. An offset index maps message numbers to positions in the segment file. A time index maps timestamps to offsets. When a consumer asks for a specific offset, the broker checks the index to find where to start reading. These index files are small compared with data files, but they are used on every fetch.

Kafka reads indexes through memory mapping, a feature that lets a file appear as part of the program’s memory. Behind the scenes, the pages of the index still live in the page cache. If an index page is not cached, the lookup causes a disk read before the data read can even begin. That doubles the delay of a miss.

Since indexes are tiny, keeping them cached costs very little. But with thousands of partitions and long retention, the total index size grows. The number of memory mappings a process may hold is limited by a system setting, and brokers with many segments need that limit raised. If the limit is too low, brokers can fail in surprising ways when they try to open more segments.

File 1

Log segment

Holds the real message bytes. This is the big file.

File 2

Offset index

Helps find the byte position of a given message number quickly.

File 3

Time index

Helps find the offset that matches a given time.

File 4

Other small files

Checkpoints and transaction helpers that are read at startup and occasionally later.

Simple Analogy

A thick book has a table of contents at the front. If the table of contents is on your desk, you flip straight to the right page. If it has been left in another room, you must fetch it before you can even begin. The index is the table of contents, and it deserves a spot on the desk.

i
Good to Know

Raise the operating system limit on memory maps for brokers with large numbers of partitions and long retention. Documentation on production deployment lists a suggested approach.

20Dirty Pages and Background Writeback

Fresh data has to reach the disk eventually. How that happens affects reads.

Dirty pages are cached pages that have changed but are not yet saved. The operating system has two levels of control. Below a certain amount of dirty data, a background helper writes pages out gently. Above a higher limit, programs that write are forced to wait while the system catches up. Both limits are set as a share of memory.

On a machine with a very large amount of memory, a share can become a very large absolute number. If the limits are too high, dirty data can pile up into a huge lump, and then the system writes it all in a rush. During that rush the disk is saturated and reads that miss the cache must wait behind the writes. Latency spikes appear at regular intervals.

Many operators lower the background limit so that flushing starts earlier and proceeds smoothly. Smaller and steadier writes leave more disk time for reads. Others use the byte based versions of the limits so that they do not scale with the total memory. The right values depend on disk speed and write rate, so measure the effect.

sequenceDiagram
  participant P as Producer writes
  participant C as Page cache
  participant B as Background flusher
  participant D as Disk
  P->>C: New bytes marked dirty
  C->>B: Dirty level rises
  B->>D: Gentle early writeback
  Note over C,D: Steady flushing keeps disk time free for reads
  P->>C: Many more writes arrive
  C->>D: Forced flush if limit is passed
  Note over P,D: Writers now wait, and misses queue behind writes
        
FIG 7 — Gentle early writeback keeps the disk free for reads, while a late rush makes everyone wait.
Simple Analogy

Washing dishes as you go keeps the kitchen calm. Letting them pile up until the sink overflows means a panic hour of scrubbing, during which nobody can cook. Early background flushing is washing as you go.

!
Common Mistake

Copying dirty-page settings from a small machine to a big one without thinking. Percentages that were fine at 16 gigabytes may be huge at 256 gigabytes.

21Swappiness and Memory Pressure

When memory gets tight, the system must choose between cache pages and program pages.

Swap is disk space that the operating system uses when memory is short. It can move rarely used program memory out to disk to free room. For most programs, swapping is a safety net. For a broker, swapping the Java heap is a disaster, because heap pages may be needed at any moment and bringing them back from disk takes ages. Long pauses cause the broker to miss heartbeats, and the cluster may think it is dead.

A setting called swappiness tells the system how eager to be about swapping program memory compared with dropping cache pages. Kafka guidance commonly suggests setting it very low so that the system prefers dropping cache over swapping the heap. Cache pages can be reloaded from files, while heap pages have nowhere else to come from.

Memory pressure from other sources also matters. If another process grows and uses memory, the cache shrinks. A shrinking cache is a silent loss of read capacity. You will see it as rising disk reads and slower fetches, long before any error message appears.

Healthy state

Heap stays in memory, cache fills the rest, and the swap area is almost unused.

Warning state

Available memory keeps shrinking, cache size falls, and disk reads rise. A growing side process is often the cause.

Danger state

The system starts to swap heap pages. Pauses appear, sessions expire, and leaders may move unexpectedly.

Simple Analogy

When a suitcase is too full, you can leave behind extra snacks you can rebuy or leave behind your passport. Cache pages are snacks. Heap pages are the passport. Low swappiness tells the packer which one to leave.

22Containers, Cgroups, and Hidden Memory Limits

In containers, the page cache may count against the limit you gave the process.

Many teams run Kafka in containers on orchestration platforms. Containers are boxes with limits on memory and processor. On Linux, these limits are enforced by a feature called control groups. In many setups, the memory used by the page cache for files that the container reads and writes is charged to that container’s memory budget.

This has two effects. First, the cache is limited by the container’s limit, not by the host’s total memory. A host with 256 gigabytes but a container limit of 16 gigabytes gives Kafka roughly 16 minus heap minus overhead as cache. Second, when the container gets close to its limit, the system reclaims cache pages inside the container, and an oversized heap can push the container over the edge and cause it to be terminated.

The safe approach is to set the memory limit deliberately as heap plus system needs plus the cache target you computed. Do not set a limit equal to the heap and expect the cache to appear from nowhere. Also remember that other containers on the same host may compete for the host’s total memory.

SetupWhere cache comes fromWatch out for
Dedicated virtual machineFree memory of the machineSide programs eating memory
Container with a memory limitLimit minus heap minus overheadLimit set too close to the heap
Shared host with many containersWhatever the neighbors leaveNoisy neighbors reading large files
Bare metal serverNearly all memoryUneven leaders creating hot machines
Simple Analogy

Renting a room in a big house means the whole house’s kitchen is not yours. If your rental agreement says you may use a certain size shelf, then your groceries and your leftovers must all fit on that shelf. The page cache is like leftovers that must also fit.

!
Common Mistake

Setting the container request and limit to almost the same value as the heap. The result is a broker with a tiny cache and constant disk reads, even though the host has plenty of memory.

23Choosing Machine Shapes in the Cloud

Cloud instance families trade memory, processors, network, and disks in different ratios.

Public cloud providers offer families of machines. Some have a lot of memory per processor, some have a lot of processors, and some have fast local disks. For a read-heavy Kafka cluster the important figures are memory size, network bandwidth, and disk throughput. Processors matter mostly when encryption or compression conversions are involved.

Sizing the cache in a cloud setting means choosing the family and size that gives the memory you computed while also providing enough network. A machine with lots of memory but a small network card cannot send data to many readers, and the cache advantage is wasted. Likewise, a machine with a huge network card and little memory forces readers to the disk.

Instances with local NVMe drives deliver fast misses but lose data if the machine is replaced, so the cluster must rebuild those replicas by copying from other brokers. That rebuild is a burst of catch-up reading that pollutes the caches of the source brokers. Network attached volumes keep data across replacements but bring throughput limits. Neither is perfect.

Advantages of memory-rich machines

  • Bigger hot set fits in cache
  • Lagging readers stay cheap for longer
  • Fewer disk operations and lower latency
  • Room for growth without immediate resizing

Disadvantages / Trade-offs

  • Higher monthly cost per machine
  • Unused memory if traffic is low
  • Cold cache after a replacement takes time to warm
  • Memory does not fix a saturated network or processor
Simple Analogy

Choosing a delivery van means matching the cargo space, the engine, and the road. A huge cargo area is useless with a tiny engine, and a strong engine is useless with no cargo space. Balanced machines win.

24NUMA, Huge Pages, and File System Choices

A few low-level choices can help or hurt the way cache pages behave.

On large servers with several processor sockets, memory is divided among the sockets. Reaching memory attached to another socket is slower. This design is called NUMA. If a Java process allocates most of its memory on one socket while the page cache fills evenly, odd imbalances can appear, and some machines report memory pressure on one socket while others have plenty free. Teams with big servers sometimes spread memory evenly or bind the broker carefully, and they test the results.

Transparent huge pages let the system use larger memory pages to save bookkeeping. For some workloads this is helpful, but for others it causes unpredictable pauses when the system compacts memory. Many production guides suggest checking this setting and, if pauses appear, turning it to a less eager mode.

The file system also matters. Kafka guidance has long favored file systems such as XFS and ext4 for their good handling of large sequential files. Mount options that skip updating the last access time on every read avoid extra writes that would otherwise happen each time a file is read. That small change removes needless disk work on a read-heavy machine.

Choice 1

NUMA layout

Matters only on big multi-socket servers. Check for uneven memory pressure.

Choice 2

Transparent huge pages

Can cause pauses. Test before and after changing.

Choice 3

File system

XFS and ext4 are the common, well understood choices for Kafka data.

Choice 4

Access-time updates

Turning them off avoids extra writes triggered by reads.

Simple Analogy

On a very large farm with two barns, carrying hay from the far barn takes longer. A smart farmer stores hay near where the cows eat. NUMA is about keeping the hay in the closer barn.

i
Practical Tip

These low-level settings matter after the big items are right. Fix heap size, lagging readers, and encryption first. Then tune the rest with measurements.

25Retention, Segment Size, and the Cache

How long you keep data and how you cut it into files both shape memory use.

Retention is the rule that says how long Kafka keeps messages before deleting old segments. Long retention does not directly demand more cache, because old data that nobody reads does not stay in memory. The cache holds what is being read, not what is being stored. So a seven day retention with tail readers needs the same cache as a one day retention with tail readers.

Long retention does create a risk, though. It makes replays possible, and replays are exactly what pollutes the cache. A cluster that keeps a month of history invites new applications to start from the beginning. If those replays run on the production brokers, they drag old pages through the cache. So retention is a policy decision that must be paired with a plan for where replays run.

Segment size also matters a little. A segment is closed and a new one started when the file reaches a size or an age. Very small segments create many files and many index entries, which increases open files and mappings. Very large segments make deletion coarse, since Kafka deletes whole segments. A middle path suits most clusters, and the default is a sensible place to start.

ChoiceEffect on cacheEffect on operations
Longer retentionNo direct need for more cacheInvites replays that pollute cache
Shorter retentionSame cache need for tail readersLimits how far replays can go
Very small segmentsMore index pages and filesMany open files and mappings
Very large segmentsLittle effectSlow, coarse cleanup of old data
Simple Analogy

A warehouse can store a hundred years of records without needing a bigger front desk. The front desk only needs to be as big as the number of records people ask for today. But the more records you keep, the more people wander in asking for ancient ones.

i
Sizing Idea

Decide the retention and the replay plan together. Ask, who may read old data, and on which machines will they do it?

26Tiered Storage and Where Old Data Goes

Moving cold data to cheaper storage changes what the local cache must do.

Tiered storage is a feature in newer Kafka versions that lets brokers keep only recent data on local disks and move older segments to cheaper remote storage, such as an object store. Readers who need old data are served from the remote tier. Readers who need recent data are served from the local disk and the page cache as before.

For cache sizing this is good news. The local tier holds a short window, so replays from far back do not walk through local files and do not pull old pages through the local cache in the same way. Reads from the remote tier are handled by a separate path with its own limits. The heavy replays are moved away from the hot area.

There are trade-offs. Remote reads are slower than local reads, and the remote tier has its own limits on throughput and request rates. Teams must watch how the remote fetches behave and make sure a big replay does not overwhelm network bandwidth on the broker. Check the current documentation and the maturity level for your version before you depend on this feature, since details have evolved over time.

flowchart LR
  T["Tail readers"] --> LC["Local disk and page cache: recent window"]
  R["Replay readers"] --> RS["Remote object storage: older segments"]
  LC -. "old segments move out" .-> RS
        
FIG 8 — With tiered storage, recent reads use the local cache while old replays are sent to a remote tier.
Simple Analogy

A shop keeps this season’s clothes on the shop floor and last year’s clothes in a warehouse across town. Most customers want this season’s clothes and are served quickly. The few who want last year’s clothes wait longer, but they no longer clog the shop floor.

!
Common Mistake

Assuming tiered storage removes the need for cache planning. The local window still needs to hold the hot set, and the remote reads add a new limit to watch.

27Reading From Followers and Spreading the Load

More brokers can answer reads if the cluster lets them.

By default, consumers read from the leader of each partition. In a read-heavy cluster, that concentrates all the read traffic on leaders. A newer feature lets consumers fetch from a follower replica that is closer to them, for example in the same cloud zone. This was designed mainly to reduce network cost and latency across zones, but it also spreads the read work across more brokers.

From a cache viewpoint, followers already hold the same fresh data in their caches, since they copied it as it arrived. So a follower is also a good place to read tail data. Spreading reads across leaders and followers puts more caches to work. The catch is that followers can lag slightly behind the leader, so readers may see data a moment later than they would from the leader.

Spreading reads by adding partitions can also work. More partitions mean more leaders, and the leaders can be placed on different brokers. But partition count is a heavy decision with its own costs, and it cannot be undone easily, so consider it carefully.

Same-zone reading

Consumers in one zone read from the replica in that zone. This cuts cross-zone traffic and shares reading among several brokers’ caches.

Balanced leadership

Preferred leader placement and periodic balancing keep the read load from piling on a few brokers.

Extra partitions for hot topics

A very busy topic gets more partitions, so its reads spread across more machines. This works when order needs are met per key.

Simple Analogy

If a store has one cashier and three assistants who could also help, customers waiting only for the cashier will stand in a long line. Letting customers choose the nearest available helper spreads the crowd.

28Fetch Settings That Shape Reads

Consumers decide how much to ask for, and that changes cache behavior.

Consumers control how much data they ask for in each request and how long the broker may wait to gather it. A minimum fetch size tells the broker to wait until at least that many bytes are ready. A maximum wait time tells it how long to wait for those bytes. A maximum fetch size caps the response. These are consumer settings, and they can be different for each application.

Tiny fetches mean many requests, each with overhead. Huge fetches mean big reads that may load many pages at once. A moderate size lets read-ahead work well, keeps requests efficient, and does not flood the cache. For tail readers, waiting a little to gather a bigger batch reduces the request count and the processing load on the broker, at the price of a small delay.

Batch jobs that scan history can use large fetches and should be limited in speed by quotas, which the next chapter explains. The main point is that consumer settings are part of capacity planning. A team that changes them without telling the platform team can change the read profile of the cluster overnight.

Setting 1

Minimum fetch bytes

How much data must be ready before the broker replies. Larger means fewer, fuller replies.

Setting 2

Maximum wait time

The longest the broker waits to fill the minimum. It caps the extra delay.

Setting 3

Maximum bytes per fetch

The upper limit for one reply. It protects memory and keeps reads reasonably sized.

Setting 4

Per-partition fetch limit

The limit for each partition inside a reply. It prevents one partition from hogging a response.

Simple Analogy

A delivery driver can make a trip for every single parcel, or wait for a full van. Trips for single parcels are wasteful. Waiting forever for a full van makes customers angry. The wait limit and the minimum size are the driver’s rules.

i
Practical Tip

Share a short guide with application teams describing recommended fetch settings for tail readers and for batch jobs. Consistent settings make sizing predictable.

29Quotas and Isolating Noisy Readers

Sometimes the best cache plan is to limit who can take from it.

Kafka supports quotas, which limit how many bytes per second a client or a group of clients may read or write. A quota on fetch traffic can cap a batch job so that it cannot pour data out of the brokers at full speed. Slower catch-up reading means less disk contention and slower pollution, giving the tail readers breathing room.

Quotas work best when they are assigned by identity. Each application uses its own client identity or authenticated user, and the platform team assigns each one a share. Applications that are business critical get generous limits, and experimental or replay applications get lower limits. When someone needs a bigger share, they ask, and the change is discussed in the open.

There is a more radical form of isolation: separate clusters. A dedicated cluster for replays, analytics, or data lake export can copy data from the main cluster using a single well behaved reader. All the other analytics applications then read from the copy. The main cluster serves only its tail readers, and its cache stays healthy.

flowchart LR
  P["Producers"] --> M["Main cluster: tail readers only"]
  M --> S["Critical apps at the tail"]
  M -- "one steady copier" --> X["Analytics cluster"]
  X --> A["Replays, experiments, batch jobs"]
        
FIG 9 — A single steady copier protects the main cluster’s cache from many replays.
Simple Analogy

A restaurant with a busy dining room can let the catering team use a separate kitchen for large weekend orders. The dining room chef keeps serving plates without being pushed aside by a hundred boxed lunches.

Advantages of isolation

  • Main cache stays full of tail data
  • Replays cannot hurt critical services
  • Each cluster is sized for its own job
  • Easier to explain who uses what

Disadvantages / Trade-offs

  • Extra machines and extra operations work
  • Data in the copy arrives a little later
  • Another system that can fail or lag

30Broker Restarts, Replacements, and Cold Caches

A restarted broker remembers, but a replaced broker starts from nothing.

When a broker process restarts, the operating system’s cache usually remains intact, so the broker comes back warm. This is one of the benefits of using the page cache rather than the heap. But a machine reboot empties the cache, and a replaced machine has never had a cache at all. The broker begins with cold pages and every read is a miss until the cache fills.

A cold broker faces a second problem: it must catch up. After being away it has to copy the messages it missed from the leaders. This is a large catch-up read on the leaders, and it can pollute their caches. Rolling restarts of a whole cluster can therefore create a chain of catch-ups, one after another, each disturbing the caches of the neighbors.

Good practice is to restart one broker at a time and wait until it is fully in sync and its cache is reasonably warm before the next. Throttling the replication speed during recovery also helps. Leaders should not be moved back to a freshly restarted broker until it has warmed up, since it would begin serving reads with a cold cache.

1

Restart one broker

Move only one machine at a time so that copies elsewhere keep serving.

2

Wait for full sync

The broker copies missed data from its peers. Watch that under-replicated counts return to zero.

3

Let the cache warm

Give the machine a little time for fresh data to fill its cache before returning leadership.

4

Move on to the next broker

Only when the previous one looks healthy on both sync and read latency.

Simple Analogy

A new waiter does not know where the salt is or which tables want extra bread. It takes a shift to learn. Sending three new waiters into the busy hour at once would ruin dinner. You introduce them one at a time.

!
Common Mistake

Rolling all brokers as fast as the automation allows. The accumulated catch-up reads can push the whole cluster into a cold-cache spiral.

31Planning for Growth and Traffic Spikes

A cache that is barely big enough today will be too small next quarter.

Traffic grows. More producers appear, existing ones send more data, and new consumer groups join. Each increase in the write rate moves your hot window boundary closer. If writes double, the same cache now covers half the time. A reader that was safely five minutes behind may now be outside the cache at only two and a half minutes of lag.

Spikes create the same problem in a shorter time. A sale event or a bug that floods a topic can multiply the write rate for a few hours. During a spike the cache covers less time, and any slow reader is in more danger. Sizing for the average day and ignoring the peak day is a common cause of surprise trouble.

A helpful practice is to size for the busiest realistic hour and then keep a headroom target, such as always keeping the hot window at least twice as long as the slowest protected reader normally lags. Review that number every quarter and after any large launch. Adding brokers reduces per-broker write rate and gives the same effect as adding memory.

2x writes
Halves the time the cache covers
2x memory
Doubles the time it covers
2x brokers
Halves each broker’s write rate
Simple Analogy

A parking lot that fits one hour of visitors on a quiet day will overflow on a festival day. The lot did not change, but the crowd did. You plan the lot for the festival, or you plan a way to send extra cars elsewhere.

i
Practical Tip

Keep a small dashboard showing the estimated cache window in minutes, the write rate, and the largest consumer lag in minutes. When the lag line gets close to the window line, act before users notice.

32Monitoring: What to Watch and Why

You cannot manage a cache you cannot see, so pick a few honest signals.

Kafka does not report a cache hit rate, because the cache belongs to the operating system. So you learn about it from signs around it. The clearest sign is disk read activity on brokers. On a healthy read-heavy cluster serving mostly tail readers, the disks show heavy writes and very little reading. When reads climb, the cache is missing.

The second sign is fetch latency, the time the broker takes to answer a consumer or follower request. Kafka exposes request timing metrics, and they usually show a rise when misses start. Watch the high percentiles, not the average, because a few slow reads hide inside a healthy-looking mean.

The third sign is consumer lag measured in time, not only in message counts. A lag of a million messages means little until you know how fast messages arrive. Convert it to minutes and compare it with your cache window. The fourth sign is memory itself: available memory, cache size, swap use, and page fault activity on each broker.

SignalHealthy looks likeTrouble looks like
Disk read rate on brokersLow and steadyRising with consumer traffic
Fetch request time, high percentilesFlat and shortSpikes and long tails
Consumer lag in minutesWell inside cache windowApproaching or beyond the window
Available memory and cache sizeStable, large cacheCache shrinking
Swap useNearly noneGrowing
Disk busy timeMostly write burstsConstantly high with reads
Simple Analogy

A doctor cannot see your blood directly, so she checks temperature, pulse, and breathing. Disk reads, fetch time, and lag are the pulse, temperature, and breathing of the page cache.

i
Good to Know

Set alerts on trends, such as disk reads doubling within an hour, rather than on fixed numbers copied from other companies. Every cluster has its own normal.

33Finding Out What Is Really in the Cache

Some tools let you peek inside and answer the question directly.

On Linux, there are tools that report how much of a given file is currently in the page cache. Pointing such a tool at the newest segment files shows what share of them is resident in memory. Others trace cache hits and misses over time and print a summary every few seconds. These tools are often part of standard performance packages, and using them is safe on a running system when done with care.

Simple system reports are useful too. A memory report shows the size of the cache and available memory. A virtual memory report shows swapping and block reads and writes over time. A disk report shows read and write rates and how busy each device is. Comparing these while a suspicious consumer runs tells you a lot in a few minutes.

A good experiment is to start a controlled replay from a test client on one broker and watch. If disk reads jump and fetch times worsen for other clients, you have learned how sensitive your cluster is to catch-up reading. This is safer to learn on a quiet afternoon than during an incident.

1

Record a baseline

Note disk reads, cache size, fetch times, and lag during a normal busy hour.

2

Check the newest segments

Measure how much of the active segment files is resident in memory. It should be nearly all of it.

3

Run a controlled lagging read

Read from a point older than your cache window and watch the change.

4

Compare with baseline

Large changes tell you the cluster has little headroom, and small changes tell you it is resilient.

Simple Analogy

Before a big storm, a captain runs a safety drill on a calm day. The drill shows which parts of the ship leak. A controlled replay is a fire drill for your cache.

34Security and Multi-Tenancy Concerns

Sharing a cache between teams raises fairness and safety questions.

The page cache is shared by everything that reads files on the broker machine. There is no per-team slice. When many teams share a cluster, one team’s replay can hurt another team’s speed. This is a fairness problem more than a secrecy problem, because access to the data itself is controlled by authentication and permissions inside Kafka.

Encryption in transit protects data on the wire and, as discussed, costs some read efficiency. Encryption at rest, provided by the storage layer or the file system, means pages in the cache are already decrypted for use by the operating system. Cached data is protected by machine access controls, so restrict who can log into brokers and who can read the data directory.

Access rules, called ACLs, decide which users can read which topics. Combined with quotas, they give each team a boundary in both permission and bandwidth. Good governance assigns each application its own identity, so that when a read pattern hurts the cache, you know whom to call.

Guard 1

Authentication

Every client proves who it is, so reads can be traced to a team.

Guard 2

Authorization

Access rules limit which topics each identity may read.

Guard 3

Quotas

Bandwidth limits per identity keep one team from taking everything.

Guard 4

Machine access

Only trusted staff can log in to brokers or read files in the data directory.

Simple Analogy

In a shared apartment building, everyone uses the same elevator. Keys decide which floors you may visit, and a rule about moving days keeps one family from blocking the elevator all afternoon. Permissions and quotas are the keys and the rule.

!
Common Mistake

Letting many applications share one client identity. When something goes wrong, no one knows who caused it, and quotas cannot separate them.

35Advantages and Trade-offs of Relying on Page Cache

Every design choice has a price. Here is the honest summary.

Relying on the page cache made Kafka simple and quick. Reads for recent data are cheap, restarts are gentle, and garbage collection stays under control. Engineers do not need to write cache logic, and the operating system improves over time.

The price is control. You cannot pin the hot pages, cannot mark some topics as more important than others in the cache, and cannot easily prevent one reader from changing what is stored. Your tools are indirect: more memory, better isolation, limits on readers, and careful operations.

Advantages

  • Very fast reads for recent data
  • Small heaps with short pauses
  • Warm cache survives process restarts
  • Low processor use with zero-copy
  • Simple design with fewer moving parts
  • Scales by adding memory or brokers

Disadvantages / Trade-offs

  • No direct control over which pages stay
  • Replays can pollute the cache
  • Cold start after machine replacement
  • No built-in hit rate metric
  • Encryption and conversions reduce the benefit
  • Container limits can hide the true cache size
Simple Analogy

Using a shared public bus is cheap and goes to many places, but you cannot choose the timetable. A private car gives you control but costs much more. Kafka picked the bus and lives by its timetable.

“Sizing the page cache is not about storing everything. It is about keeping the right few minutes close.”

36Best Practices Checklist

A short list of habits that keep read-heavy clusters healthy.

Good cache sizing is a habit, not a one-time calculation. The practices below come from the ideas in earlier chapters. None is exotic. Most teams that follow them see calmer clusters and fewer late-night incidents.

1

Keep the heap modest

Use only as much heap as measurements demand, and leave the rest of memory to the cache.

2

Size by time window

Compute the per-broker write rate times the lag window you want in memory, then add a safety margin.

3

Dedicate machines to brokers

Avoid running memory-hungry neighbors next to Kafka brokers.

4

Protect against replays

Use quotas, a copy cluster, or tiered storage so history reads do not disturb tail readers.

5

Keep clients modern

Update client libraries so down-conversion does not quietly break zero-copy.

6

Lower swappiness and tune writeback

Prefer dropping cache over swapping the heap, and let dirty data flush gently.

7

Watch lag in minutes

Compare consumer lag in time to the cache window on a shared dashboard.

8

Restart gently

Roll brokers one at a time and let them warm before moving on.

Simple Analogy

Healthy teeth need daily brushing more than one heroic visit to the dentist. Regular small habits protect the cache more than a single perfect configuration.

37Anti-Patterns to Avoid

These mistakes appear again and again in real clusters.

ANTI-PATTERN-01 Avoid
Problem

The team gives the Java heap most of the machine’s memory, believing that more heap means more speed.

Why It’s Harmful

Kafka does not cache messages in the heap. A giant heap starves the page cache, slows reads, and lengthens garbage collection pauses.

Correct Approach

Keep a modest heap, measure whether it is enough, and let the remaining memory serve as page cache.

ANTI-PATTERN-02 Avoid
Problem

Replays and backfills run directly on the production brokers during peak hours.

Why It’s Harmful

Old data floods the cache, evicts fresh pages, and slows every tail reader.

Correct Approach

Schedule replays off peak, apply quotas, or serve them from a separate copy cluster or a remote tier.

ANTI-PATTERN-03 Avoid
Problem

Sizing the cache from average daily traffic only.

Why It’s Harmful

Peaks shrink the time the cache covers, and the first slow group crosses the danger line just when traffic is highest.

Correct Approach

Size for the busiest realistic hour with headroom, and review after every big launch.

ANTI-PATTERN-04 Avoid
Problem

Container memory limits set almost equal to the heap size.

Why It’s Harmful

The cache has almost no room, so most reads reach the disk even on a huge host.

Correct Approach

Set the limit to heap plus operating system needs plus the cache target.

ANTI-PATTERN-05 Avoid
Problem

Forcing frequent flushes to disk in the name of safety.

Why It’s Harmful

It creates constant disk work that competes with reads, and replication already gives safety across machines.

Correct Approach

Rely on replicas and acknowledgement settings, and tune background writeback for smoothness.

ANTI-PATTERN-06 Avoid
Problem

Ignoring old clients that force down-conversion.

Why It’s Harmful

Each such read loses zero-copy and burns processor time, quietly reducing capacity.

Correct Approach

Track client versions, upgrade laggards, and retire very old formats.

ANTI-PATTERN-07 Avoid
Problem

Sharing one client identity between many applications.

Why It’s Harmful

Quotas cannot separate them, and nobody can tell who caused a cache storm.

Correct Approach

Give each application its own identity and its own bandwidth share.

38Myths and Misunderstandings

Some popular beliefs about Kafka memory are simply wrong.

Myth: Free memory should be high on a healthy broker

Reality: The system fills spare memory with cache on purpose. Low free memory with large cache and low disk reads is healthy.

Myth: More retention needs more RAM

Reality: The cache holds what is being read, not everything stored. Retention adds disk need, and the replay risk, not direct cache need.

Myth: More consumer groups need proportionally more cache

Reality: Groups reading the same position share the same pages. They raise network and processor load, not cache need.

Myth: Fast disks make memory unimportant

Reality: Fast disks soften misses but are still far slower than memory, and they are shared with writes and replication.

Myth: Kafka must flush every message for durability

Reality: Kafka gets durability from replication. Flushing every message costs speed and adds little.

Simple Analogy

Believing that an empty fridge shelf is a good sign is like thinking an empty parking lot means a busy shop. The fullness of the cache is the point, not a problem.

39Real-World Scenarios

Three short stories show how the ideas play out.

Scenario 1: The nightly replay that slowed checkout

An online store noticed slow order confirmations every night at the same hour. The cause was a reporting job that read the previous day of orders from the start. Disk reads on brokers tripled and the order service, a tail reader, started missing the cache. The fix was to give the job a bandwidth quota and later to feed it from a copy cluster. Order confirmations went back to normal.

Scenario 2: The tiny container limit

A team moved brokers into containers and gave each a memory limit only a little above the heap. Latency doubled even though the hosts had plenty of memory. The cache was squeezed into the leftover space. After raising the limits to cover the cache target, disk reads fell sharply and latency returned to earlier levels.

Scenario 3: The growth that crept up

A media platform doubled its write rate over a year without changing memory. The hot window shrank from ten minutes to five. One day a downstream outage put a consumer group eight minutes behind, outside the window, and the spiral began. The lesson was to keep an eye on the window and to add brokers before it fell below their slowest reader’s normal lag.

Quota
Fixed the noisy replay
Limits
Fixed the hidden squeeze
Headroom
Prevented the growth trap
Simple Analogy

These stories are like weather reports from three different towns. The clouds differ, but they all come from the same simple rule: the cache should be bigger than the time you want to protect, and no one reader should be allowed to empty it.

Large companies that run Kafka at great scale, such as social networks, streaming services, and payment companies, have shared talks and blog posts about similar lessons, including isolating replays, planning brokers by network and memory, and upgrading clients. Check their public writings for the latest details, as practices change over time.

40Frequently Asked Questions

Q1What is the page cache in the simplest words?

It is spare memory that the operating system uses to keep copies of recently used file pieces, so that reading them again is fast.

Q2Does Kafka have its own cache for messages?

No. Kafka writes to files and depends on the operating system to keep hot file pages in memory.

Q3How much RAM should a Kafka broker have?

It depends on your write rate and the lag window you want to protect. Multiply the per-broker write rate by the window, add a margin, then add heap and system memory.

Q4Why not give Kafka a huge heap?

Because the heap does not store message bodies for long. A big heap takes memory from the cache and can cause long garbage collection pauses.

Q5Why does my broker show almost no free memory?

The system uses spare memory as cache. That is normal. Look at available memory and disk reads instead.

Q6Do more consumer groups mean more cache is needed?

Not if they read the same recent data. They share cached pages. They do add network and processor work.

Q7What is a cache hit?

A read answered from memory. A read that must go to the disk is a cache miss.

Q8What is cache pollution?

It happens when reads of old, rarely needed data push out fresh, popular pages, so other readers start missing.

Q9What is zero-copy?

A way to send bytes from the page cache straight to the network card without passing through the Java program.

Q10Does encryption break zero-copy?

Yes, for encrypted client connections the broker has to process every byte, so it uses more processor time.

Q11Can I see the cache hit rate in Kafka metrics?

Not directly. Use disk read rates, fetch latency, and operating system tools that inspect the cache.

Q12Should I flush data to disk on every message?

Usually not. Kafka relies on replication for safety, and forced flushing hurts speed.

Q13Why does a replay hurt other consumers?

It reads old data from disk and loads it into the cache, taking room from fresh pages and using disk time.

Q14How do quotas help?

They limit how fast a client can read, so a batch job cannot flood the disks and the cache.

Q15Does tiered storage remove the need for cache sizing?

No. It moves old data away from local disks, but the local hot window still has to fit in memory.

Q16What happens to the cache when a broker process restarts?

The cache usually survives, since it belongs to the operating system. A machine reboot or replacement starts cold.

Q17Why is swappiness important?

A low value makes the system drop cache pages before swapping the Java heap, which avoids long pauses.

Q18How does a container limit affect the cache?

Often the cache counts toward the container’s memory limit, so a tight limit leaves little room for it.

Q19Is it better to add memory or add brokers?

Both lengthen the time the cache covers. Adding brokers also adds network and disk capacity, while adding memory is simpler for a quick fix.

Q20How often should I revisit my sizing?

Every quarter, and after any big launch, traffic change, or new consumer group with heavy reading.

41Summary and Key Takeaways

Kafka is quick because it lets the operating system keep recent data in spare memory and sends it out with almost no copying. Sizing the page cache means deciding how many minutes of fresh data must sit in memory so that readers, even slightly slow ones, never fall to the disk. You measure the write rate per broker, choose a lag window, add a margin, and then add the small memory needs of the heap and the system. After that, you protect the cache from replays, keep clients modern, tune the system gently, and watch lag in minutes.

Key Takeaways

  • Kafka leans on the page cache — recent data is served from operating system memory, not from a cache inside the Java heap.
  • Keep the heap modest — memory not needed by the heap or the system becomes cache, which is where reads get their speed.
  • Size by time — per-broker write rate multiplied by the lag window, plus a safety margin, gives the cache target.
  • Fan-out is cheap for the cache — many groups at the tail share pages, but readers spread far apart need more room.
  • Protect against replays — quotas, copy clusters, and tiered storage keep old-data reads from polluting the cache.
  • Watch for hidden costs — encryption, old clients, container limits, and swapping all reduce the benefit of the cache.
  • Measure and revisit — track disk reads, fetch latency, and lag in minutes, and review sizing as traffic grows.