Skip to content

    System Design

    Kafka Internals: Partitions, Offsets, Consumer Groups and ISR

    Follow a Kafka record from key to partition to offset, see how consumer groups split partitions and commit progress, and how segments and replication work.

    By Published 17 min read

    Share

    Flagship lessonadvancedKafka labBackend System Design

    Before this: Event Streaming and Logs

    What you'll learn: By the end of this lesson you will be able to describe a Kafka partition as a numbered log and say what its start, end and committed offsets mean, explain how a key picks a partition and why the partition count matters, trace how a consumer group assigns partitions and why a member beyond the partition count sits idle, read consumer lag, describe how a partition is stored as segment files, explain what the in-sync replica set protects, and size partitions and groups for a ShopStream topic. A lab runs all of it except replication on an in-process broker.

    Picture a very long till receipt that never ends. The shop tears it into numbered pages and files each page in a box, and the numbers never restart. Every clerk who wants to audit the day keeps a bookmark: "I have read up to number 412". Reading a page does not remove it; the manager clears out the oldest boxes whole, when the shelf is full or the pages are old. Several tills write to several rolls, and the manager keeps a spare copy of each roll in another room so a flood does not lose a day.

    That receipt roll is a Kafka partition. The earlier lessons gave the model: event streaming and logs introduces topics, partitions and groups, RabbitMQ vs Kafka compares the log with a queue, and the Confluent Kafka blog guide walks a record through the broker and its replication. This lesson does not repeat them. It looks at the three pieces of bookkeeping that decide how Kafka behaves in production: the offsets, the group assignment and the files.

    Verified on 2026-12-01 against the Apache Kafka 4.2 documentation listed under Official documentation. The lab ran against Kafka clients from Spring Boot 4.1.2 on one in-process broker, compiled for Java 25. It does not show replication.

    The core idea

    A partition is an append-only log of numbered records, and the rest of Kafka is bookkeeping around those numbers. A producer's key decides which log a record joins. Each consumer group stores one number per partition, the position of the next record it will read. The broker stores the log as files and deletes whole files by policy. Followers copy the log so a failure does not lose committed records.

    Three illustrations run through the lesson, each labelled:

    • Minimal example: the lab's nine records on a three-partition topic, read by two groups.
    • Realistic example: ShopStream's orders topic during a promotion.
    • Failure example: one hot key that makes one partition's lag grow while the others are empty.

    The partition log and its offsets

    The Kafka introduction says a topic is split into partitions, and the design page says a consumer's position in each partition is a single integer. That integer is an offset: the first record a partition ever receives is offset 0, the next is 1, and so on. An offset names a record inside one partition and means nothing across partitions.

    The lab sends nine records, one per key, to a topic with three partitions and waits for each acknowledgement, so the offsets follow the order of the list.

    Expected output, captured from a real run (one in-process broker, Kafka clients from Spring Boot 4.1.2):

    # 1. one record per key: where it landed
    key=1001 -> partition 0, offset 0
    key=1002 -> partition 0, offset 1
    key=1003 -> partition 1, offset 0
    key=1004 -> partition 1, offset 1
    key=1005 -> partition 2, offset 0
    key=1006 -> partition 2, offset 1
    key=1001 -> partition 0, offset 2
    key=1002 -> partition 0, offset 3
    key=1003 -> partition 1, offset 2
    
    # 2. what each partition holds, read from offset 0 (offset:key)
    partition 0: 0:1001 1:1002 2:1001 3:1002
    partition 1: 0:1003 1:1004 2:1003
    partition 2: 0:1005 1:1006

    Two things stand out. Every key always went to the same partition (1001 to partition 0 both times, 1002 to 0, 1003 to 1) and within a partition offsets rise in the order of the sends. Reading a partition from offset 0 returns the records in exactly that order. Ordering is a property of one partition and nothing wider.

    Which partition does a key choose?

    The producer documentation says that, with no custom partitioner, a record with a key goes to a partition chosen by a hash of the key, and a record without a key goes to a sticky partition that changes after a batch size is reached. The design page gives the reason for keys: if the key is a user id, all data for that user lands on one partition.

    flowchart LR accTitle: How a keyed record picks its partition accDescr: A record's key bytes are hashed, the hash is reduced modulo the topic's partition count, and the record is appended to that partition and receives the next offset there. If the partition count changes, the same key can map to a different partition. K["Record key
    for example an order id"] --> H["Hash of the key bytes"] H --> M["Hash modulo
    the partition count"] M --> P["Partition n"] P --> O["Append, receive
    the next offset in n"] C["Partition count changes"] -.->|"same key can map elsewhere"| M

    Figure 1. Key to partition to offset. How to read this: the mapping depends on the partition count. The lab's test reproduces the placement with Kafka's own Utils.murmur2 of the key bytes modulo 3. Adding partitions to a live topic changes where keys land, so per-key order can break across the change; size the count with headroom.

    Four numbers for one partition

    Four numbers describe where everyone stands in one partition.

    Number What it is Where you read it
    Log start offset The oldest offset still on disk Admin client listOffsets with the earliest spec
    Log end offset The offset the next record will receive Admin client with the latest spec
    Committed offset of a group The offset of the next record that group will read The group's offsets, stored by the group coordinator
    Lag Log end offset minus committed offset Computed from the two above

    The first two move with the producer and with retention. The third belongs to a consumer group and is stored by the broker: the Kafka documentation says the group coordinator appends each commit to a special compacted topic named __consumer_offsets and caches the offsets in memory for fast fetches. The fourth is arithmetic.

    flowchart LR accTitle: Offsets in one partition accDescr: A partition shown as a line from the log start offset on the left to the log end offset on the right. A consumer group's committed offset sits between them. The distance from the committed offset to the log end offset is the lag. S["Log start offset
    oldest record kept"] --> C["Committed offset of a group
    next record to read"] C --> E["Log end offset
    next record to be written"] C -. "lag = end - committed" .-> E

    Figure 2. Where a group stands in a partition. How to read this: records left of the committed offset are processed from this group's point of view, records between it and the end are the lag, and records left of the start offset are gone. Different groups have different committed offsets in the same partition.

    The lab reads the whole topic as two groups, inventory and analytics, each of which commits after reading. Then three more records arrive and nobody reads them.

    Expected output, captured from a real run (two groups, then three unread records):

    # 3. two consumer groups read the same topic, each commits its own offsets
    group inventory read 9 records, committed offsets {0=4, 1=3, 2=2}
    group analytics read 9 records, committed offsets {0=4, 1=3, 2=2}
    log start offsets {0=0, 1=0, 2=0}, log end offsets {0=4, 1=3, 2=2}
    
    # 4. three more records arrive and nobody has read them yet
    log end offsets {0=5, 1=4, 2=3}
    lag of group inventory per partition {0=1, 1=1, 2=1}

    Both groups ended with the same committed offsets because both read everything, and neither read removed anything: the log start offsets are still 0. The committed offset of a partition equals its log end offset after a full read (0=4 for the four records at offsets 0 to 3), which shows that the committed offset is the next offset to read, not the last one read. After three more records the lag per partition is the log end offset minus that committed number.

    Replay is a change to a number

    Because progress is just the committed offset, replay is changing it. The Kafka design page says a consumer can deliberately rewind to an old offset and re-consume data. The lab does it two ways: rewinding a group's committed offsets with the admin client, and reading one partition from a chosen offset with assign and seek, which needs no group.

    Expected output, captured from a real run (rewind and seek):

    # 5. replay: rewind a group, or seek without a group
    group inventory resumed from its committed offsets and read 3 records (the new ones)
    rewound group inventory to {0=0, 1=0, 2=0}
    group inventory read 12 records again, committed offsets {0=5, 1=4, 2=3}
    assign and seek to partition 0, offset 2 (no group): 2:1001 3:1002 4:1001

    The group resumed with only the three new records, then re-read all twelve after the rewind. A rewind only works while the records are still retained: a record deleted by retention cannot be replayed.

    Consumer groups: who reads which partition

    A consumer group is a set of consumers that share a topic's partitions. In the lab each partition is owned by exactly one member of a group at a time, so records in a partition reach one member in order.

    The default partition.assignment.strategy in the consumer documentation is the list RangeAssignor, CooperativeStickyAssignor, and the lab names RangeAssignor explicitly so the output does not depend on a client default. It also sets group.instance.id, which the documentation says makes a consumer a static member: only one instance with that id can be in the group, and the setting is meant to be paired with a longer session timeout so brief outages do not cause rebalances. A static id has a side effect that suits a lab: the assignors sort members by it, so the assignment is the same on every run.

    Four consumers in one group reading a topic with three partitions: three each own one partition and the fourth is idlePartition 0 to Member c1 (poll); Partition 1 to Member c2; Partition 2 to Member c3ONE CONSUMER GROUPPartition 0Partition 0Partition 1Partition 1Partition 2Partition 2Member c1: owns 0Member c1owns 0Member c2: owns 1Member c2owns 1Member c3: owns 2Member c3owns 2Member c4: idleMember c4idlepoll

    Figure 3. Partitions are the ceiling on a group's parallelism. How to read this: each partition has one owner. A fourth member joins and receives nothing, because there is no fourth partition to give it.

    The lab starts members one by one on their own threads and prints the assignment after each joins.

    Expected output, captured from a real run (range assignor, static member ids):

    # 6. partitions of a topic are split between the members of a group (range assignor, static member ids)
    1 member : {c1=[0, 1, 2]}
    2 members: {c1=[0, 1], c2=[2]}
    3 members: {c1=[0], c2=[1], c3=[2]}
    4 members: {c1=[0], c2=[1], c3=[2], c4=[]}

    With one member the whole topic goes to it; with two the range assignor gives the first member the extra partition; with three each has one; with four the last has none. The test behind the lab checks the rule rather than the layout: every partition is owned by someone, once.

    Two more facts about groups come from the documentation and the blog rather than the lab. The consumer documentation lists group.protocol with the values classic (the default) and consumer, so the rebalance protocol is a client choice, and the blog guide's section on the consume path covers rebalancing, which is not repeated here. And the documentation for max.poll.interval.ms says a consumer that does not call poll() in time is considered failed and the group rebalances; static members keep their partitions until the session timeout expires.

    The same mechanism gives work sharing. Two members of one group on a fresh topic each read only the partitions they own.

    Expected output, captured from a real run (two members, six records):

    # 7. two members of one group on a fresh topic: each record goes to the owner of its partition
    assignment {c1=[0, 1], c2=[2]}
    c1 read p0@0:1001 p0@1:1002 p1@0:1003 p1@1:1004
    c2 read p2@0:1005 p2@1:1006

    Each member saw its partition's records in offset order, and the six records were split by partition, not by arrival. A busy partition cannot be shared between members.

    How a partition is stored: segment files

    The Kafka log documentation says a partition is a directory of files, each named with the offset of the first record it contains, so the first file is 00000000000000000000.log. Appends go to the last file, which is rolled over to a fresh file when it reaches a configurable size, the topic setting segment.bytes. To find a given offset the broker searches the files by those names; the page describes it as a simple binary search variation against an in-memory range maintained for each file.

    One partition as segment files: two closed segments and an active segment, named by their first offsetAppends to Active segment (append); Segment to Segment (rolled); Segment to Active segment (rolled); Retention to Segment (oldest first)PARTITION DIRECTORYAppends: always the last fileAppendsalways the lastfileSegment: first offset 0Segmentfirst offset 0Segment: first offset 3Segmentfirst offset 3Active segment: first offset 6Active segmentfirst offset 6Retention: deletes whole filesRetentiondeletes wholefilesappendrolledrolledoldest first

    Figure 4. A partition is a directory of segments. How to read this: the file name is the first offset it holds. A write goes to the active segment; when it is full a new one starts at the next offset. Retention removes closed segments from the old end.

    The lab uses a topic with segment.bytes set to 1,048,576 (1 MiB) and records of 300,000 bytes, then lists the real .log files in the broker's data directory. In the Kafka 4.2 topic configuration page 1,048,576 is the smallest valid value, which is why the records are large.

    Expected output, captured from a real run (segment files on the broker's disk):

    # 9. segment files (topic segs: one partition, segment.bytes 1048576, records of 300000 bytes)
    after 3 records: log start offset 0, log end offset 3, segment files [00000000000000000000.log]
    after 6 records: log start offset 0, log end offset 6, segment files [00000000000000000000.log, 00000000000000000003.log]
    after 12 records: log start offset 0, log end offset 12, segment files [00000000000000000000.log, 00000000000000000003.log, 00000000000000000006.log, 00000000000000000009.log]

    Three records fit in one segment and the fourth starts a new one, so the files are named for offsets 0, 3, 6 and 9 and each name is the first offset in that file.

    Retention in this lab, and what it did not show. The documentation says data is deleted one segment at a time, that size-based retention (retention.bytes) is off by default (value -1) and time retention (retention.ms) defaults to 7 days, and that the broker checks for deletable segments every log.retention.check.interval.ms (5 minutes by default). The lab does not show a deletion. In the run attempted for this lesson on Windows, the broker's rename of a deleted segment's index file failed with a file-system error and the broker took its log directory offline, so the retention part was removed rather than shown. Treat that as a limit of running a broker on this one machine, not as a statement about Kafka on Linux; retention is described here from the documentation, and only segment rolling comes from the lab.

    Replication and the in-sync replica set

    Every partition has a leader and zero or more followers, which the design page says consume from the leader just as a normal consumer would and apply the records to their own log. The blog guide's section on the cluster covers the produce path, the high watermark and the replica table, so this section adds only the design reasoning.

    The design page contrasts two approaches. A majority vote for both commits and leader election needs three copies to tolerate one failure and five to tolerate two. Kafka instead keeps a set of in-sync replicas, the ISR, that are caught up to the leader, and with f+1 replicas a topic can tolerate f failures without losing committed messages. A message is committed only when all replicas in the ISR have it, and only committed messages are given to consumers. A producer chooses how long to wait with acks, and min.insync.replicas (default 1) sets the smallest ISR that accepts a write when acks=all. On failure, the page says Kafka by default prefers waiting for a consistent replica to a possibly stale one: unclean leader election is off.

    The lab's broker has one node, so the metadata it prints is the trivial case.

    Expected output, captured from a real run (partition metadata, one broker):

    # 8. partition metadata from the broker
    partition 0: leader broker 0, replicas [0], in-sync replicas [0]
    partition 1: leader broker 0, replicas [0], in-sync replicas [0]
    partition 2: leader broker 0, replicas [0], in-sync replicas [0]

    Each partition's only replica is the leader, and the ISR is the leader alone. Shrinking the ISR and a write rejected for too few in-sync replicas need a second broker, which the embedded cluster in this lab could not provide: a three-node embedded cluster did not start reliably with Spring Kafka 4.1.2 in the attempt made for this lesson. Those behaviours are therefore described from the documentation, not shown.

    Where Kafka sits among replication designs

    A Kafka partition is single-leader replication: one leader orders the writes and followers copy it. That is the opposite end from the leaderless stores of multi-leader and leaderless replication, where any replica may take a write and conflicts are resolved afterwards. Kafka avoids write conflicts by giving each partition exactly one ordering point, and it pays for that with the partition as the unit of both order and parallelism. Its commit rule is also not the R plus W above N rule of quorum reads and writes: the commit set is the in-sync replicas, whose size is dynamic, which is the difference the design page's majority-vote comparison draws.

    Build it: partitions, groups and segments on an in-process broker

    This is the minimal example, a lab you can run. The code uses the plain Kafka producer, consumer and admin clients against the in-process broker that the Spring Boot Kafka test starter provides, through @EmbeddedKafka.

    Goal. Watch keys map to partitions, two groups keep separate offsets, a group replay by rewinding, members split partitions and a partition roll into segments.

    Setup. From the repository root:

    cd examples/spring-labs
    ./gradlew :labs:kafka-partitions-and-groups:test

    The command runs seven tests: six check one rule each (same key same partition, per-partition order, groups keep their own offsets, rewind replays, group members share partitions and an extra member is idle, segments roll at the configured size) and one compares the whole report with the golden file. The code is in examples/spring-labs/labs/kafka-partitions-and-groups/src/main/java/buildingai/labs/kafka/KafkaLab.java.

    How it works. Every section of the output above comes from KafkaLabReport.render, which runs against one broker with broker id 0. Group members are threads that each own a consumer; the assignment is read from each consumer's assignment(). The consumer settings that matter are these:

    p.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
    p.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
    // The range assignor is named here so the assignment below does not depend on a client default.
    p.put(ConsumerConfig.PARTITION_ASSIGNMENT_STRATEGY_CONFIG, RangeAssignor.class.getName());

    Auto commit is off so the lab commits explicitly after reading, which is the at-least-once pattern the event streaming lesson describes.

    Break it. In KafkaLab.consumerProps change auto.offset.reset to latest: groups that have no committed offset start at the end and read nothing from the topic's existing records, and the golden test fails. Restore it and rerun.

    Stretch. Add a fifth member to the group in section 6 of KafkaLabReport and confirm it is idle too; then change the topic to six partitions and see how the assignment changes.

    Trade-offs

    Decision Gain Cost Wrong when
    More partitions More parallel consumers in a group, more write spread Each key may map elsewhere after a change; more files and replicas to manage The topic is low volume with one consumer
    Fewer partitions Simpler, stronger locality Parallelism ceiling for every group A group must scale past the count
    Key by entity id Per-entity order, one owner A hot entity makes a hot partition Keys are heavily skewed
    No key Even spread No per-key order Order matters
    Static group members Fewer rebalances on restart Slower detection of a dead member Members come and go often
    Small segments Finer-grained retention More files Volume is very high
    acks=all with min.insync.replicas above 1 Committed writes survive a failure Writes stop if the ISR is too small Availability matters more than durability

    In practice: ShopStream's orders topic during a promotion

    This is an educational scenario with illustrative numbers.

    The situation

    This is the realistic example. ShopStream's order service publishes an event per order to orders. The shared planning figures (illustrative) are 500,000 orders per day and about 58 checkouts per second at peak. A promotion is expected to double the peak. Inventory, payments, shipping and analytics each read the topic as their own group, and the inventory consumer can process about 20 orders per second per instance (a made-up figure for this exercise).

    This is a realistic scenario, not a case history.

    Starting architecture

    ShopStream orders topic with four consumer groupsOrder service to Topic orders (append); Topic orders to Inventory; Topic orders to Payments; Topic orders to Shipping; Topic orders to AnalyticsOrder service: key = order idOrder servicekey = order idTopic orders: partitions: to sizeTopic orderspartitions: tosizeInventory: groupInventorygroupPayments: groupPaymentsgroupShipping: groupShippinggroupAnalytics: groupAnalyticsgroupappend

    Each group has its own committed offsets and its own lag.

    Options considered

    Option Gain Cost Wrong when
    A. 3 partitions Simple Inventory cannot use more than 3 instances Doubled peak needs more instances
    B. 12 partitions Room for 12 instances per group, no repartition soon More files and replicas Volume stays small
    C. Key by customer id Per-customer order A large customer becomes a hot partition Order by order id is enough

    The decision

    Option B, keyed by order id. The arithmetic (illustrative): a doubled peak of about 116 orders per second divided by 20 per instance is 5.8, so at least 6 inventory instances; 12 partitions leave room for twice that and for a restart of some members. Order id as the key keeps one order's events in order, and orders are many and evenly spread, so no partition is hot.

    Rollout and verification

    Create the topic with 12 partitions before the promotion, since changing the count later moves keys. Run inventory with 6 members and watch the per-partition lag, using the admin client or the consumer-group tool. Rehearse a rewind on a copy of the group before the promotion, so replay is a known procedure.

    The 2 a.m. failure

    The page reads: "Inventory lag rising, 11 of 12 partitions empty". One partition's lag grows while the others are at zero. A single key is producing most of the traffic, such as a bulk-order integration using one order prefix as the key.

    First checks: lag per partition and the keys in the hot partition's latest records. Mitigation: if the key is not the order id, correct it; if one customer legitimately dominates, accept that one member serves that partition and add capacity there, or key more finely where order allows. Follow-up: alert on per-partition lag, not just the group total, and review the key choice.

    Architect's notes

    • Choose the partition count with headroom: it is the ceiling on every group's parallelism and changing it moves keys.
    • Alert on lag per partition, not only per group.
    • The key is a contract. Document what order it protects.
    • Rehearse replay, including the case where the records have already been deleted by retention.
    • Do not size from folklore. No partition count or throughput figure here was measured; measure your own broker.
    • Know what your test broker cannot show. A one-node broker cannot show ISR behaviour.

    Common mistakes

    • Adding consumers beyond the partition count and expecting more throughput.
    • Treating the committed offset as the last record read. It is the next one.
    • Changing the partition count on a live keyed topic without a migration plan.
    • Expecting replay after retention has deleted the data.
    • Reading group lag as a total and missing one hot partition.

    Key takeaways

    • A partition is an append-only log of numbered records; offsets are meaningful only inside one partition.
    • A keyed record goes to the partition its key hashes to; the mapping depends on the partition count.
    • A consumer group stores one committed offset per partition, the next offset to read; lag is the end offset minus that number.
    • Each partition has one owner in a group, so the partition count caps a group's parallelism and an extra member is idle.
    • Replay is changing a number, and it works only while the records are retained.
    • A partition is a directory of segment files named by their first offset; retention deletes whole segments.
    • Replication is single-leader with an in-sync replica set, so committed records survive up to f failures with f+1 replicas.

    Practice exercises

    Exercise 1 (20 min). For the lab's nine records, work out by hand the committed offsets of a group after it reads only partition 1, and the lag of each partition.

    Exercise 2 (45 min). Change the lab so the topic has six partitions and four members. Predict the range assignment, then run it and compare.

    Exercise 3 (30 min). For ShopStream's 12-partition topic, list which groups need the same key order and which do not, and say whether any should use a different key.

    Exercise 4 (30 min). Read the Kafka design page's replication section and write, in your own words, why a majority vote needs three copies to tolerate one failure while the ISR approach needs two.

    Later lessons in this module, named here without links: backend-delivery-guarantees, backend-dead-letter-queues-and-retries, backend-schema-evolution-avro-and-schema-registry and backend-stream-processing-basics.

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments