What Is Log Retention Monitoring in Kafka?

What Is Log Retention Monitoring in Kafka?

How to watch the rules that decide when Kafka deletes your data: segments, time and size limits, disk usage, consumer lag, compaction, alerts, capacity planning and the incidents that happen when nobody is looking.

Imagine a warehouse that keeps boxes for exactly seven days and then throws them away to make room for new ones. As long as everyone collects their boxes within a week, the system works beautifully. But what if a delivery driver falls ill for eight days? Their boxes are gone. Or what if a sudden rush fills the warehouse so quickly that the floor is full on day three, and no new boxes can enter? Someone needs to watch the shelves, the clock and the door. That someone is the person doing log retention monitoring.

Apache Kafka is that warehouse. It stores streams of messages on disk and deletes them according to rules called retention policies. Those rules protect the disks from filling up, but they also decide how long slow readers, new applications and recovery jobs have to get their data. If nobody watches the rules and the numbers behind them, two bad things can happen: data disappears before it is read, or disks fill up and brokers stop. In this guide you will learn what retention is, how Kafka deletes data, which signals to watch, how to set alerts that matter, how to plan disk capacity, and how to handle the incidents that retention causes.

1What Log Retention Monitoring Means

Log retention monitoring is the practice of continuously checking that Kafka keeps data for as long as you promised, and no longer than your disks can afford.

Start with the building blocks. A message is a small record of something that happened, such as “order 42 was shipped”. A topic is a named collection of messages, stored in order. Each topic is divided into partitions, and each partition is stored on disk as a log, a file-based sequence of messages that only grows at the end. Kafka does not delete a message when a consumer reads it. Instead, it keeps messages until a retention policy says they are old enough or the log is big enough to remove them.

Log retention monitoring is everything you do to make sure this system behaves as intended. It includes watching disk space, watching how big each log is, watching how old the oldest message is, checking that retention settings have not been changed by mistake, and making sure consumers finish reading data before it is deleted.

Everyday analogy

Think of a newspaper archive that keeps each daily edition for thirty days. A librarian walks the shelves every morning. She checks that the oldest edition is exactly thirty days old, that the shelves are not overflowing, and that nobody has moved the sign that says “thirty days” to “three days” by accident. Her walk is retention monitoring. Without it, problems are discovered only when a researcher asks for last week’s paper and finds an empty shelf.

Three questions the monitoring answers

Question 1

Will my data survive long enough?

Can the slowest consumer, the nightly batch job or a recovery replay read the data before it is deleted?

Question 2

Will my disks survive?

Is the volume of stored data growing faster than the disks can hold, so that brokers may run out of space?

Question 3

Are the rules what I think they are?

Have any retention settings changed, been overridden, or been set wrongly for a topic?

7 days
default time retention of a Kafka broker
1 GiB
default size of one log segment
5 min
default interval between retention checks
i
Remember this

Retention is a promise about time and space. Monitoring is how you notice, early and calmly, when one of those promises is about to be broken.

2Why Retention Monitoring Matters

Retention failures are quiet. Nothing crashes at first. The damage shows up later as missing data or a dead broker.

Most Kafka problems announce themselves loudly: a broker goes down, a consumer throws an error, a dashboard turns red. Retention problems are different. When data is deleted early, the deletion is a normal, healthy action. Nobody gets an error. The gap appears only when someone tries to read the missing data, which may be days or weeks later. Similarly, a disk filling up looks perfectly fine right up to the moment it is full.

The data that vanished on Monday

A team runs a weekly report job every Sunday night that reads the last seven days of events. One Thursday, an engineer lowers the topic retention from seven days to two days to save disk space. The next Sunday, the report reads only two days of data and silently produces numbers that are three quarters too small. Nobody notices for a month.

The disk that filled on a holiday

A marketing campaign multiplies traffic by five during a sale. Messages arrive faster than old segments expire, and a broker disk reaches one hundred percent at three in the morning on a public holiday. The broker stops accepting writes, producers back up, and the on-call engineer is paged with no warning.

The consumer that came back too late

A consumer application is switched off for a long weekend for maintenance. When it restarts, its saved position points to data that has since been deleted. It jumps to the earliest available message or the latest one, depending on its settings, and hundreds of thousands of events are skipped.

The four things at stake

ConcernWhat goes wrongBusiness effect
Data lossMessages deleted before they are consumedMissing orders, wrong reports, broken audits
AvailabilityDisks fill up and brokers stopOutage for every producer and consumer
CostRetention set far longer than neededLarge storage bills with no benefit
ComplianceData kept longer or shorter than rules allowLegal risk and fines
Everyday analogy

Consider the fuel gauge in a car. The engine runs smoothly whether the tank is full or nearly empty. Nothing tells you about the problem until the car stops on the highway. A gauge, and the habit of glancing at it, is the whole solution. Retention monitoring is the fuel gauge for Kafka’s storage.

3The Anatomy of a Kafka Log

To watch retention you must first understand what is being deleted. Kafka deletes files, not individual messages.

Each partition of a topic is stored as a directory on a broker’s disk. Inside that directory, the log is split into segments. A segment is a set of files that holds a slice of the partition’s messages. Only one segment at a time, the newest, accepts new messages. This is called the active segment. When the active segment becomes big enough or old enough, Kafka closes it and opens a new one. Closed segments are never changed again, except when they are deleted or compacted.

flowchart LR
  T["Topic orders"] --> P0["Partition 0"]
  T --> P1["Partition 1"]
  P0 --> S1["Segment offsets 0 to 9999 closed"]
  P0 --> S2["Segment offsets 10000 to 19999 closed"]
  P0 --> S3["Segment offsets 20000 onward active"]
  S1 --> F1["Log file and index files"]
  S2 --> F2["Log file and index files"]
  S3 --> F3["Log file and index files"]
Figure 1: A partition is a chain of segments. Only the last one is active.

The files in a segment

File

The log file

Holds the actual messages, one after another. This is the file that takes up almost all the disk space.

File

The offset index

A small file that maps message positions to file locations, so Kafka can jump quickly to any offset.

File

The time index

A small file that maps timestamps to offsets, so Kafka can find messages by time.

File

The transaction index

Used with transactions to track aborted data. It exists next to the other files of each segment.

Offsets you should know by name

NameMeaningWhy it matters for retention
Log start offsetThe offset of the oldest message still storedMoves forward each time retention deletes a segment
Log end offsetThe offset that the next new message will receiveMoves forward with every write
High watermarkThe last offset copied to all in-sync replicasThe limit for what consumers may read
Consumer offsetThe position a consumer has read up toIf it falls behind the log start offset, data was lost to that consumer
Everyday analogy

Think of a diary written in numbered notebooks. Each full notebook is closed and shelved, and a new one is opened for today’s entries. When the librarian needs space, she throws away whole old notebooks, not single pages. The log start offset is the first page of the oldest notebook still on the shelf.

i
Key idea

