Published Dec 4, 2026 ⦁ 14 min read
HiveMQ and Kafka: IoT Pipeline Portfolio Project

HiveMQ and Kafka: IoT Pipeline Portfolio Project

An MQTT acknowledgment doesn’t prove a sensor reading reached Kafka. This project builds a Python → HiveMQ → Kafka → validation pipeline and checks delivery against a saved event list. The starting target is 3,000 readings: 10 devices publishing once per second for 5 minutes.

The project covers:

  • Local setup: Docker Compose, pinned versions, Kafka topics, and a licensed HiveMQ edition that supports the Kafka extension.
  • Message checks: JSON validation, UTC timestamps, Celsius temperatures, routing keys, missing events, and duplicates.
  • Load and recovery tests: Measured throughput, p50/p95 latency, consumer lag, and behavior during HiveMQ and Kafka outages.
  • Portfolio evidence: Source code, run logs, setup commands, and a README that separates local test results from production assumptions.

The goal is a pipeline with delivery records that can be checked - not just containers that start. MQTT QoS 1 can produce duplicates, and a single-broker stack does not prove high availability.

HiveMQ to Kafka: IoT Delivery Verification Pipeline

HiveMQ to Kafka: IoT Delivery Verification Pipeline

2. Deploy HiveMQ and Kafka Locally

HiveMQ

Repository Files and Docker Compose

Docker Compose

Keep infrastructure, HiveMQ configuration, application code, tests, and documentation separate for the sensors → HiveMQ → Kafka → validator flow. Commit .env.example with non-secret defaults. Keep .env, secrets/, certificates, and generated data out of Git.

Pin every version: the HiveMQ image, Kafka image, Python dependencies, and extension. Don’t use latest. Add a setup table to README.md with the exact image tags and extension version. This layout turns the architecture from the previous section into a local stack you can run.

iot-pipeline/
├── docker-compose.yml
├── .env.example
├── README.md
├── hivemq/
│   ├── conf/
│   └── extensions/
│       └── hivemq-kafka-extension/
│           ├── conf/config.xml
│           └── DISABLED
├── kafka/
│   └── server.properties
├── scripts/
│   ├── create-topic.sh
│   ├── consume.sh
│   └── verify-stack.sh
├── simulator/
│   ├── sensor_simulator.py
│   └── requirements.txt
└── load-tests/
    ├── baseline.yaml
    └── outage-test.sh

The sample docker-compose.yml below keeps the setup local and reproducible. Check environment variable names against your selected image’s docs; names vary by image.

services:
  kafka:
    image: apache/kafka:4.2.2
    ports:
      - "127.0.0.1:9092:9092"
    environment:
      KAFKA_NODE_ID: 1
      KAFKA_PROCESS_ROLES: broker,controller
      KAFKA_CONTROLLER_QUORUM_VOTERS: 1@kafka:9093
      KAFKA_LISTENERS: INTERNAL://0.0.0.0:19092,EXTERNAL://0.0.0.0:9092,CONTROLLER://0.0.0.0:9093
      KAFKA_ADVERTISED_LISTENERS: INTERNAL://kafka:19092,EXTERNAL://localhost:9092
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: INTERNAL:PLAINTEXT,EXTERNAL:PLAINTEXT,CONTROLLER:PLAINTEXT
      KAFKA_INTER_BROKER_LISTENER_NAME: INTERNAL
      KAFKA_CONTROLLER_LISTENER_NAMES: CONTROLLER
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
    volumes:
      - kafka-data:/var/lib/kafka/data
    healthcheck:
      test: ["CMD-SHELL", "kafka-topics.sh --bootstrap-server localhost:9092 --list >/dev/null 2>&1"]
      interval: 10s
      timeout: 5s
      retries: 12

  hivemq:
    image: hivemq/hivemq-ce:2024.3
    ports:
      - "127.0.0.1:1883:1883"
      - "127.0.0.1:8080:8080"
    volumes:
      - ./hivemq/extensions:/opt/hivemq/extensions
    depends_on:
      kafka:
        condition: service_healthy

