What Is a Retention Period in Kafka?

What Is a Retention Period in Kafka?

A beginner-friendly guide to how long Kafka keeps your events, how it decides what to delete, and how this one choice shapes your storage bill, your ability to replay history, and the safety of slow consumers.

Imagine a library that receives thousands of new newspapers every single day. The shelves are large but not endless. The librarian must decide a rule: keep every newspaper for one week and then recycle the oldest, or keep a fixed number of shelves’ worth and discard the oldest whenever the shelves fill, or keep only the newest edition of each series forever. Whatever the rule, readers must know it, because a reader who arrives after the recycling day will not find the old papers. In Apache Kafka, this rule is the retention policy, and the length of time events are kept is the retention period. It is one of the most important settings in any Kafka system, and one of the most misunderstood. This guide explains it in simple words.

1Kafka Is Not a Queue That Forgets

To understand retention, we first need to see what makes Kafka different from many older messaging tools.

The old way: read it and it disappears

In many traditional message queues, a message is removed as soon as one consumer reads it. The queue is like a to-do tray: a note is picked up, done, and thrown away. The system never needs to decide how long to keep messages, because a message lives only until someone takes it.

The Kafka way: keep it, and let everyone read it

Apache Kafka stores streams of events, such as orders, payments, clicks, or sensor readings, in topics. Each topic is split into partitions, and each partition is an ordered log on disk. When a consumer reads an event, the event is not removed. It stays in the partition, so that other consumers can read it too, and so that the same consumer can read it again later. This is what allows replay, recovery, and many independent readers.

The question this raises

If reading does not delete anything, then something else must. Disks are finite, and events arrive endlessly. Kafka needs a rule for when old events may be removed. That rule is retention.

Simple Analogy

A queue is like a tray of tasks that you throw away once done. Kafka is like a security-camera recording system: everything is kept for a while, many people can watch any part of it, and the system automatically erases the oldest footage to make room for the newest. The rule for how long footage is kept is the retention period.

i
Helpful Note

Retention is decided by Kafka and by the topic settings, not by consumers. Whether ten readers or zero readers have seen an event makes no difference to when it is deleted.

2What Is a Retention Period?

A retention period is the amount of time Kafka promises to keep events before it becomes allowed to delete them.

The simple definition

The retention period is a setting on a topic that says how long its events should be kept. By default, Kafka keeps events for seven days. After that, events become eligible for deletion. You can shorten this to hours, or lengthen it to weeks, months, years, or even keep events forever.

Retention is a minimum promise, not an exact deadline

The retention period tells you the earliest time when Kafka may delete an event, not the exact moment it will. Deletion happens in chunks, checked periodically, so an event may live a little longer than the period. What you can rely on is that an event will not be deleted before its retention period has passed, unless another limit, such as a size limit, forces earlier deletion.

Three related ideas

Idea 1

Time-based retention

Keep events for a chosen length of time, such as seven days.

Idea 2

Size-based retention

Keep events until each partition reaches a chosen size, then remove the oldest.

Idea 3

Compaction

Keep at least the latest event for every key, however old, and remove older duplicates.

Simple Analogy

A supermarket labels food with a “best before” date. The date is a promise about the earliest time it may be thrown away, but the staff check the shelves only at certain times, so some items stay a little longer. Retention is the best-before date for events.

!
Common Mistake

Believing that events vanish at the exact second the retention period ends. Deletion follows a schedule and works on whole chunks of the log, so treat the period as a minimum, not as a precise timer.

3How Kafka Stores Data: Segments

To understand how deletion really works, we must look at how a partition is stored on disk.

A partition is made of segment files

A partition is not one gigantic file. It is split into smaller files called segments. At any moment, only the newest segment, called the active segment, receives new events. When it grows large enough or becomes old enough, Kafka closes it and starts a new active segment. Closed segments are never changed again.

Deletion works on whole segments

Kafka does not remove individual events one by one. It deletes entire segment files. A closed segment becomes eligible for deletion only when every event in it has passed the retention limit. In practice, Kafka looks at the newest timestamp in the segment: if even the newest event is older than the retention period, then all the events in that segment are old enough, and the whole file can go.

1

Events are appended

New events go to the end of the active segment, a very fast sequential disk operation.

2

The segment rolls

When the active segment reaches its size or age limit, it is closed and a new active segment begins.

3

Closed segments wait

