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.
Python code
50 linesimport 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
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
- Use `random.Random(seed)` for deterministic partition assignment in tests
- 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
More from Streaming & messaging
- At Most Once Fire-and-Forget Mock in Python easy
- Batch Consume Process Commit Pattern in Python medium
- Build a Streaming Messaging Helper in Python easy
- Dead Letter Queue Failed Messages List Mock in Python easy
- Dedupe processed message IDs in Python easy
- Event Envelope with Schema Version Field in Python easy
Keep learning
Related tutorials and quizzes for this topic.