Because Kafka deletes whole segments, retention has a granularity. Data can be kept a little longer than the configured time, and you must understand why to monitor it correctly. We look at this closely in a later chapter.

4Retention Policies: Delete and Compact

Kafka has two cleanup policies. One removes old data by age or size. The other keeps the latest value per key.

Every topic has a setting called the cleanup policy. It decides what Kafka does with old data. There are two basic choices, and they can be combined.

PolicyWhat it doesTypical topicsWhat to monitor
DeleteRemoves whole old segments when they exceed a time or size limitEvent streams, logs, clicks, telemetryAge of oldest message, size on disk, deletion happening
CompactKeeps only the latest message for each key and removes older ones with the same keyCurrent state such as customer profiles, configuration, offsetsCleaner health, dirty ratio, time since last clean
Compact and deleteCompacts, and also deletes anything older than the retention timeState with a limited lifetimeBoth sets of signals

Delete policy in plain words

With the delete policy, Kafka periodically checks each partition and removes closed segments that are too old or when the total size is too large. This is the default and the most common policy. It suits streams of events, where the value lies in the recent past.

Compact policy in plain words

With compaction, Kafka rewrites closed segments so that only the newest message for each key remains. The aim is not to limit age but to keep a full, up-to-date snapshot of the state while shrinking the log. A special message with a key and an empty value, called a tombstone, tells Kafka to remove that key entirely after a delay.

Everyday analogy

The delete policy is a fridge that throws away leftovers after a week. Compaction is an address book: when a friend moves, you cross out the old address and keep only the new one, so the book stays useful without growing forever. A tombstone is writing “moved abroad, remove this entry”.

!
Monitor them differently

A compacted topic can grow without a time limit if keys are always new, and its health depends on a background cleaner thread. A deleted topic depends on time and size checks. Set up separate alerts for each kind.

5Time-Based Retention

The most common rule: keep messages for a fixed length of time, then let them go.

Time-based retention says, “keep every message for this long”. At the broker level it is controlled by settings named log.retention.hours, log.retention.minutes and log.retention.ms, where the smaller unit wins if several are set. The default is one hundred and sixty-eight hours, which is seven days. Each topic can override the broker default with its own retention.ms setting. Setting it to minus one means keep forever.

SettingLevelMeaning
log.retention.hoursBroker defaultHow long to keep data, in hours; default one hundred sixty-eight
log.retention.msBroker defaultSame, in milliseconds; takes priority over the hours setting
retention.msTopic overrideRetention for one topic; overrides the broker default
log.retention.check.interval.msBrokerHow often the broker looks for segments to delete; default five minutes

How Kafka decides a message is old

Kafka does not look at each message separately. It looks at each closed segment and asks: what is the newest timestamp of any message in this segment? If even the newest message in the segment is older than the retention time, the whole segment is eligible for deletion. This detail is very important. A segment full of old messages stays on disk as long as it contains a single message that is still young enough.

Everyday analogy

Imagine a box of photographs where you have promised to discard photos older than a year. You cannot throw the box away because one photo in it is from last week. The box goes only when its newest photo is more than a year old. Kafka treats a segment the same way: it is the newest message that decides.

i
What to monitor

Track the age of the oldest message in each important topic. If you have set seven days and the oldest message is nine days old, something is stopping deletion, and you want to know why before disks fill up.

6Size-Based Retention

The second rule: keep data only until the log reaches a maximum size, whatever its age.

Size-based retention is controlled by log.retention.bytes at the broker level and retention.bytes for a topic. It sets the maximum size of a single partition’s log. When the log grows above this limit, Kafka deletes the oldest closed segments until the size is back under the limit. The default is minus one, meaning no size limit at all.

Two facts trip people up. First, the limit applies to each partition, not to the whole topic. A topic with twelve partitions and a limit of ten gigabytes per partition can hold up to a hundred and twenty gigabytes. Second, the limit counts one copy of the data. With three replicas, the total disk use across the cluster is three times larger.

Why use a size limit

  • Acts as a safety net when traffic spikes
  • Protects disks even if time settings are generous
  • Makes disk use per partition predictable

Risks of a size limit

  • Data may be deleted much earlier than the time limit, during a spike
  • Consumers may lose data they expected to still be there
  • Hard to reason about across many partitions

When both limits are set

If a topic has both a time limit and a size limit, whichever is reached first triggers deletion. A topic set to seven days and fifty gigabytes per partition keeps data for seven days during quiet periods, but during a traffic spike it may keep data for only a day, because the size limit is hit first. Monitoring must therefore track the actual age of the oldest data, not just the configured time.

!
The hidden shortening

Teams often promise consumers “seven days of history” based only on the time setting. When a size limit quietly shortens the real window, consumers that were built around seven days discover the gap only during an outage. Measure the real window, and alert when it falls below your promise.

7How Deletion Works Internally

Deletion is a background job with several steps, and each step has a delay that monitoring must allow for.

1

The checker wakes up

A background task on each broker runs at a fixed interval, five minutes by default, and reviews every partition it hosts.

2

It finds eligible segments

For each partition, it lists closed segments whose newest message is older than the time limit, or that push the log over the size limit.

3

The log start offset moves forward

Kafka advances the log start offset past the segments to be deleted, so that consumers can no longer read from them.

4

Files are renamed

The files of each eligible segment are renamed with a suffix that marks them as deleted. This step is quick and reversible only by an operator working directly on disk.

5

Physical deletion after a delay

After a short delay, one minute by default, a background thread removes the renamed files and frees the disk space.

flowchart TD
  A["Retention check runs every few minutes"] --> B{"Is a closed segment past the time limit or is log over size limit"}
  B -->|"No"| C["Keep segment and wait for next check"]
  B -->|"Yes"| D["Advance log start offset"]
  D --> E["Rename segment files with deleted suffix"]
  E --> F["Wait for file delete delay"]
  F --> G["Remove files and free disk space"]
Figure 2: The deletion pipeline for one partition.

What this means for monitoring

Delay 1

Up to five minutes

A segment that just became eligible can wait until the next check. Do not alert on data that is a few minutes past its limit.

Delay 2

One minute before space returns

Disk space is freed after the file delete delay, so free space lags behind the decision to delete.

Effect

Log start offset jumps

When deletion runs, the log start offset moves in steps. A consumer that was reading near it can suddenly find itself behind.

Effect

Deletion is irreversible

Once files are physically removed, the only way back is a backup, a replica or a tiered copy.

Everyday analogy

Think of a garbage collection service. First a note is stuck on the bins saying “to be collected”. Then the truck arrives on its scheduled round. The bins are only really empty after the truck has passed. Between the note and the truck, the rubbish is still in the yard. Retention has the same two phases: the decision, then the physical removal.

8The Segment Trap: Why Data Lives Longer Than You Set

A low-traffic topic with a one-day retention can keep data for a week. The reason is the active segment.