They stay on disk so consumers can read or replay them.

4

A periodic check runs

Every few minutes, the broker looks for closed segments whose newest event is older than the retention period.

5

Old segments are deleted

Eligible segment files are removed, and the earliest available position of the partition moves forward.

flowchart LR
  S1["Segment 1 - closed - all events older than retention"] --> S2["Segment 2 - closed - some events still young"]
  S2 --> S3["Segment 3 - closed - young"]
  S3 --> S4["Segment 4 - active - receiving new events"]
  S1 -.->|"Deleted at next check"| X["Removed from disk"]
        
FIG 1 — Only closed segments whose newest event is too old are deleted
Simple Analogy

A company files papers in boxes. Only the current box is open. When it is full, it is sealed and a new one begins. Every few days, a clerk checks the oldest sealed boxes: if even the newest paper inside is past its keep-until date, the entire box is thrown away. Nobody pulls single papers out of sealed boxes.

4Why the Active Segment Is Never Deleted

A surprising fact confuses many beginners: old events can outlive the retention period because of the segment they sit in.

The active segment stays

Kafka never deletes the active segment, because it is still being written. Even if every event in it is older than the retention period, it remains until it rolls and becomes a closed segment. Then it can be deleted at a later check.

A slow topic keeps old events longer

Consider a topic that receives very few events. Its active segment may take weeks or months to fill up. Until it rolls, everything in it stays, even events far older than the retention period. To prevent this, Kafka also rolls a segment when it becomes older than a chosen segment age, by default seven days. Setting this age smaller than the retention period makes deletion more predictable for slow topics.

A busy topic rolls quickly

On a busy topic, segments fill quickly and roll often, so old data leaves close to the retention period. On a quiet topic, data may linger much longer, which surprises teams who expected exact deadlines.

Topic TypeHow Segments RollEffect on Deletion
Very busySegments fill up quickly and roll by sizeOld data leaves shortly after the retention period
ModerateSegments roll by size or age, whichever comes firstOld data leaves within a bit more than the retention period
Very quietSegments roll only by age, since size is never reachedOld data may stay well beyond the retention period unless the segment age is tuned
Simple Analogy

A notebook is thrown away only after it is full and closed. If you write just one line a week, the notebook stays open for years, and its oldest pages stay with it. A rule such as “close every notebook after a month, however empty” makes clean-up predictable.

i
Helpful Note

If a quiet topic seems to ignore its retention period, look at its segment size and segment age settings before blaming Kafka.

5Time-Based and Size-Based Retention

Kafka offers two limits, and whichever is reached first triggers deletion.

Time-based retention

You choose how long to keep events, such as three days or thirty days. Closed segments whose newest event is older than that are deleted. This is the most common form and is easy to reason about: “we can replay the last seven days.”

Size-based retention

You can also limit how large each partition may grow. When a partition exceeds the limit, Kafka deletes the oldest closed segments until it is back under the limit. Note that the limit applies to each partition separately, not to the whole topic, so a topic with twelve partitions may hold twelve times the limit in total. The default is no size limit at all.

Both together

If you set both, Kafka deletes as soon as either limit is exceeded. Time-based limits protect against keeping data too long. Size-based limits protect the disk against sudden bursts of traffic that would fill it long before the time limit arrives.

ApproachQuestion It AnswersBest ForWatch Out For
Time onlyHow far back can I replay?Predictable replay windowsA traffic burst can fill the disk before the time limit
Size onlyHow much disk may this topic use?Protecting disk spaceThe replay window changes with traffic; it can become very short during bursts
Time and size togetherKeep data for a period, but never use more than this spaceMost production topicsData may disappear earlier than the time limit if the size limit is reached
flowchart TD
  C["Broker checks a closed segment"] --> Q1{"Is the newest event older than the retention time?"}
  Q1 -->|"Yes"| D["Delete the segment"]
  Q1 -->|"No"| Q2{"Is the partition over its size limit?"}
  Q2 -->|"Yes"| D
  Q2 -->|"No"| K["Keep the segment"]
        
FIG 2 — Whichever limit is reached first triggers deletion
Simple Analogy

A fridge has a rule: throw away food after a week, and also never let the shelves overflow. On a normal week, the one-week rule decides. After a big party, when the shelves overflow, the space rule forces the oldest food out first.

!
Common Mistake

