ArchitectMind
  1. Home
  2. Java Ecosystem
  3. Book 7 · Application Architecture & Distributed Systems
  4. Volume VI
  5. Event Log
Book 7 · Volume VI — Event-Driven & Asynchronous Architecture · Topic 2.1

Event Log

Append-only log and offset

8 min readStage 3 · Systems8 interview questions
Chapter
Chapter 2 — Event Streaming
Prerequisites
Chapter 1
You will be able to
Explain why an append-only log suits event streaming, describe how offsets identify positions and how consumers track progress, contrast logs with queues, configure retention, compaction and tiered storage, and reason about the performance characteristics of log-structured storage
Covers
Append-only log; Offset
On this page
  1. 1. Concept / Definition
  2. 2. Why It Exists
  3. 3. Core Concepts
  4. 4. How It Works Internally — Storage and Retention
  5. 4A. Deep Dive — Compaction and Tiered Storage
  6. 5. APIs / Features / Syntax
  7. 6. Practical Examples
  8. 7. Common Problems & Mistakes
  9. 8. Performance & Production Considerations
  10. 9. Architecture & Design Considerations
  11. 10. Interview Questions & Answers

1Concept / Definition

An event log is an ordered, append-only sequence of records. New events are only ever added at the end; existing records are never modified. Each record's position is its offset — a monotonically increasing number within the log (in Kafka, within a partition). Consumers read sequentially and remember the offset they have reached, so many consumers can read the same log independently.

Append-only log (TOC) and offsets (TOC)
Figure 1 — Append-only log (TOC) and offsets (TOC)
TOC conceptDefinition
Append-only logA storage structure where writes only append records to the end, records are immutable once written, and reads are sequential from any position; records are removed only by retention or compaction, not by consumption
OffsetThe sequential position of a record in a partition's log; used by consumers to request records ("fetch from 42") and to record progress (committed offset = next record to read), independently per consumer group
Table 1 — The two TOC concepts

2Why It Exists

Traditional queues delete messages once consumed, so a second consumer or a replay requires re-sending. A log keeps history: analytics, search indexing and billing can all read the same events, and any of them can rewind.

The log is also a simpler foundation for distributed systems than it first appears. Jay Kreps' argument in The Log is that if every change is written once, in order, to a durable log, then every other system, whether a search index, a cache, a data warehouse or a billing ledger, can derive its state by reading that log at its own pace. Producers no longer need to know who consumes their events, and adding a consumer requires no change upstream. Because the log keeps history, a consumer with a bug can be fixed and replayed from an earlier offset, and a new read model can be built from scratch. The same shape suits hardware: appending sequentially to disk and reading recent data from the page cache is far faster than random updates.

Queue vs log
Figure 2 — Queue vs log

3Core Concepts

3.1 Append-only log

Append and read
Figure 3 — Append and read
PropertyConsequence
Append-onlySequential disk writes — very fast
Immutable recordsSafe to cache, replicate, replay
Totally ordered (per partition)Consumers see same order
Retained independently of readsLate consumers, replays
Segmented filesCheap deletion by dropping old segments
Table 2 — Why the log shape matters
Why logs are fast (illustrative)
Figure 4 — Why logs are fast (illustrative)

3.2 Offset

JAVA
// Inspect and control offsets explicitly (plain Kafka consumer)
try (var consumer = new KafkaConsumer<String, String>(props)) {
    var tp = new TopicPartition("orders.events.v1", 3);
    consumer.assign(List.of(tp));
    consumer.seek(tp, 1_000);                                   // start at offset 1000
    for (ConsumerRecord<String, String> r : consumer.poll(Duration.ofSeconds(1))) {
        System.out.printf("p%d@%d key=%s%n", r.partition(), r.offset(), r.key());
    }
    long end = consumer.endOffsets(List.of(tp)).get(tp);        // log-end offset
}
Offset termMeaning
Log-start offsetFirst retained record
Log-end offset (LEO)Next offset to be written
High watermarkLast offset replicated to ISR — visible to consumers
Committed offsetGroup's next record to read
LagHigh watermark − committed offset
Table 3 — Offset vocabulary
BASH
kafka-consumer-groups.sh --bootstrap-server $BROKERS --describe --group billing-svc
# TOPIC            PARTITION CURRENT-OFFSET LOG-END-OFFSET LAG
# orders.events.v1 3         1042           1050           8

4How It Works Internally — Storage and Retention

Segment lifecycle
Figure 5 — Segment lifecycle
Retention options
Figure 6 — Retention options
Internal mechanismEffect
Segment files (e.g., 1 GB)Retention deletes whole segments
Offset indexFast seek to offset
Time indexSeek by timestamp (replay from time)
Page cacheRecent reads served from memory
Zero-copy (sendfile)Efficient network transfer
__consumer_offsets (compacted)Stores group offsets
Table 4 — How Kafka implements the log

4ADeep Dive — Compaction and Tiered Storage

Log compaction
Figure 7 — Log compaction
BASH
# Compacted state topic: latest value per key retained indefinitely
kafka-configs.sh --bootstrap-server $BROKERS --alter --entity-type topics \
  --entity-name products.state.v1 \
  --add-config cleanup.policy=compact,min.cleanable.dirty.ratio=0.3 \
  --add-config delete.retention.ms=86400000
