Bird
Raised Fist0
Kafkadevops~10 mins

Event sourcing pattern in Kafka - Step-by-Step Execution

Choose your learning style10 modes available
Process Flow - Event sourcing pattern
Command Received
↓
Create Event
↓
Append Event to Kafka Topic
↓
Event Stored
↓
Update State by Replaying Events
↓
Respond to Query or Next Command
The event sourcing pattern stores all changes as events in Kafka, then rebuilds state by replaying these events.
Execution Sample
Kafka
producer.send('orders', orderCreatedEvent)
consumer.subscribe(['orders'])
for event in consumer:
    state.apply(event)
    print(state)
This code sends an event to Kafka and a consumer reads events to update the state.
Process Table
StepActionEvent ProducedKafka Topic StateState After EventOutput
1Receive new order commandorderCreatedEvent[]{}No output
2Produce event to KafkaorderCreatedEvent[orderCreatedEvent]{}No output
3Consumer reads orderCreatedEventorderCreatedEvent[orderCreatedEvent]{}No output
4Apply event to stateorderCreatedEvent[orderCreatedEvent]{orderId: 123, status: 'created'}{orderId: 123, status: 'created'}
5Print updated stateorderCreatedEvent[orderCreatedEvent]{orderId: 123, status: 'created'}{orderId: 123, status: 'created'}
6Receive update commandorderUpdatedEvent[orderCreatedEvent]{orderId: 123, status: 'created'}No output
7Produce update eventorderUpdatedEvent[orderCreatedEvent, orderUpdatedEvent]{orderId: 123, status: 'created'}No output
8Consumer reads orderUpdatedEventorderUpdatedEvent[orderCreatedEvent, orderUpdatedEvent]{orderId: 123, status: 'created'}No output
9Apply update event to stateorderUpdatedEvent[orderCreatedEvent, orderUpdatedEvent]{orderId: 123, status: 'shipped'}{orderId: 123, status: 'shipped'}
10Print updated stateorderUpdatedEvent[orderCreatedEvent, orderUpdatedEvent]{orderId: 123, status: 'shipped'}{orderId: 123, status: 'shipped'}
11No more events-[orderCreatedEvent, orderUpdatedEvent]{orderId: 123, status: 'shipped'}Stop processing
💡 No more events to process, state fully updated
Status Tracker
VariableStartAfter 1After 2After 3After 4Final
Kafka Topic[][orderCreatedEvent][orderCreatedEvent][orderCreatedEvent, orderUpdatedEvent][orderCreatedEvent, orderUpdatedEvent][orderCreatedEvent, orderUpdatedEvent]
State{}{}{orderId: 123, status: 'created'}{orderId: 123, status: 'created'}{orderId: 123, status: 'shipped'}{orderId: 123, status: 'shipped'}
Key Moments - 3 Insights
Why do we store events instead of just the final state?
Because the execution_table shows events are appended to Kafka and state is rebuilt by applying each event, storing events lets us track all changes and rebuild state anytime.
How does the state get updated after producing an event?
The consumer reads the event from Kafka (see steps 3 and 8) and applies it to the state, updating it step-by-step.
What happens if the consumer crashes and restarts?
It can replay all events from Kafka topic (the full event list in variable_tracker) to rebuild the current state exactly as before.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 4, what is the state after applying the first event?
A{orderId: 123, status: 'created'}
B{}
C{orderId: 123, status: 'shipped'}
D[]
💡 Hint
Check the 'State After Event' column at step 4 in execution_table
At which step does the Kafka topic contain two events?
AStep 2
BStep 4
CStep 7
DStep 10
💡 Hint
Look at the 'Kafka Topic State' column to see when two events are present
If the consumer did not apply events, what would the state be at the end?
A{orderId: 123, status: 'shipped'}
B{}
C{orderId: 123, status: 'created'}
D[]
💡 Hint
Refer to variable_tracker for 'State' variable changes after applying events
Concept Snapshot
Event sourcing stores all changes as events in Kafka.
Commands produce events appended to Kafka topics.
Consumers read events and update state by replaying them.
State is rebuilt from event history, not stored directly.
This allows full audit and recovery by replaying events.
Full Transcript
Event sourcing pattern means every change is saved as an event in Kafka. When a command comes, it creates an event and sends it to Kafka. The event is stored in a Kafka topic. A consumer reads these events one by one and updates the application state by applying each event. This way, the current state is always rebuilt from the list of events. If the consumer stops, it can restart and replay all events to get the same state. This pattern helps keep a full history and makes recovery easy.

Practice

(1/5)
1. What is the main purpose of the event sourcing pattern in Kafka?
easy
A. To save every change as an event for a full history
B. To delete old data to save storage space
C. To process only the latest state without history
D. To send events only to one consumer