volumes:
  kafka-data:

This is a demo stack, not a production setup. It uses one broker and plaintext connections, with no high availability, TLS, authentication, or replication.

Install the Kafka Extension and Set Message Routing

Extract the complete extension distribution, including its JAR files, into hivemq/extensions/hivemq-kafka-extension/. Leave DISABLED in place while editing conf/config.xml. Remove it only when the configuration is complete.

The mapping below sends sensors/+/telemetry messages to iot-telemetry. It keeps the MQTT topic as the Kafka key and the payload as the Kafka value. Before publishing the project, check the exact key and value element names against your selected extension release.

<kafka-configuration>
  <kafka-clusters>
    <kafka-cluster>
      <id>local-kafka</id>
      <bootstrap-servers>kafka:19092</bootstrap-servers>
    </kafka-cluster>
  </kafka-clusters>

  <mqtt-to-kafka-mappings>
    <mqtt-to-kafka-mapping>
      <id>sensors-telemetry</id>
      <cluster-id>local-kafka</cluster-id>
      <mqtt-topic-filters>
        <mqtt-topic-filter>sensors/+/telemetry</mqtt-topic-filter>
      </mqtt-topic-filters>
      <kafka-topic>iot-telemetry</kafka-topic>
      <kafka-key>${MQTT_TOPIC}</kafka-key>
      <kafka-value>${MQTT_PAYLOAD}</kafka-value>
    </mqtt-to-kafka-mapping>
  </mqtt-to-kafka-mappings>
</kafka-configuration>

Configure Kafka Listeners and Create the Topic

Inside Docker, HiveMQ connects through kafka:19092. Host tools use localhost:9092 after bootstrap. Start the stack, check service health, and create the destination topic explicitly.

cp .env.example .env
docker compose pull
docker compose config
docker compose up -d
docker compose ps
docker compose logs --tail=100 kafka
docker compose logs --tail=100 hivemq

docker compose exec kafka kafka-topics.sh \
  --bootstrap-server localhost:9092 \
  --create \
  --if-not-exists \
  --topic iot-telemetry \
  --partitions 3 \
  --replication-factor 1

docker compose exec kafka kafka-topics.sh \
  --bootstrap-server localhost:9092 \
  --describe \
  --topic iot-telemetry

rm hivemq/extensions/hivemq-kafka-extension/DISABLED
docker compose restart hivemq
docker compose logs --tail=100 hivemq

# Leave this running, then publish JSON to `sensors/device-007/telemetry`.
docker compose exec kafka kafka-console-consumer.sh \
  --bootstrap-server localhost:9092 \
  --topic iot-telemetry \
  --from-beginning \
  --property print.key=true

Leave the consumer running. The next section publishes sensor JSON to this topic and checks delivery.

Use Kafka’s health check to verify the broker, then send one MQTT publish to check HiveMQ. Add client timeouts, reconnects, and retry backoff. Three partitions demonstrate consumer parallelism, but replication factor 1 means there’s no broker redundancy. Production requires multiple brokers, replication, TLS, authenticated access, least-privilege permissions, managed secrets, monitoring, and recovery testing.

Document cleanup commands in the README: docker compose down preserves named volumes, while docker compose down -v deletes local broker data and must be labeled as a destructive reset. Keep this stack running for the sensor messages and load tests in the next section.

3. Create and Validate Sensor Messages

Define the Schema and Build the Simulator

Turn the architecture into sensor events you can test, with an audit trail you can check later.