Retention designUse case
7 days deleteOperational event streams
CompactedEntity state for bootstrap (Topic 1.3)
Tiered 1 yearReplay/audit without large local disks
Infinite + compactionReference data
Table 5 — Choosing retention by purpose

5APIs / Features / Syntax

NeedTooling
Read/seekKafkaConsumer.seek, offsetsForTimes
Inspect lagkafka-consumer-groups.sh, Burrow, MSK metrics
RetentionTopic configs (retention.ms, cleanup.policy)
Long historyTiered storage (MSK tiered, KIP-405)
SpringConsumerSeekAware, KafkaAdmin topic beans
Table 6 — Toolkit

6Practical Examples

6.1 Search index rebuilt from the log

A search mapping change required re-indexing all products. Because products.state.v1 was compacted, a new consumer group read it from the beginning and rebuilt the index in 40 minutes without touching catalog-svc.

6.2 Retention too short

Orders were kept only 24 hours; a consumer bug found three days later couldn't be fixed by replay. Retention was raised to 14 days hot plus tiered storage for 180 days.

6.3 Worked example — lag calculation

HWCommittedLag
105010428
Table 7 — Consumer health

6.4 Worked example — independent groups

GroupOffset p3
billing1042
analytics300
Table 8 — Separate bookmarks

6.5 Worked example — seek by time

JAVA
var ts = Instant.parse("2026-09-25T09:00:00Z").toEpochMilli();
var offs = consumer.offsetsForTimes(Map.of(tp, ts));
consumer.seek(tp, offs.get(tp).offset());

6.6 Worked example — retention sizing

ThroughputRetentionStorage (RF=3)
5 MB/s7 days~9 TB
Table 9 — Capacity planning

6.7 Worked example — tiered savings

LocalRemote (S3)
1 day hot180 days cheap
Table 10 — Cost

6.8 Worked example — compaction semantics

GuaranteeDetail
Latest per key eventuallyNot immediately
Table 11 — Consumers still see some duplicates

6.9 Worked example — tombstone retention

SettingWhy
delete.retention.ms 1 dayConsumers see deletes before removal
Table 12 — Erasure propagation

6.10 Worked example — queue use case

NeedBetter fit
Task queue, per-message delaySQS/RabbitMQ
Table 13 — Not everything is a log

6.11 Worked example — high watermark

Consumer can readUp to HW
Table 14 — Committed data only

6.12 Worked example — offset out of range

CauseResult
Committed offset deleted by retentionauto.offset.reset applies
Table 15 — Monitor lag vs retention

6.13 Worked example — segment size

segment.bytesEffect
SmallerFiner retention, more files
Table 16 — Tuning

6.14 Worked example — audit trail

RequirementLog design
7-year auditArchive to S3 via connector
Table 17 — Beyond broker

6.15 Worked example — Spring topic bean

JAVA
@Bean
NewTopic orders() {
    return TopicBuilder.name("orders.events.v1").partitions(12).replicas(3)
            .config("retention.ms", "1209600000")          // 14 days
            .build();
}

6.16 Worked example — consumer offsets topic

TopicPolicy
__consumer_offsetsCompacted
Table 18 — Offsets are a log too

6.17 Worked example — ordering reminder

ScopeOrdered
Partition✔
Topic✘
Table 19 — Topic 2.3

6.18 Worked example — monitoring

MetricAlert
Lag approaching retentionData loss risk
Table 20 — Critical alert

6.19 Worked example — ADR

DecisionRationale
14 d hot + 180 d tieredReplay window
Table 21 — Recorded

6.20 Worked example — review checklist

Check✔
Retention matches replay needs✔
Compaction for state topics✔
Lag monitored✔
Tiered storage considered✔
Table 22 — Log review

6.21 Worked example — interview answer

ConceptAnswer
LogAppend-only, immutable, retained
OffsetPosition; each group commits its own
Table 23 — Structured answer

7Common Problems & Mistakes

  • Treating Kafka like a queue (expecting deletion).
  • Retention shorter than recovery needs.
  • Ignoring lag vs retention.
  • Compaction expected to be immediate.
  • Assuming topic-wide ordering.
  • Storing years on broker disks without tiering.

Most of these mistakes come from carrying queue intuitions into a log. Teams expect consumed events to disappear, then are surprised when disks fill or a new consumer group sees weeks of history. Retention is often set from disk cost rather than recovery needs, so when a bug is found after three days, a 24-hour topic cannot be replayed. Lag that grows towards the retention limit is especially dangerous: once a group's committed offset falls before the log-start offset, auto.offset.reset takes over and the consumer either skips data or reprocesses everything that is left. Compaction is eventual, so consumers of a compacted topic still see several values per key. Ordering exists only within a partition, and keeping years of data on broker disks costs far more than tiered storage.

8Performance & Production Considerations

AspectGuideline
WritesSequential, batched
ReadsPage cache, sequential
RetentionBy replay needs
HistoryTiered storage
MonitoringLag, disk, under-replication
Table 24 — Operational guidelines

