All sheets / Architecture
Event-Driven & Kafka
Event-driven architecture concepts and Apache Kafka essentials.
Event types
| Type | Carries | Example |
|---|---|---|
| Event notification | "something happened" + id | OrderPlaced { orderId } |
| Event-carried state transfer | full state | OrderPlaced { order... } |
| Domain event | business fact, past tense | PaymentCaptured |
| Command | request to do something | ChargeCard (one handler) |
Events are immutable facts; name them in past tense.
Delivery semantics
- At-most-once: may lose, never duplicates.
- At-least-once: never loses, may duplicate → consumers must be idempotent.
- Exactly-once: Kafka transactions + idempotent producer within Kafka; end-to-end still needs idempotent sinks.
Kafka architecture
- Topic split into partitions (ordered, append-only logs). Ordering is per partition.
- Message key → partition (hash). Same key, same partition, ordered.
- Brokers store partitions; replication factor (3 typical); leader + followers; ISR = in-sync replicas.
- Consumer group: each partition consumed by one member of the group; max parallelism = partition count.
- Offsets committed per group/partition; consumers can rewind and replay.
- KRaft replaces ZooKeeper for metadata (Kafka 3.x+).
Producer & consumer config
| Setting | Meaning |
|---|---|
acks=all | wait for all ISR (durability) |
enable.idempotence=true | no duplicates on producer retry |
min.insync.replicas=2 | with RF=3 tolerates 1 broker down |
linger.ms, batch.size, compression.type | throughput tuning |
enable.auto.commit=false | commit after processing (at-least-once) |
auto.offset.reset | earliest / latest for new groups |
max.poll.interval.ms | exceeded → rebalance |
Node (kafkajs)
const kafka = new Kafka({ clientId: 'orders', brokers: ['b1:9092'] });
const producer = kafka.producer({ idempotent: true });
await producer.send({ topic: 'orders', messages: [{ key: orderId, value: JSON.stringify(evt) }] });
const consumer = kafka.consumer({ groupId: 'billing' });
await consumer.subscribe({ topic: 'orders', fromBeginning: false });
await consumer.run({ eachMessage: async ({ message }) => handle(JSON.parse(message.value)) });Kafka vs SQS vs EventBridge
| Kafka / MSK | SQS | EventBridge | |
|---|---|---|---|
| Model | log, replayable | queue, deleted on ack | router/bus |
| Ordering | per partition | FIFO per group | none guaranteed |
| Consumers | many groups, independent | competing consumers | many rules/targets |
| Retention | configurable, long | ≤ 14 days | archive & replay |
| Ops | heavy (MSK eases) | none | none |
Patterns
- Event sourcing: store events as source of truth; rebuild state by replay; snapshots for speed.
- CQRS: commands update write model; events project into read models.
- Outbox: DB transaction writes outbox row; CDC (Debezium) or poller publishes.
- Saga (choreography): services react to each other's events with compensations.
- DLQ / retry topics with backoff for poison messages.
- Schema registry (Avro/Protobuf/JSON Schema) with compatibility rules (backward/forward).
Pitfalls
- Consumer lag: monitor it; scale partitions + consumers.
- Rebalance storms: long processing, low
max.poll.interval.ms. - Hot partitions from skewed keys.
- Changing partition count remaps keys → breaks ordering assumptions.
- Event versioning: add fields, don't break; include
typeandversionin envelopes.