How to Mock a Kafka Producer Batch Send in Python

Simulate a Kafka producer in Python that sends batched JSON events with mock partitions and latency for testing streaming pipelines without a real broker.

Medium Python 3.9+ Aug 9, 2026 Streaming & messaging 13 views 0 copies

Python code

50 lines
Python 3.9+
import json
import random
import time
from datetime import datetime


class MockKafkaProducer:
    def __init__(self, topic):
        self.topic = topic
        self.sent_messages = []

    def send(self, value, key=None):
        message = {
            "topic": self.topic,
            "key": key,
            "value": value,
            "timestamp": datetime.utcnow().isoformat(),
            "partition": random.randint(0, 3)
        }
        self.sent_messages.append(message)
        time.sleep(0.01)  # Simulate network latency
        return len(self.sent_messages) - 1

    def flush(self):
        print(f"Flushing {len(self.sent_messages)} messages to topic '{self.topic}'")
        for msg in self.sent_messages:
            print(f"  [partition {msg['partition']}] {msg['timestamp']}: {msg['value']}")


def main():
    producer = MockKafkaProducer("user-events")

    batch_size = 10
    events = [
        {"user_id": i, "action": random.choice(["click", "view", "purchase"]), "amount": random.randint(1, 100)}
        for i in range(1, batch_size + 1)
    ]

    batch_ids = []
    for event in events:
        batch_ids.append(producer.send(json.dumps(event), key=str(event["user_id"])))

    producer.flush()

    print(f"\nBatch of {len(batch_ids)} messages sent successfully.")
    print(f"Sample event: {events[0]}")


if __name__ == "__main__":
    main()

Output

stdout
Flushing 10 messages to topic 'user-events'
  [partition 2] 2025-01-01T12:00:00.123456: {"user_id": 1, "action": "click", "amount": 42}
  [partition 1] 2025-01-01T12:00:00.133456: {"user_id": 2, "action": "view", "amount": 87}
  [partition 0] 2025-01-01T12:00:00.143456: {"user_id": 3, "action": "purchase", "amount": 15}
  [partition 3] 2025-01-01T12:00:00.153456: {"user_id": 4, "action": "click", "amount": 64}
  [partition 2] 2025-01-01T12:00:00.163456: {"user_id": 5, "action": "view", "amount": 33}
  [partition 1] 2025-01-01T12:00:00.173456: {"user_id": 6, "action": "purchase", "amount": 99}
  [partition 0] 2025-01-01T12:00:00.183456: {"user_id": 7, "action": "click", "amount": 51}
  [partition 3] 2025-01-01T12:00:00.193456: {"user_id": 8, "action": "view", "amount": 24}
  [partition 2] 2025-01-01T12:00:00.203456: {"user_id": 9, "action": "purchase", "amount": 76}
  [partition 1] 2025-01-01T12:00:00.213456: {"user_id": 10, "action": "click", "amount": 58}

Batch of 10 messages sent successfully.
Sample event: {'user_id': 1, 'action': 'click', 'amount': 42}

How it works

The MockKafkaProducer mimics the real kafka-python client interface (send and flush) so your code stays drop-in compatible. Each call to send wraps the event with topic, key, timestamp, and a randomly assigned partition while appending it to an in-memory list. The time.sleep(0.01) simulates network latency so downstream code experiences timing similar to a real broker call. On flush, the mock prints all buffered messages, letting you verify payloads and ordering before they reach a real Kafka topic.

Common mistakes

  • Using `datetime.utcnow()` which returns naive UTC — prefer `datetime.now(timezone.utc)` for timezone-aware timestamps
  • Forgetting to call `flush()` before inspecting `sent_messages`, as Kafka batches may buffer messages
  • Making the mock too simple — missing key or partition logic that your real producer would apply

Variations

  1. Use `random.Random(seed)` for deterministic partition assignment in tests
  2. Write sent messages to a JSON file or list for later assertions instead of printing

Real-world use cases

  • Unit-testing an application's messaging layer without spinning up a real Kafka broker in CI.
  • Integration-testing event-driven microservices where producers and consumers need deterministic payloads.
  • Local development of streaming pipelines when you want to inspect message flow before deploying to Kafka.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Streaming & messaging

Related tutorials and quizzes for this topic.