Scrivio Interview library

Kafka producers and consumers in depth

40 questions in 9 subtopics.

About this topic

The producer and consumer clients decide most of what an application experiences with Kafka: latency, throughput, ordering, duplicates and data loss. Their defaults are reasonable, but each setting interacts with others, and many production incidents come from a client tuned by guesswork, a slow poll loop or an offset reset nobody expected. These questions go beyond the basics into how the Java clients batch, compress and partition records, how delivery timeouts and retries keep order, how the poll loop and the rebalance protocols manage group membership, including the protocol that became generally available in Kafka 4.0, and how fetch settings, offset resets, parallel processing, headers and large payloads are handled. They range from reading client metrics to setting client standards for a whole company.

Batching, linger and compression

The producer groups records per partition into batches before sending them, and linger.ms, batch.size and compression decide how full those batches get. Understand how batching trades a little latency for far fewer requests, how codecs compare in speed and ratio, and why small batches cost broker CPU, network and disk across a whole cluster.

ConceptFoundations6 min read

A Java producer with default settings in a Kafka 4.x client sends 2,000 keyed records per second, 300 bytes each, spread evenly over a 12-partition topic.

Explain how the producer groups records into batches, roughly how many records each batch holds, and what changes if linger.ms is set to 50.
DesignIntermediate6 min read

A service sends 50,000 JSON events per second of about 1 KB each, and both the cross-zone network bill and broker disk usage are high.

Which compression codec and settings would you choose, what ratio can you expect, and how do you avoid making brokers recompress?
DesignAdvanced6 min read

Brokers on a shared cluster are CPU-bound at 400,000 produce requests per second, while producer metrics across 150 services show an average of 1.3 records per request.

How do you diagnose this and fix it across the fleet without breaking teams' latency goals?
LeadershipPrincipal5 min read

Product wants end-to-end event latency below 20 ms at p99 for a new real-time feature, while finance wants Kafka cluster costs cut by 30 percent this year.

Client batching and compression settings sit in the middle of this conflict. How do you frame and settle the trade-off?

Partitioners and message keys

The partition a record lands in decides its ordering relative to other records and how load spreads across consumers. Know how the default partitioner treats keyed and unkeyed records, why different client libraries may hash the same key differently, and how skewed keys create hot partitions that no amount of consumers can fix.

ConceptFoundations5 min read

Every record a producer sends must go to one partition of the topic, and the rule that picks the partition decides both ordering and how evenly load spreads.

In current Java producers, how is the partition chosen for (a) a record with a key, (b) a record without a key, and (c) a record with an explicit partition? What changed in Kafka 3.3 for records without keys?
DebuggingIntermediate5 min read

A Java service and a Python service both produce to the topic "account-events" keyed by account id.

A Kafka Streams join and per-account ordering both break: events for the same account land on different partitions depending on which service sent them. Explain the cause and the fix.
DesignAdvanced7 min read

In a multi-tenant SaaS event pipeline keyed by tenant id, 3 of 4,000 tenants produce 45 percent of all events, and the partitions they hash to are lagging while others are idle.

Design a partitioning approach that balances load while keeping the ordering the business actually needs.
LeadershipPrincipal6 min read

Across the company, event keys were chosen ad hoc: some topics are keyed by user, some by order, some have no key, and changing a key has broken consumers several times.

Should keys be part of the governed event contract, and what standard would you set?

Delivery timeouts, retries and in-flight requests

A producer send can wait in the buffer, travel to the broker, fail and be retried, all within limits set by several timeout settings. Understand how delivery.timeout.ms bounds the whole attempt, how idempotence keeps retried batches in order without duplicates, and what an application must do when a send finally fails.

ConceptFoundations7 min read

The Java producer sends records asynchronously, so several timers and retry settings together decide how long a record may wait inside the client before it is sent or fails.

Explain how delivery.timeout.ms, request.timeout.ms, linger.ms, retries, retry.backoff.ms and max.block.ms work together in the Java producer, with their defaults. When does the application's send callback receive an error?
InternalsIntermediate7 min read

With enable.idempotence=true and max.in.flight.requests.per.connection=5, batch 1 to a partition fails with NOT_LEADER_OR_FOLLOWER while batches 2 to 5 are already in flight.

Explain what the producer and broker do so that the records still end up in order without duplicates, and what changes if idempotence is off.
DebuggingIntermediate7 min read

During a 2-minute network partition between one availability zone and the brokers, a service's producer logs errors like "Expiring 37 record(s) for orders-7: 120012 ms has passed since batch creation".

The team's code calls kafkaTemplate.send() and never looks at the result. What happened to those records, and what should the service change?
DesignAdvanced7 min read

A checkout service must never lose an OrderPlaced event, even when the Kafka cluster is unreachable for 15 minutes, and it must not slow checkout by more than a few milliseconds.

Design the producer side: which client settings, what happens to events during the outage, and how ordering and duplicates are handled after recovery.
LeadershipPrincipal6 min read

