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 6

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.

  • 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 and activate .venv in ~/kafka-streaming-lab.

Step by step

  1. 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.

    Run this on your lab server
    kafka topics --create --topic order-totals --partitions 3 --config cleanup.policy=compact
    kafka topics --describe --topic order-totals
    You should see:

    Configs: cleanup.policy=compact.

  2. 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 as totals_processor.py.

    File: totals_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. 3 Run it

    It processes every order produced so far, then stops after 10 quiet seconds.

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

    restored {} then lines such as alice total is now 2.

  4. 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.

    Run this on your lab server
    python producer.py > /dev/null
    python totals_processor.py
    You should see:

    restored {...} with the earlier totals, then higher totals.

  5. 5 Read the latest totals

    Each customer’s newest total is in the compacted topic. Before compaction runs you may also see older values.

    Run this on your lab server
    kafka console-consumer --topic order-totals --from-beginning --property print.key=true --timeout-ms 5000
    You should see:

    Lines such as alice 4.

  6. 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.

    File: 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. 7 Commit and push

    Save your work.

    Run this on your lab server
    git add totals_processor.py notes
    git commit -m "Add live order totals processor"
    git push

You are done when

  • order-totals is 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.

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.