Setting a size limit for a topic without calculating how it interacts with traffic. During a busy sale, the size limit may delete data in hours that you expected to keep for days.

6How Kafka Decides an Event Is “Old”

Age needs a clock. Kafka has to decide which time to use.

The record’s timestamp

Every event carries a timestamp. Kafka looks at the timestamps inside a segment to decide whether it is old enough to delete. There are two ways a timestamp can be set. In create time, the producer sets the timestamp when it creates the event. In log append time, the broker sets the timestamp at the moment it stores the event.

Why the choice matters

Create time and honest clocks

If producers set accurate times, retention follows the real age of the events. This is the usual default and works well.

Create time and wrong clocks

If a producer’s clock is far in the past, its events look old at once and may be deleted very early. If its clock is far in the future, its events look young and stay far longer than expected, and the whole segment they sit in stays with them.

Old data loaded later

If you load last year’s data into a topic with create time, those events appear a year old and may be deleted almost immediately, before anyone can read them.

Log append time for predictability

When the broker stamps events on arrival, retention counts from the moment of storage, which is predictable even when producers have unreliable clocks or are loading historical data.

Simple Analogy

A warehouse can decide a parcel’s age by the date the sender wrote on the label, or by the date it was received at the warehouse door. If senders write wrong dates, the door date is more trustworthy. If you are shipping antiques, the label date and the door date differ greatly, and you must choose which one matters.

i
Helpful Note

When back-loading old data into Kafka for testing or migration, be careful: with create time, old timestamps can cause instant deletion. Check the timestamp setting for that topic first.

7Compaction: A Different Kind of Retention

Sometimes the age of an event matters less than whether it is the latest one for its key.

The idea

With log compaction, Kafka keeps at least the latest event for every key, however old it is, and may remove older events with the same key. The topic then behaves like a table of current values. A new application can read the topic from the beginning and rebuild the current state of everything, without replaying every historical change.

An example

Suppose a topic stores each customer’s current address, keyed by customer number. A customer moves three times, producing three events with the same key. After compaction, only the newest address remains for that customer. Customers who never move keep their single event indefinitely.

Deleting with a tombstone

To remove a key completely, a producer sends an event with that key and an empty value, called a tombstone. Compaction eventually removes earlier events for that key, and later removes the tombstone itself after a grace period, by default one day, so readers have time to see the deletion.

Delete, compact, or both

Cleanup PolicyWhat Is KeptGood For
DeleteEverything within the time or size limitEvent streams such as clicks, logs, and orders where history has a natural expiry
CompactAt least the latest event per key, indefinitelyCurrent state, such as profiles, settings, or inventory levels
Compact and deleteLatest per key, but even those are removed after the time limitCurrent state that should also expire, such as sessions
Simple Analogy

Delete-by-time is like a notice board where notices older than a week are taken down. Compaction is like a contact list where each person’s old phone numbers are crossed out but the newest always remains. A tombstone is a note saying “remove this person entirely”.

flowchart LR
  A["Before: key A=1, key B=1, key A=2, key A=3, key B=2"] --> B["Compaction"]
  B --> C["After: key A=3, key B=2"]
        
FIG 3 — Compaction keeps the latest event for each key
!
Common Mistake

Enabling compaction on a topic whose events have no keys. Compaction works by key, so events without keys cannot be compacted, and the setting will not behave as expected.

8Retention and Consumers: The Danger of Falling Behind

Retention affects readers directly. A consumer that falls too far behind can lose events forever.

The race against deletion

A consumer reads events at some position, called its offset. If the consumer is slow, stopped for maintenance, or broken for a long weekend, it falls behind the newest events. Meanwhile, Kafka keeps deleting old segments. If the consumer’s position falls behind the earliest event that still exists, the events it wanted to read are gone.

What happens when the position is gone

When the consumer returns and asks for an event that has been deleted, Kafka answers that the requested position is out of range. The consumer must then decide where to start instead, according to its reset setting: from the earliest event that still exists, or from the newest event only. Starting from the earliest means it processes everything still available, but it has permanently missed what was deleted. Starting from the newest means it skips all the events it had not yet read.

1

The consumer stops

A bug or outage halts the consumer at offset 1,000 on a Friday evening.

2

Events keep arriving and old ones expire

Over the weekend, new events arrive, and retention deletes the oldest segments, including those around offset 1,000.

3

The consumer returns