Producer reliability across 200 services varies: some block on every send, some ignore failures, some set retries=0 copied from old blog posts.

Should the platform team ship an internal producer library, enforce configuration through policy, or educate teams? What delivery guarantee should the platform promise?

The consumer poll loop and max.poll.interval

A Kafka consumer stays in its group only while it heartbeats and keeps calling poll often enough. Understand which thread does what, how session timeouts and max.poll.interval.ms detect different failures, why the consumer object is not thread safe, and how slow processing leads to members being removed and partitions moving around the group.

ConceptFoundations7 min read

A Kafka consumer uses the classic group protocol with session.timeout.ms=45000, heartbeat.interval.ms=3000, max.poll.interval.ms=300000 and max.poll.records=500.

Explain which failure each timeout detects, which thread enforces it, and how poll() relates to the records that are actually fetched.
DebuggingFoundations6 min read

A developer shares one KafkaConsumer between a scheduler thread that calls poll() and an HTTP handler that calls commitSync() and seek().

Under load the service throws ConcurrentModificationException: KafkaConsumer is not safe for multi-threaded access. Explain the rule and how to restructure the code.
CodingIntermediate7 min read

Each record on the topic "video-jobs" starts a transcoding job that takes 2 to 20 minutes.

Outline a plain Java consumer loop that processes one job at a time without being removed from the group, and explain how it commits offsets.
ScenarioIntermediate6 min read

A batch listener receives up to 500 records per poll and calls a downstream API for each, one at a time, with p50 latency of 80 ms and p99 of 900 ms. Most polls finish in 45 seconds, but in downstream slow periods some take over 5 minutes and the group rebalances repeatedly.

How do you choose max.poll.records and max.poll.interval.ms, and what else would you change?

Rebalance protocols and static membership

When members join or leave a consumer group, partitions must be reassigned. The classic protocol offers eager and cooperative rebalancing plus static membership, while the newer protocol from KIP-848 moves assignment to the broker. Know how each behaves during restarts and deployments, what pauses processing, and what a migration between protocols involves.

ConceptFoundations6 min read

When a consumer group's membership changes, Kafka moves partitions between members, and the protocol in use decides how much of the group stops working while that happens.

Compare eager rebalancing, cooperative incremental rebalancing (CooperativeStickyAssignor) and static membership (group.instance.id) in the classic consumer group protocol. What does each do when one consumer out of ten restarts?
InternalsIntermediate6 min read

Kafka 4.0 made a new consumer group protocol, designed under KIP-848, generally available, the largest change to group coordination since consumer groups were introduced.

Explain the consumer group protocol introduced by KIP-848 and generally available in Kafka 4.0. How does it differ from the classic protocol in where assignment is computed and how members heartbeat, and why does it avoid group-wide pauses? Which client settings stop applying?
DebuggingIntermediate6 min read

A deployment rolls 30 consumer pods one by one.

Each restart takes about 40 seconds, lag climbs from near zero to 2 million records during every deploy, and the logs show more than 60 rebalances in ten minutes. Explain the cause and how you would make deploys cheap.
ScenarioAdvanced6 min read

You run 200 consumer groups from Java, Go and Python services on a Kafka 4.x cluster and want to move them to the new consumer group protocol.

Plan the migration: prerequisites, order, what can break, and how to roll back.

Fetch tuning and throughput

Consumers pull data with fetch requests whose size and timing are governed by a few settings. Understand how fetch.min.bytes, fetch.max.wait.ms and the byte limits shape latency, throughput and consumer memory, which client metrics reveal whether fetching or processing is the bottleneck, and what limits a consumer group hits on very busy topics.

ConceptFoundations6 min read

A consumer does not receive records one by one; it fetches them from brokers in batches, and a handful of settings decide how large and how frequent those fetches are.

Explain fetch.min.bytes, fetch.max.wait.ms, max.partition.fetch.bytes, fetch.max.bytes and max.poll.records in the Java consumer, with their defaults, and how they decide when the broker answers a fetch and how much data comes back.
DebuggingIntermediate6 min read

A consumer assigned 400 partitions, with max.partition.fetch.bytes raised to 10 MB for throughput, crashes with OutOfMemoryError on a 2 GB heap after a backlog builds up.

Explain how fetch settings drive consumer memory and how you would size them.
ScenarioIntermediate6 min read

A consumer group reading a 48-partition topic tops out at 20 MB/s although brokers and network have plenty of headroom.

Metrics show fetch-size-avg around 60 KB, fetch-latency-avg of 3 ms, a few hundred fetches per second, and poll-idle-ratio-avg near 0.05. Where is the bottleneck and what do you change?
DesignAdvanced6 min read

Three consumer groups with very different jobs must keep up with one of the busiest topics in a cluster spread over three availability zones.

Design the consumer side for a topic carrying 1.5 GB/s of compressed data read by three consumer groups (a real-time enrichment service, a lake loader and a search indexer) in a three-zone cluster. How many consumers per group, which fetch settings, and which limits will you hit first?

