Skip to content

Event Sourcing

Event Sourcing sits at the heart of event-driven patterns in Apache Kafka. This guide walks through the concept step by step, with examples, a cheatsheet, and common mistakes to avoid.

Event Sourcing Overview

At its core, event sourcing is about doing one thing well inside your Apache Kafka project. Once you understand the pattern, you can apply it consistently across features and teams.

Good event sourcing pays off across the whole codebase: fewer surprises, easier testing, and smoother onboarding. The snippet below is a solid starting point.

// each service reacts to events and emits new ones
await consumer.subscribe({ topic: 'payment-completed' });
await consumer.run({
  eachMessage: async ({ message }) => {
    const payment = JSON.parse(message.value.toString());
    await producer.send({
      topic: 'order-confirmed',
      messages: [{ key: payment.orderId, value: JSON.stringify(payment) }],
    });
  },
});

Event-driven services stay decoupled by reacting to and emitting Kafka events.

Event Sourcing Example

import { Kafka } from 'kafkajs';

const kafka = new Kafka({ clientId: 'app', brokers: ['localhost:9092'] });
const producer = kafka.producer();
const consumer = kafka.consumer({ groupId: 'group' });
  • Start from a minimal Event Sourcing example and grow it only as needed.
  • Keep configuration explicit so Event Sourcing behaves the same in every environment.
  • Name things clearly so teammates understand your Event Sourcing at a glance.
  • Add tests around Event Sourcing early to lock in expected behaviour.

Apache Kafka Cheatsheet

Handy KafkaJS reference related to event sourcing.

Task Example Purpose
Create client new Kafka({ clientId, brokers }) Connect to the cluster
Produce producer.send({ topic, messages }) Publish events
Consume consumer.run({ eachMessage }) Process events
Subscribe consumer.subscribe({ topic }) Choose topics to read
Group kafka.consumer({ groupId }) Scale consumers
Admin admin.createTopics(...) Manage topics
Commit offset auto-commit or commitOffsets Track progress

How Event Sourcing Works in Apache Kafka

Event Sourcing builds on Kafka's log-based design, where producers append events to partitioned topics and consumer groups read them independently, tracking their own offsets.

Event-driven services stay decoupled by reacting to and emitting Kafka events.

  • Topics are split into partitions for parallelism and ordering per key.
  • Producers choose a partition, usually by message key.
  • Consumer groups share partitions so work scales horizontally.
  • Offsets record how far each group has read.

Practical Guidance for Event Sourcing

In production, event sourcing needs attention to delivery guarantees, retries, and observability. Make handlers idempotent and monitor consumer lag closely.

Concern Recommendation
Ordering Key related events so they land on one partition
Reliability Use acks=all and idempotent producers
Idempotency Handle duplicate deliveries safely
Monitoring Track consumer lag and error rates

Common Mistakes

  • Skipping error handling and edge cases when wiring up event sourcing.
  • Leaving event sourcing untested, so regressions slip into production.
  • Over-engineering event sourcing before you actually need the extra flexibility.
  • Ignoring documentation, which makes event sourcing hard for the next developer to change.

Key Takeaways

  • Event Sourcing is a core part of working effectively with Apache Kafka.
  • Start small and keep event sourcing focused on a single responsibility.
  • Apply consistent patterns so event sourcing scales across your project.
  • Test and document event sourcing to keep it maintainable over time.

Pro Tip

Bookmark this event sourcing pattern and reuse it. Consistency across your Apache Kafka codebase is worth more than clever one-off solutions.