Save the schema below as simulator/schema.json. It requires UTC timestamps, an event_id for deduplication, and explicit temperature and humidity fields. Location metadata stays optional. These test payloads pass through HiveMQ into Kafka and use Celsius, as defined in the pipeline architecture.

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "additionalProperties": false,
  "required": ["device_id", "event_id", "event_ts", "temperature_c", "humidity_pct"],
  "properties": {
    "device_id": {"type": "string", "minLength": 1},
    "event_id": {"type": "string", "minLength": 1},
    "event_ts": {
      "type": "string",
      "format": "date-time",
      "pattern": "Z$"
    },
    "temperature_c": {"type": "number", "minimum": -40, "maximum": 85},
    "humidity_pct": {"type": "number", "minimum": 0, "maximum": 100},
    "location": {
      "type": "object",
      "additionalProperties": false,
      "properties": {
        "site": {"type": "string"},
        "latitude": {"type": "number", "minimum": -90, "maximum": 90},
        "longitude": {"type": "number", "minimum": -180, "maximum": 180}
      }
    }
  }
}

Install the clients below, then save the publisher as simulator/sensor_simulator.py. It writes each event to a JSON Lines manifest for later comparison. Paho’s network loop handles callbacks and reconnects. The publish callback confirms only the MQTT exchange - not Kafka delivery.

python -m venv .venv
source .venv/bin/activate
pip install paho-mqtt==2.1.0 confluent-kafka==2.6.1 jsonschema==4.23.0
pip freeze > simulator/requirements.txt
import argparse
import json
import random
import signal
import threading
import time
import uuid
from datetime import datetime, timezone

import paho.mqtt.client as mqtt

p = argparse.ArgumentParser()
p.add_argument("--broker", default="localhost")
p.add_argument("--port", type=int, default=1883)
p.add_argument("--devices", type=int, default=1)
p.add_argument("--interval", type=float, default=1)
p.add_argument("--qos", type=int, choices=[0, 1, 2], default=1)
p.add_argument("--duration", type=float, default=10)
p.add_argument("--manifest", default="generated-events.jsonl")
a = p.parse_args()
if min(a.devices, a.interval, a.duration) <= 0:
    p.error("devices, interval, and duration must be positive")

stop = threading.Event()
connected = threading.Event()
for sig in (signal.SIGINT, signal.SIGTERM):
    signal.signal(sig, lambda *_: stop.set())

def log(**fields):
    print(json.dumps(fields), flush=True)

def on_connect(client, userdata, flags, reason, properties):
    log(event="connect", reason=str(reason))
    if not reason.is_failure:
        connected.set()

def on_disconnect(client, userdata, flags, reason, properties):
    connected.clear()
    log(event="disconnect", reason=str(reason))

def on_publish(client, userdata, mid, reason, properties):
    log(event="mqtt_confirmation", mid=mid, qos=a.qos, reason=str(reason))

client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
client.on_connect = on_connect
client.on_disconnect = on_disconnect
client.on_publish = on_publish
client.reconnect_delay_set(min_delay=1, max_delay=16)
client.connect_async(a.broker, a.port)
client.loop_start()
pending = []
deadline = time.monotonic() + a.duration

try:
    with open(a.manifest, "w", buffering=1) as manifest:
        while not stop.is_set() and time.monotonic() < deadline:
            if not connected.wait(timeout=0.2):
                continue
            for n in range(1, a.devices + 1):
                if stop.is_set():
                    break
                device = f"sensor-{n:03d}"
                payload = {
                    "device_id": device,
                    "event_id": str(uuid.uuid4()),
                    "event_ts": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
                    "temperature_c": round(random.uniform(18.3, 29.4), 1),
                    "humidity_pct": round(random.uniform(30, 65), 1)
                }
                topic = f"sensors/{device}/telemetry"
                manifest.write(json.dumps({"topic": topic, "payload": payload}) + "\n")
                info = client.publish(topic, json.dumps(payload), qos=a.qos)
                pending.append(info)
                log(event="publish_attempt", event_id=payload["event_id"],
                    device_id=device, mid=info.mid, rc=int(info.rc))
            stop.wait(a.interval)
finally:
    drain_deadline = time.monotonic() + 10
    for info in pending:
        if info.rc == mqtt.MQTT_ERR_SUCCESS:
            info.wait_for_publish(timeout=max(0, drain_deadline - time.monotonic()))
    client.disconnect()
    client.loop_stop()