Solution

  1. Step 1: Understand event sourcing concept

    Event sourcing means saving every change as a separate event instead of just the current state.
  2. Step 2: Relate to Kafka usage

    Kafka topics store these events so consumers can read the full history and rebuild state if needed.
  3. Final Answer:

    To save every change as an event for a full history -> Option A
  4. Quick Check:

    Event sourcing = full history saved as events [OK]
Hint: Event sourcing always stores all changes, not just current state [OK]
Common Mistakes:
  • Thinking event sourcing deletes old data
  • Believing it only keeps latest state
  • Assuming events go to only one consumer
2. Which Kafka component is primarily used to store events in event sourcing?
easy
A. Kafka Topic
B. Kafka Producer
C. Kafka Consumer
D. Kafka Broker

Solution

  1. Step 1: Identify Kafka components roles

    Kafka Producer sends data, Consumer reads data, Broker manages servers, Topic stores data.
  2. Step 2: Match storage role

    Events are stored in Kafka Topics, which keep the event log for consumers.
  3. Final Answer:

    Kafka Topic -> Option A
  4. Quick Check:

    Events stored in Kafka Topic [OK]
Hint: Events are stored in topics, not producers or consumers [OK]
Common Mistakes:
  • Confusing producer with storage
  • Thinking consumer stores events
  • Mixing broker with event storage
3. Given this Kafka event stream, what will the consumer state be after processing all events?
events = [
  {"type": "create", "id": 1, "value": 10},
  {"type": "update", "id": 1, "value": 20},
  {"type": "create", "id": 2, "value": 5},
  {"type": "delete", "id": 1}
]

state = {}
for event in events:
    if event["type"] == "create" or event["type"] == "update":
        state[event["id"]] = event["value"]
    elif event["type"] == "delete":
        state.pop(event["id"], None)

print(state)
medium
A. {}
B. {"1": 20, "2": 5}
C. {"1": 10, "2": 5}
D. {"2": 5}

Solution

  1. Step 1: Process each event in order

    First create id 1 with value 10, then update id 1 to 20, create id 2 with 5, then delete id 1.
  2. Step 2: Determine final state

    After deletion, id 1 is removed, only id 2 with value 5 remains.
  3. Final Answer:

    {"2": 5} -> Option D
  4. Quick Check:

    Delete removes id 1, only id 2 left [OK]
Hint: Track events step-by-step to update state correctly [OK]
Common Mistakes:
  • Forgetting the delete event removes id 1
  • Confusing update with create
  • Assuming old values remain after update
4. Identify the bug in this Kafka event consumer code snippet for event sourcing:
state = {}
for event in events:
    if event["type"] == "create":
        state[event["id"]] = event["value"]
    elif event["type"] == "update":
        if event["id"] in state:
            state[event["id"]] = event["value"]
    elif event["type"] == "delete":
        del state[event["id"]]
medium
A. Missing else clause for unknown event types
B. Using del without checking if id exists causes KeyError
C. Create should not overwrite existing id
D. Update should create new id if not present

Solution

  1. Step 1: Analyze delete operation

    Using del without checking if the key exists can cause a KeyError if id is missing.
  2. Step 2: Check other conditions

    Update correctly checks if id exists before updating; create overwrites which is allowed; else clause is optional.
  3. Final Answer:

    Using del without checking if id exists causes KeyError -> Option B
  4. Quick Check:

    del without check = KeyError risk [OK]
Hint: Always check key exists before deleting from dict [OK]
Common Mistakes:
  • Ignoring KeyError on delete
  • Thinking update must create new id
  • Believing create cannot overwrite
5. You want to rebuild the current state from a Kafka topic storing events using event sourcing. Which approach is best to handle a large number of events efficiently?
hard
A. Read all events from the beginning every time to rebuild state
B. Only read the latest event for each entity from the topic
C. Use snapshots periodically and then replay only recent events
D. Delete old events from the topic to reduce size

Solution

  1. Step 1: Understand rebuilding state from events

    Replaying all events from the start is slow for large data; deleting events loses history.
  2. Step 2: Use snapshots to optimize

    Snapshots save a recent state, so only new events after snapshot need replay, improving efficiency.
  3. Final Answer:

    Use snapshots periodically and then replay only recent events -> Option C
  4. Quick Check:

    Snapshots + replay recent events = efficient rebuild [OK]
Hint: Snapshots speed up rebuilding by avoiding full replay [OK]
Common Mistakes:
  • Replaying all events every time (slow)
  • Deleting events loses full history
  • Reading only latest event misses changes
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard