Kafka Interview Questions and Answers Part 9 - Performance, Monitoring and Operations

Kafka Interview Q&A · Part 9 of 10

In this post we are going to cover performance, monitoring and operations in Kafka. These are 7 real Kafka interview questions for data engineers, asked the way they come up on a real project, and the last one is a scenario: consumer lag that grows every night at the same hour and catches up by morning.

Running Kafka in production is more than creating topics. We size partitions, find bottlenecks, alert on the right metrics, handle bad records, stop noisy teams and control who can read what. Interviewers ask about this because it shows whether you have actually kept a cluster healthy, not just used one.

Part 9 of the Real Time Kafka Interview Questions and Answers series on TechBrothersIT.

The short answer

Say this first

Size partitions from measured throughput with headroom, find bottlenecks with producer and broker metrics, and alert on under-replicated, under-min-ISR and offline partitions plus consumer lag. Send poison pills to a dead letter topic, cap noisy clients with quotas, and protect topics with authentication, TLS and ACLs.

Let's set up the cluster and some sample data

We use a local Kafka 4.4 cluster in KRaft mode with 1 broker, running the standard authorizer for the ACL example. Here are the starting files: small Python scripts for the consumer group, producers and consumers, and perf.sh for the producer baseline.

group.py
import time
from confluent_kafka import Consumer

conf = {'bootstrap.servers': 'localhost:9092', 'group.id': 'billing'}
consumers = [Consumer(conf) for _ in range(3)]
for c in consumers:
    c.subscribe(['orders'])
end = time.time() + 15
while time.time() < end:              # let the group settle
    for c in consumers:
        c.poll(0.1)
counts = sorted(len(c.assignment()) for c in consumers)
print('3 consumers, partitions per consumer:', counts)
for c in consumers:
    c.close()
perf.sh
# baseline: the same acks and linger as the app; values are cut, names kept
kafka-producer-perf-test.sh --bootstrap-server localhost:9092 \
  --topic perf --num-records 20000 --record-size 200 \
  --throughput -1 --command-property acks=all linger.ms=10 \
  --print-metrics | grep -oE \
  -e '^20000 records sent' \
  -e 'producer-metrics:(record-queue-time|request-latency)-avg' \
  -e 'producer-metrics:bufferpool-wait-ratio' \
  -e 'producer-metrics:(batch-size|records-per-request)-avg'
produce_payments.py
from confluent_kafka import Producer

rows = ['{"amount": 25.0}', '{"amount": 40.5}',
        'amount=12.50',                   # a poison pill: not JSON
        '{"amount": 9.99}', '{"amount": 60.0}']
p = Producer({'bootstrap.servers': 'localhost:9092',
              'enable.idempotence': True})
for v in rows:
    p.produce('card-payments', value=v)
p.flush()
print('sent', len(rows), 'payments')
naive.py
import json
from confluent_kafka import Consumer

c = Consumer({'bootstrap.servers': 'localhost:9092',
              'group.id': 'ledger', 'enable.auto.commit': False,
              'auto.offset.reset': 'earliest'})
c.subscribe(['card-payments'])
try:
    while True:
        m = c.poll(1.0)
        if m is None or m.error():
            continue
        payment = json.loads(m.value())       # crashes on a bad record
        print('offset', m.offset(), 'amount', payment['amount'])
        c.commit(m, asynchronous=False)
finally:
    c.close()                                 # leave the group
safe.py
import json
from confluent_kafka import Consumer, Producer

c = Consumer({'bootstrap.servers': 'localhost:9092',
              'group.id': 'ledger', 'enable.auto.commit': False,
              'auto.offset.reset': 'earliest'})
dlq = Producer({'bootstrap.servers': 'localhost:9092',
                'enable.idempotence': True})
c.subscribe(['card-payments'])
idle = 0
while idle < 5:
    m = c.poll(1.0)
    if m is None or m.error():
        idle += 1
        continue
    try:
        amount = json.loads(m.value())['amount']
        print('offset', m.offset(), 'amount', amount)
    except (ValueError, KeyError) as e:
        dlq.produce('card-payments.dlq', value=m.value(), headers={
            'error': str(e), 'source.offset': str(m.offset())})
        dlq.flush()                           # stored before we commit
        print('offset', m.offset(), 'sent to the DLQ:', e)
    c.commit(m, asynchronous=False)
c.close()
read_dlq.py
from confluent_kafka import Consumer

c = Consumer({'bootstrap.servers': 'localhost:9092', 'group.id': 'dlq-check',
              'auto.offset.reset': 'earliest'})
c.subscribe(['card-payments.dlq'])
m = None
while m is None or m.error():
    m = c.poll(1.0)
print('value:', m.value().decode())
print('headers:', ', '.join('%s=%s' % (k, v.decode()) for k, v in m.headers()))
c.close()
throttle.py
import sys
from confluent_kafka import Producer

throttled = []
p = Producer({'bootstrap.servers': 'localhost:9092', 'client.id': sys.argv[1],
              'throttle_cb': lambda event: throttled.append(event)})
for i in range(2000):
    p.produce('reports', value=b'x' * 1000)     # 2 MB in total
    p.poll(0)
p.flush()
print(sys.argv[1], 'sent 2 MB, throttled by the broker:', bool(throttled))
read_payments.py
import logging
from confluent_kafka import Consumer

quiet = logging.getLogger('quiet')
quiet.addHandler(logging.NullHandler())
quiet.propagate = False
c = Consumer({'bootstrap.servers': 'localhost:9092', 'group.id': 'reporting',
              'auto.offset.reset': 'earliest', 'logger': quiet})
c.subscribe(['payments'])
m = None
while m is None:
    m = c.poll(1.0)
print(m.error().name() if m.error() else m.value().decode())
c.close()
nightly.py
import sys
from confluent_kafka import Producer

n = int(sys.argv[1])
p = Producer({'bootstrap.servers': 'localhost:9092', 'enable.idempotence': True})
for i in range(n):
    p.produce('orders-nightly', value='order-%d' % i, partition=i % 3)
p.flush()
print('sent', n, 'orders')
loader.py
from confluent_kafka import Consumer

c = Consumer({'bootstrap.servers': 'localhost:9092', 'group.id': 'warehouse-loader',
              'auto.offset.reset': 'earliest'})
c.subscribe(['orders-nightly'])
n, idle = 0, 0
while idle < 5:
    m = c.poll(1.0)
    if m is None or m.error():
        idle += 1
        continue
    n += 1
c.close()          # commits the last offsets
print('loaded', n, 'orders')

Question 1: A topic has one partition and consumers cannot keep up. How do you choose the number of partitions?

Partitions are the unit of parallelism. In a consumer group, each partition goes to at most one consumer.

Let's create an orders topic with one partition, then start three consumers in the billing group with group.py.

Terminal
$ kafka-topics.sh --bootstrap-server localhost:9092 --create --topic orders --partitions 1
Created topic orders.
$ python group.py
3 consumers, partitions per consumer: [0, 0, 1]

The output is [0, 0, 1]: one consumer does all the work, and two sit idle. Now let's increase the topic to six partitions and run the same three consumers again.

Terminal
$ kafka-topics.sh --bootstrap-server localhost:9092 --alter --topic orders --partitions 6
$ python group.py
3 consumers, partitions per consumer: [2, 2, 2]

Now they get [2, 2, 2], two each, and the group can scale out to six consumers.

To size it, we measure. Find what one partition can take from your real producer, and what one consumer can process, including the database it writes to. Then:

  • partitions ≥ max(peak ÷ per-partition producer rate, peak ÷ per-consumer processing rate) + headroom

It's a heuristic, not an official formula. And don't overshoot. Every partition costs open files, metadata, producer batch memory and recovery time. We can only add partitions, and adding them changes which partition a key goes to.

Real project

Pick a count that divides evenly, like 6, 12 or 24, and set it before the topic carries keyed data.

Question 2: The producer is slow at peak hours. How do you find whether the bottleneck is the producer, the network or the brokers?

Measure, don't guess. First, we take a baseline with kafka-producer-perf-test.sh, from the same host, with the same acks and linger as the app. perf.sh runs it and keeps only the metric names.

Terminal
$ sh perf.sh
20000 records sent
producer-metrics:batch-size-avg
producer-metrics:bufferpool-wait-ratio
producer-metrics:record-queue-time-avg
producer-metrics:records-per-request-avg
producer-metrics:request-latency-avg

All 20000 records were sent, and we get the producer metrics to read. If the tool is fast and your app is slow, the problem is in the app: serialization, a flush per message, or one thread.

Then we read the producer metrics:

  • record-queue-time-avg: how long records wait in the producer's buffer before they're sent.
  • bufferpool-wait-ratio: above zero means sends are blocking on buffer memory.
  • request-latency-avg: the round trip to the broker.

If request latency is high, records queue up behind it, so look at the network and the brokers. If only queue time is high, the bottleneck is in the producer. On the broker, produce request time splits up like this.

Broker: Produce request timeHigh means
RequestQueueTimeMsrequest handler threads are busy
LocalTimeMsthe leader is slow writing to its log
RemoteTimeMswaiting for followers (acks=all)
ResponseSendTimeMsthe network back to the client
Why the values are cut

Numbers from a laptop cluster mean nothing for production. Compare your own metrics at peak and at a quiet hour.

Question 3: Your manager asks which metrics to alert on for a Kafka cluster. What do you monitor?

Start with data safety, then the controller, then broker load.

Broker metric (JMX)MeansAlert when
UnderReplicatedPartitionsreplicas are behind or downabove 0
UnderMinIsrPartitionCountacks=all writes failabove 0
OfflinePartitionsCountno leader: data unavailableabove 0
ActiveControllerCountone active controllercluster total is not 1
RequestHandlerAvgIdlePercentbroker saturationfalling
TotalTimeMs (Produce, Fetch)request latencyabove your baseline

Under-replicated partitions should be zero. An under-min-ISR partition count above zero means acks=all writes to those partitions fail. Offline partitions above zero means data is unavailable. There should be exactly one active controller in the cluster. A falling request handler idle percent means saturated brokers, and the produce and fetch request times show latency.

The same signals are in the CLI. Let's create an invoices topic with one replica that requires two in sync, a classic misconfiguration, and list the under-min-ISR partitions.

Terminal
$ kafka-topics.sh --bootstrap-server localhost:9092 --create --topic invoices --partitions 1 --replication-factor 1 --config min.insync.replicas=2
Created topic invoices.
$ kafka-topics.sh --bootstrap-server localhost:9092 --describe --under-min-isr-partitions
  Topic: invoices  Partition: 0  Leader: 1  Replicas: 1  Isr: 1  Elr:   LastKnownElr:

invoices partition 0 is listed with Isr: 1, so every acks=all write to it fails.

On the client side, we also alert on:

  • Consumer lag: records-lag-max, or LAG from kafka-consumer-groups.sh.
  • Producer errors and retries: record-error-rate, record-retry-rate.
  • The basics: disk, network, GC pauses.
Tip

Alert only on symptoms that need action, like under-min-ISR or growing lag, and put the rest on a dashboard. A noisy alert gets ignored.

Question 4: One bad message crashes the consumer again and again. How do you handle poison pills?

A poison pill is a record the consumer can't process, like broken JSON. We catch it, send it to a dead letter topic, commit, and continue.

Let's send five payments where the third one isn't JSON, then run naive.py twice.

Terminal
$ python produce_payments.py
sent 5 payments
$ python naive.py
offset 0 amount 25.0
offset 1 amount 40.5
Traceback (most recent call last):
  File "naive.py", line 13, in <module>
    payment = json.loads(m.value())       # crashes on a bad record
  File "/usr/lib/python3.13/json/__init__.py", line 352, in loads
    return _default_decoder.decode(s)
           ~~~~~~~~~~~~~~~~~~~~~~~^^^
  File "/usr/lib/python3.13/json/decoder.py", line 345, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
               ~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.13/json/decoder.py", line 363, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
