Python & Data Science

Kafka And Python Streaming Data Into A Pipeline In

You run a daily batch job to analyze user behavior. Every morning, you look at yesterday’s data and think, “If only I had known this last night, I could have stopped the fraud, fixed the bug, or caught the trend.” That’s the pain of batch processing: you’re always looking backward.

What if you could react the moment a user clicks? What if your dashboard updated in real time, not once a day? That’s the promise of streaming data.

Think of batch processing like checking your mailbox once a day. You get a pile of letters, but you miss the urgent one until tomorrow. Streaming is like getting a text message for every single letter the moment it arrives. You can act immediately.

Real-world examples are everywhere: fraud detection systems that block a transaction before it completes, live dashboards that show website traffic right now, IoT sensors that alert maintenance teams the instant a machine vibrates oddly.

By the end of this tutorial, you’ll build a pipeline that reads a static CSV file and replays it as a live stream, processing events in near real-time. You don’t need any prior Kafka knowledge — we’ll build intuition first, then code.

What Actually Is a Data Stream?

Let’s get the definition out of the way, but only after you’ve seen why it matters.

Imagine a river. Water flows continuously. You can’t stop it, you can’t go back to the water that passed an hour ago (unless you stored it in a bucket). That’s a stream: an ordered, replayable sequence of events that arrives continuously.

Now imagine a lake. The water is still. You can take a sample, analyze it, and come back tomorrow for another sample. That’s batch: you have all the data before you start processing.

Here’s the hardest part of shifting from batch to streaming thinking: in a batch world, you have all the data before you start. In a stream world, you never have all the data. It keeps coming. Your code must be ready for the next event, even if it never arrives.

Key properties of a stream:

  • Unbounded: it has no end.
  • Time-ordered: events have timestamps, and order matters.
  • Immutable: once an event is recorded, it’s never changed. You can only append new events.

In plain English: a stream is a never-ending list of things that happened, in the order they happened, that you can read and react to as they occur.

Meet Kafka: The Plumbing for Streams

Now that you know what a stream is, you need a way to build one. That’s where Kafka comes in.

Kafka is a distributed commit log. Think of it as a post office.

  • Producers are people who drop letters (messages) into mail slots.
  • Topics are the mail slots themselves — each slot is labeled (e.g., “clicks”, “purchases”).
  • Consumers are people who pick up letters from those slots.
  • Brokers are the post offices — servers that store and serve the data.
  • Partitions are sorting bins inside a mail slot. If a topic has multiple partitions, letters can be sorted into different bins for parallel processing.

What this actually means: Kafka is a durable, scalable message bus. Producers send events to topics. Consumers read events from topics. Kafka keeps events for a configurable time (even after consumers read them), so you can replay the stream later.

Let’s see what happens when you set it up.

Setting Up Kafka Locally (The Easy Way)

You don’t need to install Kafka natively. Docker Compose makes it trivial. Here’s a file that spins up Kafka and ZooKeeper (ZooKeeper is the coordinator that keeps Kafka’s cluster healthy — think of it as the post office manager).

version: '3'
services:
  zookeeper:
    image: confluentinc/cp-zookeeper:latest
    environment:
      ZOOKEEPER_CLIENT_PORT: 2181
      ZOOKEEPER_TICK_TIME: 2000

  kafka:
    image: confluentinc/cp-kafka:latest
    depends_on:
      - zookeeper
    ports:
      - "9092:9092"
    environment:
      KAFKA_BROKER_ID: 1
      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://localhost:9092
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1

Save this as docker-compose.yml. Then run:

docker-compose up -d

Wait a minute for everything to start. To verify, create a topic:

docker exec -it kafka kafka-topics --create --topic test --bootstrap-server localhost:9092 --partitions 1 --replication-factor 1

You should see a message like Created topic test. Now you have a running Kafka broker. Let’s send some data.

Your First Python Producer

Install the Python client:

pip install confluent-kafka

Now write a producer that sends a few messages. Every line is annotated so you know exactly what’s happening.

from confluent_kafka import Producer
import json

# Create a Producer instance. bootstrap.servers tells it where Kafka is running.
# This is like telling the post office which building to deliver letters to.
p = Producer({'bootstrap.servers': 'localhost:9092'})

# Define a callback function that Kafka calls when a message is delivered (or fails).
# This is how you know your message made it.
def delivery_report(err, msg):
    if err is not None:
        print(f"Message delivery failed: {err}")
    else:
        print(f"Message delivered to topic {msg.topic()} at offset {msg.offset()}")