Kafka never deletes the active segment, the one currently receiving writes. It closes a segment and starts a new one when the segment reaches its maximum size, controlled by segment.bytes with a default of one gibibyte, or its maximum age, controlled by segment.ms with a default of seven days. Only after a segment is closed does it become eligible for retention.

Now picture a topic that receives only ten megabytes a day. The active segment will take about a hundred days to reach one gibibyte, so the size trigger never fires. The age trigger of seven days fires instead. Suppose the retention is set to one day. Data written on Monday sits in the active segment. The segment closes the following Monday. From that moment, the retention check finds it eligible, but the newest message in it is from that Monday, so it must wait another day. In the end, Monday’s data survives for about eight days, not one.

SettingDefaultEffect on retention accuracy
segment.bytes1 GiBLarge segments on quiet topics may take very long to fill
segment.ms7 daysForces a roll at least this often; sets the worst-case extra lifetime
retention.ms7 daysCounted from the newest message in a closed segment
Everyday analogy

Consider a filing cabinet where you only shred a whole folder once it is full and closed. If you add one sheet a day, the folder stays open for months. Even if you promised to destroy papers after a week, the old sheets stay in the open folder until it is finally closed and its newest sheet is a week old.

i
The fix

For topics where accurate retention matters, especially for privacy rules, set a smaller segment age so the active segment rolls often. Balance this against the cost of having many small files.

!
Too many small segments

Very small segments create many files per partition, which uses more open file handles and slows recovery. Choose an age such as an hour or a day for special topics, not a few seconds.

9Timestamps and Retention Gotchas

Retention is measured with message timestamps. If those are wrong, retention is wrong.

Every Kafka message carries a timestamp. By default the timestamp is set by the producer when it creates the message, a mode called CreateTime. A topic can instead be set to LogAppendTime, where the broker stamps the message when it stores it. Time-based retention uses these timestamps to decide the age of a segment.

Gotcha 1

Timestamps in the future

A producer with a wrong clock stamps a message one year ahead. Its segment appears young for a year and is never deleted, so disk usage grows without limit.

Gotcha 2

Timestamps in the past

A backfill job replays data stamped months ago. Segments containing only such messages look ancient and are deleted almost immediately after they are closed.

Gotcha 3

Mixed old and new

A segment holding a mixture of old and new stamps lives as long as the newest one, keeping the old messages longer than expected.

Gotcha 4

Clock skew across producers

Slightly different clocks blur the age of segments. Small differences are harmless, but large ones cause the effects above.

Production example: the backfill that vanished

A data team replays last year’s events into a topic with a seven-day retention, keeping the original event times as timestamps. The broker sees segments whose newest message is a year old and deletes them at the next check. The team spends a day wondering where the data went before realizing the retention rule did exactly what it was told.

Protecting yourself

Use the broker-stamped mode, LogAppendTime, for topics where retention must be predictable. Where producer timestamps must be kept, limit how far a timestamp may differ from the broker’s clock, using the topic-level settings that reject or adjust messages with extreme timestamps. Monitor the gap between the newest timestamp in a topic and the current time; a large positive gap is a warning sign of a producer with a bad clock.

i
Design tip

Give backfills their own topic with its own retention, or use a mode that stamps on arrival, so that historical events do not disturb the retention of live data.

10Compaction and What to Monitor

Compacted topics do not expire by age, so their health depends on a background cleaner that must be watched.

On a compacted topic, a background pool of cleaner threads rewrites closed segments. The cleaner picks the partitions with the highest proportion of duplicate keys, called the dirty ratio, once it passes a threshold set by min.cleanable.dirty.ratio, default one half. It copies only the newest message for each key into new segments and discards the rest.

1

Writes create duplicates

As new values arrive for existing keys, older values become garbage that still occupies disk.

2

The dirty ratio rises

The proportion of the log that is not yet cleaned grows until it passes the threshold.

3

The cleaner rewrites segments

Only the latest value per key is kept in the new segments, and old segments are swapped out.

4

Tombstones are removed later

A deletion marker is kept for a period set by delete.retention.ms, default one day, so consumers can observe it, and then it is removed.

What can go wrong

ProblemSymptomWhat to watch
Cleaner thread diedCompacted topics keep growing; duplicate keys pile upTime since the last cleaner run; cleaner thread alive status
Cleaner too slowDirty ratio stays highMaximum dirty percentage; cleaning duration
Huge key spaceThe offset map cannot hold all keys at once, so cleaning takes several passesCleaner buffer usage and pass counts
Tombstones not removedDeleted keys still visible in the logDelete retention setting and cleaning progress
Everyday analogy

Think of a contact list on a phone that only keeps each person’s latest number. If the cleaning routine stops working, the list fills with duplicates of the same friend’s old numbers. Everything still works, but the list grows, searches slow down and storage shrinks. Nobody notices until the phone is full.

!
Silent failure

If the cleaner thread on a broker stops because of an error, Kafka does not stop. Compacted topics on that broker simply stop shrinking. The only way to notice is to monitor the cleaner itself and the growth of the compacted topics.

11Consumer Offsets Also Expire

Kafka keeps track of where each consumer group stopped reading, and that record has its own retention rule.

Consumers save their position in an internal compacted topic named __consumer_offsets. When a consumer group has no active members, Kafka starts a countdown. After the time set by offsets.retention.minutes, which is seven days by default in recent versions, the saved positions of that group are deleted. If the group returns after that, it no longer knows where it stopped and falls back to its reset policy.

The reset policy is a client setting called auto.offset.reset. With “earliest”, the group starts from the oldest available message and may reprocess a great deal. With “latest”, it starts from the newest and skips everything in between. With “none”, it stops with an error. None of these is good if the group merely paused for a long weekend and lost its place.

Risk 1

Weekend shutdowns

Batch consumers that run rarely may lose their saved position if the gap is longer than the offset retention.

Risk 2

Disaster recovery drills

Groups on a standby cluster are idle for long periods and may lose their positions before a failover.

Risk 3

Renamed groups

Changing a group name starts from scratch with no saved offsets, which is easily mistaken for expiry.

Risk 4

Different clocks

The offset countdown and the data retention run independently. Both must be long enough for your slowest group.

i
What to monitor

List consumer groups that are empty or stopped, and show how long they have been idle compared with the offset retention. Warn when a group is halfway to losing its position.

12Tiered Storage and Retention

Tiered storage splits retention into two parts: a short stay on fast local disks and a long stay in cheap remote storage.

In recent versions of Kafka, a feature called tiered storage lets a broker copy closed segments to a remote store, such as object storage, and later remove them from local disk. The total retention still applies to the data as a whole, but a second, shorter local retention says how long data stays on the broker’s own disks. Consumers reading recent data are served from local disk, and consumers reading old data are served from the remote store, more slowly.

Setting ideaMeaningMonitoring focus
Total retentionHow long data exists anywhere, local or remoteAge of oldest data across both tiers
Local retentionHow long data stays on the broker diskLocal disk usage stays low and steady
Upload progressSegments copied to the remote storeCopy lag; segments waiting to be uploaded
Remote fetch performanceSpeed of reads that go to the remote tierLatency and error rate of remote reads
Everyday analogy