$ python naive.py
Traceback (most recent call last):
  File "naive.py", line 13, in <module>
    payment = json.loads(m.value())       # crashes on a bad record
  File "/usr/lib/python3.13/json/__init__.py", line 352, in loads
    return _default_decoder.decode(s)
           ~~~~~~~~~~~~~~~~~~~~~~~^^^
  File "/usr/lib/python3.13/json/decoder.py", line 345, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
               ~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.13/json/decoder.py", line 363, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

The first run processes offsets 0 and 1, commits them, and crashes on offset 2 with JSONDecodeError. The second run crashes on offset 2 again, because that offset was never committed. The partition is blocked, and lag grows behind it.

The fix in safe.py: catch the error, send the raw record to a dead letter topic with the error and source offset in headers, and commit only after that write is stored. Let's run it and read the DLQ.

Terminal
$ python safe.py
offset 2 sent to the DLQ: Expecting value: line 1 column 1 (char 0)
offset 3 amount 9.99
offset 4 amount 60.0
$ python read_dlq.py
value: amount=12.50
headers: error=Expecting value: line 1 column 1 (char 0), source.offset=2

Offset 2 went to the DLQ, and offsets 3 and 4 were processed. The DLQ record keeps the original bytes, amount=12.50, and its headers say why it failed and source.offset=2, so someone can fix and replay it.

Catch only data errors this way. If the database is down, don't DLQ everything: retry, or pause the consumer.

Prevent it

Use schemas and producer validation at the source. In Java, RecordDeserializationException.offset() gives the offset to skip. Kafka Streams and Connect have a DLQ built in.

Question 5: A team keeps flooding the cluster and slowing everyone else. How do quotas help?

Quotas cap how fast a client can produce or fetch, in bytes per second on each broker, or how much broker thread time it may use:

  • producer_byte_rate, consumer_byte_rate: bytes per second, per broker.
  • request_percentage: I/O and network thread time.

We set them on a client ID, a user, or both, with kafka-configs.sh. Let's give the reporting app 100 KB a second to produce and 200 KB to fetch.

Terminal
$ kafka-configs.sh --bootstrap-server localhost:9092 --alter --entity-type clients --entity-name reporting-app --add-config 'producer_byte_rate=102400,consumer_byte_rate=204800'
Completed updating config for client reporting-app.
$ kafka-configs.sh --bootstrap-server localhost:9092 --describe --entity-type clients --entity-name reporting-app
Quota configs for client-id 'reporting-app' are consumer_byte_rate=204800.0, producer_byte_rate=102400.0

Describe shows consumer_byte_rate=204800.0, producer_byte_rate=102400.0. Now both apps send 2 MB with throttle.py.

Terminal
$ python throttle.py reporting-app
reporting-app sent 2 MB, throttled by the broker: True
$ python throttle.py billing-app
billing-app sent 2 MB, throttled by the broker: False

The broker throttles reporting-app by delaying its responses, and the client reports a throttle event: True. billing-app has no quota and isn't throttled. Nobody gets an error: the noisy client just slows down.

The most specific quota wins, so we can set a default for every client and raise it for teams that need more. A controller_mutation_rate even limits how fast a team creates and deletes partitions.

Real project

Quotas go with authentication, so a team can't escape by changing its client ID. And alert on throttle time, so the team knows why it slowed down.

Question 6: An auditor asks who can read the payments topic. How do authentication, ACLs and encryption work?

There are three layers:

  • Authentication proves who the client is: SASL (SCRAM, Kerberos, OAuth) or mutual TLS.
  • Encryption in transit is TLS on the listeners.
  • Authorization, the ACLs, says what each principal may do.

This KRaft cluster runs the standard authorizer. Let's allow user analytics to consume payments with its group, give finance a prefixed ACL on every topic starting with pay, and list them with the match filter.