On Tuesday, it asks for offset 1,000, which no longer exists.

4

The reset rule applies

The consumer jumps to the earliest available position or to the newest, and the deleted events are lost for this consumer forever.

Simple Analogy

You are watching a recorded series on a service that deletes episodes after thirty days. If you take a two-month holiday, the episodes you meant to watch next are gone. You can restart from the earliest one still available, or skip to the latest, but you cannot see what has been deleted.

i
Helpful Note

A useful rule: retention should be several times longer than the longest outage or slowdown your consumers might suffer, including weekends and holidays. Alert on consumer lag long before it approaches the retention period.

flowchart LR
  A["Earliest available offset moves forward as old segments are deleted"] --> B["Consumer position falls behind it"]
  B --> C["Position is out of range"]
  C --> D{"Reset rule"}
  D -->|"Earliest"| E["Restart from oldest remaining event; deleted events are missed"]
  D -->|"Latest"| F["Skip to the newest event; unread events are missed"]
        
FIG 4 — What happens when a slow consumer’s position is deleted

9Retention of Consumer Bookmarks

The consumer’s own progress is stored in Kafka too, and it also has a retention rule.

Where bookmarks live

The committed offsets of consumer groups are stored in a special internal Kafka topic. Like other data, they are not kept forever. When a group has no active members, its stored bookmarks are kept for a limited time, by default seven days, and then removed.

What this means in practice

If a consumer group is stopped for longer than this period, its bookmarks vanish. When the group returns, Kafka has no record of where it stopped, and the group starts according to its reset rule, either from the earliest available event or from the newest. This can cause a large amount of reprocessing or a large gap, even though the events themselves might still exist on disk.

A monthly batch consumer

A reporting job runs once a month and stops in between. Its bookmarks expire after the idle period, so each run starts from scratch unless the settings are adjusted or the job stores its own position.

A holiday shutdown

A whole system is switched off for two weeks. On return, groups whose bookmarks expired reread everything or skip everything, depending on their reset rule.

Simple Analogy

A library keeps a reading club’s bookmark card in a drawer. If the club does not meet for a whole year, the librarian clears out the old cards. When the club returns, nobody remembers which page they had reached.

!
Common Mistake

Focusing only on how long events are kept and forgetting how long bookmarks are kept. Both must be longer than the longest expected pause of the consumer group.

10Retention and Your Storage Bill

Every extra day of retention is paid for in disk space, on every copy of every partition.

The simple formula in words

The disk space a topic needs is roughly the volume of data per day, multiplied by the number of days kept, multiplied by the replication factor, which is the number of copies. That total is then spread over all brokers, with extra room for growth and for safety.

An example in words

Suppose a topic receives fifty gigabytes of events per day and keeps them for seven days, with three copies. That is fifty times seven times three, or one thousand and fifty gigabytes, just over a terabyte, for this one topic. Extending the retention to thirty days multiplies the requirement by more than four, to about four and a half terabytes. Adding compression on the producer side can reduce all of these numbers, sometimes by a large margin.

Volume
Data written per day
Days
How long it is kept
Copies
Replication factor, usually three
RetentionRelative Storage NeedTypical Reason
A few hoursVery smallEphemeral data consumed immediately
Seven days (default)ModerateNormal replay and recovery window
Thirty daysSeveral times largerLonger recovery windows, delayed batch jobs, audits
Very long or unlimitedGrows without boundEvent sourcing, compliance archives, permanent history
Simple Analogy

Keeping security footage for a week needs a certain number of hard drives. Keeping it for a month needs four times as many. Keeping two copies in different buildings doubles it again. The retention period is the biggest lever on the price of your storage room.

i
Helpful Note

Always keep free disk space on brokers, commonly a third or more, to absorb traffic bursts and to allow reassignments and recovery, which temporarily use extra space.

11Very Long Retention and Tiered Storage

Some businesses want to keep events for months or years. Kafka has ways to make this affordable.

Why keep data for so long?

Event sourcing

The full history of events is the source of truth, and the current state can be rebuilt from it at any time.

Compliance and audit

Regulations may require keeping transaction records for years.

Reprocessing with new logic

A better fraud model or analytics job can be run over the full history when it becomes available.

The cost problem

Keeping everything on the brokers’ local fast disks is expensive, because you pay for fast storage across every replica, and you must add brokers simply to hold old data that is rarely read.

Tiered storage