Picture a shop with a small stockroom behind the counter and a large warehouse across town. Recent goods are kept in the stockroom for quick sale. Older goods are moved to the warehouse and fetched only on request. Local retention is how long stock stays in the stockroom, and total retention is how long anything is kept at all.

!
New failure modes

With tiered storage, a segment must be uploaded before it can leave local disk. If uploads fall behind, local disk fills even though local retention says it should not. Add monitoring for upload lag and remote store errors, and check that your Kafka version and your topics support the feature before relying on it.

13The Signals: What to Monitor

A small catalog of signals covers almost every retention risk. Learn these first and add others only when you need them.

SignalQuestion it answersWhere it comes from
Disk used and free per brokerHow close are we to a full disk?Operating system metrics
Log size per partition and topicWhich topics use the space?Broker metrics or log directory reports
Log start offset and log end offsetHow much data is stored and how fast does the start move?Broker metrics or offset tools
Age of the oldest messageIs real retention close to the configured promise?Computed from time index or a sample consumer
Number of segmentsAre there too many small files, or old segments stuck?Broker metrics
Bytes in per secondHow fast is new data arriving?Broker topic metrics
Consumer lag in messages and in timeWill consumers finish before expiry?Client metrics or lag tools
Topic configuration valuesHave retention settings changed?Admin API or command line tool
Cleaner healthAre compacted topics still shrinking?Cleaner metrics
Offline log directoriesHas a disk failed or become unwritable?Broker metrics

Group them into four families

Family 1

Capacity

Disk used, disk free, log size, growth rate. They tell you when space will run out.

Family 2

Age

Age of oldest message, log start offset movement. They tell you whether the promised window is real.

Family 3

Readers

Consumer lag and idle groups. They tell you whether readers will beat the deletion.

Family 4

Configuration

Retention values and cleaner health. They tell you whether the rules are right and working.

i
Start small

If you do nothing else, monitor free disk on every broker, the age of the oldest message on your most important topics, and consumer lag measured in time. These three catch the majority of retention incidents.

14Architecture of a Retention Monitoring Stack

Metrics travel from brokers and hosts to a time-series store, then to dashboards and alerts.

flowchart LR
  B["Kafka Brokers"] --> JX["JMX Exporter Agent"]
  H["Host Metrics Agent for Disk and CPU"] --> TS["Time Series Database"]
  JX --> TS
  CG["Consumer Lag Exporter"] --> TS
  CF["Config Checker Job using Admin API"] --> TS
  TS --> GR["Dashboards"]
  TS --> AM["Alert Manager"]
  AM --> ON["On Call Pager and Chat"]
  GR --> TM["Team Review"]
  LB["Load Balancer and API Gateway for Dashboards"] --> GR
Figure 3: A typical monitoring pipeline for Kafka retention.

The pieces in plain words

Source

Brokers and JMX

Kafka brokers expose many measurements through Java Management Extensions, known as JMX. An exporter agent turns these into a form a metrics system can collect.

Source

Host agent

A small program on each server reports disk usage, free space and disk health, which Kafka itself may not describe fully.

Source

Lag exporter

A service that asks Kafka for each group’s position and the log end offset, and computes lag in messages and time.

Source

Config checker

A scheduled job that reads topic configurations and compares them with an approved list, reporting differences as metrics.

Storage

Time-series database

Stores metrics with timestamps, so you can see trends and compute growth rates.

Action

Dashboards and alerts

Dashboards show the situation to humans. The alert manager routes warnings to pagers and chat rooms.

Everyday analogy

Think of a hospital ward. Sensors on each patient send readings to a central station. The station records them over time, draws charts, and rings a bell when a reading crosses a line. Nurses do not stare at every sensor; they trust the bell. Your monitoring stack is the central station for Kafka’s storage.

!
Monitor the monitor

Run the monitoring stack on separate infrastructure from the Kafka cluster it watches. If the same disks that fill up also host the metrics, you lose your eyes exactly when you need them.

15Monitoring Disk Usage

Disk space is the first and most important signal. Watch both the level and the speed of change.

Disk usage on a broker is the sum of all partition logs it hosts, plus indexes, plus a small amount of other data. What matters for alerting is not just the percentage used, but how quickly it is changing. A disk at seventy percent that is growing by one percent an hour has about thirty hours left. A disk at seventy percent that is flat is comfortable.

MeasureHow to read itTypical action
Percent usedCurrent fullness of the data volumeWarn at seventy percent; page near eighty-five
Growth rateChange in used space per hourAlert if the disk will fill within a day
Time to fullFree space divided by growth rateBest single number to alert on
Balance across brokersDifference between the fullest and emptiest brokerRebalance partitions if far apart
Balance across disksUsage of each directory when using several disksMove partitions from the fullest disk

Why a disk should never be allowed to fill

A full disk is not a graceful failure. When a broker cannot write, it may mark the log directory as offline. If that was its only directory, the broker shuts down, and all its partitions must move to other brokers. Those brokers now receive extra work and extra data, and may themselves run short of space. What began as one full disk can spread through the cluster.

Production example: the cascade

A streaming company runs eight brokers, all at seventy-eight percent full. One broker crashes during a traffic spike. Its partitions move to the other seven, each of which now needs about twelve percent more space. Within an hour, three more brokers run out of room. A single early warning on time-to-full would have allowed the team to add capacity days before.

i
Leave room for failure

Plan disk targets so that the cluster still fits after losing one broker. In a cluster of N brokers, running each at more than roughly (N minus one) divided by N of its capacity leaves no room to absorb a failure.

16Log Size, Segment and Offset Metrics

Broker metrics show the size and shape of every log, which lets you find the topics that consume the space.

Kafka brokers publish per-partition measurements, including the size of the log in bytes, the log start offset, the log end offset and the number of segments. Summing size across a topic’s partitions, and multiplying by the replication factor, tells you the true cost of a topic on disk.

Metric

Log size

Bytes used by one partition on one broker. Sum across partitions and replicas for the topic total.

Metric

Log start offset

Its movement over time shows how fast retention is deleting. A flat value on a busy topic means nothing is being deleted.

Metric

Log end offset

Its movement over time shows the message rate. The difference between end and start is the number of stored messages.

Metric

Number of segments

A very high count suggests tiny segments; a count that only grows suggests deletion is stuck.

Reading the shape

What you seeLikely meaningWhat to check
Log size grows steadily with no plateauRetention is not deletingTimestamps in the future, size or time settings, active segment trap
Log size shows a sawtooth patternHealthy: growth then deletion of a segmentNothing; this is normal
Log start offset never movesNothing has aged out, or deletion is blockedRetention value and segment rolling
Log start offset jumps a lotBig deletion after a change or spikeRecent configuration change or size limit
Segment count keeps risingSegments not being deleted or rolled too smallSegment settings and retention
Everyday analogy