# Send three messages. Each is a JSON-encoded dictionary.
# The produce() method is asynchronous — it returns immediately.
# The callback will fire later when Kafka acknowledges the message.
for i in range(3):
    data = {'user_id': i, 'action': 'click', 'timestamp': '2024-01-01T00:00:0' + str(i)}
    p.produce('test', key=str(i), value=json.dumps(data), callback=delivery_report)

# Flush ensures all messages are sent before the program exits.
# Without this, the program might exit before messages are delivered.
p.flush()

When you run this, you’ll see output like:

Message delivered to topic test at offset 0
Message delivered to topic test at offset 1
Message delivered to topic test at offset 2

What this means: each message was stored in Kafka at a specific offset (position) in the topic. The offset starts at 0 and increments with each message. Now let’s read them.

Your First Python Consumer

A consumer subscribes to a topic and polls for new messages. Kafka doesn’t push messages to consumers — consumers must ask for them.

from confluent_kafka import Consumer
import json

# Create a Consumer instance.
# group.id: consumers in the same group share the workload (more on this later).
# auto.offset.reset: 'earliest' means start reading from the beginning of the topic.
c = Consumer({
    'bootstrap.servers': 'localhost:9092',
    'group.id': 'my-group',
    'auto.offset.reset': 'earliest'
})

# Subscribe to the topic.
c.subscribe(['test'])

# Poll in a loop. This is the core pattern: keep asking for new messages.
# The timeout (1.0 seconds) means if no message arrives, it returns None after 1 second.
# This prevents an infinite blocking wait.
try:
    while True:
        msg = c.poll(1.0)
        if msg is None:
            continue
        if msg.error():
            print(f"Consumer error: {msg.error()}")
            continue
        # Decode the message value (it's bytes) and parse JSON.
        value = json.loads(msg.value().decode('utf-8'))
        print(f"Received: key={msg.key().decode()}, value={value}, partition={msg.partition()}, offset={msg.offset()}")
except KeyboardInterrupt:
    pass
finally:
    c.close()

Run this consumer while the producer is running (or after it, since Kafka keeps messages). You’ll see:

Received: key=0, value={'user_id': 0, 'action': 'click', 'timestamp': '2024-01-01T00:00:00'}, partition=0, offset=0
Received: key=1, value={'user_id': 1, 'action': 'click', 'timestamp': '2024-01-01T00:00:01'}, partition=0, offset=1
Received: key=2, value={'user_id': 2, 'action': 'click', 'timestamp': '2024-01-01T00:00:02'}, partition=0, offset=2

Notice the partition and offset — they tell you exactly where in the stream each message lives.

Simulating a Real-Time Stream from Historical Data

Now here’s the interesting part. You probably have historical data in a CSV file. You can replay it as if it were live by respecting the original timestamps.

Let’s create a sample CSV:

import pandas as pd
from datetime import datetime, timedelta
import random

# Generate 10 events with increasing timestamps (1 second apart).
base_time = datetime(2024, 1, 1, 0, 0, 0)
events = []
for i in range(10):
    events.append({
        'user_id': random.randint(1, 100),
        'event_type': random.choice(['click', 'purchase', 'view']),
        'timestamp': (base_time + timedelta(seconds=i)).isoformat()
    })
df = pd.DataFrame(events)
df.to_csv('events.csv', index=False)
print(df.head())

Now write a producer that reads this CSV and replays it with realistic timing:

from confluent_kafka import Producer
import pandas as pd
import json
import time
from datetime import datetime

p = Producer({'bootstrap.servers': 'localhost:9092'})

# Read and sort by timestamp (important to preserve order).
df = pd.read_csv('events.csv')
df['timestamp'] = pd.to_datetime(df['timestamp'])
df = df.sort_values('timestamp')

# Track the previous timestamp to compute delay.
prev_time = None

for _, row in df.iterrows():
    current_time = row['timestamp']
    
    if prev_time is not None:
        # Compute the real-world delay between events.
        delay = (current_time - prev_time).total_seconds()
        # Sleep for that delay. This is what makes it "real-time."
        time.sleep(delay)
    
    # Send the event as JSON.
    data = row.to_dict()
    # Convert Timestamp to string for JSON serialization.
    data['timestamp'] = str(data['timestamp'])
    p.produce('events', key=str(row['user_id']), value=json.dumps(data))
    print(f"Sent: {data}")
    
    prev_time = current_time

p.flush()

Run this producer, and in another terminal run the consumer from earlier (subscribed to ‘events’ instead of ‘test’). You’ll see messages arriving with realistic gaps — the same gaps as in the original data. This is how you turn static data into a live stream.

Processing the Stream: Filtering and Transforming

Now that data is flowing, let’s add logic. A common pattern is to filter out irrelevant events and transform others.