Offset reset and replaying data

Committed offsets record where a group has read to, and auto.offset.reset decides what happens when there is no valid offset. Understand the reset policies and their silent failure modes, how to seek by time or offset for a replay, and how to reprocess data safely when side effects and downstream consumers are involved.

ConceptFoundations6 min read

Every consumer group must decide where in a partition to start reading, and auto.offset.reset is the setting that steers that decision.

When does auto.offset.reset apply in a Kafka consumer, and what do earliest, latest and none do? Why can latest, the default, silently skip data, and what newer option exists in recent clients?
CodingIntermediate6 min read

After a bug fix, you must reprocess the records written between 09:00 and 11:30 UTC yesterday through a Spring Kafka listener in a new consumer group, and then stop.

Show how you would seek to the start time on assignment and stop at the end time, and what makes this safe to run alongside the live group.
DebuggingIntermediate6 min read

A consumer group was down for 10 hours during an incident. The topic has 8 hours of retention.

When the group came back, lag dropped to zero at once and no errors appeared, but downstream reports show 10 hours of missing data. auto.offset.reset is latest. Explain exactly what happened and how to prevent it.
ScenarioAdvanced6 min read

A bug in a projection service corrupted about 2 million rows over three days, and the service's own output topic fed three downstream services during that time.

Plan the repair using Kafka replay, including how to avoid repeating side effects and how to coordinate the downstream teams.
LeadershipPrincipal6 min read

In the past year, three incidents came from engineers resetting consumer group offsets in production by hand, once on the wrong group. Replay is also a capability teams depend on.

What policy and tooling would you put in place for offset changes and replays?

Consumer threading models and parallel processing

A consumer instance processes its partitions on one thread, so higher throughput needs more consumers, more threads or finer parallelism by key. Understand what each model gives up in ordering and offset safety, how commits must track completed work, and why adding partitions is not always the right way to scale processing.

ConceptFoundations6 min read

A single Kafka consumer handles its partitions on one thread, so a service that needs more throughput than that has to add parallelism somewhere.

Compare three ways to process Kafka records in parallel in a Java service: one consumer per thread, one consumer feeding a worker pool, and key-based parallel processing. What does each give up in ordering and offset safety?
CodingIntermediate6 min read

A Spring Boot 3.5 service on Java 21 consumes a topic with a batch listener. Each record needs an independent HTTP call of about 200 ms, and order within a batch does not matter.

Show how you would process each batch concurrently on virtual threads, acknowledge only after all records succeed, and handle failures.
DesignIntermediate6 min read

A slow external call for every record limits how fast a simple consumer can go, yet the business still needs ordering per account and a firm throughput target.

Design a consumer for a 6-partition topic where each record needs a 150 ms call to an external service, ordering must be kept per account id, and the target is 2,000 records per second. Describe the threading, how offsets are committed, and what happens on rebalance.
ScenarioAdvanced5 min read

To keep up with slow processing, a team has grown a topic from 24 to 480 partitions over two years and now asks for 960.

Brokers carry many small partitions, rebalances take minutes, and end-to-end latency has risen. How do you respond, and what alternatives do you propose?
LeadershipPrincipal5 min read

Teams have built five different in-house frameworks for parallel record processing on Kafka, each with its own offset-tracking bugs.

The options are to adopt an open-source parallel consumer library, standardise on Spring Kafka features, wait for share groups, or keep building. How do you decide for the next three years?

Headers, tracing and large messages

Records carry headers for metadata such as type information, trace context and retry details, and every size limit along the path caps how large a record can be. Understand how frameworks use headers, how trace context travels through Kafka, which settings bound record size, and when large payloads belong in external storage instead.

ConceptFoundations5 min read

Besides a key and a value, every Kafka record can carry extra metadata that frameworks and applications read without touching the payload.

What are Kafka record headers, what are they good for, and what are their limits? Give examples of headers that a Spring Kafka application adds or reads automatically.
DebuggingFoundations5 min read

A producer sending a 3 MB JSON document fails with RecordTooLargeException. The team raised max.message.bytes on the topic to 5 MB, but the error remains.

List the limits a large record must pass from producer to consumer, and fix the configuration.
CodingIntermediate5 min read

A request enters service A over HTTP; A publishes an event with KafkaTemplate, and service B consumes it with @KafkaListener and calls service C. Traces in the tracing backend stop at A.

Show the Spring Boot configuration needed for the trace to continue through Kafka, and explain how the context travels.
DesignAdvanced6 min read

A document-processing pipeline passes scanned files of 20 to 80 MB between five services, 200,000 files a day, with ordering per customer and a 30-day audit trail.

Design it with Kafka using the claim-check pattern, covering storage, lifecycle, security and failure handling.
LeadershipPrincipal5 min read

The company has 300 services in five languages producing to Kafka. Incident reviews cannot follow an event from the user's action through all its consumers, header conventions differ per team, and tracing every record at 2 million records per second is too expensive.

What standard would you set for event metadata and tracing, and how would you roll it out?