Think of a water tank with a tap filling it and a valve emptying it in bursts. A healthy tank rises and falls in a sawtooth pattern around a stable average. A tank whose level only climbs means the valve is stuck. Log size follows the same pattern, and the sawtooth is the sign of a working retention system.

17Consumer Lag Versus Retention

The most important retention question: can every consumer read its data before Kafka deletes it?

Consumer lag is the distance between the newest message and the position of a consumer. It can be measured in messages, but for retention purposes it is much more useful in time: how old is the message the consumer is about to read? If that age approaches the retention time, the consumer is about to lose data.

flowchart LR
  OLD["Oldest stored message: log start offset"] --> RISK["Danger zone: consumer position near here"]
  RISK --> POS["Consumer position"]
  POS --> LAG["Lag: messages not yet read"]
  LAG --> NEW["Newest message: log end offset"]
Figure 4: The closer the consumer position is to the log start offset, the closer it is to losing data.

The number to watch: time to expiry

A helpful measure is the time to expiry: how long until the message at the consumer’s position will be deleted. It is roughly the retention time minus the age of that message. If retention is seven days and the consumer is reading a message that is five days old, only two days remain. If lag is growing, the time to expiry is shrinking, and the alert should fire well before it reaches zero.

RetentionAge of message at consumer positionTime to expiryStatus
7 days10 minutesAbout 7 daysHealthy
7 days2 days5 daysLagging but safe
7 days5 days2 daysWarning
7 days6.5 days12 hoursCritical
Everyday analogy

Think of a student borrowing library books that must be returned in fourteen days. What matters is not how many books remain unread, but how many days are left on the loan of the oldest unread one. A student with a huge pile but three weeks left is fine. A student with one book and one day left is in trouble.

!
Lag in messages misleads

A lag of one million messages may be ten seconds on a busy topic and ten days on a quiet one. Always convert lag into time before comparing it with retention.

18Configuration Drift and Audit

Retention settings live in several layers. Without checks, they drift away from what you intended.

A topic’s effective retention comes from layers. The broker file sets a default. A topic-level override, set through the admin tools, replaces the default for one topic. A dynamic broker setting can change the cluster default while brokers are running. Different brokers can even hold different files if they were configured by hand. Because the layers are invisible to most people, the value that actually applies is often not the value that people believe applies.

Drift 1

Manual overrides

An engineer changes a topic during an incident and forgets to undo it. Months later the topic keeps far more or far less than planned.

Drift 2

Different broker files

One broker was started with old settings, so its defaults differ from the rest.

Drift 3

Auto-created topics

Topics created automatically by applications take the broker default, which may be unsuitable for them.

Drift 4

Tool differences

Infrastructure code, scripts and consoles may each write different values for the same setting.

A simple audit routine

1

Keep an approved list

Store the intended retention, cleanup policy and segment settings for each important topic in version control.

2

Read the real values

A scheduled job asks the cluster for the effective configuration of every topic, including defaults.

3

Compare and report

Differences between the approved list and the real values become a metric or a ticket.

4

Alert on unexpected changes

Any change to a retention value outside a planned deployment raises an alert to the topic owner.

i
Treat retention as code

Manage topic settings through reviewed, versioned definitions applied by automation. Manual changes should be rare, logged and reverted.

19Designing Alerts That People Trust

Good alerts are few, clear and actionable. Bad alerts teach people to ignore the pager.

AlertConditionSeverityFirst action
Disk fillingTime to full under twenty-four hoursWarningFind the fastest growing topics; plan capacity
Disk criticalTime to full under four hours, or usage above eighty-five percentPageFree space safely or add storage now
Retention not deletingOldest message age above the retention plus one segment periodWarningCheck timestamps, segment settings and cleaner
Window shorter than promisedOldest message age below the promised windowWarningCheck size limits and recent configuration changes
Consumer near expiryTime to expiry under a set fraction of retentionWarning, then pageSpeed up or pause deletion by raising retention
Configuration driftReal value differs from approved valueWarningConfirm with owner; restore approved value
Cleaner stalledLong time since last cleaner run on compacted topicsWarningInspect broker logs for cleaner errors
Offline log directoryAny directory reported offlinePageCheck disk health and free space immediately

Rules for good alerts

Rule 1

Alert on time, not just size

“Full in three hours” is more actionable than “eighty percent used”.

Rule 2

Two levels only

A warning for the working day and a page for the night. More levels blur the meaning.

Rule 3

Link to a runbook

Every alert names the page that says what to check first and who to call.

Rule 4

Send to the owner

Topic-level alerts go to the team that owns the topic, not to a general channel.

!
Avoid alert fatigue

An alert that fires often and needs no action should be fixed or removed. When people learn that the pager is usually wrong, they miss the night it is right.

20Capacity Planning with Retention

A simple formula turns your traffic and retention promise into the disk space you must buy.

The disk space needed for a topic is the product of four things: how fast data arrives, how long you keep it, how many copies you store, and a safety margin. In words: bytes per second, times seconds of retention, times replication factor, times a margin. Compression changes the number of bytes actually stored, so use the compressed rate measured on the broker, not the size of the raw messages.

1

Measure the incoming rate

Read the bytes in per second from broker metrics, using a busy period rather than an average day.

2

Multiply by the retention time

Convert the retention to seconds and multiply. This gives the data stored for one copy.

3

Multiply by the replication factor

With three replicas, each byte exists three times across the cluster.

4

Add a margin

Add room for growth, indexes, the active segments, and the loss of one broker. Twenty to forty percent is common.

A worked example

An online retailer has a topic that receives fifty megabytes per second of compressed data at peak. It promises seven days of retention and uses three replicas. In one day there are 86,400 seconds, so one day of data is 50 times 86,400, which equals 4,320,000 megabytes, or about 4.3 terabytes. Seven days is about 30.2 terabytes for one copy. With three replicas, the cluster stores about 90.7 terabytes. Adding a thirty percent margin gives roughly 118 terabytes across all brokers.

4.3 TB
one day of data at 50 MB per second
90.7 TB
seven days with three replicas
~118 TB
with a thirty percent margin
LeverEffect on diskTrade-off
Shorter retentionDirectly reduces stored dataLess time for slow consumers and recovery
Better compressionFewer bytes per messageMore CPU on producers or brokers
Lower replication factorReduces copiesLess protection against broker loss
Tiered storageMoves older data to cheaper storageSlower reads of old data; new moving parts
Trimming large messagesSends less data per eventRequires changes in producers
i
Illustrative numbers

These figures show the method. Use your own measured rates, and repeat the calculation whenever traffic changes noticeably or the retention promise changes.

21Incident Walkthrough: The Disk That Filled

Follow a typical incident from the first sign of trouble to the recovery, and see which signals would have warned earlier.