Consume Records and Check Delivery

Save the validator below as simulator/validate.py. It checks JSON, schema compliance, UTC timestamps, a 60-second future tolerance, and the topic-derived device key. It then compares accepted event IDs with the manifest and logs each record’s partition and offset. That comparison lets you verify which published events reached Kafka.

Use a new topic or isolated test data to avoid stale records. Set the observation window longer than the publish run so forwarding has time to finish.

import argparse
import json
import time
from collections import Counter
from datetime import datetime, timezone
from pathlib import Path

from confluent_kafka import Consumer
from jsonschema import Draft202012Validator, FormatChecker

p = argparse.ArgumentParser()
p.add_argument("--bootstrap", default="localhost:9092")
p.add_argument("--topic", default="iot-telemetry")
p.add_argument("--group", required=True)
p.add_argument("--manifest", required=True)
p.add_argument("--seconds", type=int, default=45)
a = p.parse_args()

schema = json.loads(Path(__file__).with_name("schema.json").read_text())
validator = Draft202012Validator(schema, format_checker=FormatChecker())
consumer = Consumer({
    "bootstrap.servers": a.bootstrap,
    "group.id": a.group,
    "auto.offset.reset": "earliest",
    "enable.auto.commit": False
})
consumer.subscribe([a.topic])
seen = Counter()
invalid = 0
deadline = time.monotonic() + a.seconds

try:
    while time.monotonic() < deadline:
        record = consumer.poll(0.5)
        if record is None:
            continue
        if record.error():
            raise RuntimeError(str(record.error()))
        result = {
            "partition": record.partition(), "offset": record.offset(),
            "received_at": datetime.now(timezone.utc).isoformat()
        }
        try:
            value = json.loads(record.value().decode("utf-8"))
            validator.validate(value)
            timestamp = datetime.fromisoformat(value["event_ts"].replace("Z", "+00:00"))
            if (timestamp - datetime.now(timezone.utc)).total_seconds() > 60:
                raise ValueError("timestamp more than 60 seconds in the future")
            key = record.key().decode("utf-8") if record.key() else ""
            if key != f'sensors/{value["device_id"]}/telemetry':
                raise ValueError("key does not match device_id")
            seen[value["event_id"]] += 1
            result.update(status="valid", key=key, device_id=value["device_id"],
                          event_id=value["event_id"])
        except Exception as exc:
            invalid += 1
            result.update(status="invalid", error=str(exc))
        print(json.dumps(result), flush=True)
        consumer.commit(message=record, asynchronous=False)
finally:
    consumer.close()

with open(a.manifest) as manifest:
    expected = {json.loads(line)["payload"]["event_id"] for line in manifest}
missing = expected - seen.keys()
unexpected = seen.keys() - expected
duplicates = {key: count for key, count in seen.items() if count > 1}
print(json.dumps({
    "generated": len(expected), "valid_kafka_records": sum(seen.values()),
    "missing": len(missing), "unexpected": len(unexpected),
    "duplicates": sum(count - 1 for count in duplicates.values()),
    "invalid": invalid,
    "examples": {
        "missing": sorted(missing)[:5], "unexpected": sorted(unexpected)[:5],
        "duplicates": dict(list(duplicates.items())[:5])
    }
}), flush=True)
raise SystemExit(bool(missing or unexpected or duplicates or invalid))

Once the destination topic and extension are ready, start the validator first, then publish one sensor. Repeat with --devices 3 --duration 60, a separate manifest, a new group, and --seconds 90. Check the summary rather than expecting an exact generated count: scheduling and connection delays affect the total. For more insights on building robust data pipelines, join the DataExpert.io Newsletter community.

MQTT QoS alone does not guarantee Kafka receipt. This validator commits after inspecting each record, including rejected records, so keep its saved logs as the audit trail. The earliest setting applies only when the group has no committed offset yet.