Terminal
$ kafka-acls.sh --bootstrap-server localhost:9092 --add --allow-principal User:analytics --consumer --topic payments --group analytics > /dev/null
$ kafka-acls.sh --bootstrap-server localhost:9092 --add --allow-principal User:finance --operation Read --topic pay --resource-pattern-type prefixed > /dev/null
$ kafka-acls.sh --bootstrap-server localhost:9092 --list --topic payments --resource-pattern-type match
Current ACLs for resource `ResourcePattern(resourceType=TOPIC, name=payments, patternType=LITERAL)`:
  (principal=User:analytics, host=*, operation=DESCRIBE, permissionType=ALLOW)
  (principal=User:analytics, host=*, operation=READ, permissionType=ALLOW)

Current ACLs for resource `ResourcePattern(resourceType=TOPIC, name=pay, patternType=PREFIXED)`:
  (principal=User:finance, host=*, operation=READ, permissionType=ALLOW)

The list shows both, the wildcards included. That's the auditor's answer. Now let's read payments as any other principal.

Terminal
$ python read_payments.py
TOPIC_AUTHORIZATION_FAILED

Our anonymous lab consumer gets TOPIC_AUTHORIZATION_FAILED. This lab has no authentication. In production, SASL or mutual TLS gives every client its real principal, with a client config like this one.

client.properties
# client.properties for the analytics service
security.protocol=SASL_SSL
sasl.mechanism=SCRAM-SHA-512
sasl.jaas.config=org.apache.kafka.common.security.scram.ScramLoginModule \
    required username="analytics" password="from-a-secret-store";
ssl.truststore.location=/etc/kafka/truststore.jks

With SCRAM, the credentials live in the KRaft metadata log. Let's add one and describe it.

Terminal
$ kafka-configs.sh --bootstrap-server localhost:9092 --alter --entity-type users --entity-name analytics --add-config 'SCRAM-SHA-512=[iterations=8192,password=lab-only-secret]'
Completed updating config for user analytics.
$ kafka-configs.sh --bootstrap-server localhost:9092 --describe --entity-type users --entity-name analytics
SCRAM credential configs for user-principal 'analytics' are SCRAM-SHA-512=iterations=8192

kafka-configs.sh shows only the mechanism and iterations, never the password.

Lab only

This lab sets allow.everyone.if.no.acl.found=true, so resources without ACLs stay open. The default is false: no ACL, no access. Auditors also ask: super users bypass every ACL, so keep that list short. And Kafka has no built-in encryption at rest, so use encrypted disks, or encrypt sensitive fields in the producer.

Scenario 7: Consumer lag grows every night at the same hour and catches up by morning. How do you investigate and fix it?

The same hour every night means a schedule, not a bug. There are two suspects: more data arriving, like a nightly batch job, or slower processing, like a backup on the warehouse database the consumer writes to.

Let's start with the warehouse-loader group caught up on orders-nightly, which has 3 partitions.

Terminal
$ python nightly.py 300
sent 300 orders
$ python loader.py
loaded 300 orders

Now the nightly batch lands 600 orders, and we look at lag per partition first.

Terminal
$ python nightly.py 600
sent 600 orders
$ kafka-consumer-groups.sh --bootstrap-server localhost:9092 --describe --group warehouse-loader | cut -c1-92
Consumer group 'warehouse-loader' has no active members.

GROUP            TOPIC           PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG
warehouse-loader orders-nightly  0          100             300             200
warehouse-loader orders-nightly  1          100             300             200
warehouse-loader orders-nightly  2          100             300             200

LAG is 200 on every partition, so it's volume spread evenly, not one hot key. Then we compare the topic's incoming rate with the consumer's processing rate at that hour, and check sink latency and rebalances. Let's run the loader again.

Terminal
$ python loader.py
loaded 600 orders
$ kafka-consumer-groups.sh --bootstrap-server localhost:9092 --describe --group warehouse-loader | cut -c1-92
Consumer group 'warehouse-loader' has no active members.

GROUP            TOPIC           PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG
warehouse-loader orders-nightly  0          300             300             0
warehouse-loader orders-nightly  1          300             300             0
warehouse-loader orders-nightly  2          300             300             0