flowchart TD
  A["Traffic spike doubles bytes in per second"] --> B["Retention deletes at normal pace"]
  B --> C["Disk usage climbs past eighty five percent"]
  C --> D{"Was time to full alert configured"}
  D -->|"Yes"| E["Team acts early: adds size limit or capacity"]
  D -->|"No"| F["Disk reaches one hundred percent"]
  F --> G["Log directory goes offline and broker stops"]
  G --> H["Partitions fail over to other brokers"]
  H --> I["Neighbor brokers take extra load and may also fill"]
Figure 5: A time-to-full alert changes the ending of this incident.

What the responders should do

1

Find what is growing

Rank topics by log size and by growth over the last day. One or two topics usually explain most of the increase.

2

Decide what data can be shortened

Choose topics whose consumers are up to date and whose data can be reduced. Confirm with their owners.

3

Lower retention on those topics only

Reduce time or size limits on the chosen topics through the topic configuration tool, and watch the log start offset move.

4

Wait for the next check and delay

Space comes back only after the next retention check and the file delete delay, which can take several minutes.

5

Add capacity and fix the cause

Add disks or brokers, rebalance partitions, and add the missing alert so that the next spike is seen early.

!
Never delete files by hand

In a panic, someone may delete segment files directly on the server. This can corrupt logs and cause long recovery. Use the supported configuration route so Kafka removes data safely.

22Incident Walkthrough: Data Expired Before It Was Read

The opposite problem: retention worked perfectly, and that is exactly what hurt.

A nightly job reads yesterday’s data from a topic and loads it into a warehouse. One night it fails because the warehouse is down. The team fixes the warehouse two days later and restarts the job, expecting it to pick up where it left off. But the topic retention is only twenty-four hours, and the job’s saved position now points to deleted data. The job resets to the earliest available message, the oldest of which is only a day old. Two days of events are missing from the warehouse.

QuestionAnswer in this incidentWhat would have helped
Was the deletion a bug?No, retention worked as configuredRetention that matches the recovery time needed
Did the consumer know?It only saw an offset out of range and resetAn alert on time to expiry of the consumer
Could it be repaired?Only from another sourceA longer retention or a backup copy
Was there a warning sign?Job failure and rising lag for two daysLag measured in time, compared with retention

Lessons

Lesson 1

Retention must exceed recovery time

If your team needs up to three days to notice and fix a failure, retention of one day is a gamble.

Lesson 2

Alert before expiry, not after

A warning at half the retention gives a full half of the window to react.

Lesson 3

Set the reset policy on purpose

Choose earliest, latest or none deliberately for each consumer, knowing what each will do when data is missing.

Lesson 4

Pause deletion in an emergency

Raising the retention on the affected topic while the consumer recovers can save data that has not yet been deleted.

Everyday analogy

Think of a dairy that throws out yesterday’s milk every night. A shop that misses its collection for two days finds the shelves empty, not because the dairy made a mistake, but because the rule was faster than the shop’s recovery. The solution is either a longer shelf life, or an alarm that rings before the milk is thrown away.

23Changing Retention Safely

Retention changes are quick to make and impossible to undo once data is deleted. Follow a routine.

Retention can be changed while brokers are running, using the topic configuration tool. Increasing retention is safe and takes effect immediately: data that would have been deleted simply stays. Decreasing retention is the risky direction. At the next retention check, Kafka may delete a large amount of data in one go, and there is no undo.

1

Identify all readers of the topic

List consumer groups, batch jobs, replay tools and disaster recovery processes that use the topic.

2

Check the slowest reader

Confirm that the slowest reader, and the longest planned outage, fit inside the new retention.

3

Estimate what will be deleted

Use the log size and the age of the oldest data to predict how much will go and how much space will be freed.

4

Announce and record the change

Tell the topic owners, write the change in the change log, and use reviewed automation where possible.

5

Reduce in steps for large cuts

For big reductions, lower retention in stages, watching consumers and disk after each step.

6

Verify afterwards

Check that the log start offset moved as expected, that space was freed, and that consumers are healthy.

i
Rule of thumb

Raise retention freely, lower it carefully. Any decrease deserves a second pair of eyes.

24Designing Useful Dashboards

A good retention dashboard answers the three questions of chapter one in one glance.

Panel 1

Cluster disk overview

Used space, free space and time to full for each broker, with the fullest broker highlighted.

Panel 2

Top topics by size

The largest topics with their growth rates over the last day and week.

Panel 3

Real retention window

For key topics, the age of the oldest message beside the configured retention, so gaps between promise and reality are visible.

Panel 4

Consumer time to expiry

A list of groups sorted by how close they are to losing data.

Panel 5

Configuration changes

A log of recent changes to retention settings, with who and when.

Panel 6

Cleaner and directory health

Compaction status, offline directories and deletion activity.

Design guidelines

Do

  • Put the most urgent panel at the top
  • Show trends, not only current values
  • Use consistent units, especially time
  • Link each panel to its runbook

Avoid

  • Dozens of panels nobody reads
  • Averages that hide the worst broker
  • Message counts without time context
  • Colors that are the only carrier of meaning
Everyday analogy

A car dashboard shows speed, fuel and warning lights, not every reading of the engine. Drivers glance at it in a second and know whether to worry. A retention dashboard should have the same quality: quick to read, and silent when all is well.

25Advantages, Disadvantages and Trade-offs

Monitoring costs effort and money, and saves far more. Still, every choice trades one thing for another.

Advantages

  • Early warning before disks fill
  • Confidence that promised history really exists
  • Fewer surprises during consumer outages
  • Clear evidence for compliance audits
  • Better capacity plans and lower storage cost
  • Faster diagnosis when something breaks

Disadvantages

  • Extra infrastructure to build and run
  • Metrics and alerts need tuning to avoid noise
  • Some signals, such as age of oldest message, need custom work
  • Monitoring cannot restore data that is already deleted
  • Teams must agree on owners and thresholds
  • Dashboards need upkeep as topics come and go

The main trade-offs

Trade-off 1

Long retention versus cost

Longer retention gives readers more time and costs more disk. Tiered storage softens this at the price of complexity.

Trade-off 2

Time limit versus size limit

A size limit protects disks but may shorten the real window during spikes.

Trade-off 3

Sensitive alerts versus noise

Tight thresholds catch problems early and page people more often.

Trade-off 4

Small segments versus file counts

Small segments make retention more precise and multiply the number of files.

26Performance and Scalability of Monitoring

Watching a big cluster generates a lot of data. Keep the monitoring itself light and useful.

A cluster with thousands of partitions can produce hundreds of thousands of metric series. Collecting every one of them every few seconds is costly, both in network and in storage of the metrics system. The aim is to keep the signals that drive decisions and to summarize the rest.

