All topics

Kafka interview questions

31 questions with answers. 849 open jobs in India ask for Kafka.

  1. What are delivery guarantees in Kafka?
    • At-most-once: Messages may be lost but never redelivered (e.g., acks=0). Fastest, least reliable.
    • At-least-once: Messages are never lost but may be duplicated (e.g., acks=all). Default for most production use cases.
    • Exactly-once: Each message is delivered and processed exactly once, using idempotent producers and transactions. Strongest guarantee, highest overhead. Links
    • https://docs.confluent.io/kafka/design/delivery-semantics.html#exactly-once-support

    From Java interview (MIT)

  2. What do in-sync replicas mean in Kafka, and what are the related configs?

    In-Sync Replicas are the set of replica followers that are fully caught up with the partition leader (no lag). Only ISR members can become the new leader after a failure, preventing data loss. Key configs:

    • min.insync.replicas – minimum ISR size required for a write with acks=all
    • replica.lag.time.max.ms – max time a follower can lag before being removed from ISR
    • unclean.leader.election.enable=false – prevents non-ISR replicas from becoming leader (avoids data loss) Links
    • https://kafka.apache.org/42/design/design/#replication

    From Java interview (MIT)

  3. What happens if a consumer doesn't process a message in time?

    The consumer is considered failed, leaves the consumer group, and triggers a rebalance to reassign its partitions. This is controlled by max.poll.interval.ms (default 300 seconds) – if poll() isn't called within this time, the consumer times out and exits the group. Links

    • https://kafka.apache.org/42/configuration/consumer-configs/#consumerconfigs_max.poll.interval.ms

    From Java interview (MIT)

  4. If the number of consumers is greater than the number of partitions, what will happen?

    The extra consumers will remain idle because each partition can be assigned to at most one consumer in a group.

    From Java interview (MIT)

  5. There is increasing Kafka lag, but the service works as expected. What are possible options to solve the issue?
    1. Consumer group state → Is it Stable, Rebalancing, or Empty?
    2. Partition lag distribution → Even lag or hot partitions?
    3. Production rate → Did throughput spike on the source side?
    4. Consumer processing time → Where is the time spent (fetch, process, write)?
    5. Rebalance frequency → Are consumers bouncing?
    6. GC pauses → Is the JVM stalling?
    7. Sink health → Is the destination keeping up?
    8. Scale or fix → Based on the bottleneck, choose the right action Links
    • https://streamkap.com/resources-and-guides/debug-kafka-consumer-lag-runbook

    From Java interview (MIT)

  6. Is it possible to change the number of partitions while downstream components are processing messages?

    Yes, but only to increase (cannot decrease). If you use message keys, ordering may break because hashing changes. Existing data is not redistributed. Links

    • https://www.baeldung.com/kafka-add-partitions-topic

    From Java interview (MIT)

  7. How to calculate the optimal number of partitions per Kafka topic?

    The optimal number balances producer/consumer throughput with minimal overhead. A simple formula: max(target throughput / producer rate, target throughput / consumer rate). Links

    • https://www.conduktor.io/blog/stop-over-partitioning-kafka

    Home Page

    From Java interview (MIT)

  8. When to use RabbitMQ over Kafka?

    RabbitMQ is a solid, general-purpose message broker that supports several protocols such as AMQP (1.0 and 0.9.1), MQTT, STOMP, etc. It can handle high throughput. A common use case for RabbitMQ is to handle background jobs or long-running task, such as file scanning, image scaling or PDF conversion. RabbitMQ is also used between microservices, where it serves as a means of communicating between applications, avoiding bottlenecks passing messages.

    Update since the release of RabbitMQ Streams: RabbitMQ stands out for offering various queue types, each designed for specific messaging needs. Traditionally, all RabbitMQ's queues would delete messages once consumed and acknowledged, which made them unsuitable for long-term storage or replaying messages - but that changed with RabbitMQ v3.9 when another queue type was introduced, Stream Queues. Stream Queues are persistent and replicated, and like traditional queues, they buffer messages from producers for consumers. Under the hood, Streams model an append-only log that's immutable. In this context, messages written to a Stream can't be erased; they can only be read. To read messages from a Stream in RabbitMQ, one or more consumers subscribe to it and read the same message as many times as they want. This functionality mirrors Kafka's behavior, making RabbitMQ's stream queues attractive for users seeking Kafka-like features in a RabbitMQ environment.

    Kafka is a message bus optimized for high-throughput ingestion data streams and replay. Use Kafka when you need to move a large amount of data, process data in real-time, or analyze data over a time period. In other words, where data need to be collected, stored, and handled. An example is when you want to track user activity on a webshop and generate suggested items to buy. Another example is data analysis for tracking, ingestion, logging or security.

    Kafka and RabbitMQ Streams can be seen as durable message brokers where applications can process and re-process streamed data on disk. With both Kafka and RabbitMQ Streams, the data sent is stored until a specified retention period has passed, either a period of time or a size limit. The message stays in the queue until the retention period/size limit is exceeded, meaning the message is not removed once it’s consumed. Instead, it can be replayed or consumed multiple times, which is a setting that can be adjusted.

    If you are planning to use replay in RabbitMQ or Apache Kafka, ensure that you are using it correctly and for the correct reason! Replaying an event multiple times that should just happen a single time; e.g. if you happen to save a customer order multiple times, is not ideal in most usage scenarios. Where a replay does come in handy is when you have a bug in the consumer that requires deploying a newer version, and you need to re-processing some or all of the messages.

    Kafka has a very simple routing approach. RabbitMQ has other options if you need to route your messages in a more complex ways, to your consumers. Use Kafka if you need to support batch consumers that could be offline or consumers that want messages at low latency.

    In order to understand how to read data from Kafka, we first need to understand its consumers and consumer groups. Partitions allow you to parallelize a topic by splitting the data across multiple nodes. Each record in a partition is assigned and identified by its unique offset. This offset points to the record in a partition. In the latest version of Kafka, Kafka maintains a numerical offset for each record in a partition. A consumer in Kafka can either automatically commit offsets periodically, or it can choose to control this committed position manually. RabbitMQ will keep all states about consumed/acknowledged/unacknowledged messages. I find Kafka more complex to understand than the case of RabbitMQ, where the message is simply removed from the queue once it's acked. RabbitMQ does also require less recourses the Kafka and works well for most use cases.

    Read the rest at the sourceFrom Stack Overflow: asked by Joe, answered by Lovisa Johansson (CC BY-SA 4.0)

  9. Understanding Kafka Topics and Partitions

    This post already has answers, but I am adding my view with a few pictures from Kafka Definitive Guide

    Before answering the questions, let's look at an overview of producer components:

    1. When a producer is producing a message, it will specify the topic it wants to send the message to. Is that right? Does it care about partitions?

    The producer will decide target partition to place any message, depending on:

    • Partition id, if it's specified within the message
    • key % num partitions, if no partition id is mentioned
    • Round robin if neither partition id nor message key is available in the message means only the value is available
    1. When a subscriber is running - Does it specify its group id so that it can be part of a cluster of consumers of the same topic or several topics that this group of consumers is interested in?

    You should always configure group.id unless you are using the simple assignment API and you don’t need to store offsets in Kafka. It will not be a part of any group. Source.

    1. Does each consumer group have a corresponding partition on the broker or does each consumer have one?

    In one consumer group, each partition will be processed by one consumer only. These are the possible scenarios

    • If the number of consumers is less than the number of topic partitions, then multiple partitions can be assigned to one of the consumers in the group

    • If the number of consumers is the same as the number of topic partitions, then partition and consumer mapping can be like below,

    • If the number of consumers is higher than the number of topic partitions, then partition and consumer mapping can be as seen below, Not effective, check Consumer 5

    1. As the partitions created by the broker, therefore not a concern for the consumers?

    Consumer should be aware of the number of partitions, as was discussed in question 3.

    1. Since this is a queue with an offset for each partition, is it the consumer's responsibility to specify which messages it wants to read? Does it need to save its state?

    Kafka (to be specific Group Coordinator) takes care of the offset state by producing a message to an internal __consumer_offsets topic, this behavior can be configurable to manual as well by setting enable.auto.commit to false. In that case consumer.commitSync() and consumer.commitAsync() can help manage offset.

    More about Group Coordinator:

    1. It's one of the elected brokers in the cluster from Kafka server side.
    2. Consumers interact with the Group Coordinator for offset commits and fetch requests.
    3. Consumer sends periodic heartbeats to Group Coordinator.
    1. What happens when a message is deleted from the queue? - For example, The retention was for 3 hours, then the time passes, how is the offset being handled on both sides?

    If any consumer starts after the retention period, messages will be consumed as per auto.offset.reset configuration which could be latest/earliest. Technically, it's latest (start processing new messages), because all the messages got expired by that time and retention is a topic-level configuration.

    more details here: https://mrsrinivas.github.io/posts/kafka-topics-and-partitions-explained/

    From Stack Overflow: asked by Pinidbest, answered by mrsrinivas (CC BY-SA 4.0)

  10. What determines Kafka consumer offset?

    It is a bit more complex than you described.
    The auto.offset.reset config kicks in ONLY if your consumer group does not have a valid offset committed somewhere (2 supported offset storages now are Kafka and Zookeeper), and it also depends on what sort of consumer you use.

    If you use a high-level java consumer then imagine following scenarios:

    1. You have a consumer in a consumer group group1 that has consumed 5 messages and died. Next time you start this consumer it won't even use that auto.offset.reset config and will continue from the place it died because it will just fetch the stored offset from the offset storage (Kafka or ZK as I mentioned).

    2. You have messages in a topic (like you described) and you start a consumer in a new consumer group group2. There is no offset stored anywhere and this time the auto.offset.reset config will decide whether to start from the beginning of the topic (earliest) or from the end of the topic (latest)

    One more thing that affects what offset value will correspond to earliest and latest configs is log retention policy. Imagine you have a topic with retention configured to 1 hour. You produce 5 messages, and then an hour later you post 5 more messages. The latest offset will still remain the same as in previous example but the earliest one won't be able to be 0 because Kafka will already remove these messages and thus the earliest available offset will be 5.

    Everything mentioned above is not related to SimpleConsumer and every time you run it, it will decide where to start from using the auto.offset.reset config.

    If you use Kafka version older than 0.9, you have to replace earliest, latest with smallest,largest.

    From Stack Overflow: asked by Asif Iqbal, answered by serejja (CC BY-SA 4.0)

  11. Is there a way to purge the topic in Kafka?

    Temporarily update the retention time on the topic to one second:

    kafka-topics.sh \
      --zookeeper <zkhost>:2181 \
      --alter \
      --topic <topic name> \
      --config retention.ms=1000
    

    And in newer Kafka releases, you can also do it with kafka-configs --entity-type topics

    kafka-configs.sh \
      --zookeeper <zkhost>:2181 \
      --entity-type topics \
      --alter \
      --entity-name <topic name> \
      --add-config retention.ms=1000
    

    then wait for the purge to take effect (duration depends on size of the topic). Once purged, restore the previous retention.ms value.

    From Stack Overflow: asked by Peter Klipfel, answered by steven appleyard (CC BY-SA 4.0)

  12. Is key required as part of sending messages to Kafka?

    Keys are mostly useful/necessary if you require strong order for a key and are developing something like a state machine. If you require that messages with the same key (for instance, a unique id) are always seen in the correct order, attaching a key to messages will ensure messages with the same key always go to the same partition in a topic. Kafka guarantees order within a partition, but not across partitions in a topic, so alternatively not providing a key - which will result in round-robin distribution across partitions - will not maintain such order.

    In the case of a state machine, keys can be used with log.cleaner.enable to deduplicate entries with the same key. In that case, Kafka assumes that your application only cares about the most recent instance of a given key and the log cleaner deletes older duplicates of a given key only if the key is not null. This form of log compaction is controlled by the log.cleaner.delete.retention property and requires keys.

    Alternatively, the more common property log.retention.hours, which is enabled by default, works by deleting complete segments of the log that are out of date. In this case keys do not have to be provided. Kafka will simply delete chunks of the log that are older than the given retention period.

    That's all to say, if you've enabled log compaction or require strict order for messages with the same key then you should definitely be using keys. Otherwise, null keys may provide better distribution and prevent potential hot spotting issues in cases where some keys may appear more than others.

    From Stack Overflow: asked by gaurav, answered by kuujo (CC BY-SA 3.0)

  13. Kafka: Consumer API vs Streams API

    Update January 2021: I wrote a four-part blog series on Kafka fundamentals that I'd recommend to read for questions like these. For this question in particular, take a look at part 3 on processing fundamentals.

    Update April 2018: Nowadays you can also use ksqlDB, the event streaming database for Kafka, to process your data in Kafka. ksqlDB is built on top of Kafka's Streams API, and it too comes with first-class support for Streams and Tables.

    what is the difference between Consumer API and Streams API?

    Kafka's Streams library (https://kafka.apache.org/documentation/streams/) is built on top of the Kafka producer and consumer clients. Kafka Streams is significantly more powerful and also more expressive than the plain clients.

    It's much simpler and quicker to write a real-world application start to finish with Kafka Streams than with the plain consumer.

    Here are some of the features of the Kafka Streams API, most of which are not supported by the consumer client (it would require you to implement the missing features yourself, essentially re-implementing Kafka Streams).

    Read the rest at the sourceFrom Stack Overflow: asked by sabtharishi, answered by miguno (CC BY-SA 4.0)

  14. Is Zookeeper a must for Kafka?

    Yes, Zookeeper is required for running Kafka. From the Kafka Getting Started documentation:

    Step 2: Start the server

    Kafka uses zookeeper so you need to first start a zookeeper server if you don't already have one. You can use the convenience script packaged with kafka to get a quick-and-dirty single-node zookeeper instance.

    As to why, well people long ago discovered that you need to have some way to coordinating tasks, state management, configuration, etc across a distributed system. Some projects have built their own mechanisms (think of the configuration server in a MongoDB sharded cluster, or a Master node in an Elasticsearch cluster). Others have chosen to take advantage of Zookeeper as a general purpose distributed process coordination system. So Kafka, Storm, HBase, SolrCloud to just name a few all use Zookeeper to help manage and coordinate.

    Kafka is a distributed system and is built to use Zookeeper. The fact that you are not using any of the distributed features of Kafka does not change how it was built. In any event there should not be much overhead from using Zookeeper. A bigger question is why you would use this particular design pattern -- a single broker implementation of Kafka misses out on all of the reliability features of a multi-broker cluster along with its ability to scale.

    From Stack Overflow: asked by Paaji, answered by John Petrone (CC BY-SA 4.0)

  15. Difference between Redis and Kafka

    Redis pub-sub is mostly like a fire and forget system where all the messages you produced will be delivered to all the consumers at once and the data is kept nowhere. You have limitation in memory with respect to Redis. Also, the number of producers and consumers can affect the performance in Redis.

    Kafka, on the other hand, is a high throughput, distributed log that can be used as a queue. Here any number of users can produce and consumers can consume at any time they want. It also provides persistence for the messages sent through the queue.

    Final Take:

    Use Redis:

    1. If you want a fire and forget kind of system, where all the messages that you produce are delivered instantly to consumers.
    2. If speed is most concerned.
    3. If you can live up with data loss.
    4. If you don't want your system to hold the message that has been sent.
    5. The amount of data that is gonna be dealt with is not huge.

    Use kafka:

    1. If you want reliability.
    2. If you want your system to have a copy of messages that has been sent even after consumption.
    3. If you can't live up with data loss.
    4. If Speed is not a big concern.
    5. data size is huge

    From Stack Overflow: asked by Sweta Sharma, answered by Karthikeyan Gopall (CC BY-SA 4.0)

  16. What's the purpose of Kafka's key/value pair-based messaging?

    Kafka uses the abstraction of a distributed log that consists of partitions. Splitting a log into partitions allows to scale-out the system.

    Keys are used to determine the partition within a log to which a message get's appended to. While the value is the actual payload of the message. The examples are actually not very "good" with this regard; usually you would have a complex type as value (like a tuple-type or a JSON or similar) and you would extract one field as key.

    See: http://kafka.apache.org/intro#intro_topics and http://kafka.apache.org/intro#intro_producers

    In general the key and/or value can be null, too. If the key is null a random partition will the selected. If the value is null it can have special "delete" semantics in case you enable log-compaction instead of log-retention policy for a topic (http://kafka.apache.org/documentation#compaction).

    From Stack Overflow: asked by smeeb, answered by Matthias J. Sax (CC BY-SA 3.0)

  17. I am evaluating Google Pub/Sub vs Kafka. What are the differences?

    In addition to Google Pub/Sub being managed by Google and Kafka being open source, the other difference is that Google Pub/Sub is a message queue (e.g. Rabbit MQ) where as Kafka is more of a streaming log. You can't "re-read" or "replay" messages with Pubsub. (EDIT - as of 2019 Feb, you CAN replay messages and seek backwards in time to a certain timestamp, per comment below)

    With Google Pub/Sub, once a message is read out of a subscription and ACKed, it's gone. In order to have more copies of a message to be read by different readers, you "fan-out" the topic by creating "subscriptions" for that topic, where each subscription will have an entire copy of everything that goes into the topic. But this also increases cost because Google charges Pub/Sub usage by the amount of data read out of it.

    With Kafka, you set a retention period (I think it's 7 days by default) and the messages stay in Kafka regardless of how many consumers read them. You can add a new consumer (a.k.a. subscriber), and have it start consuming from the front of the topic any time you want. You can also set the retention period to be infinite, and then you can basically use Kafka as an immutable datastore, as described here: http://stackoverflow.com/a/22597637/304262

    Amazon AWS Kinesis is a managed version of Kafka whereas I think of Google Pubsub as a managed version of Rabbit MQ. Amazon SNS with SQS is also similar to Google Pubsub (SNS provides the fanout and SQS provides the queueing).

    From Stack Overflow: asked by Naresh, answered by gunit (CC BY-SA 4.0)

  18. Difference between session.timeout.ms and max.poll.interval.ms for Kafka >= 0.10.1

    Before KIP-62, there was only session.timeout.ms (ie, Kafka 0.10.0 and earlier). max.poll.interval.ms was introduced via KIP-62 (part of Kafka 0.10.1).

    KIP-62, decouples heartbeats from calls to poll() via a background heartbeat thread, allowing for a longer processing time (ie, time between two consecutive poll()) than heartbeat interval.

    Assume processing a message takes 1 minute. If heartbeat and poll were coupled (ie, before KIP-62), you will need to set session.timeout.ms larger than 1 minute to prevent consumer to time out. However, if a consumer dies, it also takes longer than 1 minute to detect the failed consumer.

    KIP-62 decouples polling and heartbeat allowing to send heartbeats between two consecutive polls. Now you have two threads running, the heartbeat thread and the processing thread and thus, KIP-62 introduced a timeout for each. session.timeout.ms is for the heartbeat thread while max.poll.interval.ms is for the processing thread.

    Assume, you set session.timeout.ms=30000, thus, the consumer heartbeat thread must sent a heartbeat to the broker before this time expires. On the other hand, if processing of a single message takes 1 minutes, you can set max.poll.interval.ms larger than one minute to give the processing thread more time to process a message.

    If the processing thread dies, it takes max.poll.interval.ms to detect this. However, if the whole consumer dies (and a dying processing thread most likely crashes the whole consumer including the heartbeat thread), it takes only session.timeout.ms to detect it.

    The idea is, to allow for a quick detection of a failing consumer even if processing itself takes quite long.

    Implementation Detail

    The new timeout max.poll.interval.ms is mainly a client side concept: if poll() is not called within max.poll.interval.ms, the heartbeat thread will detect this case and send a leave-group request to the broker. -- max.poll.interval.ms is still relevant for consumer group rebalances: if a rebalance is triggered, consumers have max.poll.interval.ms time to re-join the group by calling poll() client side which triggers a join-group request.

    From Stack Overflow: asked by Deeps, answered by Matthias J. Sax (CC BY-SA 4.0)

  19. Can multiple Kafka consumers read same message from the partition

    It depends on Group ID. Suppose you have a topic with 12 partitions. If you have 2 Kafka consumers with the same Group Id, they will both read 6 partitions, meaning they will read different set of partitions = different set of messages. If you have 4 Kafka consumers with the same Group Id, each of them will all read three different partitions etc.

    But when you set different Group Id, the situation changes. If you have two Kafka consumers with different Group Id they will read all 12 partitions without any interference between each other. Meaning both consumers will read the exact same set of messages independently. If you have four Kafka consumers with different Group Id they will all read all partitions etc.

    From Stack Overflow: asked by shiv455, answered by Lukáš Havrlant (CC BY-SA 4.0)

  20. Is it possible to add partitions to an existing topic in Kafka 0.8.2

    Looks like you can use this script instead:

    bin/kafka-topics.sh --zookeeper zk_host:port/chroot --alter --topic my_topic_name 
       --partitions 40 
    

    In the code it looks like they do same thing:

     AdminUtils.createOrUpdateTopicPartitionAssignmentPathInZK(topic, partitionReplicaList, zkClient, true)
    

    kafka-topics.sh executes this piece of code as well as AddPartitionsCommand used by kafka-add-partition script.

    However you have to be aware of re-partitioning when using key:

    Be aware that one use case for partitions is to semantically partition data, and adding partitions doesn't change the partitioning of existing data so this may disturb consumers if they rely on that partition. That is if data is partitioned by hash(key) % number_of_partitions then this partitioning will potentially be shuffled by adding partitions but Kafka will not attempt to automatically redistribute data in any way.

    From Stack Overflow: asked by Asif Iqbal, answered by blockR (CC BY-SA 3.0)

  21. Difference between stream processing and message processing

    In traditional message processing, you apply simple computations on the messages -- in most cases individually per message.

    In stream processing, you apply complex operations on multiple input streams and multiple records (ie, messages) at the same time (like aggregations and joins).

    Furthermore, traditional messaging systems cannot go "back in time" -- ie, they automatically delete messages after they got delivered to all subscribed consumers. In contrast, Kafka keeps the messages as it uses a pull-based model (ie, consumers pull data out of Kafka) for a configurable amount of time. This allows consumers to "rewind" and consume messages multiple times -- or if you add a new consumer, it can read the complete history. This makes stream processing possible, because it allows for more complex applications. Furthermore, stream processing is not necessarily about real-time processing -- it's about processing infinite input streams (in contrast to batch processing, which is applied to finite inputs).

    And Kafka offers Kafka Connect and Streams API -- so it is a stream-processing platform and not just a messaging/pub-sub system (even if it uses this in its core).

    From Stack Overflow: asked by TechEnthusiast, answered by Matthias J. Sax (CC BY-SA 4.0)

  22. Is there a way to delete all the data from a topic or delete the topic before every run?

    Don't think it is supported yet. Take a look at this JIRA issue "Add delete topic support".

    To delete manually:

    1. Shutdown the cluster
    2. Clean kafka log dir (specified by the log.dir attribute in kafka config file ) as well the zookeeper data
    3. Restart the cluster

    For any given topic what you can do is

    1. Stop kafka
    2. Clean kafka log specific to partition, kafka stores its log file in a format of "logDir/topic-partition" so for a topic named "MyTopic" the log for partition id 0 will be stored in /tmp/kafka-logs/MyTopic-0 where /tmp/kafka-logs is specified by the log.dir attribute
    3. Restart kafka

    This is NOT a good and recommended approach but it should work. In the Kafka broker config file the log.retention.hours.per.topic attribute is used to define The number of hours to keep a log file before deleting it for some specific topic

    Also, is there a way the messages gets deleted as soon as the consumer reads it?

    From the Kafka Documentation :

    The Kafka cluster retains all published messages—whether or not they have been consumed—for a configurable period of time. For example if the log retention is set to two days, then for the two days after a message is published it is available for consumption, after which it will be discarded to free up space. Kafka's performance is effectively constant with respect to data size so retaining lots of data is not a problem.

    In fact the only metadata retained on a per-consumer basis is the position of the consumer in in the log, called the "offset". This offset is controlled by the consumer: normally a consumer will advance its offset linearly as it reads messages, but in fact the position is controlled by the consumer and it can consume messages in any order it likes. For example a consumer can reset to an older offset to reprocess.

    For finding the start offset to read in Kafka 0.8 Simple Consumer example they say

    Kafka includes two constants to help, kafka.api.OffsetRequest.EarliestTime() finds the beginning of the data in the logs and starts streaming from there, kafka.api.OffsetRequest.LatestTime() will only stream new messages.

    You can also find the example code there for managing the offset at your consumer end.

        public static long getLastOffset(SimpleConsumer consumer, String topic, int partition,
                                     long whichTime, String clientName) {
        TopicAndPartition topicAndPartition = new TopicAndPartition(topic, partition);
        Map<TopicAndPartition, PartitionOffsetRequestInfo> requestInfo = new HashMap<TopicAndPartition, PartitionOffsetRequestInfo>();
        requestInfo.put(topicAndPartition, new PartitionOffsetRequestInfo(whichTime, 1));
        kafka.javaapi.OffsetRequest request = new kafka.javaapi.OffsetRequest(requestInfo, kafka.api.OffsetRequest.CurrentVersion(),clientName);
        OffsetResponse response = consumer.getOffsetsBefore(request);
        if (response.hasError()) {
            System.out.println("Error fetching data Offset Data the Broker. Reason: " + response.errorCode(topic, partition) );
            return 0;
        }
        long[] offsets = response.offsets(topic, partition);
        return offsets[0];
    }
    

    From Stack Overflow: asked by TommyT, answered by Hild (CC BY-SA 4.0)

  23. Apache Kafka vs Apache Storm

    You use Apache Kafka as a distributed and robust queue that can handle high volume data and enables you to pass messages from one end-point to another.

    Storm is not a queue. It is a system that has distributed real time processing abilities, meaning you can execute all kind of manipulations on real time data in parallel.

    The common flow of these tools (as I know it) goes as follows:

    real-time-system --> Kafka --> Storm --> NoSql --> BI(optional)

    So you have your real time app handling high volume data, sends it to Kafka queue. Storm pulls the data from kafka and applies some required manipulation. At this point you usually like to get some benefits from this data, so you either send it to some Nosql db for additional BI calculations, or you could simply query this NoSql from any other system.

    From Stack Overflow: asked by Ananth Duari, answered by forhas (CC BY-SA 3.0)

  24. When to use Apache kafka instead of ActiveMQ?

    Kafka and ActiveMQ may have some overlaps but they were originally designed for different purposes. So comparing them is just like comparing an Apple and an Orange.

    Kafka

    Kafka is a distributed streaming platform with very good horizontal scaling capability. It allows applications to process and re-process streamed data on disk. Due to it's high throughput it's commonly used for real-time data streaming.

    ActiveMQ

    ActiveMQ is a general-purpose message broker that supports several messaging protocols such as AMQP, STOMP, MQTT. It supports more complicated message routing patterns as well as the Enterprise Integration Patterns. In general it is mainly used for integration between applications/services especially in a Service Oriented Architecture.

    From Stack Overflow: asked by Boxer Robert, answered by Chris Lam (CC BY-SA 3.0)

  25. Kafka server configuration - listeners vs. advertised.listeners

    Since I cannot comment yet I will post this as an "answer", adding on to M.Situations answer.

    Within the same document he links there is this blurb about which listener is used by a KAFKA client (https://cwiki.apache.org/confluence/display/KAFKA/KIP-103%3A+Separation+of+Internal+and+External+traffic):

    As stated previously, clients never see listener names and will make metadata requests exactly as before. The difference is that the list of endpoints they get back is restricted to the listener name of the endpoint where they made the request.

    This is important as depending on what URL you use in your bootstrap.servers config that will be the URL* that the client will get back if it is mapped in advertised.listeners (do not know what the behavior is if the listener does not exist).

    Also note this:

    The exception is ZooKeeper-based consumers. These consumers retrieve the broker registration information directly from ZooKeeper and will choose the first listener with PLAINTEXT as the security protocol (the only security protocol they support).

    As an example broker config (for all brokers in cluster):

    advertised.listeners=EXTERNAL://XXXXX.compute-1.amazonaws.com:9990,INTERNAL://ip-XXXXX.ec2.internal:9993

    inter.broker.listener.name=INTERNAL

    listener.security.protocol.map=EXTERNAL:SSL,INTERNAL:PLAINTEXT

    If the client uses XXXXX.compute-1.amazonaws.com:9990 to connect, the metadata fetch will go to that broker. However, the returning URL to use with the Group Coordinator or Leader could be 123.compute-1.amazonaws.com:9990* (a different machine!). This means that the match is done on the listener name as advertised by KIP-103 irrespective of the actual URL (node).

    Since the protocol map for EXTERNAL is SSL this would force you to use an SSL keystore to connect.

    If on the other hand you are within AWS lets say, you can then issue ip-XXXXX.ec2.internal:9993 and the corresponding connection would be plaintext as per the protocol map.

    This is especially needed in IaaS where in my case brokers and consumers live on AWS, whereas my producer lives on a client site, thus needing different security protocols and listeners.

    EDIT: Also adding Inbound Rules is much easier now that you have different ports for different clients (brokers, producers, consumers).

    EDIT2: This article is a great in depth guide if the above is still not clear: https://rmoff.net/2018/08/02/kafka-listeners-explained/

    From Stack Overflow: asked by CPA, answered by PragmaticProgrammer (CC BY-SA 4.0)

  26. Why is Kafka pull-based instead of push-based?

    Scalability was the major driving factor when we design such systems (pull vs push). Kafka is very scalable. One of the key benefits of Kafka is that it is very easy to add large number of consumers without affecting performance and without down time.

    Kafka can handle events at 100k+ per second rate coming from producers. Because Kafka consumers pull data from the topic, different consumers can consume the messages at different pace. Kafka also supports different consumption models. You can have one consumer processing the messages at real-time and another consumer processing the messages in batch mode.

    The other reason could be that Kafka was designed not only for single consumers like Hadoop. Different consumers can have diverse needs and capabilities.

    Pull-based systems have some deficiencies like resources wasting due to polling regularly. Kafka supports a 'long polling' waiting mode until real data comes through to alleviate this drawback.

    From Stack Overflow: asked by user1870400, answered by kanishka vatsa (CC BY-SA 4.0)

  27. What does "Rebalancing" mean in Apache Kafka context?

    When a new consumer joins a consumer group the set of consumers attempt to "rebalance" the load to assign partitions to each consumer. If the set of consumers changes while this assignment is taking place the rebalance will fail and retry. This setting controls the maximum number of attempts before giving up.

    the command for this is: rebalance.max.retries and is set to 4 by default.

    also, it might be happening if the following is true:

    ZooKeeper session timeout. If the consumer fails to send a heartbeat to ZooKeeper for this period of time it is considered dead and a rebalance will occur.

    Hope this helps!

    From Stack Overflow: asked by Jeff Gong, answered by George Davis (CC BY-SA 4.0)

  28. Using Kafka as a (CQRS) Eventstore. Good idea?

    I am one of the original authors of Kafka. Kafka will work very well as a log for event sourcing. It is fault-tolerant, scales to enormous data sizes, and has a built in partitioning model.

    We use it for several use cases of this form at LinkedIn. For example our open source stream processing system, Apache Samza, comes with built-in support for event sourcing.

    I think you don't hear much about using Kafka for event sourcing primarily because the event sourcing terminology doesn't seem to be very prevalent in the consumer web space where Kafka is most popular.

    I have written a bit about this style of Kafka usage here.

    From Stack Overflow: asked by Geert-Jan, answered by Jay Kreps (CC BY-SA 3.0)

  29. Leader Not Available Kafka in Console Producer

    It could be related to advertised.host.name setting in your server.properties.

    What could happen is that your producer is trying to find out who is the leader for a given partition, figures out its advertised.host.name and advertised.port and tries to connect. If these settings are not configured correctly it then may think that the leader is unavailable.

    From Stack Overflow: asked by Vishesh, answered by Alexey Raga (CC BY-SA 3.0)

  30. How can I send large messages with Kafka (over 15MB)?

    You need to adjust three (or four) properties:

    • Consumer side:fetch.message.max.bytes - this will determine the largest size of a message that can be fetched by the consumer.
    • Broker side: replica.fetch.max.bytes - this will allow for the replicas in the brokers to send messages within the cluster and make sure the messages are replicated correctly. If this is too small, then the message will never be replicated, and therefore, the consumer will never see the message because the message will never be committed (fully replicated).
    • Broker side: message.max.bytes - this is the largest size of the message that can be received by the broker from a producer.
    • Broker side (per topic): max.message.bytes - this is the largest size of the message the broker will allow to be appended to the topic. This size is validated pre-compression. (Defaults to broker's message.max.bytes.)

    I found out the hard way about number 2 - you don't get ANY exceptions, messages, or warnings from Kafka, so be sure to consider this when you are sending large messages.

    From Stack Overflow: asked by Sonson123, answered by laughing_man (CC BY-SA 3.0)

Related topics

Where these questions come from

Open-source collections on GitHub, official documentation, a government careers service and the Stack Exchange sites, each used under its own licence. The answers are the authors' own words: we only tidy the layout, leave out pictures, and cut a long answer with a link to the rest. Stack Exchange answers stay under CC BY-SA and name who asked and who answered.