Tiered storage splits the log into two layers. Recent data stays on the brokers’ local disks for fast access. Older data is moved to cheaper, larger storage, such as cloud object storage, while remaining readable through Kafka. You then set two limits: a shorter one for how long data stays on local disks, and a longer one for how long it is kept overall. Consumers can still read old data through the normal interface, though it is slower to fetch than recent data. This feature is available in current Kafka releases, and its exact status and maturity should be checked for the version and service you use.

flowchart LR
  N["New events"] --> L["Local broker disks: recent data, fast"]
  L -->|"After local retention"| R["Remote storage: older data, cheaper"]
  R -->|"After total retention"| D["Deleted"]
  C["Consumers"] --> L
  C --> R
        
FIG 5 — Tiered storage keeps recent data close and old data cheap
Simple Analogy

A company keeps this month’s papers in the office filing cabinet for quick reference and moves older years to a cheaper warehouse across town. Any paper can still be fetched, but old ones take longer to arrive.

!
Common Mistake

Choosing “keep forever” without a plan for cost, privacy, and data protection rules. Unlimited retention is a real commitment: storage grows every day, and personal data may need to be deleted on request.

12Choosing a Retention Period

There is no universal right answer. A few questions lead you to a sensible choice.

Question 1

How long can consumers be down?

Retention must comfortably exceed your longest expected outage or slowdown, including weekends and holidays.

Question 2

How far back must we replay?

If you need to reprocess after bugs or add new consumers with history, choose the window that supports this.

Question 3

What are the legal requirements?

Some data must be kept for a minimum time, and other data must be deleted after a maximum time.

Question 4

How much can we afford to store?

Multiply volume, days, and copies to see the cost and the number of brokers you need.

Question 5

Is Kafka the system of record?

If the data also lives in a durable database, Kafka can keep less. If Kafka is the only copy, longer retention or compaction is needed.

Kind of TopicSensible ApproachReason
High-volume clicks or logsShort time-based retention, perhaps a day or a few daysLow value per event, high storage cost
Business events such as orders and paymentsDays to weeks, with safe replicationEnough to recover and replay after problems
Current-state data such as profiles or settingsCompactionOnly the latest value per key matters
Audit and event-sourced dataVery long retention or tiered storageHistory is the product
Data with privacy limitsRetention no longer than the allowed periodAutomatic deletion helps meet the rules
Retry and dead letter topicsLong enough for people to investigateFailed events must not vanish before they are examined
i
Helpful Note

Retention is set per topic, so you can choose different values for different needs. A default for the whole cluster is only a starting point.

13Privacy and Compliance

Retention is not only a technical setting. It is often a legal and ethical one.

Keeping too long is a risk

Many privacy rules say that personal data should not be kept longer than necessary. Events containing customer details that sit in Kafka for years, and in every backup and replica, can become a liability. A short, well-chosen retention period is a simple, automatic way of respecting such limits.

Deleting on request

When a person asks for their data to be erased, Kafka’s append-only nature makes this awkward. For compacted topics, a tombstone for that person’s key eventually removes their earlier events. For ordinary topics, the events stay until retention removes them, so short retention, or keeping personal data out of events, becomes important. Some organisations encrypt personal fields with a per-person key and delete the key when erasure is requested, making the old events unreadable.

Keeping long enough

Other rules require records to be kept for a minimum time, such as financial transactions. In such cases, retention must not be shorter than the required period, or a separate long-term archive must hold the records.

Simple Analogy

A hospital must keep some records for many years but destroy others promptly. It labels each folder with a destruction date, and the records room follows the label. Retention settings are the labels on your event folders.

!
Common Mistake

Assuming that deleting a record from the source database also deletes it from Kafka. The events already in topics, and their replicas and backups, follow their own retention rules and must be handled separately.

14Monitoring Retention

A few signals show whether retention is healthy or heading for trouble.

Disk
Space used and space left on each broker
Lag
How far consumers trail behind the newest events
Size
Growth of each topic and partition over time

What to watch

1

Disk usage per broker

Alert well before disks fill. A broker with a full disk stops working, and the cluster loses capacity at the worst possible time.

2

Consumer lag compared to retention

Watch how much time of data your slowest consumers are behind. If they approach the retention period, they are close to losing events.

3

Topic size trends

A topic growing faster than expected signals a traffic change or a wrongly set retention.

4

Earliest available offset