ChallengeEffectApproach
Many partitionsVery large number of per-partition seriesAggregate to topic level; keep partition detail only for large topics
Frequent collectionHeavy load on brokers and the metrics storeCollect every thirty to sixty seconds; retention signals change slowly
Lag calculation for many groupsMany calls to the clusterUse an efficient exporter and cache results
Age of oldest messageNeeds reading the time index or a sample messageCompute every few minutes for a chosen list of topics
Long history of metricsStorage grows over timeDownsample old data; keep raw data for weeks
Everyday analogy

A weather station does not report every gust of wind to the public. It records fine detail locally and publishes hourly summaries. Retention signals move slowly, so a reading every minute is already generous. Save the fine detail for the few signals that change quickly.

i
Focus on tiers of importance

Give business-critical topics detailed monitoring and tight alerts. Give the long tail of small topics a simple, shared rule, such as a cluster-wide disk alert and a weekly configuration report.

27High Availability and Reliability

Retention has its own reliability concerns, and so does the system that watches it.

Data

Replication protects retained data

Three replicas mean a failed disk does not destroy history. Retention applies independently on each replica, so watch replicas for divergence in size.

Capacity

Plan for the loss of a broker

Keep enough free space that the survivors can absorb a failed broker’s partitions.

Directories

Multiple disks per broker

With several log directories, one failing disk takes only its partitions offline. Monitor each directory separately.

Monitoring

Redundant collectors

Run more than one collector and alert manager, so a single failure does not blind you.

Watch replicas, not just leaders

Retention runs on every replica of a partition, so leaders and followers may hold slightly different amounts of data at any moment. Large, lasting differences point to a problem such as a follower that has fallen out of sync, a disk that is failing or a broker that was configured differently. Compare the log start offsets and sizes across replicas of the same partition and investigate anything that does not converge.

Production example: the follower that could not delete

A streaming platform notices one broker using far more disk than its peers. A comparison of replica sizes shows that its copies of several partitions are larger. The cause is a stuck file deletion after a storage fault. Without per-replica comparison, the problem would have looked like a general capacity shortage.

!
Dead man’s switch

Add an alert that fires when the monitoring data stops arriving. Silence from the monitoring system should itself be treated as an incident.

28Security and Governance

Whoever can change retention can destroy data or fill disks. Control that power.

Access

Restrict who can alter configs

Use access control lists so that only platform administrators and approved automation can change topic settings, and read-only roles can view them.

Audit

Record every change

Log who changed a retention value, when and from where, and keep the log longer than the longest retention it can affect.

Compliance

Match legal retention rules

Some data must be deleted after a set time, and some must be kept for a minimum time. Turn these rules into topic settings and monitor them.

Privacy

Watch personal data lifetimes

Where personal data is stored, verify that retention, the segment trap and compaction do not keep it longer than allowed.

Transport

Secure the metrics path

Encrypt and authenticate connections to metrics endpoints and dashboards, since they reveal topic names and volumes.

Ownership

Every topic has an owner

Alerts and change approvals go to a named team. Topics without owners are the first to be forgotten.

!
Deletion is also a security event

An attacker or a careless script that shortens retention can erase evidence. Alert on any large drop in retention for audit and security topics, and protect those settings with the strictest access rules.

29A Runbook Cheat Sheet

When the pager rings, a short table of symptoms and first checks saves precious minutes.

SymptomLikely causeFirst checksSafe first action
Disk usage climbing on many brokersTraffic spike or retention too longBytes in rate; top topics by sizeShorten retention on non-critical large topics after confirming owners
One topic never shrinksFuture timestamps or active segment trapNewest timestamp versus clock; segment age settingsFix the producer clock; lower segment age for the topic
Data missing for a consumerLag exceeded retentionConsumer position versus log start offsetRaise retention if data remains; plan a replay from another source
Consumer restarted from the beginningSaved offsets expired or group renamedOffset retention; group name; reset policySet the position manually to the intended offset
Compacted topic growing without limitCleaner stalled or new keys onlyCleaner logs; dirty ratio; key growthRestart the cleaner by fixing the underlying error; review key design
Broker down with a disk errorDisk full or failed diskDirectory status; free space; hardware logsFree space through configuration; replace disk; rebalance
Real window shorter than promisedSize limit hit during a spikeSize limit value; growth patternRaise the size limit or add capacity
Retention value differs from planManual override or driftEffective config versus approved listRestore the approved value and inform the owner
i
Keep it next to the alerts

Attach this table, adapted to your cluster, to every relevant alert. Runbooks that live in a forgotten wiki do not help at three in the morning.

30Design Patterns and Anti-patterns

A few habits keep retention healthy. A few shortcuts create the incidents in this guide.

Patterns that work

Pattern

Retention tiers

Define a few standard classes, such as short, standard and long, and assign every topic to one. Fewer variants mean easier monitoring.

Pattern

Both limits together

Set a time limit for the promise and a generous size limit as a safety net for disks.

Pattern

Retention above recovery time

Choose retention as a multiple of the longest realistic outage plus the time to notice and repair it.

Pattern

Config as code

Define topics and retention in version control, applied by automation, with drift checks.

Pattern

Time-to-expiry alerts

Alert on the remaining time for each consumer group, not on lag counts.

Pattern

Separate backfill topics

Historical replays go to their own topics so they do not disturb live retention.

Anti-patterns to avoid

AP-01Avoid
What people do

Leave every topic on the broker default retention and never look at it again.

Why it hurts

The default suits nobody in particular. Some topics keep data far longer than needed and fill disks, and others lose data before consumers can read it.

Do this instead

Choose retention per topic from its readers and recovery needs, and record the reason.

AP-02Avoid
What people do

Alert only when the disk is above ninety percent.

Why it hurts

On a large disk with fast growth, ninety percent may be minutes from full. The alert arrives when there is no time to react.

Do this instead

Alert on time to full, with an early warning measured in many hours.

AP-03Avoid
What people do

Cut retention during an incident without checking the readers.

Why it hurts

Data needed by a slow consumer or a replay is deleted permanently, turning a capacity problem into a data loss problem.

Do this instead

Check consumer positions first, and shorten retention only on topics whose readers are safe.

AP-04Avoid
What people do

Delete segment files by hand to free space quickly.

Why it hurts

The broker’s view of the log no longer matches the disk. This can cause errors, long recovery and even loss of consistency between replicas.

Do this instead

Change configuration and let Kafka delete data itself.

AP-05Avoid
What people do

Assume that a compacted topic looks after itself.

Why it hurts

A stalled cleaner lets the topic grow silently until the disk is full, often on a broker that also hosts other topics.

Do this instead

Monitor cleaner activity, dirty ratio and topic growth, and alert when cleaning stops.

31Best Practices and Common Mistakes

A short checklist gathered from production clusters. Follow it and most retention problems never happen.

1

Write down the promise for each topic

State the retention, the reason and the owner. If nobody can explain the value, review it.

2

Alert on time to full

Watch growth as well as level, on every broker and every log directory.

3

Measure the real retention window

Compare the age of the oldest message with the configured value on your key topics.

4

Convert consumer lag into time

Alert when time to expiry falls below a fraction of the retention.

5