It loaded 600 orders, and lag is back to 0. So what do we fix?

  • Maybe fine: if it's caught up before anyone needs the data. Alert on lag in time, not offsets.
  • Scale out: consumers up to the partition count, bigger sink batches, more partitions.
  • Shape the load: a quota on the batch producer, or bulk loads on their own topic.
  • Prove it: replay one night's volume in test, and watch the lag dashboard the next night.

Key points to remember

  • Partitions = parallelism: size from measured throughput + headroom
  • Bottlenecks: record queue time, request latency, broker request time
  • Alert on under-min-ISR, offline, under-replicated and lag
  • Poison pills: catch, dead letter topic, commit, continue
  • Quotas for noisy clients; SASL/mTLS + TLS + ACLs for access

The full script

This is a Python script that writes the files and runs every command in order against a local Kafka 4.4. Run pip install confluent-kafka first.

Show the full script that writes the files and runs every step
Full script - Kafka 4.4 running locally, pip install confluent-kafka, then run it with Python
# ========================================================================
# Kafka Interview Q&A #9 - Performance, monitoring and operations
# TechBrothersIT. Sample data is invented for teaching.
# Every step below was run on Apache Kafka 4.4.0 (KRaft mode, 1 node) with confluent-kafka 2.16.0;
# the outputs in the video and the blog post are the real outputs. To run it yourself (Linux, macOS or WSL):
#   1. Download Kafka 4.4.0 from kafka.apache.org, extract it, and put its bin folder on your PATH.
#   2. Start a local cluster (see the Kafka quickstart; node 1 listens on localhost:9092).
#   3. pip install confluent-kafka   then   python Kafka_Interview_QA_09_Code.py   in an empty folder.
# Steps that stop or start a broker say so in a comment: do that by hand at that point.
# ========================================================================

import os, subprocess

def write(path, text):
    os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
    with open(path, "w", encoding="utf-8") as f:
        f.write(text.strip("\n") + "\n")

def run(cmd, expect_error=False):
    print("\n$ " + cmd, flush=True)
    rc = subprocess.run(cmd, shell=True).returncode
    if rc != 0 and not expect_error:
        raise SystemExit("stopped: this command was expected to succeed")