9Architecture & Design Considerations

  • Use logs where history and multiple readers matter.
  • Design retention per topic purpose.
  • Use compacted topics as state sources.
  • Plan replay windows explicitly.

10Interview Questions & Answers

Q1L1 · BasicConcept

What is an append-only log?

An append-only log is an ordered sequence of records where writes only ever add to the end, and records are immutable once written. Readers can start at any position and read sequentially. Crucially, reading does not remove anything; records leave the log only through retention by time or size, or through compaction, which keeps the latest value per key. This structure gives total order within a partition, safe caching and replication because records never change, cheap writes because the disk only appends, and replay because history remains available. In Kafka each partition is such a log, stored as segment files with offset and time indexes.

Q2L1 · BasicConcept

What is an offset?

An offset is a record's sequential position within a partition's log, a 64-bit number that increases as records are appended. It identifies a record only together with its topic and partition: offset 42 in partition 3 is unrelated to offset 42 in partition 4. Consumers use offsets in two ways: to request data, by fetching from a given offset, and to record progress, by committing the offset of the next record to read. Each consumer group stores its own committed offsets in the compacted __consumer_offsets topic, so billing can be at 1042 while analytics is at 300 on the same partition, each reading independently.

Q3L2 · IntermediateTrade-off

How does a log differ from a queue?

In a queue, a message is delivered to one consumer and deleted once acknowledged; in a log, records stay after being read and each consumer group keeps its own offset. That makes logs better for multiple independent readers, replay after a bug, rebuilding read models and ordering per partition. Queues such as SQS or RabbitMQ are better for task distribution: per-message acknowledgement and redelivery, dead-letter handling for individual messages, delayed messages and competing consumers without a partition limit. A log's parallelism within a group is bounded by its partition count, and one slow record holds up its partition. Use a log for event streams and a queue for work items.

Q4L2 · IntermediateConcept

What is consumer lag?

Consumer lag is how far a consumer group is behind the end of a partition: the latest readable offset, the high watermark, minus the group's committed offset. In the note's example the high watermark is 1050 and billing has committed 1042, so the lag is 8 records; total lag is the sum across partitions. Lag is the main health signal for consumers: steady, low lag is fine, while growing lag means consumers cannot keep up or are stuck. It also drives autoscaling, for example with KEDA. Most importantly, alert when lag approaches the retention window, because records beyond it will be deleted before the group reads them.

Q5L3 · Senior EngineerConcept

What is log compaction?

Log compaction is a retention policy that keeps at least the latest record for each key instead of deleting records by age. A background cleaner rewrites older segments, dropping records that have been superseded by a newer value with the same key. A record with a null value, called a tombstone, marks a key as deleted and is itself removed after delete.retention.ms. The result is a topic that acts as a durable table of current state, such as products.state.v1, which a new consumer can read from the beginning to bootstrap a search index. Compaction is eventual, so consumers may still see several values per key and must treat them as upserts.

Q6L3 · Senior EngineerTricky

What happens if a committed offset falls outside retention?

The consumer hits an offset-out-of-range condition, and its auto.offset.reset setting decides what happens. With latest, it jumps to the end and silently skips every record between its old position and now, which is data loss from that consumer's point of view. With earliest, it restarts from the log-start offset and reprocesses whatever is still retained, which duplicates side effects unless consumers are idempotent. With none, it throws an exception so that a human can decide. This usually happens when a consumer is down or slow for longer than the retention period. Prevent it by alerting when lag approaches retention and sizing retention for realistic recovery times.

Q7L4 · Technical ArchitectInternals

Why are logs fast?

Because the log shape matches what disks and operating systems do best. Producers append sequentially, and sequential writes are far faster than random updates, even on SSDs. Kafka producers batch and compress records, so each request carries many of them. Reads are mostly served from the operating system's page cache, because consumers usually read data that was written moments earlier. When sending to consumers, Kafka can use zero-copy sendfile to move bytes from the page cache to the socket without copying them through the JVM heap, although TLS encryption prevents this. Offset and time indexes make seeks cheap, and retention deletes whole segment files rather than individual records.

Q8L5 · Solution ArchitectDesign

How would you set retention for a platform's topics?

I set retention by each topic's purpose, then check it against replay and compliance needs. Operational event streams such as orders.events.v1 get days to weeks of hot retention, long enough to detect and fix a consumer bug, for example 14 days. Entity state topics use compaction so that the latest value per key is kept indefinitely for bootstrapping. Long replay or audit windows use tiered storage, for example one day on local disk and 180 days in S3, and multi-year audit goes to an archive through a connector. Capacity is sized from throughput times retention times replication factor, lag against retention is alerted, and each choice is recorded in an ADR.

Test your knowledge on this topic →Flashcards from this topic's 8 questions, filtered by level and type.

Free question pack

Get 100 free Core Java interview questions

Subscribe for the Book 1 question pack (PDF, every answer explained) and new tutorials once a week. No spam, unsubscribe anytime. What is in the pack?

Almost done! Check your inbox and click the confirmation link. Your download link arrives as soon as you confirm.