Track how far back each partition can be read. It shows the actual replay window rather than the promised one.

5

Out-of-range errors in consumers

Any occurrence means a consumer asked for events that were already deleted and has lost data.

Simple Analogy

A warehouse manager watches how full the shelves are, how quickly the oldest stock is being cleared, and whether any customer tried to order something that had already been thrown away. Those three signals tell whether the storage rules are working.

15Advantages and Trade-offs

Retention is a bargain between memory and cost.

Advantages of Longer Retention

  • More time to recover from consumer outages and bugs
  • New consumers can start with history
  • Data can be replayed after fixing logic
  • Supports audits and event-sourced designs
  • Gives teams room to react without panic

Disadvantages / Trade-offs of Longer Retention

  • Higher storage cost across all replicas
  • More brokers or bigger disks needed
  • Slower recovery when a broker must copy large amounts of data
  • Greater exposure of personal or sensitive data
  • Bigger effort to move or rebalance partitions

16Anti-Patterns and Best Practices

Most retention troubles come from the same few mistakes.

ANTI-PATTERN-01 Avoid
Problem

Leaving every topic on the default retention without thinking about its purpose.

Why It’s Harmful

Some topics keep data far longer than needed, wasting money, while others lose data before consumers or investigators can use it.

Correct Approach

Choose retention per topic, based on recovery needs, replay needs, cost, and legal rules.

ANTI-PATTERN-02 Avoid
Problem

Setting retention shorter than the longest possible consumer outage, such as a long weekend.

Why It’s Harmful

Consumers return to find their unread events deleted, causing permanent data loss.

Correct Approach

Make retention several times longer than the worst realistic outage, and alert on lag well before it nears the limit.

ANTI-PATTERN-03 Avoid
Problem

Using unlimited retention as a lazy substitute for a proper archive or database.

Why It’s Harmful

Storage grows forever, recovery and rebalancing become slow, and privacy obligations pile up.

Correct Approach

Use compaction for current state, tiered storage or an external archive for long history, and set explicit limits.

ANTI-PATTERN-04 Avoid
Problem

Loading historical data into a topic that uses create time without checking timestamps.

Why It’s Harmful

Old timestamps make events look expired, and they may be deleted almost at once.

Correct Approach

Use broker-assigned time for such topics, or temporarily extend the retention while the data is loaded and consumed.

ANTI-PATTERN-05 Avoid
Problem

Ignoring free disk space and relying on retention alone to protect the brokers.

Why It’s Harmful

A traffic burst can fill the disks long before old data expires, stopping the broker.

Correct Approach

Combine time limits with size limits where sensible, keep spare capacity, and alert on disk usage.

Best practices at a glance

Habit 1

Set retention per topic

Match it to the purpose of the data, not to a cluster-wide habit.

Habit 2

Exceed the worst outage

Keep data several times longer than the longest expected consumer downtime.

Habit 3

Do the storage arithmetic

Volume, days, and copies give the real cost. Add headroom.

Habit 4

Tune segment age for quiet topics

So that old data leaves close to the retention period.

Habit 5

Align bookmark retention

Make sure consumer offsets outlive the longest expected pause.

Habit 6

Use compaction for state

Keep latest values per key without keeping every historical change.

Habit 7

Respect privacy rules

Keep personal data only as long as allowed, and plan for erasure requests.

Habit 8

Monitor and review

Watch disk, lag, and earliest available offsets, and revisit settings as traffic grows.

“Retention is the promise you make to every consumer: whatever you miss, you can still find it here for this long.”

17A Real-World Walk-Through

Let us see how an online shop might design retention for its main topics.

1

List the topics and their purposes

The shop has topics for website clicks, orders, payments, customer profiles, and failed events awaiting investigation.

2

Clicks: short and cheap

Click events are huge in volume and of low individual value. Retention is set to two days, with compression on the producers, since analytics consumers keep up in near real time.

3

Orders and payments: a comfortable window

These matter greatly. Retention is set to fourteen days, longer than any planned or unplanned outage the team has seen, so services can recover and replay after bugs.

4

Profiles: compaction

The customer profile topic is compacted by customer number, so new services can load the latest profile of every customer without replaying years of changes. Deletion requests are handled with tombstones.

5

Failed events: long enough to investigate

The dead letter topic keeps events for thirty days, so engineers have time to investigate and fix problems before evidence disappears.