This consumer filters for ‘purchase’ events only, converts the currency to USD (assuming the original is in cents), and adds a derived field (hour of day). Then it writes the processed results to a new topic.

from confluent_kafka import Consumer, Producer
import json
from datetime import datetime

# Consumer reads from 'events' topic.
c = Consumer({
    'bootstrap.servers': 'localhost:9092',
    'group.id': 'processor-group',
    'auto.offset.reset': 'earliest'
})
c.subscribe(['events'])

# Producer writes to 'processed_events' topic.
p = Producer({'bootstrap.servers': 'localhost:9092'})

def delivery_report(err, msg):
    if err is not None:
        print(f"Delivery failed: {err}")

try:
    while True:
        msg = c.poll(1.0)
        if msg is None:
            continue
        if msg.error():
            print(f"Consumer error: {msg.error()}")
            continue
        
        # Decode and parse.
        value = json.loads(msg.value().decode('utf-8'))
        
        # Filter: only process 'purchase' events.
        if value['event_type'] != 'purchase':
            continue
        
        # Transform: convert price from cents to dollars.
        # Assume 'amount_cents' field exists.
        if 'amount_cents' in value:
            value['amount_usd'] = value['amount_cents'] / 100.0
            del value['amount_cents']
        
        # Add derived field: hour of day.
        ts = datetime.fromisoformat(value['timestamp'])
        value['hour_of_day'] = ts.hour
        
        # Send processed event to new topic.
        p.produce('processed_events', key=msg.key(), value=json.dumps(value), callback=delivery_report)
        print(f"Processed: {value}")
        
except KeyboardInterrupt:
    pass
finally:
    c.close()
    p.flush()

Run this processor. You’ll see only ‘purchase’ events appear, with added fields. The original events remain untouched in the ‘events’ topic — that’s immutability in action.

Scaling Up: Partitions and Consumer Groups

What happens when you have millions of events per second? A single consumer can’t keep up. Kafka partitions allow parallel consumption.

Think of it like a grocery store with multiple checkout lanes. Each lane (partition) can serve a customer (message) independently. If you have 4 lanes, you can serve 4 customers at once.

Let’s create a topic with 3 partitions:

docker exec -it kafka kafka-topics --create --topic scaled --bootstrap-server localhost:9092 --partitions 3 --replication-factor 1

Now run two consumers in the same group. They’ll automatically split the partitions between them.

Consumer 1:

from confluent_kafka import Consumer

c = Consumer({
    'bootstrap.servers': 'localhost:9092',
    'group.id': 'scaled-group',
    'auto.offset.reset': 'earliest'
})
c.subscribe(['scaled'])

try:
    while True:
        msg = c.poll(1.0)
        if msg is None:
            continue
        if msg.error():
            print(f"Consumer 1 error: {msg.error()}")
            continue
        print(f"Consumer 1 received: partition={msg.partition()}, offset={msg.offset()}, value={msg.value()}")
except KeyboardInterrupt:
    pass
finally:
    c.close()

Consumer 2 is identical except for the print statement (change ‘Consumer 1’ to ‘Consumer 2’). Run both in separate terminals.

Now produce messages with different keys:

from confluent_kafka import Producer

p = Producer({'bootstrap.servers': 'localhost:9092'})

# Messages with the same key go to the same partition.
# This ensures ordering for that key.
for i in range(10):
    key = str(i % 3)  # Keys: 0, 1, 2, 0, 1, 2, ...
    p.produce('scaled', key=key, value=f'message-{i}')
    print(f"Sent: key={key}, message-{i}")

p.flush()

You’ll see each consumer handles a subset of partitions. Consumer 1 might get partitions 0 and 2, while Consumer 2 gets partition 1. This is how Kafka scales: add more consumers to handle more data.

Error Handling and Delivery Guarantees

This is the hardest part of streaming: what happens when things go wrong?

Kafka offers three delivery semantics, explained in plain English:

  • At-most-once: The producer sends a message once. If it fails, it’s lost. The consumer commits the offset before processing, so if it crashes, the message is never processed. Risk: data loss.
  • At-least-once: The producer retries until it gets an acknowledgment. The consumer commits the offset after processing. If the consumer crashes after processing but before committing, the message is reprocessed. Risk: duplicates.
  • Exactly-once: The producer is idempotent (sending the same message twice has no effect) and uses transactions. The consumer uses transactional APIs. This is the gold standard but adds complexity.

For most use cases, at-least-once is the sweet spot. Here’s how to handle errors in the producer with delivery callbacks:

from confluent_kafka import Producer
import json