# Step 0: files used by the steps
write('group.py', """\
import time
from confluent_kafka import Consumer

conf = {'bootstrap.servers': 'localhost:9092', 'group.id': 'billing'}
consumers = [Consumer(conf) for _ in range(3)]
for c in consumers:
    c.subscribe(['orders'])
end = time.time() + 15
while time.time() < end:              # let the group settle
    for c in consumers:
        c.poll(0.1)
counts = sorted(len(c.assignment()) for c in consumers)
print('3 consumers, partitions per consumer:', counts)
for c in consumers:
    c.close()
""")
write('perf.sh', "# baseline: the same acks and linger as the app; values are cut, names kept\nkafka-producer-perf-test.sh --bootstrap-server localhost:9092 \\\n  --topic perf --num-records 20000 --record-size 200 \\\n  --throughput -1 --command-property acks=all linger.ms=10 \\\n  --print-metrics | grep -oE \\\n  -e '^20000 records sent' \\\n  -e 'producer-metrics:(record-queue-time|request-latency)-avg' \\\n  -e 'producer-metrics:bufferpool-wait-ratio' \\\n  -e 'producer-metrics:(batch-size|records-per-request)-avg'\n")
write('produce_payments.py', """\
from confluent_kafka import Producer

rows = ['{"amount": 25.0}', '{"amount": 40.5}',
        'amount=12.50',                   # a poison pill: not JSON
        '{"amount": 9.99}', '{"amount": 60.0}']
p = Producer({'bootstrap.servers': 'localhost:9092',
              'enable.idempotence': True})
for v in rows:
    p.produce('card-payments', value=v)
p.flush()
print('sent', len(rows), 'payments')
""")
write('naive.py', """\
import json
from confluent_kafka import Consumer

c = Consumer({'bootstrap.servers': 'localhost:9092',
              'group.id': 'ledger', 'enable.auto.commit': False,
              'auto.offset.reset': 'earliest'})
c.subscribe(['card-payments'])
try:
    while True:
        m = c.poll(1.0)
        if m is None or m.error():
            continue
        payment = json.loads(m.value())       # crashes on a bad record
        print('offset', m.offset(), 'amount', payment['amount'])
        c.commit(m, asynchronous=False)
finally:
    c.close()                                 # leave the group
""")
write('safe.py', """\
import json
from confluent_kafka import Consumer, Producer

c = Consumer({'bootstrap.servers': 'localhost:9092',
              'group.id': 'ledger', 'enable.auto.commit': False,
              'auto.offset.reset': 'earliest'})
dlq = Producer({'bootstrap.servers': 'localhost:9092',
                'enable.idempotence': True})
c.subscribe(['card-payments'])
idle = 0
while idle < 5:
    m = c.poll(1.0)
    if m is None or m.error():
        idle += 1
        continue
    try:
        amount = json.loads(m.value())['amount']
        print('offset', m.offset(), 'amount', amount)
    except (ValueError, KeyError) as e:
        dlq.produce('card-payments.dlq', value=m.value(), headers={
            'error': str(e), 'source.offset': str(m.offset())})
        dlq.flush()                           # stored before we commit
        print('offset', m.offset(), 'sent to the DLQ:', e)
    c.commit(m, asynchronous=False)
c.close()
""")
write('read_dlq.py', """\
from confluent_kafka import Consumer

c = Consumer({'bootstrap.servers': 'localhost:9092', 'group.id': 'dlq-check',
              'auto.offset.reset': 'earliest'})
c.subscribe(['card-payments.dlq'])
m = None
while m is None or m.error():
    m = c.poll(1.0)
print('value:', m.value().decode())
print('headers:', ', '.join('%s=%s' % (k, v.decode()) for k, v in m.headers()))
c.close()
""")
write('throttle.py', """\
import sys
from confluent_kafka import Producer

throttled = []
p = Producer({'bootstrap.servers': 'localhost:9092', 'client.id': sys.argv[1],
              'throttle_cb': lambda event: throttled.append(event)})
for i in range(2000):
    p.produce('reports', value=b'x' * 1000)     # 2 MB in total
    p.poll(0)
p.flush()
print(sys.argv[1], 'sent 2 MB, throttled by the broker:', bool(throttled))
""")
write('read_payments.py', """\
import logging
from confluent_kafka import Consumer

quiet = logging.getLogger('quiet')
quiet.addHandler(logging.NullHandler())
quiet.propagate = False
c = Consumer({'bootstrap.servers': 'localhost:9092', 'group.id': 'reporting',
              'auto.offset.reset': 'earliest', 'logger': quiet})
c.subscribe(['payments'])
m = None
while m is None:
    m = c.poll(1.0)
print(m.error().name() if m.error() else m.value().decode())
c.close()
""")
write('nightly.py', """\
import sys
from confluent_kafka import Producer

n = int(sys.argv[1])
p = Producer({'bootstrap.servers': 'localhost:9092', 'enable.idempotence': True})
for i in range(n):
    p.produce('orders-nightly', value='order-%d' % i, partition=i % 3)
p.flush()
print('sent', n, 'orders')
""")
write('loader.py', """\
from confluent_kafka import Consumer

c = Consumer({'bootstrap.servers': 'localhost:9092', 'group.id': 'warehouse-loader',
              'auto.offset.reset': 'earliest'})
c.subscribe(['orders-nightly'])
n, idle = 0, 0
while idle < 5:
    m = c.poll(1.0)
    if m is None or m.error():
        idle += 1
        continue
    n += 1
c.close()          # commits the last offsets
print('loaded', n, 'orders')
""")
run('kafka-topics.sh --bootstrap-server localhost:9092 --create --topic card-payments --partitions 1')
run('kafka-topics.sh --bootstrap-server localhost:9092 --create --topic perf --partitions 1')
run('kafka-topics.sh --bootstrap-server localhost:9092 --create --topic payments --partitions 1')
run('kafka-topics.sh --bootstrap-server localhost:9092 --create --topic reports --partitions 1')
run('kafka-topics.sh --bootstrap-server localhost:9092 --create --topic orders-nightly --partitions 3')
run('python -c "from confluent_kafka import Producer; p = Producer({\'bootstrap.servers\': \'localhost:9092\'}); p.produce(\'payments\', value=\'p1\'); p.flush()"')

