📖 Scenario: You are building a simple Kafka consumer application that listens to messages from a specific topic. This is common in real-world systems where services communicate by sending messages through Kafka topics.
🎯 Goal: Create a Kafka consumer that subscribes to a topic named test-topic and prints any messages it receives.
📋 What You'll Learn
Create a Kafka consumer configuration dictionary with the required settings
Create a variable called topic with the value 'test-topic'
Subscribe the consumer to the topic
Print the messages received from the topic
💡 Why This Matters
🌍 Real World
Kafka consumers are used in real systems to process streams of data like logs, user activity, or sensor data.
💼 Career
Understanding how to subscribe and consume messages from Kafka topics is essential for backend developers, data engineers, and anyone working with real-time data pipelines.
Progress0 / 4 steps
1
Create Kafka consumer configuration
Create a dictionary called consumer_config with these exact entries: 'bootstrap.servers': 'localhost:9092', 'group.id': 'my-group', and 'auto.offset.reset': 'earliest'.
Kafka
Hint
Use a Python dictionary with the exact keys and values as shown.
2
Set the topic name
Create a variable called topic and set it to the string 'test-topic'.
Kafka
Hint
Assign the string 'test-topic' to the variable named topic.
3
Subscribe the consumer to the topic
Import Consumer from confluent_kafka. Create a Consumer instance called consumer using consumer_config. Use consumer.subscribe([topic]) to subscribe to the topic.
Kafka
Hint
Use the Consumer class and call subscribe with a list containing topic.
4
Print messages from the topic
Write a loop that calls consumer.poll(1.0) to get messages. If a message is received and no error, print message.value().decode('utf-8'). Break the loop after printing one message. Finally, call consumer.close().
Kafka
Hint
Use poll to get messages, check for errors, decode the message value, print it, and then close the consumer.
Practice
(1/5)
1. What is the main purpose of the subscribe() method in Kafka consumers?
easy
A. To close the Kafka consumer connection
B. To send messages to Kafka topics
C. To listen to one or more Kafka topics and receive messages automatically
D. To create new Kafka topics
Solution
Step 1: Understand the role of subscribe()
The subscribe() method is used by Kafka consumers to specify which topics they want to listen to.
Step 2: Identify what subscribe() enables
Once subscribed, the consumer automatically receives messages from those topics when calling poll().
Final Answer:
To listen to one or more Kafka topics and receive messages automatically -> Option C
Quick Check:
subscribe() = listen to topics [OK]
Hint: subscribe() means start listening to topics [OK]
Common Mistakes:
Confusing subscribe() with sending messages
Thinking subscribe() creates topics
Assuming subscribe() closes connections
2. Which of the following is the correct way to subscribe a Kafka consumer to multiple topics named "topicA" and "topicB"?
easy
A. consumer.subscribe(["topicA", "topicB"])
B. consumer.subscribe("topicA", "topicB")
C. consumer.subscribe("topicA" + "," + "topicB")
D. consumer.subscribe({"topicA", "topicB"})
Solution
Step 1: Recall the subscribe() method signature
In Kafka, subscribe() takes a list (or collection) of topic names as an argument.
Step 2: Identify correct syntax for multiple topics
Passing a list like ["topicA", "topicB"] is the correct way to subscribe to multiple topics.
Final Answer:
consumer.subscribe(["topicA", "topicB"]) -> Option A
Quick Check:
subscribe() needs a list for multiple topics [OK]
Hint: Use a list to subscribe to multiple topics [OK]
Common Mistakes:
Passing multiple string arguments instead of a list
Concatenating topic names into one string
Using curly braces instead of square brackets
3. Given the following Kafka consumer code snippet, what will be the output if the consumer is subscribed to topic "news" and there are two messages "Hello" and "World" in the topic?
consumer.subscribe(["news"])
records = consumer.poll(timeout_ms=1000)
for record in records:
print(record.value)
medium
A. ['Hello', 'World']
B. Hello\nWorld
C. HelloWorld
D. No output because poll() is missing a loop
Solution
Step 1: Understand subscribe() and poll() behavior
The consumer subscribes to "news" and calls poll() once, which fetches available messages.
Step 2: Analyze the for loop printing each record
The loop prints each message value on its own line, so "Hello" and "World" appear separately.
Final Answer:
Hello\nWorld -> Option B
Quick Check:
poll() returns messages, loop prints each [OK]
Hint: poll() returns messages; loop prints each on new line [OK]
Common Mistakes:
Thinking poll() returns a list printed directly
Assuming messages print concatenated without newline
Believing poll() needs a loop to work at all
4. What is wrong with the following Kafka consumer code snippet?
consumer.subscribe("topic1")
while True:
records = consumer.poll(1000)
for record in records:
print(record.value)
medium
A. subscribe() expects a list, not a single string
B. poll() must be called outside the loop
C. print() cannot be used inside the loop
D. The loop should be a for loop, not while
Solution
Step 1: Check subscribe() argument type
The subscribe() method requires a list of topics, even if subscribing to one topic.
Step 2: Identify the error in argument
Passing a single string instead of a list causes a type error or unexpected behavior.
Final Answer:
subscribe() expects a list, not a single string -> Option A
Quick Check:
subscribe() needs list argument [OK]
Hint: Always pass a list to subscribe(), even for one topic [OK]
Common Mistakes:
Passing a string instead of a list to subscribe()
Thinking poll() can't be inside a loop
Misunderstanding loop type requirements
5. You want to subscribe a Kafka consumer to all topics starting with "logs-" dynamically, without listing each topic name. Which approach correctly achieves this?
hard
A. Use consumer.assign() with topic partitions matching "logs-"
B. Manually list all topics starting with "logs-" in a list and pass to subscribe()
C. Call subscribe() multiple times, once per topic starting with "logs-"
D. Use consumer.subscribe(Pattern.compile("logs-.*")) to subscribe by regex pattern
Solution
Step 1: Understand dynamic topic subscription
Kafka consumers can subscribe to topics matching a regex pattern using subscribe(Pattern).
Step 2: Identify correct method for pattern subscription
Using consumer.subscribe(Pattern.compile("logs-.*")) subscribes to all topics starting with "logs-" automatically.
Final Answer:
Use consumer.subscribe(Pattern.compile("logs-.*")) to subscribe by regex pattern -> Option D
Quick Check:
subscribe() supports regex patterns [OK]
Hint: Use regex pattern with subscribe() for dynamic topic matching [OK]
Common Mistakes:
Listing topics manually instead of using regex
Calling subscribe() multiple times incorrectly
Using assign() which requires partitions, not topics
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.