Bird
0
0

Identify the bug in this Kafka event consumer code snippet for event sourcing:

medium📝 Debug Q14 of 15
Kafka - Event-Driven Architecture
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"]]
AMissing else clause for unknown event types
BUsing del without checking if id exists causes KeyError
CCreate should not overwrite existing id
DUpdate should create new id if not present
Step-by-Step Solution
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]
Quick Trick: 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

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kafka Quizzes