# Step 1: One partition, three consumers in a group
run('kafka-topics.sh --bootstrap-server localhost:9092 --create --topic orders --partitions 1')
run('python group.py')

# Step 2: Six partitions, the same three consumers
run('kafka-topics.sh --bootstrap-server localhost:9092 --alter --topic orders --partitions 6')
run('python group.py')

# Step 3: kafka-producer-perf-test as a baseline: the record count and the producer metrics to read (values cut)
run('sh perf.sh')

# Step 4: A topic that needs 2 in-sync replicas but has only 1: the CLI shows the alert condition
run('kafka-topics.sh --bootstrap-server localhost:9092 --create --topic invoices --partitions 1 --replication-factor 1 --config min.insync.replicas=2')
run('kafka-topics.sh --bootstrap-server localhost:9092 --describe --under-min-isr-partitions')

# Step 5: A poison pill: the consumer crashes on the same record every time
run('python produce_payments.py')
run('python naive.py')
run('python naive.py')

# Step 6: Catch it, send it to a dead letter topic, commit, continue
run('python safe.py')
run('python read_dlq.py')

# Step 7: A client quota for the reporting app
run("kafka-configs.sh --bootstrap-server localhost:9092 --alter --entity-type clients --entity-name reporting-app --add-config 'producer_byte_rate=102400,consumer_byte_rate=204800'")
run('kafka-configs.sh --bootstrap-server localhost:9092 --describe --entity-type clients --entity-name reporting-app')

# Step 8: The broker throttles only the client with the quota
run('python throttle.py reporting-app')
run('python throttle.py billing-app')

# Step 9: ACLs: who can read payments
run('kafka-acls.sh --bootstrap-server localhost:9092 --add --allow-principal User:analytics --consumer --topic payments --group analytics > /dev/null')
run('kafka-acls.sh --bootstrap-server localhost:9092 --add --allow-principal User:finance --operation Read --topic pay --resource-pattern-type prefixed > /dev/null')
run('kafka-acls.sh --bootstrap-server localhost:9092 --list --topic payments --resource-pattern-type match')

# Step 10: Any other principal is denied
run('python read_payments.py')

# Step 11: SCRAM credentials live in the KRaft metadata log
run("kafka-configs.sh --bootstrap-server localhost:9092 --alter --entity-type users --entity-name analytics --add-config 'SCRAM-SHA-512=[iterations=8192,password=lab-only-secret]'")
run('kafka-configs.sh --bootstrap-server localhost:9092 --describe --entity-type users --entity-name analytics')

# Step 12: The loader is caught up
run('python nightly.py 300')
run('python loader.py')

# Step 13: The nightly batch lands: lag per partition
run('python nightly.py 600')
run('kafka-consumer-groups.sh --bootstrap-server localhost:9092 --describe --group warehouse-loader | cut -c1-92')

# Step 14: The loader catches up
run('python loader.py')
run('kafka-consumer-groups.sh --bootstrap-server localhost:9092 --describe --group warehouse-loader | cut -c1-92')
Next in this series

Part 10: Real-World Manager Scenarios

The sample data on this page is invented for teaching. Every terminal output is the real output of the command above it, run on Apache Kafka 4.4.0 in KRaft mode with confluent-kafka 2.16.0; topic IDs are masked. Part of the Real Time Kafka Interview Questions and Answers series on TechBrothersIT. Features, limits and their status (GA or preview) are current as of October 2026; check the official Apache Kafka documentation (kafka.apache.org) for anything you quote in an interview.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.