Audit configuration daily

Compare real values with the approved list and investigate every difference.

6

Control who can change retention

Restrict, record and review every change, especially reductions.

7

Rehearse the incidents

Practice the disk-full and expired-data runbooks in a test cluster so the real event is familiar.

Mistakes seen again and again

Mistake

Confusing per-partition and per-topic size limits

A size limit applies to each partition. Multiply by the number of partitions and replicas for the real cost.

Mistake

Expecting exact deletion times

Segments, check intervals and delays make deletion approximate. Allow for a margin.

Mistake

Ignoring offset retention

Consumer positions expire too. A long pause can lose the position even when data still exists.

Mistake

Trusting producer clocks

Future timestamps stop deletion. Validate or use broker timestamps.

Mistake

Monitoring averages

The fullest broker matters more than the average of all brokers.

Mistake

No plan for loss of a broker

Running all brokers at high usage leaves no room to recover from a single failure.

32Real-World and Industry Examples

Retention monitoring appears wherever Kafka carries data that matters. These examples show the pattern.

Kafka began at LinkedIn to move activity data, and today it carries huge volumes at many companies. Public talks and blog posts describe how operators manage disks, retention and lag at scale. Internal details differ and change, so treat the following as illustrations of the technique rather than exact blueprints.

Streaming video: playback events

Services such as Netflix collect playback and device events in very large volumes. Short retention keeps disks manageable, and monitoring focuses on consumer lag against retention so that analytics pipelines never fall behind the deletion window.

Ride-hailing: trip and location data

Ride platforms stream location updates and trip events. Peaks at rush hour and during events cause sudden growth, so time-to-full alerts and size limits act as protection for brokers.

Banking: audit and transaction topics

Banks keep some topics for long periods to satisfy regulations and others for short periods to limit sensitive data. Retention configuration is audited and changes are approved and logged.

E-commerce: sales events

Retailers see sharp peaks during sales. They plan capacity for the peak rate, extend retention before big events so that recovery jobs have room, and reduce it afterwards.

Social networks: activity feeds

Activity events feed search, recommendations and analytics. Each consumer has different needs, so operators track time to expiry per consumer group and warn owners before data is lost.

Data platforms: change streams

Database change streams are often compacted so that the latest state of each record remains. Operators watch the cleaner and the growth of these topics because a stalled cleaner quietly fills disks.

i
Pattern to notice

In every example, monitoring ties three things together: how fast data arrives, how long it is kept, and how quickly readers consume it. When one changes, the other two must be re-checked.

33Glossary of Terms

A quick reference for the vocabulary used throughout this guide.

TermPlain meaning
RetentionThe rule that decides how long or how much data Kafka keeps
SegmentA file-based slice of a partition’s log; the unit of deletion
Active segmentThe newest segment, which receives writes and is never deleted
Log start offsetThe offset of the oldest message still stored
Log end offsetThe offset the next new message will receive
Cleanup policyDelete, compact, or both
CompactionKeeping only the latest message for each key
TombstoneA message with a key and no value that marks the key for removal
Dirty ratioThe share of a log that has not yet been cleaned by compaction
Consumer lagHow far a consumer’s position is behind the newest message
Time to expiryHow long until the message at a consumer’s position will be deleted
Time to fullFree disk space divided by its rate of consumption
Tiered storageStoring older segments in cheaper remote storage
Replication factorThe number of copies of each partition
Configuration driftReal settings that have moved away from the approved ones

34Frequently Asked Questions

Quick answers to the questions that come up most when teams start watching retention.

Q1What is log retention in Kafka?
It is the rule that decides how long, or up to what size, Kafka keeps messages in a partition before deleting the oldest closed segments. Compacted topics instead keep the latest message per key.
Q2What is log retention monitoring?
Continuously checking disk usage, log sizes, the age of stored data, consumer lag against retention and configuration values, so that data is neither lost early nor allowed to fill the disks.
Q3Does Kafka delete a message as soon as its retention time passes?
No. Kafka deletes whole closed segments at periodic checks. A segment is removed only when its newest message is older than the limit, so messages often live longer than the configured time.
Q4Why is my data still there after the retention time?
The most common reasons are the active segment not having rolled yet, timestamps in the future, a newer message in the same segment, or a size limit that has not been reached. Check segment settings and timestamps.
Q5Why was my data deleted earlier than the retention time?
A size limit may have been reached during a spike, messages may carry old timestamps, or someone may have lowered the retention. Check the effective configuration and recent changes.
Q6Is the size limit per topic or per partition?
Per partition. The total for a topic is the limit times the number of partitions, and the disk cost is multiplied again by the replication factor.
Q7How do I know if a consumer will lose data?
Measure its lag in time and compare it with the retention. When the age of the message at its position approaches the retention time, the consumer is close to losing data. Alert well before that point.
Q8What happens if a consumer’s position has been deleted?
The consumer receives an out-of-range signal and follows its offset reset policy: start from the earliest message, start from the latest, or stop with an error. In the first two cases, data may be skipped or reprocessed.
Q9Do consumer group offsets expire?
Yes. After a group has been empty for the offsets retention period, its saved positions are removed. When the group returns, it falls back to its reset policy.
Q10What should I alert on first?
Time to full for each broker disk, consumer time to expiry, and unexpected changes to retention settings. These three catch most serious incidents.
Q11Is it safe to increase and decrease retention while running?
Increasing is safe and immediate. Decreasing can delete a large amount of data at the next check, and it cannot be undone, so confirm the readers first and reduce in steps for large cuts.
Q12How much disk do I need for my retention?
Multiply the compressed incoming bytes per second by the retention in seconds and by the replication factor, then add a margin for growth and for the loss of a broker.
Q13Do compacted topics need retention monitoring too?
Yes. Watch the cleaner and the growth of the topic, because a stalled cleaner lets duplicate keys pile up until the disk fills.

35Summary and Key Takeaways

Retention is a promise about time and space. Monitoring is how you keep that promise.

Key Takeaways

  • Kafka deletes segments, not messages. Time and size limits apply to closed segments at periodic checks, so real retention is approximate, and the active segment and message timestamps can make data live longer or shorter than planned.
  • Watch three families of signals. Capacity (disk and log size), age (the real retention window) and readers (consumer lag in time), plus the configuration and cleaner health that support them.
  • Alert on time, not only on levels. Time to full and time to expiry give people hours to act, where percentages and message counts give minutes.
  • Retention must exceed recovery time. Set it from the slowest reader and the longest realistic outage, and remember that consumer offsets and compacted topics have their own expiry and cleaning rules.
  • Change retention carefully. Raise it freely, lower it only after checking every reader, reduce large amounts in steps, and never delete segment files by hand.
  • Plan capacity with a simple formula. Bytes per second times retention seconds times replication factor, plus a margin that survives the loss of a broker.
  • Govern the settings. Keep retention as reviewed code, audit for drift, restrict who can change it, and treat large reductions as security-relevant events.