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.
- A terminalOfficial install page ↗
/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 ↗
brew install --cask multipassCheck it worked:
multipass version
Before you start
Start your server with
multipass start kafka-laband open a shell on it.
Step by step
1 Create a Python environment
A virtual environment keeps this project’s packages separate.
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 3You should see:Successfully installed confluent-kafka-2.12.1andCreated topic orders.2 Write the producer
acks=allwaits until the broker has stored each event;enable.idempotencestops retries from creating duplicates.murmur2_randommakes the Python client place keys exactly like Kafka’s own tools. Save it asproducer.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 Run it
Every order gets a delivery report with its partition and offset.
python producer.pyYou should see:Six
sent ...lines. Both of alice’s orders go to the same partition, with increasing offsets.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 asconsumer.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 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.
python consumer.py python consumer.pyYou should see:Six order lines from the first run, then nothing from the second.
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 thesentlines. Put the flush back afterwards.python producer.py | grep -c sentYou should see:Without flush, the script can exit before delivery reports arrive, so you may see fewer than 6.
7 Commit and push
Save your code to GitHub.
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=allandflush()protect against.
We check your public GitHub repository and give you a page to share with recruiters, and can add the project to your resume.