Event Streaming and Log-Based Brokers

Kafka-style brokers that store events in an ordered, replayable log instead of deleting them once delivered.

What is it?

A traditional message queue (RabbitMQ, SQS) works like a to-do list: a consumer takes a message, processes it, acknowledges it, and the broker deletes it. Once handled, it's gone.

A log-based broker such as Apache Kafka (also Pulsar, Redpanda, Amazon Kinesis) works like an append-only ledger. Producers append events to the end of a log; the broker keeps them for a retention period; each consumer tracks its own position (offset) and reads forward. Reading doesn't delete anything, so:

- Many independent consumers can read the same events at their own pace (analytics, search indexing, notifications). - A consumer can rewind and replay history, e.g. to rebuild a database after fixing a bug. - Events within one partition keep a strict order.

The core concepts are topics (named streams), partitions (the unit of ordering and parallelism), offsets (positions in a partition), consumer groups (how consumers share work), and retention (how long events are kept).

Explain like I'm 10

A queue is a stack of letters on a desk: whoever picks one up deals with it and throws it away. A log is a newspaper archive: each day's edition is added to the end, nobody removes it, and every reader keeps their own bookmark. A new reader can even start from last month's edition.

Examples

Producer with a key, consumer in a group (kafkajs-style)

// Producer: same key → same partition → per-key ordering.
await producer.send({
  topic: "orders",
  messages: [{ key: order.customerId, value: JSON.stringify(order) }],
});

// Consumer: every instance with groupId "billing" shares the partitions.
const consumer = kafka.consumer({ groupId: "billing" });
await consumer.subscribe({ topics: ["orders"], fromBeginning: false });

await consumer.run({
  autoCommit: false,
  eachMessage: async ({ topic, partition, message }) => {
    await chargeOrderIdempotently(JSON.parse(message.value!.toString()));
    // Commit AFTER processing: a crash before this line means the message
    // is redelivered (at-least-once), never skipped.
    await consumer.commitOffsets([
      { topic, partition, offset: (BigInt(message.offset) + 1n).toString() },
    ]);
  },
});

The committed offset is the next one to read, hence +1. Committing per message is shown for clarity; real consumers usually commit in batches.

Compacted topic as a changelog

Topic: user-profiles  (cleanup.policy=compact)

Before compaction (offset: key=value)
  0: u1={name:"Ana"}
  1: u2={name:"Bo"}
  2: u1={name:"Ana P."}
  3: u3={name:"Cy"}
  4: u2=null               ← tombstone: delete u2

After compaction (latest value per key; tombstones removed later)
  2: u1={name:"Ana P."}
  3: u3={name:"Cy"}

A new service can read this topic from offset 0 to build a full,
current snapshot of profiles, then keep consuming live updates.

Offsets never change; compaction only removes records that a newer record with the same key has superseded.

How it works

Topics and partitions. A topic is split into partitions, each an ordered, append-only sequence of records stored as segment files on a broker. Producers choose a partition by hashing the record's key (Kafka's default partitioner uses murmur2), so records with the same key land in the same partition. Without a key, records are spread across partitions.

Offsets. Each record in a partition gets a sequential offset. Ordering is guaranteed only within a partition, not across a whole topic. If you need all events of an entity in order, give them the same key.

Consumer groups. Consumers with the same group id divide the partitions: each partition is read by at most one consumer in the group at a time. So a group's parallelism is capped at the number of partitions; extra consumers sit idle. Different groups each get every record independently. When consumers join or leave, the group rebalances partitions. Groups store their progress as committed offsets (in Kafka, an internal compacted topic).

Replication. Each partition has one leader and follower replicas on other brokers. Followers that are caught up form the in-sync replica set (ISR). With acks=all and min.insync.replicas=2 (replication factor 3), a write is acknowledged only after enough replicas have it, so losing one broker loses no acknowledged data.

Retention. Kafka keeps records by time (log.retention.hours defaults to 168, i.e. 7 days) or size, regardless of whether anyone consumed them. Compacted topics instead keep at least the latest record per key, making a topic a durable changelog or table snapshot. A null value is a tombstone that deletes the key after compaction.

Delivery semantics. Committing offsets after processing gives at-least-once; before processing gives at-most-once. Kafka's idempotent producer removes duplicates caused by producer retries, and transactions let a consume-transform-produce app atomically write output records and its input offsets, giving exactly-once within Kafka. Side effects outside Kafka still need idempotency.

Log vs traditional queue.

  • After consume: a log (Kafka) keeps messages until retention expires; a queue (RabbitMQ, SQS) deletes them after ack.
  • Ordering: a log orders per partition; a queue orders per queue, weakened by redelivery and parallel consumers.
  • Parallelism: a log allows up to one consumer per partition in a group; a queue lets you add consumers freely.
  • Replay: a log can seek to any offset; a queue cannot (once acked, gone).
  • Slow message: in a log it blocks its partition (head-of-line); in a queue others proceed, with per-message ack, retry and DLQ.
  • Best for: logs suit event streams, CDC, fan-out and high throughput; queues suit task/job distribution and per-message routing.
