Find duplicate Kafka messages and check consumer lag
To find duplicate Kafka messages and check consumer lag from the command line, you can use kaf-inspect, a small open source (Apache-2.0) Python CLI at github.com/novatechflow/kaf-inspect. It finds duplicates by message value, by key or by a nested JSON field such as order.id, checks lag per partition for any consumer group, searches topics like grep, peeks at the first or last messages, and prints a cluster overview. It never joins a consumer group and never commits offsets, so it is safe to point at production groups. It works with TLS and SASL clusters through librdkafka settings. This post shows the commands, explains how the duplicate check and the lag numbers work, and lists the mistakes that make the results misleading.
Most Kafka debugging sessions start with the same two questions. Is the consumer behind? And did something get processed twice? The first one you can answer with kafka-consumer-groups.sh if you have a Kafka distribution and Java on the box you are working from. The second one Kafka does not answer at all. You end up writing a throwaway consumer script at the worst possible moment.
That is why I wrote kaf-inspect. It is one Python file on top of the confluent-kafka client, and it does the handful of things you need when a topic looks wrong.
Code: github.com/novatechflow/kaf-inspect. Open source under Apache-2.0, written in Python, built on confluent-kafka (librdkafka). Tests run without a live cluster.
Why duplicate Kafka messages happen
Most Kafka pipelines run with at-least-once delivery. That is a sane default, but it means duplicates are a normal event, not a bug report. The usual sources are these.
- Producer retries. A send times out, the producer retries, and both writes land. Idempotent producers stop this for retries inside one producer session, but not for an application that sends the same event again after a restart.
- Consumer crashes between work and commit. The consumer processes a record, writes the result, and dies before it commits the offset. On restart it does the work again. I walked through this exact case and the transactional fix in why we built our multi-agent system on Kafka.
- Upstream replays. CDC snapshots, connector restarts and backfills can send the same rows again. With at-least-once CDC, you handle duplicates downstream, as I describe in production CDC architecture with Debezium.
- Rebalances. When partitions move between consumers, work that was done but not committed gets done again.
So the useful question is not "do we have duplicates" but "how many, where, and since when". That is what the tool answers.
Install kaf-inspect
git clone https://github.com/novatechflow/kaf-inspect.git
cd kaf-inspect
pip install -r requirements.txt
# optional, runs with mocks, no cluster needed
python3 -m unittest test_kafkainspect.py
Find duplicate Kafka messages
The default compares full message values:
python3 kafkainspect.py \
--bootstrap-servers localhost:9092 \
--topic my-topic \
--dedup-by value
Use --dedup-by key to compare keys instead. For JSON messages, the most useful option is a field, with dot notation for nested values:
python3 kafkainspect.py \
--bootstrap-servers localhost:9092 \
--topic orders.json \
--field order.id
Every duplicate is printed with partition, offset and timestamp. To keep the results, write them to a file as JSONL, CSV or text, and add --silent if you do not want them on screen too:
python3 kafkainspect.py \
--bootstrap-servers localhost:9092 \
--topic orders.json \
--field order.id \
--output duplicates.jsonl:jsonl \
--silent
How the duplicate check works
It helps to know what the tool actually compares, because that decides whether the result means anything.
- It reads every partition of the topic and hashes the chosen payload (value, key or JSON field) with SHA-256.
- The first time a hash shows up, it is remembered. Every later record with the same hash is reported as a duplicate. The check runs across all partitions, not per partition.
- Records with no payload are skipped. That covers tombstones when you compare values, records without a key when you compare keys, and messages without the field when you use
--field. - It only sees what the topic still holds. Anything already deleted by retention is out of the picture.
Pick the right thing to compare
This is where most duplicate hunts go wrong.
- Value comparison only finds byte-identical messages. If the producer puts a fresh timestamp or a request ID into every send, a retried event looks unique. Compare on a business ID like
order.idor an event ID instead. - Key comparison is wrong for changelog topics. On a keyed or compacted topic, many records with the same key are normal updates, not duplicates. Use a field that should be unique per event.
- Decide what a duplicate means before you count. Two payments with the same order ID can be a bug or a valid partial payment. The tool finds the matches. The meaning is your call.
Large topics with SQLite
By default the hashes are kept in memory and the scan stops after 1,000,000 messages, so a big topic does not eat the laptop. For larger scans, raise the cap and move the hashes to disk:
python3 kafkainspect.py \
--bootstrap-servers localhost:9092 \
--topic big-data-topic \
--max-messages 10000000 \
--sqlite /tmp/kafka_dedup.db
Hashes are stored per topic. A new run clears the hashes for that topic first, so a second scan does not report everything as a duplicate. Add --sqlite-resume when you want to continue an earlier scan instead.
A duplicate hunt from production. Not every duplicate comes from Kafka itself. One of the worst I saw came from a job queue sitting next to it.
- The problem. New users got the same welcome email up to 87 times.
- The check. We matched the background task data against the email delivery times.
- The cause. Welcome emails went into a queue and waited 96 hours before sending.
- The glitch. The queue system assumed any task waiting that long had crashed.
- The loop. So it retried, and sent the same email again every hour.
- The quick fix. We deleted all the stuck tasks in the queue by hand.
- The permanent fix. We stopped putting long delayed tasks in the queue at all.
- The new process. A daily script now checks the database for users who joined exactly four days ago.
- The safeguard. A strict limit on how many emails one person can receive.
The lesson carries over to Kafka. When the same message shows up again and again, look at retries and timeouts first, then count the duplicates with a scan like the one above.
Check Kafka consumer lag from the CLI
python3 kafkainspect.py \
--bootstrap-servers <host:port> \
--topic my-topic \
--group-id my-consumer-group \
--check-lag
You get one line per partition with the high watermark, the committed offset of the group and the lag, plus a total at the end.
How to read the lag numbers
- Lag is the high watermark minus the committed offset. It is a count of messages, not time. A lag of a few thousand can be seconds on a busy topic or hours on a quiet one.
- N/A means no committed offset. The group never committed on that partition, or its offsets expired. In that case the tool shows everything the partition still holds as lag. Do not read that as a sudden spike.
- One partition far behind the rest usually points at a hot key or a stuck consumer instance.
- All partitions growing together usually means the consumers are too slow for the input rate, or something downstream, like an API with rate limits, is slowing them down.
Safe to use on production consumer groups
This part matters most. Debug tools that join a consumer group can trigger a rebalance in the middle of an incident, which is the last thing you need.
- kaf-inspect assigns partitions directly. It never joins a consumer group, so it cannot cause a rebalance.
- It runs with
enable.auto.commit=falseand never commits, so it cannot move anyone's offsets. --check-lagonly reads the committed offsets of the group you name.
Search and peek at messages
Search works like grep on message values. Add --regex for regular expressions:
python3 kafkainspect.py \
--bootstrap-servers <host:port> \
--topic logs.production \
--search "error"
Peek shows the last N messages, or the first N with a negative number. For the last N it jumps to the end of each partition, so it does not read the whole topic first:
python3 kafkainspect.py --bootstrap-servers <host:port> --topic my-topic --peek 5
python3 kafkainspect.py --bootstrap-servers <host:port> --topic my-topic --peek -5
When a consumer stops on a record it cannot handle, peek and search are the quickest way to look at that record. For the older, harder version of this problem, see my post on handling corrupted Kafka messages and offset recovery.
Get a quick cluster overview
python3 kafkainspect.py \
--bootstrap-servers <host:port> \
--overview \
--schema-registry-url http://localhost:8081 \
--connect-url http://localhost:8083
This prints topic, partition, broker and consumer group counts, plus Schema Registry subjects and Kafka Connect connectors if you pass their URLs. Credentials for those two come from environment variables, so they stay out of your shell history:
export KAFKAINSPECT_SCHEMA_REGISTRY_AUTH='user:password'
export KAFKAINSPECT_CONNECT_AUTH='user:password'
Use --list-topics to list topics. With more than 50 topics it opens an interactive search.
Connect to TLS and SASL clusters
Any librdkafka setting can be passed with -X, as often as you need:
python3 kafkainspect.py \
--bootstrap-servers broker:9093 \
--topic my-topic \
-X security.protocol=SASL_SSL \
-X sasl.mechanism=SCRAM-SHA-512 \
-X sasl.username=inspector \
-X sasl.password="$KAFKA_PASSWORD" \
--peek 5
Give the tool its own read-only user. It only needs to describe topics, read data and read group offsets. If you cannot connect at all, the problem is usually DNS, TLS or SASL, not the tool. kshark-core is built for that kind of connection debugging.
Once the data is clean and the consumers keep up, the next question is often what the events mean together. For security and operations data on Kafka, that is what kafSIEM, an open source Kafka SIEM is for.
Which command for which question
| Question | Command |
|---|---|
| Is my consumer falling behind? | --check-lag --group-id ... |
| Are we producing duplicates? | --field order.id or --dedup-by key |
| Where are the error messages? | --search "error" |
| What is actually in this topic? | --peek 10 |
| What does this cluster look like? | --overview or --list-topics |
Frequently asked questions
How do I find duplicate messages in a Kafka topic?
Read the topic and compare a hash of each message value, key or business ID. kaf-inspect does this with --dedup-by value, --dedup-by key or --field and reports the partition and offset of each duplicate.
How do I check consumer lag without kafka-consumer-groups.sh?
Run kaf-inspect with --topic, --group-id and --check-lag. It needs Python and network access to the brokers. No Kafka distribution or Java.
Does kaf-inspect change consumer offsets?
No. It never joins a group and never commits offsets.
Can it remove duplicates from a topic?
No. Kafka topics are append-only, and the tool only reads. Fix duplicates where they start, with idempotent producers, transactions or idempotent consumers, and use the scan to confirm the fix.
Does it work with secured clusters?
Yes. Pass TLS and SASL settings with -X, the same way you configure any librdkafka client.
Source code
The tool is on GitHub at github.com/novatechflow/kaf-inspect. Issues and pull requests are welcome. Before you put AI agents or new consumers on a Kafka estate, run these checks first. My post on why AI agents on Kafka are only as smart as your architecture explains what to look for.
If your team keeps fighting the same lag and duplicate problems, that is usually a design issue and not a tooling issue. That is the kind of work I do in my Kafka consulting.
Need help with distributed systems, backend engineering or data platforms? See my consulting services.