p = Producer({'bootstrap.servers': 'localhost:9092', 'acks': 'all'})  # 'all' means wait for all replicas to acknowledge

def delivery_report(err, msg):
    if err is not None:
        print(f"Failed to deliver message: {err}")
        # Here you could write to a dead-letter queue or log.
    else:
        print(f"Delivered to {msg.topic()} [{msg.partition()}] at offset {msg.offset()}")

# Simulate a message that might fail (e.g., invalid topic).
p.produce('nonexistent-topic', value='test', callback=delivery_report)
p.flush()

And here’s how to manually commit offsets in the consumer for precise control:

from confluent_kafka import Consumer, KafkaError
import json

c = Consumer({
    'bootstrap.servers': 'localhost:9092',
    'group.id': 'manual-commit-group',
    'enable.auto.commit': False,  # We'll commit manually
    'auto.offset.reset': 'earliest'
})
c.subscribe(['events'])

try:
    while True:
        msg = c.poll(1.0)
        if msg is None:
            continue
        if msg.error():
            if msg.error().code() == KafkaError._PARTITION_EOF:
                continue
            else:
                print(f"Error: {msg.error()}")
                break
        
        # Process the message.
        value = json.loads(msg.value().decode('utf-8'))
        print(f"Processing: {value}")
        
        # Commit only after successful processing.
        # This ensures at-least-once semantics.
        c.commit(msg)
        print(f"Committed offset {msg.offset()} for partition {msg.partition()}")
except KeyboardInterrupt:
    pass
finally:
    c.close()

Next Steps: Schema Registry, PySpark, and Beyond

You’ve built a working streaming pipeline. But production systems need more. Here’s where to go next:

  • Schema Registry: Ensures producers and consumers agree on data format (Avro, JSON Schema). Without it, a producer could send a malformed message that crashes all consumers.
  • PySpark Structured Streaming: For heavy lifting (aggregations, joins, machine learning on streams). PySpark can consume directly from Kafka.
  • Faust: A Python library that mimics Kafka Streams, allowing stateful processing (e.g., counting clicks per user over a window).
  • ksqlDB: A streaming SQL engine that lets you query streams like tables.

Here’s a quick peek at PySpark reading from Kafka:

# This is a conceptual snippet — requires PySpark and Spark Kafka integration.
from pyspark.sql import SparkSession

spark = SparkSession.builder.appName("KafkaStream").getOrCreate()

df = spark \
  .readStream \
  .format("kafka") \
  .option("kafka.bootstrap.servers", "localhost:9092") \
  .option("subscribe", "events") \
  .load()

df.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)") \
  .writeStream \
  .format("console") \
  .start() \
  .awaitTermination()

Conclusion

You started with a static CSV and ended with a live streaming pipeline. Here’s what you learned:

  1. What a stream is: an unbounded, ordered, immutable sequence of events.
  2. How Kafka works: producers send to topics, consumers read from topics, brokers store data.
  3. How to produce and consume: with the confluent-kafka Python client.
  4. How to simulate real-time: by sleeping between events based on original timestamps.
  5. How to process: filter, transform, and write to new topics.
  6. How to scale: partitions and consumer groups for parallelism.
  7. How to handle errors: delivery callbacks and manual offset commits.

Key takeaway: streaming is not magic — it’s just a different way of thinking about time. Instead of processing all data at once, you process each event as it arrives.

In the next part of this series, we’ll add Schema Registry and Avro for production-ready pipelines. You’ll learn how to enforce data contracts and evolve schemas without breaking consumers.

Check Your Understanding

Remember: What are the three key properties of a data stream?

Understand: Explain in your own words why a consumer must poll for messages instead of receiving them automatically.

Apply: Given a CSV of timestamped sensor readings, write pseudocode for a producer that replays them as a live stream.

Analyze: Compare at-least-once and at-most-once delivery semantics. When would you choose each?

Evaluate: A colleague suggests using a single partition for a high-throughput topic. Why might this be a bad idea?

Create: Design a streaming pipeline that reads user clicks, filters for ‘purchase’ events, enriches with user profile data from a database, and writes the result to a new topic. Sketch the components and data flow.

  • “Python and Kafka: A Beginner’s Guide to Streaming Data” — A gentler introduction that covers the same concepts with more hand-holding.
  • “Real-Time Data Pipelines with PySpark and Kafka” — Explores the PySpark integration mentioned in the Next Steps section.
  • “Schema Registry: The Key to Data Quality in Kafka” — Dives deep into the schema management tool we previewed.

Apply What You Learned is for Supporter and Insider subscribers.

Subscribe to unlock the exercises on this post.

See plans

Looking for something else?

Search every article by title, summary or topic.