# Terminal 1
python simulator/validate.py \
  --group sensor-validator-one \
  --manifest one.jsonl --seconds 45 > one-validation.jsonl

# Terminal 2
python simulator/sensor_simulator.py \
  --devices 1 --interval 1 --duration 10 --qos 1 \
  --manifest one.jsonl > one-publish.jsonl

Use the validation output to help locate failures in MQTT delivery, HiveMQ routing, or Kafka consumption.

Inspect Metrics and Troubleshoot Failures

Start with the saved validation logs. If counts don’t match, check broker and consumer state with the commands below. They show record placement and group progress. Zero lag means the consumer reached the partition heads - not that every payload passed validation.

For missing records, trace the manifest ID through publish logs, HiveMQ logs, and Kafka output. Check filter matching (+ matches one level; # matches a multi-level suffix), extension compatibility, destination spelling, and startup errors. If connections fail, check host versus container addresses. For TLS or authentication errors, check protocols, trust settings, and credentials.

A quiet consumer may already have committed its offsets. Reset offsets only while its group is inactive, and expect replay to produce apparent duplicates. Use HiveMQ Control Center or extension metrics only if the installed edition supports them.

docker compose logs --tail=100 hivemq

docker compose exec kafka kafka-console-consumer.sh \
  --bootstrap-server localhost:9092 --topic iot-telemetry \
  --from-beginning --timeout-ms 10000 \
  --property print.key=true --property print.partition=true \
  --property print.offset=true

docker compose exec kafka kafka-consumer-groups.sh \
  --bootstrap-server localhost:9092 \
  --group sensor-validator-one --describe

# Topic description helps show partition count and replication settings.
docker compose exec kafka kafka-topics.sh \
  --bootstrap-server localhost:9092 \
  --describe --topic iot-telemetry

# Intentional replay.
docker compose exec kafka kafka-consumer-groups.sh \
  --bootstrap-server localhost:9092 --group sensor-validator-one \
  --reset-offsets --to-earliest --topic iot-telemetry --execute

4. Test Throughput and Outage Recovery

Run Baseline, Sustained, and Outage Tests

Make device count, message rate, payload size, QoS, and duration configurable so you can repeat each benchmark on the same hardware. Test a one-device baseline, multi-device scale, a longer sustained workload, a HiveMQ outage, and a Kafka outage. Keep the simulator, validator, and topic path the same. Only change the workload profile.

Treat the presets below as placeholders until you measure them on the target system. For each run, record the run ID, timestamps, workload settings, event counts, MQTT successes and failures, reconnects, simulator errors, Kafka records, duplicates, missing IDs, drain time, and CPU and memory use for each component. Also record producer retries, buffer exhaustion, and available buffer memory.

Use these run names in your logs and portfolio notes.

Run Devices Publish rate Payload QoS Duration Observed throughput p50 / p95 latency Peak lag Result
baseline-001 1 1 msg/s 256 bytes 1 5 min To measure To measure To measure pass or fail
scale-001 25 100 msg/s aggregate 512 bytes 1 15 min To measure To measure To measure pass or fail
sustained-001 50 100 msg/s aggregate 512 bytes 1 30 min To measure To measure To measure pass or fail
hivemq-outage-001 25 100 msg/s aggregate 512 bytes 1 outage plus drain To measure To measure To measure pass or fail
kafka-outage-001 25 100 msg/s aggregate 512 bytes 1 outage plus drain To measure To measure To measure pass or fail

Stop HiveMQ or Kafka while publishing continues. Then restart the service and measure recovery.

# Stop one service, keep publishing, then restart it.
SERVICE=hivemq # Use kafka for the downstream outage test.
docker compose stop "$SERVICE"
# Restore after the configured outage interval.
docker compose start "$SERVICE"

Document how the HiveMQ-to-Kafka extension handles messages during an outage: whether it buffers in memory or on disk, its maximum capacity, retry policy, backoff, and overflow behavior. Also note whether it acknowledges MQTT messages before or after Kafka confirms delivery.

Measure Results Against Acceptance Criteria

Set pass/fail rules before each run: every generated event ID appears exactly once after drain; every record matches the schema; Kafka keys match device IDs; no invalid records enter the primary topic; and reconnects finish within the recovery window. Document QoS 1 duplicates - don't describe QoS 1 delivery as exactly once.

Define end-to-end latency as consumer receipt time minus event creation time. Specify timestamp precision and time-zone handling. Use synchronized host clocks where possible. If all components run on one host, state that the measurements assume a shared local clock.

Report p50 and p95 latency, maximum consumer lag, and the percentage of events reconciled. Under each run ID, save the configuration, hardware, OS version, container image tags, client versions, Git commit, persistence settings, raw logs, and resource samples.

Local Limits and Production Requirements

A local restart is not high availability. A single Docker host shares CPU, memory, disk, and simplified networking. These tests don't prove replica failover or multi-broker recovery. Document volume mappings, retention, JVM limits, Docker limits, and extension buffering settings.

For production, add schema governance, quarantine or dead-letter handling, capacity planning, backpressure controls, and a replay/idempotency strategy. Test network partitions, disk pressure, consumer slowdown, extension restarts, certificate rotation, and sustained peak traffic. Use the limits and recovery notes to describe what the stack proves in your repository.

Webinar: HiveMQ + Kafka - The Ideal Solution for IoT MQTT Data Integration

5. Conclusion: Publish Your Portfolio Results

With local tests complete, report only what the saved artifacts prove about sensor-to-Kafka delivery. Label results tested locally and link performance and recovery claims to specific runs. Mark anything the local stack hasn’t proved as a production assumption.

Complete the Repository and README

Make the repository reproducible from a clean checkout. Pin versions and include the code, tests, scripts, and a results/ folder with timestamped run outputs.

In the README, connect results to run IDs and measurement windows. Document commands for startup, publishing, validation, testing, and shutdown. Clearly warn that docker compose down -v deletes persistent volumes and test data.

Help reviewers follow the pipeline at a glance. Include a simulator-to-consumer architecture diagram, plus one sanitized MQTT payload and its matching Kafka record. Show the topic, key, partition, offset, and validation result so reviewers can check them against the run artifacts. Label dashboard screenshots with run IDs and time windows.

Document the routing key used in this project - MQTT topic - why you chose it, and how it affects ordering and the partition spread observed in your runs.

Keep the portfolio warning brief: QoS 1 can duplicate messages, replication factor 1 means single-copy storage, and plaintext listeners and demo credentials aren’t for production. Add symptom-to-fix notes for missing records, incorrect keys, and rising lag. These are lab results, not production proof; leave security hardening and multi-broker testing in the production backlog.

Continue Learning with DataExpert.io Academy

DataExpert.io Academy

After publishing your portfolio, keep practicing with DataExpert.io Academy, which offers hands-on data engineering training, capstone projects, and community support.

FAQs

Which HiveMQ edition supports the Kafka extension?

The provided search results don’t say which HiveMQ edition supports the Kafka extension, so there isn’t enough information to identify the correct edition.

How can I deduplicate events without losing valid readings?

Use stable, unique identifiers and idempotent writes so processing the same ID more than once leaves the final results unchanged. Check deduplication against totals calculated independently with a reference script or spreadsheet.

Use event-time windows and allowed lateness - deduplication alone doesn’t make aggregate updates safe. Your destination sink should support transactional writes or idempotent upserts so it can safely handle duplicates replayed after failures or restarts.

How can I keep each device’s readings in order?

Publish and consume messages with a per-device key so every event from the same device reaches the same Kafka partition and gets processed in sequence.

For stream processing, use event time - not just processing time. Set allowed lateness and window rules, along with watermarks or grace periods, to account for delayed or out-of-order readings. Keyed partitioning and event-time handling work together to keep state updates and window outputs consistent.