Lab 6 of 8 · Stream processing
Live order totals per customer
Build a processor that reads orders, keeps each customer’s total quantity, and publishes the latest total to a compacted topic.
- Time
- 75 minutes
- Cost
- Free.
What you learn
Stream processing turns events into live results as they arrive. You build a processor that keeps running totals per customer and publishes them to a compacted topic, the pattern behind Kafka Streams and Flink.
- Consume, transform, produce: the stream-processing loop
- Keeping state and rebuilding it after a restart
- Compacted topics: the latest value per key
- When to use Kafka Streams, Flink or plain consumers
In the AI era: AI can write a processor in minutes. The hard parts are state, restarts and duplicates. Test what happens when your processor stops halfway and starts again.
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 and activate
.venvin~/kafka-streaming-lab.
Step by step
1 Create a compacted output topic
With
cleanup.policy=compact, Kafka eventually keeps only the latest record per key: exactly what a "current total" needs.kafka topics --create --topic order-totals --partitions 3 --config cleanup.policy=compact kafka topics --describe --topic order-totalsYou should see:Configs: cleanup.policy=compact.2 Write the processor
On start it rebuilds its state from
order-totals, so a restart does not reset the totals. Then it reads new orders and publishes each customer’s new total. Save it astotals_processor.py.import json from confluent_kafka import Consumer, Producer BROKER = "localhost:9092" totals: dict[str, int] = {} # 1. Rebuild state from the latest totals. restore = Consumer({"bootstrap.servers": BROKER, "group.id": "totals-restore", "auto.offset.reset": "earliest", "enable.auto.commit": False}) restore.subscribe(["order-totals"]) idle = 0 while idle < 5: msg = restore.poll(1.0) if msg is None: idle += 1 continue if not msg.error(): totals[msg.key().decode()] = int(msg.value()) restore.close() print("restored", totals) # 2. Process new orders. producer = Producer({"bootstrap.servers": BROKER, "acks": "all", "partitioner": "murmur2_random"}) consumer = Consumer({"bootstrap.servers": BROKER, "group.id": "totals-processor", "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(): continue idle = 0 order = json.loads(msg.value()) customer = order["customer"] totals[customer] = totals.get(customer, 0) + order["qty"] producer.produce("order-totals", key=customer, value=str(totals[customer])) producer.flush(10) consumer.commit(message=msg, asynchronous=False) print(f"{customer} total is now {totals[customer]}") finally: consumer.close()3 Run it
It processes every order produced so far, then stops after 10 quiet seconds.
python totals_processor.pyYou should see:restored {}then lines such asalice total is now 2.4 Restart it and add orders
Produce six more orders and run the processor again. It restores the totals first, so they keep growing instead of starting from zero.
python producer.py > /dev/null python totals_processor.pyYou should see:restored {...}with the earlier totals, then higher totals.5 Read the latest totals
Each customer’s newest total is in the compacted topic. Before compaction runs you may also see older values.
kafka console-consumer --topic order-totals --from-beginning --property print.key=true --timeout-ms 5000You should see:Lines such as
alice 4.6 Find the duplicate risk
The processor publishes a total, then commits the order. Ask your AI assistant what happens if it crashes between those two steps, then write the answer in
notes/06-streams.md.# Stream processing - What the processor does: ... - How it survives a restart: ... - What happens if it crashes after publishing but before committing: ... - How Kafka Streams or Flink solve this (transactions, state stores): ...7 Commit and push
Save your work.
git add totals_processor.py notes git commit -m "Add live order totals processor" git push
You are done when
order-totalsis a compacted topic with a total per customer.After a restart, the totals continued from where they were.
Your notes explain the crash-between-steps duplicate risk.
We check your public GitHub repository and give you a page to share with recruiters, and can add the project to your resume.