Topic "orders", 3 partitions, two consumer groups

  P0: [0][1][2][3][4][5]          group "billing"     group "analytics"
  P1: [0][1][2][3]                  consumer A ← P0     consumer X ← P0,P1,P2
  P2: [0][1][2][3][4]               consumer B ← P1
            ▲                       consumer C ← P2
     producers append to the end   (a 4th billing consumer would be idle)

  Each group tracks its own committed offset per partition:
     billing:   P0=4  P1=3  P2=5
     analytics: P0=1  P1=0  P2=2   ← lagging, but nothing is lost

Why does it exist?

Modern systems need the same events in many places: databases, caches, search indexes, warehouses, ML features, notifications. A durable, ordered, replayable log decouples producers from any number of consumers, absorbs bursts, lets new consumers backfill from history, and turns "what happened" into a source of truth that derived data can be rebuilt from. Partitioning makes it scale horizontally to millions of events per second.

When to use it

- Event-driven architectures where several services react to the same events. - Change data capture pipelines and keeping derived stores (search, caches, warehouse) in sync. - High-throughput ingest: clickstreams, logs, metrics, IoT. - Stream processing (Kafka Streams, Flink) and event sourcing, where replay and ordering per entity matter.

When not to use it

- Simple background job queues with per-message retries, delays, priorities or dead-lettering: a traditional queue (SQS, RabbitMQ) is simpler and doesn't block on one slow message. - Request/response interactions that need an immediate answer. - Small systems where running and tuning a Kafka cluster outweighs the benefit; a managed queue or pub/sub service may be enough. - When you need global ordering across all events at high throughput; a single partition gives order but no parallelism.

Common mistakes

  • Expecting ordering across a whole topic. Kafka orders only within a partition, so related events must share a key.

  • Adding more consumers than partitions and expecting more throughput; the extras sit idle. Plan partition counts for future parallelism.

  • Committing offsets before processing (or with auto-commit), so a crash silently skips messages; or committing after but processing non-idempotently, so redeliveries double-apply.

  • Increasing a topic's partition count later without realizing it changes which partition each key maps to, breaking per-key ordering for in-flight data.

  • Using a skewed key (e.g. one huge tenant) so one partition becomes a hot spot while others are idle.

Practice exercises

  1. Easy:

    Explain the difference between a topic, a partition and an offset, using a 'payments' topic as an example.

  2. Medium:

    A topic has 6 partitions and a consumer group has 4 consumers. How are partitions assigned? What happens when one consumer crashes, and when you scale to 8 consumers?

  3. Hard:

    Design a pipeline that keeps a search index in sync with a PostgreSQL orders table using CDC and Kafka. Address ordering per order, schema changes, reprocessing after an indexing bug, and how you'd handle duplicates.

Interview questions

How does a log-based broker differ from a traditional queue?

A log appends records and retains them for a configured period regardless of consumption; consumers track their own offsets and can replay. A traditional queue deletes each message once a consumer acknowledges it.

What is a partition and why does it matter?

An ordered, append-only shard of a topic. It's the unit of ordering (order is guaranteed only within a partition), of parallelism (one consumer per partition per group) and of distribution across brokers.

How do keys affect partitioning?

The producer hashes the key to pick a partition, so all records with the same key go to the same partition and stay in order. Records without keys are spread across partitions.

What is a consumer group?

A set of consumers sharing a group id that divide a topic's partitions among themselves, each partition read by exactly one member. Different groups consume independently, each receiving every record.

What happens during a consumer group rebalance?

Partitions are reassigned among the current members after a join, leave or failure. Consumers must commit progress before losing partitions; otherwise the new owner reprocesses from the last committed offset.

What is a compacted topic?

A topic whose cleanup keeps at least the latest record for each key and discards superseded ones. It acts as a durable changelog from which you can rebuild current state; a null-valued record is a tombstone that deletes the key.

How does Kafka avoid losing acknowledged writes?

Each partition is replicated; with acks=all the leader acknowledges only once all in-sync replicas have the record, and min.insync.replicas sets how many must be in sync for writes to be accepted at all.

Can Kafka provide exactly-once processing?

Within Kafka, yes: the idempotent producer removes retry duplicates and transactions atomically commit output records together with consumer offsets. Effects on external systems still need idempotency or transactional sinks.

When would you choose SQS or RabbitMQ over Kafka?

For job or task distribution where each message is handled independently and needs per-message ack, retries, delays, priorities or dead-letter queues, and where you don't need replay or strict per-key ordering. A slow message doesn't block others.

One partition's consumer lag keeps growing while others are fine. What could cause it and how do you fix it?

A hot key funnelling disproportionate traffic to one partition, or a 'poison' record that the consumer keeps failing on. Fix skew by salting or re-keying (if per-key ordering allows) or giving the hot entity a dedicated topic; for poison records, route failures to a dead-letter topic after bounded retries so the partition keeps moving.