6

Audit copies go elsewhere

For legal records, a connector copies orders and payments to long-term archive storage, so Kafka itself need not hold them for years.

7

Protect and monitor

Disks are kept less than about two thirds full, size limits guard against bursts, alerts watch consumer lag against retention, and consumer bookmarks are kept longer than the longest planned shutdown.

flowchart LR
  CL["Clicks topic - 2 days"] --> AN["Analytics consumers"]
  OR["Orders topic - 14 days"] --> SV["Order and email services"]
  PY["Payments topic - 14 days"] --> SV
  PR["Profiles topic - compacted"] --> NS["New services load latest state"]
  DL["Dead letter topic - 30 days"] --> EN["Engineers investigate"]
  OR --> AR["Connector copies to long-term archive"]
  PY --> AR
        
FIG 6 — Different topics, different retention, chosen by purpose

18Frequently Asked Questions

Q1What is a retention period in one sentence?

It is the length of time Kafka keeps the events of a topic before they become eligible for deletion, regardless of whether anyone has read them.

Q2What is the default retention period?

Seven days for ordinary topics, unless the cluster or the topic has been configured differently. Always check the actual setting of your topic.

Q3Are events deleted after a consumer reads them?

No. Reading does not delete anything. Events stay until retention removes them, which is why many consumers can read the same data and why replay is possible.

Q4Why are my old events still there after the retention period?

Deletion works on whole closed segments and runs on a schedule. If the segment has not rolled yet, especially on a quiet topic, or its newest event is still young, older events stay with it.

Q5Can I keep events forever?

Yes, by turning off time and size limits, or by using compaction or tiered storage. But storage grows continuously, so plan for cost, recovery time, and privacy obligations.

Q6What happens if a consumer falls behind the retention period?

The events it had not read are deleted, and its saved position becomes invalid. It must restart from the earliest available or the newest event according to its reset rule, and the deleted events are lost for it.

Q7Does size-based retention apply to the whole topic?

No. It applies to each partition separately, so the total size of a topic can be the limit multiplied by the number of partitions.

Q8What is the difference between deletion and compaction?

Deletion removes events older than a time or beyond a size, regardless of key. Compaction keeps at least the latest event for every key and removes older events with the same key.

Q9Does retention apply to consumer bookmarks too?

Yes. The committed offsets of a group with no active members are kept for a limited time, by default seven days, and then removed. A group that stays idle longer starts again according to its reset rule.

Q10Can each topic have a different retention?

Yes. Retention is a topic-level setting, and different topics should have different values according to their purposes.

19Summary and Key Takeaways

We began with a library that must decide how long to keep newspapers before recycling them, and whose readers must know the rule. Kafka’s retention period is that rule. Unlike a traditional queue, Kafka does not delete events when they are read. It keeps them in segment files on disk and removes whole closed segments only when their events are older than the time limit or when the partition exceeds its size limit, checking on a schedule, never touching the active segment, and judging age by timestamps. Compaction offers a different rule: keep the latest event per key. Retention shapes everything around it: how long a slow consumer can be away before it loses events, how long consumer bookmarks survive, how much disk and money the cluster needs, how long personal data is exposed, and how deep your replay window is. Choose retention topic by topic, make it longer than your worst realistic outage, calculate the storage honestly, use compaction and tiered storage where they fit, and watch disk, lag, and earliest available offsets. Done well, retention is a quiet promise that keeps every reader safe.

Key Takeaways

  • Kafka keeps events after they are read — retention, not consumption, decides when events are deleted, which makes replay and many independent readers possible.
  • Retention is a minimum promise — the default is seven days, and deletion happens on whole closed segments during periodic checks, so events may live a little longer, especially on quiet topics.
  • Time and size limits work together — whichever is reached first triggers deletion, and the size limit applies to each partition, not to the whole topic.
  • Compaction is another policy — it keeps at least the latest event per key, with tombstones used to delete a key completely.
  • Slow consumers are at risk — if their position falls behind the earliest remaining event, the unread events are lost, so retention must exceed the longest realistic outage, and bookmarks must outlive long pauses.
  • Retention drives cost and compliance — storage is volume times days times copies, and privacy rules may require both minimum and maximum keeping times.
  • Set it on purpose and watch it — choose per topic, consider tiered storage or archives for long history, and monitor disk usage, consumer lag, and the earliest available offset.