Lecture 07 ยท Module 2

Reading from Kafka

Console Consumer ยท Python Consumer ยท Two Producers, One Stream

๐Ÿ“… Module 2 โ€” Making Kafka Work
โฑ 90 min
๐ŸŽ“ MBA Streaming Data Analytics
02 / 08 Agenda

Today's 90 Minutes

TimeSegmentFormat
0 โ€“ 10Recap โ€” TCS + INFY producers from Lecture 6Q&A
10 โ€“ 20What is a consumer? How it connects to a topicLecture
20 โ€“ 40Console consumer โ€” verify stream is liveDemo + Lab
40 โ€“ 70Python consumer โ€” read from stock-topicLab
70 โ€“ 85One consumer reading both TCS & INFY dataLab
85 โ€“ 90Takeaways + Lecture 8 previewWrap-up
03 / 08 Recap

Where We Left Off โ€” Lecture 6

In Lecture 6 you built two producers that both write to stock-topic. Today we read from it.

๐Ÿ
tcs_producer.py
TCS.NS ยท yFinance
historical prices
โ†’
๐Ÿ“จ
stock-topic
Kafka topic
all messages here
โ†’
๐Ÿ‘๏ธ
consumer.py
Today's goal
read everything
๐Ÿ
infy_producer.py
INFY.NS ยท yFinance
writes same topic
โ†—

Key insight: One consumer subscribing to stock-topic automatically sees messages from all producers writing to it โ€” TCS and INFY arrive in the same stream.

04 / 08 Demo

Step 1 โ€” Kafka Console Consumer

Before writing Python โ€” verify your stream is live with zero code. Run a producer in one terminal, this in another.

Read all messages (from the beginning)

bash
docker exec -it sda-kafka-1 kafka-console-consumer.sh \
  --bootstrap-server localhost:9092 \
  --topic stock-topic \
  --from-beginning

Read live messages only (from now)

bash
docker exec -it sda-kafka-1 kafka-console-consumer.sh \
  --bootstrap-server localhost:9092 \
  --topic stock-topic
โš™๏ธ Command Builder โ€” Enter your details
Generated command:

          
        
05 / 08 Lab

Step 2 โ€” Python Consumer

Subscribe to stock-topic and print every message. Open a terminal alongside your running producer.

python ยท consumer_stock.py
from kafka import KafkaConsumer
import json

consumer = KafkaConsumer(
    'stock-topic',
    bootstrap_servers=['localhost:9092'],
    auto_offset_reset='earliest',   # read ALL past messages first
    value_deserializer=lambda x: json.loads(x.decode('utf-8'))
)

print("Listening on stock-topic...")
for msg in consumer:
    data = msg.value
    print(data)

Try it: Start the consumer first, then run python tcs_producer.py in another terminal. Watch messages arrive live.

Install kafka-python first

bash
pip install kafka-python
06 / 08 Lab

One Consumer, Two Producers

Run tcs_producer.py and infy_producer.py simultaneously. One consumer reads both โ€” differentiate by the symbol field.

python ยท consumer_stock.py (updated)
from kafka import KafkaConsumer
import json

consumer = KafkaConsumer(
    'stock-topic',
    bootstrap_servers=['localhost:9092'],
    auto_offset_reset='earliest',
    value_deserializer=lambda x: json.loads(x.decode('utf-8'))
)

tcs_count = infy_count = 0

print("๐Ÿ“ก Listening to stock-topic (TCS + INFY)...")
for msg in consumer:
    data  = msg.value
    sym   = data.get('symbol', '?')
    price = data.get('price', data.get('Close', '?'))

    if sym == 'TCS.NS':
        tcs_count += 1
        print(f"๐Ÿ”ต TCS   โ‚น{price}  (msg #{tcs_count})")
    elif sym == 'INFY.NS':
        infy_count += 1
        print(f"๐ŸŸข INFY  โ‚น{price}  (msg #{infy_count})")
    else:
        print(f"โšช {sym} โ†’ {data}")

Expected output

terminal
๐Ÿ“ก Listening to stock-topic (TCS + INFY)...
๐Ÿ”ต TCS   โ‚น3842.5  (msg #1)
๐Ÿ”ต TCS   โ‚น3851.0  (msg #2)
๐ŸŸข INFY  โ‚น1724.3  (msg #1)
๐Ÿ”ต TCS   โ‚น3860.2  (msg #3)
๐ŸŸข INFY  โ‚น1731.8  (msg #2)
07 / 08 Hands-On Lab

Lab โ€” Run It All Together

Open 4 terminal windows. Follow the sequence below.

TerminalCommandWhat it does
T1 docker-compose up -d Start Kafka + Zookeeper
T2 python tcs_producer.py Stream TCS prices โ†’ stock-topic
T3 python infy_producer.py Stream INFY prices โ†’ stock-topic
T4 python consumer_stock.py Read all messages, tag by symbol

Challenge: Modify consumer_stock.py to also print the count of messages received for each symbol every 5 messages. Hint: use a counter variable and if (tcs_count + infy_count) % 5 == 0.

Next โ†’ Lecture 8: Save this streaming data to MongoDB Atlas so it persists beyond the terminal session.

08 / 08 Wrap-Up

Key Takeaways

Download Lab Files

Next โ†’ Lecture 8: Save streaming data to MongoDB Atlas โ€” free cluster setup + persistent storage

1 / 8