PleinIQ
Menu
Language

Choose your language

This page is only in English for now. Choosing a language opens its home page.

Other languages

Your browser can translate any page into almost any language.

Other browsers: Open the browser menu and look for “Translate”.

Your resume, your downloads and lab commands are never translated.

Roadmaps / Kafka / Lab 2

Lab 2 of 8 · Producers and consumers in Python

Send and read orders from Python

Write a producer that sends six JSON orders with delivery reports, and a consumer that prints them.

Time
60 minutes
Cost
Free.

What you learn

Real systems produce and consume events from code. You write a Python producer that sends JSON orders safely and a consumer that reads them, using the confluent-kafka client.

  • The confluent-kafka Python client
  • Delivery reports, acks=all and idempotent producers
  • Matching the partitioner used by Kafka’s own tools
  • Polling, deserialising and closing a consumer cleanly

In the AI era: AI writes producer and consumer code quickly, but often leaves out delivery callbacks, flush() and error handling. Always check that failures are reported, not silently dropped.

Get set up

Commands use Homebrew in the Terminal app. Already have a tool? Skip it.

  • Install
    /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

    Use the Terminal app. The command installs Homebrew, which the other macOS commands use.

  • Multipass (a free Ubuntu server on your computer)Official install page ↗
    Install
    brew install --cask multipass

    Check it worked: multipass version

Before you start

  • Start your server with multipass start kafka-lab and open a shell on it.

Step by step

  1. 1 Create a Python environment

    A virtual environment keeps this project’s packages separate.

    Run this on your lab server
    cd ~/kafka-streaming-lab
    python3 -m venv .venv
    source .venv/bin/activate
    echo "confluent-kafka[avro,schemaregistry]==2.12.1" > requirements.txt
    pip install -r requirements.txt
    printf ".venv/\n__pycache__/\n" > .gitignore
    kafka topics --create --topic orders --partitions 3
    You should see:

    Successfully installed confluent-kafka-2.12.1 and Created topic orders.

  2. 2 Write the producer

    acks=all waits until the broker has stored each event; enable.idempotence stops retries from creating duplicates. murmur2_random makes the Python client place keys exactly like Kafka’s own tools. Save it as producer.py.

    File: producer.py
    import json
    
    from confluent_kafka import Producer
    
    producer = Producer(
        {
            "bootstrap.servers": "localhost:9092",
            "acks": "all",
            "enable.idempotence": True,
            "partitioner": "murmur2_random",
        }
    )
    
    
    def delivered(err, msg):
        if err:
            print(f"FAILED {msg.key().decode()}: {err}")
        else:
            print(f"sent {msg.key().decode()} to partition {msg.partition()} at offset {msg.offset()}")
    
    
    orders = [
        ("alice", "book", 1),
        ("bob", "pen", 3),
        ("carol", "lamp", 1),
        ("dave", "mug", 2),
        ("alice", "desk", 1),
        ("erin", "chair", 4),
    ]
    for number, (customer, item, qty) in enumerate(orders, start=1):
        value = {"order_id": number, "customer": customer, "item": item, "qty": qty}
        producer.produce("orders", key=customer, value=json.dumps(value), callback=delivered)
        producer.poll(0)
    
    left = producer.flush(10)
    if left:
        raise SystemExit(f"{left} orders were not delivered")
    
  3. 3 Run it

    Every order gets a delivery report with its partition and offset.

    Run this on your lab server
    python producer.py
    You should see:

    Six sent ... lines. Both of alice’s orders go to the same partition, with increasing offsets.

  4. 4 Write the consumer

    The consumer belongs to the group order-printer, starts from the earliest event the first time, and commits its position after printing each order. It stops after 10 seconds with no new events. Save it as consumer.py.

    File: consumer.py
    import json
    
    from confluent_kafka import Consumer
    
    consumer = Consumer(
        {
            "bootstrap.servers": "localhost:9092",
            "group.id": "order-printer",
            "auto.offset.reset": "earliest",
            "enable.auto.commit": False,
        }
    )
    consumer.subscribe(["orders"])
    idle = 0
    try:
        while idle < 10:
            msg = consumer.poll(1.0)
            if msg is None:
                idle += 1
                continue
            if msg.error():
                print("error:", msg.error())
                continue
            idle = 0
            order = json.loads(msg.value())
            print(
                f"partition {msg.partition()} offset {msg.offset()}: "
                f"{order['customer']} ordered {order['qty']} x {order['item']}"
            )
            consumer.commit(message=msg, asynchronous=False)
    finally:
        consumer.close()
    
  5. 5 Run the consumer twice

    The first run prints all six orders. The second prints nothing, because the group committed its position: it only reads what is new.

    Run this on your lab server
    python consumer.py
    python consumer.py
    You should see:

    Six order lines from the first run, then nothing from the second.

  6. 6 Ask AI to review your producer, then test one claim

    Ask your AI assistant what happens to undelivered orders if you remove producer.flush(10). Then test it: comment out the flush lines, run the producer, and count the sent lines. Put the flush back afterwards.

    Run this on your lab server
    python producer.py | grep -c sent
    You should see:

    Without flush, the script can exit before delivery reports arrive, so you may see fewer than 6.

  7. 7 Commit and push

    Save your code to GitHub.

    Run this on your lab server
    git add .gitignore requirements.txt producer.py consumer.py
    git commit -m "Add Python order producer and consumer"
    git push

You are done when

  • The producer reports a partition and offset for all six orders.

  • The consumer prints the orders once, then nothing on a second run.

  • You can explain what acks=all and flush() protect against.

Finished? Get your proof page

We check your public GitHub repository and give you a page to share with recruiters, and can add the project to your resume.

Join PleinIQ Updates

What are you interested in?

Read how we handle your information in our privacy notice.