InterviewTreedInterviewTreed

InterviewTreed Question Bank

Messaging & Event Streaming Interview Questions and Answers

Prepare for message queues, event-driven architecture, distributed messaging systems, Apache Kafka, asynchronous communication, and reliable event processing.

Total Questions

125

Beginner

20

Intermediate

70

Advanced

35

Beginner Questions

Foundational concepts, terminology, and core ideas.

Q1Kafka Architecture

What is Apache Kafka?

Apache Kafka is a distributed event-streaming platform that stores records in partitioned, replicated logs.

Answer

Apache Kafka is a distributed event-streaming platform that stores records in partitioned, replicated logs. Producers write records to topics and consumers read them using offsets. Kafka is useful for event pipelines, integration, replay, and stream processing, especially when many consumers need to read the same durable history.

Syntax

Producer example:
```ts
await producer.send({ topic: "orders", messages: [{ key: orderId, value: JSON.stringify(event) }] });
```
Consumer example:
```ts
await consumer.run({ eachMessage: async ({ message }) => {
  const event = JSON.parse(message.value?.toString() ?? "{}");
  await handleIdempotently(event);
} });
```
Diagram: Producer -> Topic partition -> Consumer group -> Handler -> Offset commit

Example

// KafkaJS-style example await producer.send({ topic: "orders", messages: [{ key: order.id, value: JSON.stringify({ eventId, orderId: order.id }) }] });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q2Kafka Architecture

What is a Kafka topic?

A topic is a named stream of records divided into partitions.

Answer

A topic is a named stream of records divided into partitions. Producers publish records to a topic and consumers subscribe to it. Retention policies determine how long records remain available, so a topic is not simply a queue where each read necessarily deletes a message.

Syntax

Producer example:
```ts
await producer.send({ topic: "orders", messages: [{ key: orderId, value: JSON.stringify(event) }] });
```
Consumer example:
```ts
await consumer.run({ eachMessage: async ({ message }) => {
  const event = JSON.parse(message.value?.toString() ?? "{}");
  await handleIdempotently(event);
} });
```
Diagram: Producer -> Topic partition -> Consumer group -> Handler -> Offset commit

Example

// KafkaJS-style example await producer.send({ topic: "orders", messages: [{ key: order.id, value: JSON.stringify({ eventId, orderId: order.id }) }] });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q3Kafka Architecture

What is a Kafka partition?

A partition is an ordered append-only log within a topic.

Answer

A partition is an ordered append-only log within a topic. Ordering is guaranteed within a partition, not across all partitions of a topic. Partitions allow parallelism and distribution across brokers, but choosing a partition key affects ordering, load balance, and the maximum parallelism available to a consumer group.

Syntax

Producer example:
```ts
await producer.send({ topic: "orders", messages: [{ key: orderId, value: JSON.stringify(event) }] });
```
Consumer example:
```ts
await consumer.run({ eachMessage: async ({ message }) => {
  const event = JSON.parse(message.value?.toString() ?? "{}");
  await handleIdempotently(event);
} });
```
Diagram: Producer -> Topic partition -> Consumer group -> Handler -> Offset commit

Example

// KafkaJS-style example await producer.send({ topic: "orders", messages: [{ key: order.id, value: JSON.stringify({ eventId, orderId: order.id }) }] });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q4Kafka Architecture

What is a Kafka offset?

An offset identifies a record's position within a partition.

Answer

An offset identifies a record's position within a partition. A consumer tracks offsets to resume reading after restart. Committing an offset before business processing finishes can lose work, while committing after processing can cause replay after a crash, so offset strategy must align with idempotency and the desired delivery semantics.

Syntax

Producer example:
```ts
await producer.send({ topic: "orders", messages: [{ key: orderId, value: JSON.stringify(event) }] });
```
Consumer example:
```ts
await consumer.run({ eachMessage: async ({ message }) => {
  const event = JSON.parse(message.value?.toString() ?? "{}");
  await handleIdempotently(event);
} });
```
Diagram: Producer -> Topic partition -> Consumer group -> Handler -> Offset commit

Example

// KafkaJS-style example await producer.send({ topic: "orders", messages: [{ key: order.id, value: JSON.stringify({ eventId, orderId: order.id }) }] });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q5Kafka Architecture

What is a Kafka broker?

A Kafka broker is a server that stores partition replicas and serves producer and consumer requests.

Answer

A Kafka broker is a server that stores partition replicas and serves producer and consumer requests. A cluster distributes partitions among brokers for capacity and resilience. Broker health, disk usage, network throughput, replication health, and controller status are essential operational signals.

Syntax

Producer example:
```ts
await producer.send({ topic: "orders", messages: [{ key: orderId, value: JSON.stringify(event) }] });
```
Consumer example:
```ts
await consumer.run({ eachMessage: async ({ message }) => {
  const event = JSON.parse(message.value?.toString() ?? "{}");
  await handleIdempotently(event);
} });
```
Diagram: Producer -> Topic partition -> Consumer group -> Handler -> Offset commit

Example

// KafkaJS-style example await producer.send({ topic: "orders", messages: [{ key: order.id, value: JSON.stringify({ eventId, orderId: order.id }) }] });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q6Kafka Producers and Consumers

What does a Kafka producer do?

A Kafka producer serializes records and sends them to a topic partition, often choosing the partition from a key or partitioner.

Answer

A Kafka producer serializes records and sends them to a topic partition, often choosing the partition from a key or partitioner. Batching and compression improve throughput, while acknowledgements and retries influence durability and latency. Producers should handle timeouts and use idempotence where supported to reduce duplicate writes.

Syntax

Producer example:
```ts
await producer.send({ topic: "orders", messages: [{ key: orderId, value: JSON.stringify(event) }] });
```
Consumer example:
```ts
await consumer.run({ eachMessage: async ({ message }) => {
  const event = JSON.parse(message.value?.toString() ?? "{}");
  await handleIdempotently(event);
} });
```
Diagram: Producer -> Topic partition -> Consumer group -> Handler -> Offset commit

Example

// KafkaJS-style example await producer.send({ topic: "orders", messages: [{ key: order.id, value: JSON.stringify({ eventId, orderId: order.id }) }] });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q7Kafka Producers and Consumers

What does a Kafka consumer do?

A Kafka consumer fetches records from topic partitions, processes them, and advances its position using offsets.

Answer

A Kafka consumer fetches records from topic partitions, processes them, and advances its position using offsets. Consumers can read independently or participate in a consumer group that shares partitions. Processing and offset commits must be coordinated carefully to avoid losing work or repeatedly applying side effects.

Syntax

Producer example:
```ts
await producer.send({ topic: "orders", messages: [{ key: orderId, value: JSON.stringify(event) }] });
```
Consumer example:
```ts
await consumer.run({ eachMessage: async ({ message }) => {
  const event = JSON.parse(message.value?.toString() ?? "{}");
  await handleIdempotently(event);
} });
```
Diagram: Producer -> Topic partition -> Consumer group -> Handler -> Offset commit

Example

// KafkaJS-style example await producer.send({ topic: "orders", messages: [{ key: order.id, value: JSON.stringify({ eventId, orderId: order.id }) }] });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q8Kafka Producers and Consumers

What is a Kafka consumer group?

A consumer group is a set of consumers that share topic partitions, with each partition assigned to one consumer in the group at a time.

Answer

A consumer group is a set of consumers that share topic partitions, with each partition assigned to one consumer in the group at a time. Different groups can independently read the same topic. Parallelism within one group is bounded by the number of assigned partitions, so adding consumers beyond that may not increase throughput.

Syntax

Producer example:
```ts
await producer.send({ topic: "orders", messages: [{ key: orderId, value: JSON.stringify(event) }] });
```
Consumer example:
```ts
await consumer.run({ eachMessage: async ({ message }) => {
  const event = JSON.parse(message.value?.toString() ?? "{}");
  await handleIdempotently(event);
} });
```
Diagram: Producer -> Topic partition -> Consumer group -> Handler -> Offset commit

Example

// KafkaJS-style example await producer.send({ topic: "orders", messages: [{ key: order.id, value: JSON.stringify({ eventId, orderId: order.id }) }] });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q9Kafka Producers and Consumers

What is a Kafka record key?

A record key commonly determines partition placement and groups related records onto the same partition.

Answer

A record key commonly determines partition placement and groups related records onto the same partition. Using an order ID as a key can preserve order for that order while distributing different orders across partitions. A poor or highly skewed key can create hot partitions and reduce throughput.

Syntax

Producer example:
```ts
await producer.send({ topic: "orders", messages: [{ key: orderId, value: JSON.stringify(event) }] });
```
Consumer example:
```ts
await consumer.run({ eachMessage: async ({ message }) => {
  const event = JSON.parse(message.value?.toString() ?? "{}");
  await handleIdempotently(event);
} });
```
Diagram: Producer -> Topic partition -> Consumer group -> Handler -> Offset commit

Example

// KafkaJS-style example await producer.send({ topic: "orders", messages: [{ key: order.id, value: JSON.stringify({ eventId, orderId: order.id }) }] });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q10Kafka Producers and Consumers

What is consumer lag?

Consumer lag measures how far a consumer group is behind the end of the log, often in records or offsets.

Answer

Consumer lag measures how far a consumer group is behind the end of the log, often in records or offsets. Lag can grow because production spikes, processing slows, partitions are imbalanced, or consumers are unhealthy. Track both lag and the age of the oldest unprocessed event because record counts alone can mislead.

Syntax

Producer example:
```ts
await producer.send({ topic: "orders", messages: [{ key: orderId, value: JSON.stringify(event) }] });
```
Consumer example:
```ts
await consumer.run({ eachMessage: async ({ message }) => {
  const event = JSON.parse(message.value?.toString() ?? "{}");
  await handleIdempotently(event);
} });
```
Diagram: Producer -> Topic partition -> Consumer group -> Handler -> Offset commit

Example

// KafkaJS-style example await producer.send({ topic: "orders", messages: [{ key: order.id, value: JSON.stringify({ eventId, orderId: order.id }) }] });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q11RabbitMQ Fundamentals

What is RabbitMQ?

RabbitMQ is a message broker that commonly uses AMQP and routes messages through exchanges into queues.

Answer

RabbitMQ is a message broker that commonly uses AMQP and routes messages through exchanges into queues. It supports acknowledgements, durable queues, flexible routing, and dead-lettering. It is often suited to task distribution and application messaging where routing behavior and work-queue semantics are important.

Syntax

Publish/consume example:
```ts
channel.publish("events", "order.created", Buffer.from(JSON.stringify(event)), { persistent: true });
channel.consume("orders", async msg => {
  if (!msg) return;
  try { await handleIdempotently(JSON.parse(msg.content.toString())); channel.ack(msg); }
  catch { channel.nack(msg, false, false); }
});
```
Diagram: Producer -> Exchange --routing key/binding--> Queue -> Consumer -> ack/nack

Example

// amqplib-style example channel.publish("events", "order.created", Buffer.from(JSON.stringify(event)), { persistent: true }); channel.consume("orders", async msg => { if (!msg) return; try { await handleIdempotently(JSON.parse(msg.content.toString())); channel.ack(msg); } catch { channel.nack(msg, false, false); } });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q12RabbitMQ Fundamentals

What is a RabbitMQ exchange?

An exchange receives published messages and routes them to queues according to its type, bindings, and routing keys.

Answer

An exchange receives published messages and routes them to queues according to its type, bindings, and routing keys. Common exchange types are direct, topic, fanout, and headers. A successful publish to an exchange does not by itself guarantee a message reached a queue, so publisher confirms and unroutable-message handling matter.

Syntax

Publish/consume example:
```ts
channel.publish("events", "order.created", Buffer.from(JSON.stringify(event)), { persistent: true });
channel.consume("orders", async msg => {
  if (!msg) return;
  try { await handleIdempotently(JSON.parse(msg.content.toString())); channel.ack(msg); }
  catch { channel.nack(msg, false, false); }
});
```
Diagram: Producer -> Exchange --routing key/binding--> Queue -> Consumer -> ack/nack

Example

// amqplib-style example channel.publish("events", "order.created", Buffer.from(JSON.stringify(event)), { persistent: true }); channel.consume("orders", async msg => { if (!msg) return; try { await handleIdempotently(JSON.parse(msg.content.toString())); channel.ack(msg); } catch { channel.nack(msg, false, false); } });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q13RabbitMQ Fundamentals

What is a RabbitMQ queue?

A queue stores messages until consumers receive and acknowledge them or they expire or are otherwise removed according to configuration.

Answer

A queue stores messages until consumers receive and acknowledge them or they expire or are otherwise removed according to configuration. Queue durability and message persistence are separate concerns. Queue type and replication configuration affect availability, ordering, and performance.

Syntax

Publish/consume example:
```ts
channel.publish("events", "order.created", Buffer.from(JSON.stringify(event)), { persistent: true });
channel.consume("orders", async msg => {
  if (!msg) return;
  try { await handleIdempotently(JSON.parse(msg.content.toString())); channel.ack(msg); }
  catch { channel.nack(msg, false, false); }
});
```
Diagram: Producer -> Exchange --routing key/binding--> Queue -> Consumer -> ack/nack

Example

// amqplib-style example channel.publish("events", "order.created", Buffer.from(JSON.stringify(event)), { persistent: true }); channel.consume("orders", async msg => { if (!msg) return; try { await handleIdempotently(JSON.parse(msg.content.toString())); channel.ack(msg); } catch { channel.nack(msg, false, false); } });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q14RabbitMQ Fundamentals

What is a routing key?

A routing key is a string used by exchanges to decide which queues receive a message.

Answer

A routing key is a string used by exchanges to decide which queues receive a message. A direct exchange matches keys exactly, while a topic exchange supports dot-separated patterns such as order.* or order.#. Routing keys should be documented as part of the message contract.

Syntax

Publish/consume example:
```ts
channel.publish("events", "order.created", Buffer.from(JSON.stringify(event)), { persistent: true });
channel.consume("orders", async msg => {
  if (!msg) return;
  try { await handleIdempotently(JSON.parse(msg.content.toString())); channel.ack(msg); }
  catch { channel.nack(msg, false, false); }
});
```
Diagram: Producer -> Exchange --routing key/binding--> Queue -> Consumer -> ack/nack

Example

// amqplib-style example channel.publish("events", "order.created", Buffer.from(JSON.stringify(event)), { persistent: true }); channel.consume("orders", async msg => { if (!msg) return; try { await handleIdempotently(JSON.parse(msg.content.toString())); channel.ack(msg); } catch { channel.nack(msg, false, false); } });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q15RabbitMQ Fundamentals

What is a RabbitMQ binding?

A binding connects an exchange to a queue or another exchange and can include a routing key or arguments.

Answer

A binding connects an exchange to a queue or another exchange and can include a routing key or arguments. Bindings define the routing topology independently of publishers. Review bindings when a message is unexpectedly missing or delivered to unintended queues.

Syntax

Publish/consume example:
```ts
channel.publish("events", "order.created", Buffer.from(JSON.stringify(event)), { persistent: true });
channel.consume("orders", async msg => {
  if (!msg) return;
  try { await handleIdempotently(JSON.parse(msg.content.toString())); channel.ack(msg); }
  catch { channel.nack(msg, false, false); }
});
```
Diagram: Producer -> Exchange --routing key/binding--> Queue -> Consumer -> ack/nack

Example

// amqplib-style example channel.publish("events", "order.created", Buffer.from(JSON.stringify(event)), { persistent: true }); channel.consume("orders", async msg => { if (!msg) return; try { await handleIdempotently(JSON.parse(msg.content.toString())); channel.ack(msg); } catch { channel.nack(msg, false, false); } });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q21Event-Driven Architecture

What is event-driven architecture?

Event-driven architecture structures systems around events that describe changes or occurrences.

Answer

Event-driven architecture structures systems around events that describe changes or occurrences. Producers publish events and consumers react asynchronously, reducing direct service coupling and enabling multiple downstream workflows. The trade-offs include eventual consistency, harder tracing, schema evolution, and the need to manage duplicates and reprocessing.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q22Event-Driven Architecture

What is eventual consistency?

Eventual consistency means independently updated views may temporarily disagree but converge when asynchronous updates complete.

Answer

Eventual consistency means independently updated views may temporarily disagree but converge when asynchronous updates complete. It is common when events propagate state changes between services. User experiences should account for delay, and business invariants that require immediate coordination may need synchronous validation or a different transaction boundary.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q23Event-Driven Architecture

What is an event notification versus event-carried state transfer?

An event notification says that something changed and may require the consumer to fetch details, while event-carried state transfer includes the relevant data in the event itself.

Answer

An event notification says that something changed and may require the consumer to fetch details, while event-carried state transfer includes the relevant data in the event itself. Notifications keep payloads small but introduce a dependency on the source service; state transfer reduces calls but increases payload and schema-management responsibilities.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q24Event-Driven Architecture

What is choreography in event-driven systems?

Choreography lets services react to events and emit subsequent events without a central coordinator.

Answer

Choreography lets services react to events and emit subsequent events without a central coordinator. It can be simple and resilient for straightforward flows, but complex processes may become hard to understand because control flow is distributed. Correlation IDs, documented state transitions, and clear event ownership improve operability.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q25Event-Driven Architecture

What is orchestration?

Orchestration uses a coordinator or workflow engine to direct steps, track state, and decide what happens after success or failure.

Answer

Orchestration uses a coordinator or workflow engine to direct steps, track state, and decide what happens after success or failure. It makes long-running workflows more visible but introduces a central component and its own availability concerns. Use it when process visibility and explicit compensation outweigh the cost of coordination.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.

Intermediate Questions

Implementation details, practical patterns, and common workflows.

Q16RabbitMQ Delivery and Reliability

What is a publisher confirm?

A publisher confirm lets RabbitMQ tell a publisher that the broker has accepted responsibility for a published message.

Answer

A publisher confirm lets RabbitMQ tell a publisher that the broker has accepted responsibility for a published message. It is different from a consumer acknowledgement, which tells the broker a delivered message has been handled. Applications should combine confirms with unroutable-message detection and safe retry behavior.

Syntax

Publish/consume example:
```ts
channel.publish("events", "order.created", Buffer.from(JSON.stringify(event)), { persistent: true });
channel.consume("orders", async msg => {
  if (!msg) return;
  try { await handleIdempotently(JSON.parse(msg.content.toString())); channel.ack(msg); }
  catch { channel.nack(msg, false, false); }
});
```
Diagram: Producer -> Exchange --routing key/binding--> Queue -> Consumer -> ack/nack

Example

// amqplib-style example channel.publish("events", "order.created", Buffer.from(JSON.stringify(event)), { persistent: true }); channel.consume("orders", async msg => { if (!msg) return; try { await handleIdempotently(JSON.parse(msg.content.toString())); channel.ack(msg); } catch { channel.nack(msg, false, false); } });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q17RabbitMQ Delivery and Reliability

What is a consumer acknowledgement?

A consumer acknowledgement tells RabbitMQ that a delivery has been processed and can be removed from the queue.

Answer

A consumer acknowledgement tells RabbitMQ that a delivery has been processed and can be removed from the queue. If the consumer crashes before acknowledging, the message can be requeued and delivered again. Acknowledge only after the required work is safely completed, and make processing idempotent.

Syntax

Publish/consume example:
```ts
channel.publish("events", "order.created", Buffer.from(JSON.stringify(event)), { persistent: true });
channel.consume("orders", async msg => {
  if (!msg) return;
  try { await handleIdempotently(JSON.parse(msg.content.toString())); channel.ack(msg); }
  catch { channel.nack(msg, false, false); }
});
```
Diagram: Producer -> Exchange --routing key/binding--> Queue -> Consumer -> ack/nack

Example

// amqplib-style example channel.publish("events", "order.created", Buffer.from(JSON.stringify(event)), { persistent: true }); channel.consume("orders", async msg => { if (!msg) return; try { await handleIdempotently(JSON.parse(msg.content.toString())); channel.ack(msg); } catch { channel.nack(msg, false, false); } });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q18RabbitMQ Delivery and Reliability

What is the difference between durable queues and persistent messages?

A durable queue survives broker restart, while a persistent message requests that the message be stored durably.

Answer

A durable queue survives broker restart, while a persistent message requests that the message be stored durably. Both settings may be needed for restart survival, but they do not alone guarantee every failure scenario. Replication, confirms, storage behavior, and broker configuration also affect reliability.

Syntax

Publish/consume example:
```ts
channel.publish("events", "order.created", Buffer.from(JSON.stringify(event)), { persistent: true });
channel.consume("orders", async msg => {
  if (!msg) return;
  try { await handleIdempotently(JSON.parse(msg.content.toString())); channel.ack(msg); }
  catch { channel.nack(msg, false, false); }
});
```
Diagram: Producer -> Exchange --routing key/binding--> Queue -> Consumer -> ack/nack

Example

// amqplib-style example channel.publish("events", "order.created", Buffer.from(JSON.stringify(event)), { persistent: true }); channel.consume("orders", async msg => { if (!msg) return; try { await handleIdempotently(JSON.parse(msg.content.toString())); channel.ack(msg); } catch { channel.nack(msg, false, false); } });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q19RabbitMQ Delivery and Reliability

What is a dead-letter exchange?

A dead-letter exchange routes messages that are rejected without requeue, expire, or exceed configured queue limits to a destination exchange.

Answer

A dead-letter exchange routes messages that are rejected without requeue, expire, or exceed configured queue limits to a destination exchange. It allows failed messages to be inspected and replayed deliberately. Dead-letter queues need alerting, retention policies, and a safe remediation process rather than becoming permanent message graveyards.

Syntax

Publish/consume example:
```ts
channel.publish("events", "order.created", Buffer.from(JSON.stringify(event)), { persistent: true });
channel.consume("orders", async msg => {
  if (!msg) return;
  try { await handleIdempotently(JSON.parse(msg.content.toString())); channel.ack(msg); }
  catch { channel.nack(msg, false, false); }
});
```
Diagram: Producer -> Exchange --routing key/binding--> Queue -> Consumer -> ack/nack

Example

// amqplib-style example channel.publish("events", "order.created", Buffer.from(JSON.stringify(event)), { persistent: true }); channel.consume("orders", async msg => { if (!msg) return; try { await handleIdempotently(JSON.parse(msg.content.toString())); channel.ack(msg); } catch { channel.nack(msg, false, false); } });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q20RabbitMQ Delivery and Reliability

How do retries work in RabbitMQ?

Retries can use delayed retry queues, TTL-based dead-letter routing, or application-managed retry scheduling.

Answer

Retries can use delayed retry queues, TTL-based dead-letter routing, or application-managed retry scheduling. Immediate requeue loops can overload a failing dependency and starve healthy work. Apply bounded attempts, exponential backoff with jitter where possible, and a dead-letter path after the retry budget is exhausted.

Syntax

Publish/consume example:
```ts
channel.publish("events", "order.created", Buffer.from(JSON.stringify(event)), { persistent: true });
channel.consume("orders", async msg => {
  if (!msg) return;
  try { await handleIdempotently(JSON.parse(msg.content.toString())); channel.ack(msg); }
  catch { channel.nack(msg, false, false); }
});
```
Diagram: Producer -> Exchange --routing key/binding--> Queue -> Consumer -> ack/nack

Example

// amqplib-style example channel.publish("events", "order.created", Buffer.from(JSON.stringify(event)), { persistent: true }); channel.consume("orders", async msg => { if (!msg) return; try { await handleIdempotently(JSON.parse(msg.content.toString())); channel.ack(msg); } catch { channel.nack(msg, false, false); } });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q26Delivery Semantics

What does at-most-once delivery mean?

At-most-once delivery means a message is delivered zero or one times, so duplicates are avoided at the cost of possible loss.

Answer

At-most-once delivery means a message is delivered zero or one times, so duplicates are avoided at the cost of possible loss. For example, committing a Kafka offset before processing can skip work if the process crashes afterward. This can be acceptable for disposable telemetry but is risky for important business operations.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q27Delivery Semantics

What does at-least-once delivery mean?

At-least-once delivery aims to ensure a message is processed one or more times, usually by acknowledging or committing only after processing.

Answer

At-least-once delivery aims to ensure a message is processed one or more times, usually by acknowledging or committing only after processing. A crash between the side effect and acknowledgement can cause redelivery, so consumers must tolerate duplicates through idempotency, deduplication, or transactional handling.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q28Delivery Semantics

What does exactly-once processing mean?

Exactly-once is not a universal end-to-end switch; its meaning depends on the boundaries covered by the broker and application.

Answer

Exactly-once is not a universal end-to-end switch; its meaning depends on the boundaries covered by the broker and application. Kafka transactions can atomically write records and offsets within Kafka, but external database or payment side effects need additional coordination or idempotency. Define the guarantee precisely for each workflow.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q29Delivery Semantics

Why can messages be duplicated?

Duplicates can arise when a broker redelivers after missing acknowledgements, a producer retries after an ambiguous timeout, or a consumer crashes after applying a side effect but before committing progress.

Answer

Duplicates can arise when a broker redelivers after missing acknowledgements, a producer retries after an ambiguous timeout, or a consumer crashes after applying a side effect but before committing progress. Duplicate handling is a normal part of reliable messaging, not necessarily a broker defect.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q30Delivery Semantics

How do you choose delivery semantics?

Choose semantics based on the consequence of loss versus duplication, processing cost, and whether the side effect can be made idempotent.

Answer

Choose semantics based on the consequence of loss versus duplication, processing cost, and whether the side effect can be made idempotent. At-least-once plus idempotent handlers is a practical default for many business workflows. Use stronger transactional features only where their boundaries match the required invariant.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q31Idempotency and Deduplication

What is idempotent message processing?

An idempotent handler can process the same message repeatedly while producing the same intended business outcome as processing it once.

Answer

An idempotent handler can process the same message repeatedly while producing the same intended business outcome as processing it once. Common techniques include unique event IDs, conditional updates, idempotency keys, and database uniqueness constraints. Idempotency should cover the actual side effect, not merely the in-memory handler.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q32Idempotency and Deduplication

How can a consumer deduplicate messages?

A consumer can store each message's stable event ID in a processed-message table with a unique constraint in the same database transaction as its business update.

Answer

A consumer can store each message's stable event ID in a processed-message table with a unique constraint in the same database transaction as its business update. If the ID already exists, the consumer treats the delivery as a duplicate. The deduplication record's retention period must cover the likely replay window.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q33Idempotency and Deduplication

What is an idempotency key in payment processing?

An idempotency key identifies one logical payment request across retries.

Answer

An idempotency key identifies one logical payment request across retries. The payment service stores the result associated with the key and returns that result for repeated requests rather than charging again. Keys must be scoped appropriately, retained long enough, and checked against request parameters to prevent accidental reuse.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q34Idempotency and Deduplication

Why is checking then inserting unsafe?

A separate read followed by an insert can race: two workers may both see no processed record and then perform the side effect.

Answer

A separate read followed by an insert can race: two workers may both see no processed record and then perform the side effect. Enforce uniqueness in the database and make the deduplication claim atomic with the business update. Handle unique-constraint conflicts as a duplicate rather than assuming the pre-check guarantees exclusivity.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q35Idempotency and Deduplication

How should deduplication work with external APIs?

Use the external API's idempotency key when available and persist a local operation state to recover after ambiguous timeouts.

Answer

Use the external API's idempotency key when available and persist a local operation state to recover after ambiguous timeouts. If the external system has no idempotency support, reconciliation or compensating workflows may be needed because a timeout does not prove the action failed. Avoid blindly repeating irreversible operations.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q36Ordering and Partitioning

How is message ordering guaranteed?

Ordering is typically guaranteed only within a defined scope, such as a RabbitMQ queue under specific conditions or a Kafka partition.

Answer

Ordering is typically guaranteed only within a defined scope, such as a RabbitMQ queue under specific conditions or a Kafka partition. Multiple consumers, retries, and parallel handlers can reorder completion even when delivery order is preserved. Identify the business entity that needs ordering and serialize work for that entity.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q37Ordering and Partitioning

How do you preserve per-customer order in Kafka?

Use a stable customer identifier as the record key so events for one customer normally go to the same partition.

Answer

Use a stable customer identifier as the record key so events for one customer normally go to the same partition. Keep the consumer's processing sequential for that partition when strict completion order matters. Be careful when changing partition counts or partitioning strategies because key-to-partition mapping can change.

Syntax

Producer example:
```ts
await producer.send({ topic: "orders", messages: [{ key: orderId, value: JSON.stringify(event) }] });
```
Consumer example:
```ts
await consumer.run({ eachMessage: async ({ message }) => {
  const event = JSON.parse(message.value?.toString() ?? "{}");
  await handleIdempotently(event);
} });
```
Diagram: Producer -> Topic partition -> Consumer group -> Handler -> Offset commit

Example

// KafkaJS-style example await producer.send({ topic: "orders", messages: [{ key: order.id, value: JSON.stringify({ eventId, orderId: order.id }) }] });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q38Ordering and Partitioning

What is a hot partition?

A hot partition receives disproportionately more records or expensive work than others, often because many events share one key.

Answer

A hot partition receives disproportionately more records or expensive work than others, often because many events share one key. It limits throughput even when other partitions are idle. Inspect key distribution and processing time; remedies include better keys, splitting workloads, or redesigning the ordering requirement where business rules permit.

Syntax

Producer example:
```ts
await producer.send({ topic: "orders", messages: [{ key: orderId, value: JSON.stringify(event) }] });
```
Consumer example:
```ts
await consumer.run({ eachMessage: async ({ message }) => {
  const event = JSON.parse(message.value?.toString() ?? "{}");
  await handleIdempotently(event);
} });
```
Diagram: Producer -> Topic partition -> Consumer group -> Handler -> Offset commit

Example

// KafkaJS-style example await producer.send({ topic: "orders", messages: [{ key: order.id, value: JSON.stringify({ eventId, orderId: order.id }) }] });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q39Ordering and Partitioning

What is head-of-line blocking?

Head-of-line blocking occurs when a slow or repeatedly failing message prevents later messages from progressing in the same ordered stream or queue.

Answer

Head-of-line blocking occurs when a slow or repeatedly failing message prevents later messages from progressing in the same ordered stream or queue. Isolate poison messages, bound retries, and use separate queues or partitions for workloads with different latency needs. Reordering is only safe if the business semantics allow it.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q40Ordering and Partitioning

How should retries affect ordering?

Retries can delay a failed event while later events proceed, or they can block the stream until it succeeds.

Answer

Retries can delay a failed event while later events proceed, or they can block the stream until it succeeds. The right choice depends on whether later events depend on the failed one. Use per-key sequencing, retry topics or queues, and explicit state validation rather than assuming all retry strategies preserve order.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q41Kafka Reliability and Replication

What is a Kafka replication factor?

The replication factor is the number of replicas maintained for each partition.

Answer

The replication factor is the number of replicas maintained for each partition. Replication can preserve data when a broker fails, but it consumes storage and network capacity. A replica count alone does not define durability; producer acknowledgements, in-sync replica settings, and clean leader election policy also matter.

Syntax

Producer example:
```ts
await producer.send({ topic: "orders", messages: [{ key: orderId, value: JSON.stringify(event) }] });
```
Consumer example:
```ts
await consumer.run({ eachMessage: async ({ message }) => {
  const event = JSON.parse(message.value?.toString() ?? "{}");
  await handleIdempotently(event);
} });
```
Diagram: Producer -> Topic partition -> Consumer group -> Handler -> Offset commit

Example

// KafkaJS-style example await producer.send({ topic: "orders", messages: [{ key: order.id, value: JSON.stringify({ eventId, orderId: order.id }) }] });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q42Kafka Reliability and Replication

What is an ISR in Kafka?

The in-sync replica set contains replicas considered sufficiently caught up to the partition leader.

Answer

The in-sync replica set contains replicas considered sufficiently caught up to the partition leader. With acks=all, Kafka waits for the required in-sync replicas according to cluster configuration. If the ISR shrinks, writes may be rejected or durability expectations weakened depending on settings, so monitor ISR changes.

Syntax

Producer example:
```ts
await producer.send({ topic: "orders", messages: [{ key: orderId, value: JSON.stringify(event) }] });
```
Consumer example:
```ts
await consumer.run({ eachMessage: async ({ message }) => {
  const event = JSON.parse(message.value?.toString() ?? "{}");
  await handleIdempotently(event);
} });
```
Diagram: Producer -> Topic partition -> Consumer group -> Handler -> Offset commit

Example

// KafkaJS-style example await producer.send({ topic: "orders", messages: [{ key: order.id, value: JSON.stringify({ eventId, orderId: order.id }) }] });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q43Kafka Reliability and Replication

What does acks=all mean?

With acks=all, the producer waits for acknowledgement from the leader after the current in-sync replicas have acknowledged the write, subject to broker configuration such as minimum in-sync replicas.

Answer

With acks=all, the producer waits for acknowledgement from the leader after the current in-sync replicas have acknowledged the write, subject to broker configuration such as minimum in-sync replicas. It improves durability compared with acknowledging only the leader but can increase latency and cause writes to fail when too few replicas remain.

Syntax

Producer example:
```ts
await producer.send({ topic: "orders", messages: [{ key: orderId, value: JSON.stringify(event) }] });
```
Consumer example:
```ts
await consumer.run({ eachMessage: async ({ message }) => {
  const event = JSON.parse(message.value?.toString() ?? "{}");
  await handleIdempotently(event);
} });
```
Diagram: Producer -> Topic partition -> Consumer group -> Handler -> Offset commit

Example

// KafkaJS-style example await producer.send({ topic: "orders", messages: [{ key: order.id, value: JSON.stringify({ eventId, orderId: order.id }) }] });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q44Kafka Reliability and Replication

What is producer idempotence in Kafka?

Producer idempotence uses producer identity and sequence numbers to suppress duplicates caused by producer retries within Kafka's supported scope.

Answer

Producer idempotence uses producer identity and sequence numbers to suppress duplicates caused by producer retries within Kafka's supported scope. It helps prevent retry-related duplicate log entries but does not automatically make external database updates or arbitrary downstream side effects exactly once. Configure compatible producer settings and still design consumers carefully.

Syntax

Producer example:
```ts
await producer.send({ topic: "orders", messages: [{ key: orderId, value: JSON.stringify(event) }] });
```
Consumer example:
```ts
await consumer.run({ eachMessage: async ({ message }) => {
  const event = JSON.parse(message.value?.toString() ?? "{}");
  await handleIdempotently(event);
} });
```
Diagram: Producer -> Topic partition -> Consumer group -> Handler -> Offset commit

Example

// KafkaJS-style example await producer.send({ topic: "orders", messages: [{ key: order.id, value: JSON.stringify({ eventId, orderId: order.id }) }] });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q45Kafka Reliability and Replication

What is an unclean leader election?

An unclean leader election allows a replica outside the in-sync set to become leader when no in-sync replica is available.

Answer

An unclean leader election allows a replica outside the in-sync set to become leader when no in-sync replica is available. This can restore availability but risks losing records that were acknowledged by the previous leader. Decide whether availability or avoiding data loss is more important for the topic's business purpose.

Syntax

Producer example:
```ts
await producer.send({ topic: "orders", messages: [{ key: orderId, value: JSON.stringify(event) }] });
```
Consumer example:
```ts
await consumer.run({ eachMessage: async ({ message }) => {
  const event = JSON.parse(message.value?.toString() ?? "{}");
  await handleIdempotently(event);
} });
```
Diagram: Producer -> Topic partition -> Consumer group -> Handler -> Offset commit

Example

// KafkaJS-style example await producer.send({ topic: "orders", messages: [{ key: order.id, value: JSON.stringify({ eventId, orderId: order.id }) }] });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q46Schemas and Event Evolution

Why should event schemas be versioned?

Schemas define the shape and meaning of event payloads.

Answer

Schemas define the shape and meaning of event payloads. Versioning and compatibility checks help producers evolve fields without unexpectedly breaking consumers. Prefer additive changes, sensible defaults, and explicit deprecation windows; a syntactically valid field change can still break business semantics.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q47Schemas and Event Evolution

What is backward compatibility for event schemas?

Backward compatibility generally means a newer consumer can read records written with an older schema.

Answer

Backward compatibility generally means a newer consumer can read records written with an older schema. Optional fields and defaults often help, while removing required fields can break readers. The exact rules depend on the schema format and registry policy, so test producer and consumer combinations before deployment.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q48Schemas and Event Evolution

What is forward compatibility?

Forward compatibility generally means an older consumer can read records written with a newer schema.

Answer

Forward compatibility generally means an older consumer can read records written with a newer schema. It often requires consumers to ignore unknown fields and avoid assumptions that every producer uses the same version. Test unknown-field handling and document how consumers behave when new enum values appear.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q49Schemas and Event Evolution

What belongs in a CloudEvents-style envelope?

A standard event envelope commonly includes event ID, source, type, subject, time, and data content or data reference.

Answer

A standard event envelope commonly includes event ID, source, type, subject, time, and data content or data reference. A consistent envelope improves routing, tracing, deduplication, and tooling across teams. Keep domain meaning in the data payload and avoid duplicating conflicting identifiers in multiple places.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q50Schemas and Event Evolution

How do you handle an unknown event type?

A consumer should follow an explicit policy for unknown event types: safely ignore, quarantine, or dead-letter them with observability, depending on the contract.

Answer

A consumer should follow an explicit policy for unknown event types: safely ignore, quarantine, or dead-letter them with observability, depending on the contract. Silently treating an unknown event as success can hide compatibility failures. Log the event type and schema version without exposing sensitive payload data.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q51Retries, Backoff, and Poison Messages

What is a poison message?

A poison message repeatedly fails because of invalid data, a permanent business-rule violation, or a bug.

Answer

A poison message repeatedly fails because of invalid data, a permanent business-rule violation, or a bug. Infinite retries waste capacity and can block healthy work. Use bounded retries, classify transient versus permanent failures, capture diagnostic metadata, and route exhausted messages to a dead-letter destination for controlled investigation.

Syntax

Bounded retry example:
```ts
const delayMs = Math.min(60_000, 1_000 * 2 ** attempt);
if (isTransient(error) && attempt < MAX_ATTEMPTS) {
  await scheduleRetry(event, delayMs);
} else {
  await publishDeadLetter(event, { reason: classify(error), attempt });
}
```
Diagram: Consume -> Classify error -> Retry with backoff -> Success / Dead-letter after limit

Example

const delayMs = Math.min(60_000, 1_000 * 2 ** attempt); if (isTransient(error) && attempt < MAX_ATTEMPTS) { await scheduleRetry(event, delayMs + Math.random() * 250); } else { await publishDeadLetter(event, { reason: classify(error), attempt }); }

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q52Retries, Backoff, and Poison Messages

What is exponential backoff?

Exponential backoff increases the wait between attempts, commonly multiplying the previous delay by a factor until a maximum is reached.

Answer

Exponential backoff increases the wait between attempts, commonly multiplying the previous delay by a factor until a maximum is reached. It reduces pressure on recovering dependencies compared with immediate retries. Add jitter to avoid many workers retrying at the same moment, and cap both attempts and total elapsed time.

Syntax

Bounded retry example:
```ts
const delayMs = Math.min(60_000, 1_000 * 2 ** attempt);
if (isTransient(error) && attempt < MAX_ATTEMPTS) {
  await scheduleRetry(event, delayMs);
} else {
  await publishDeadLetter(event, { reason: classify(error), attempt });
}
```
Diagram: Consume -> Classify error -> Retry with backoff -> Success / Dead-letter after limit

Example

const delayMs = Math.min(60_000, 1_000 * 2 ** attempt); if (isTransient(error) && attempt < MAX_ATTEMPTS) { await scheduleRetry(event, delayMs + Math.random() * 250); } else { await publishDeadLetter(event, { reason: classify(error), attempt }); }

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q53Retries, Backoff, and Poison Messages

When should a message be retried?

Retry when failure is plausibly transient, such as a temporary network issue or throttling response.

Answer

Retry when failure is plausibly transient, such as a temporary network issue or throttling response. Do not repeatedly retry invalid schemas or deterministic business-rule failures without a change in conditions. Use error classification, bounded attempts, backoff, and a dead-letter or remediation path.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q54Retries, Backoff, and Poison Messages

What is a retry topic or retry queue?

A retry topic or queue stores messages for later reprocessing, often with a delay tier such as short, medium, and long backoff.

Answer

A retry topic or queue stores messages for later reprocessing, often with a delay tier such as short, medium, and long backoff. It separates waiting retries from fresh work, but may alter ordering and require careful correlation. Preserve the original event ID and attempt metadata and ensure retry loops cannot run forever.

Syntax

Publish/consume example:
```ts
channel.publish("events", "order.created", Buffer.from(JSON.stringify(event)), { persistent: true });
channel.consume("orders", async msg => {
  if (!msg) return;
  try { await handleIdempotently(JSON.parse(msg.content.toString())); channel.ack(msg); }
  catch { channel.nack(msg, false, false); }
});
```
Diagram: Producer -> Exchange --routing key/binding--> Queue -> Consumer -> ack/nack

Example

// amqplib-style example channel.publish("events", "order.created", Buffer.from(JSON.stringify(event)), { persistent: true }); channel.consume("orders", async msg => { if (!msg) return; try { await handleIdempotently(JSON.parse(msg.content.toString())); channel.ack(msg); } catch { channel.nack(msg, false, false); } });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q55Retries, Backoff, and Poison Messages

How do you safely replay dead-letter messages?

Replay only after understanding and fixing the cause, then validate payloads, control the replay rate, and monitor side effects.

Answer

Replay only after understanding and fixing the cause, then validate payloads, control the replay rate, and monitor side effects. Keep the original event ID and use idempotency to prevent duplicate business actions. Consider replaying to a staging destination first and retain audit information about who initiated the replay.

Syntax

Bounded retry example:
```ts
const delayMs = Math.min(60_000, 1_000 * 2 ** attempt);
if (isTransient(error) && attempt < MAX_ATTEMPTS) {
  await scheduleRetry(event, delayMs);
} else {
  await publishDeadLetter(event, { reason: classify(error), attempt });
}
```
Diagram: Consume -> Classify error -> Retry with backoff -> Success / Dead-letter after limit

Example

const delayMs = Math.min(60_000, 1_000 * 2 ** attempt); if (isTransient(error) && attempt < MAX_ATTEMPTS) { await scheduleRetry(event, delayMs + Math.random() * 250); } else { await publishDeadLetter(event, { reason: classify(error), attempt }); }

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q56Transactional Outbox and CDC

What problem does the transactional outbox solve?

The outbox pattern prevents a database update and event publication from diverging when they cannot share a single atomic transaction.

Answer

The outbox pattern prevents a database update and event publication from diverging when they cannot share a single atomic transaction. The application writes the business change and an outbox row in one database transaction; a separate publisher delivers the row to the broker. Publication may still repeat, so consumers should be idempotent.

Syntax

Transactional outbox example:
```sql
BEGIN;
UPDATE orders SET status = 'CREATED' WHERE id = :order_id;
INSERT INTO outbox(event_id, event_type, payload)
VALUES (:event_id, 'OrderCreated', :payload);
COMMIT;
```
Diagram: Business transaction -> Outbox table -> Relay/CDC -> Broker -> Idempotent consumer

Example

-- Outbox rows are written in the same transaction as the business change BEGIN; UPDATE orders SET status = 'CREATED' WHERE id = :order_id; INSERT INTO outbox(event_id, event_type, payload) VALUES (:event_id, 'OrderCreated', :payload); COMMIT;

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q57Transactional Outbox and CDC

How does an outbox publisher work?

An outbox publisher scans or streams unpublished rows, publishes each event, and marks it delivered only after broker confirmation.

Answer

An outbox publisher scans or streams unpublished rows, publishes each event, and marks it delivered only after broker confirmation. Crashes can occur between publishing and marking delivered, causing a duplicate; stable event IDs handle that case. Use bounded batches, retry policies, and monitoring for the oldest unpublished row.

Syntax

Transactional outbox example:
```sql
BEGIN;
UPDATE orders SET status = 'CREATED' WHERE id = :order_id;
INSERT INTO outbox(event_id, event_type, payload)
VALUES (:event_id, 'OrderCreated', :payload);
COMMIT;
```
Diagram: Business transaction -> Outbox table -> Relay/CDC -> Broker -> Idempotent consumer

Example

-- Outbox rows are written in the same transaction as the business change BEGIN; UPDATE orders SET status = 'CREATED' WHERE id = :order_id; INSERT INTO outbox(event_id, event_type, payload) VALUES (:event_id, 'OrderCreated', :payload); COMMIT;

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q58Transactional Outbox and CDC

What is change data capture (CDC)?

CDC captures database changes from a log or change stream and makes them available to downstream systems.

Answer

CDC captures database changes from a log or change stream and makes them available to downstream systems. It can publish outbox rows or replicate changes for analytics and integration. CDC reduces polling but adds operational dependencies on database logs, connectors, schema evolution, and recovery offsets.

Syntax

Transactional outbox example:
```sql
BEGIN;
UPDATE orders SET status = 'CREATED' WHERE id = :order_id;
INSERT INTO outbox(event_id, event_type, payload)
VALUES (:event_id, 'OrderCreated', :payload);
COMMIT;
```
Diagram: Business transaction -> Outbox table -> Relay/CDC -> Broker -> Idempotent consumer

Example

-- Outbox rows are written in the same transaction as the business change BEGIN; UPDATE orders SET status = 'CREATED' WHERE id = :order_id; INSERT INTO outbox(event_id, event_type, payload) VALUES (:event_id, 'OrderCreated', :payload); COMMIT;

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q59Transactional Outbox and CDC

What is the dual-write problem?

The dual-write problem occurs when an application separately updates a database and publishes a message.

Answer

The dual-write problem occurs when an application separately updates a database and publishes a message. If one operation succeeds and the other fails, systems disagree. An outbox, CDC, or a carefully designed distributed transaction can address this, with the outbox often being a practical option for service-owned databases.

Syntax

Transactional outbox example:
```sql
BEGIN;
UPDATE orders SET status = 'CREATED' WHERE id = :order_id;
INSERT INTO outbox(event_id, event_type, payload)
VALUES (:event_id, 'OrderCreated', :payload);
COMMIT;
```
Diagram: Business transaction -> Outbox table -> Relay/CDC -> Broker -> Idempotent consumer

Example

-- Outbox rows are written in the same transaction as the business change BEGIN; UPDATE orders SET status = 'CREATED' WHERE id = :order_id; INSERT INTO outbox(event_id, event_type, payload) VALUES (:event_id, 'OrderCreated', :payload); COMMIT;

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q60Transactional Outbox and CDC

How do you avoid publishing before a transaction commits?

Do not publish an event before the database transaction that creates its underlying fact is committed, because consumers may observe an event for a change that later rolls back.

Answer

Do not publish an event before the database transaction that creates its underlying fact is committed, because consumers may observe an event for a change that later rolls back. Write an outbox row in the same transaction and publish it afterward. This creates a durable record of publication intent.

Syntax

Transactional outbox example:
```sql
BEGIN;
UPDATE orders SET status = 'CREATED' WHERE id = :order_id;
INSERT INTO outbox(event_id, event_type, payload)
VALUES (:event_id, 'OrderCreated', :payload);
COMMIT;
```
Diagram: Business transaction -> Outbox table -> Relay/CDC -> Broker -> Idempotent consumer

Example

-- Outbox rows are written in the same transaction as the business change BEGIN; UPDATE orders SET status = 'CREATED' WHERE id = :order_id; INSERT INTO outbox(event_id, event_type, payload) VALUES (:event_id, 'OrderCreated', :payload); COMMIT;

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q66Consumer Groups and Rebalancing

What triggers a Kafka consumer rebalance?

A rebalance redistributes partitions when group membership or subscription changes, or when a consumer is considered unhealthy.

Answer

A rebalance redistributes partitions when group membership or subscription changes, or when a consumer is considered unhealthy. Rebalances can pause processing and increase lag. Use appropriate poll intervals, graceful shutdown, stable membership where supported, and monitor rebalance frequency.

Syntax

Producer example:
```ts
await producer.send({ topic: "orders", messages: [{ key: orderId, value: JSON.stringify(event) }] });
```
Consumer example:
```ts
await consumer.run({ eachMessage: async ({ message }) => {
  const event = JSON.parse(message.value?.toString() ?? "{}");
  await handleIdempotently(event);
} });
```
Diagram: Producer -> Topic partition -> Consumer group -> Handler -> Offset commit

Example

// KafkaJS-style example await producer.send({ topic: "orders", messages: [{ key: order.id, value: JSON.stringify({ eventId, orderId: order.id }) }] });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q67Consumer Groups and Rebalancing

What is a cooperative rebalance?

Cooperative rebalancing incrementally transfers partitions rather than revoking all assignments at once, reducing the disruption of group changes.

Answer

Cooperative rebalancing incrementally transfers partitions rather than revoking all assignments at once, reducing the disruption of group changes. It depends on compatible client configuration and protocol support. Consumers must still clean up partition-specific resources and avoid processing a partition after ownership is revoked.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q68Consumer Groups and Rebalancing

What is the difference between assignment and subscription?

Subscription declares which topics a consumer wants to read and lets group coordination assign partitions.

Answer

Subscription declares which topics a consumer wants to read and lets group coordination assign partitions. Manual assignment gives the application direct control over specific partitions without the same group-managed distribution. Manual assignment can be useful for specialized workloads but transfers failover and balancing responsibility to the application.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q69Consumer Groups and Rebalancing

Why should a Kafka consumer poll regularly?

The consumer poll loop participates in group coordination and returns records.

Answer

The consumer poll loop participates in group coordination and returns records. If processing blocks too long between polls, the consumer may exceed configured limits and trigger a rebalance. Move long work to bounded worker pools or tune settings carefully while ensuring offset commits and partition ownership remain correct.

Syntax

Producer example:
```ts
await producer.send({ topic: "orders", messages: [{ key: orderId, value: JSON.stringify(event) }] });
```
Consumer example:
```ts
await consumer.run({ eachMessage: async ({ message }) => {
  const event = JSON.parse(message.value?.toString() ?? "{}");
  await handleIdempotently(event);
} });
```
Diagram: Producer -> Topic partition -> Consumer group -> Handler -> Offset commit

Example

// KafkaJS-style example await producer.send({ topic: "orders", messages: [{ key: order.id, value: JSON.stringify({ eventId, orderId: order.id }) }] });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q70Consumer Groups and Rebalancing

How should a consumer handle partition revocation?

During partition revocation, stop scheduling new work for revoked partitions, finish or safely abandon in-flight work, and commit only offsets for completed records.

Answer

During partition revocation, stop scheduling new work for revoked partitions, finish or safely abandon in-flight work, and commit only offsets for completed records. Asynchronous handlers need partition-aware tracking to avoid committing past unfinished records. Graceful handling reduces duplicate work and prevents progress from being lost.

Syntax

Producer example:
```ts
await producer.send({ topic: "orders", messages: [{ key: orderId, value: JSON.stringify(event) }] });
```
Consumer example:
```ts
await consumer.run({ eachMessage: async ({ message }) => {
  const event = JSON.parse(message.value?.toString() ?? "{}");
  await handleIdempotently(event);
} });
```
Diagram: Producer -> Topic partition -> Consumer group -> Handler -> Offset commit

Example

// KafkaJS-style example await producer.send({ topic: "orders", messages: [{ key: order.id, value: JSON.stringify({ eventId, orderId: order.id }) }] });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q71RabbitMQ Topology and Queue Types

When should you use a direct exchange?

A direct exchange routes a message to queues whose binding key exactly matches the message routing key.

Answer

A direct exchange routes a message to queues whose binding key exactly matches the message routing key. It suits explicit routing such as invoice.created or priority.high. Keep routing keys stable and test bindings because a message with no matching route may be dropped unless unroutable handling is configured.

Syntax

Publish/consume example:
```ts
channel.publish("events", "order.created", Buffer.from(JSON.stringify(event)), { persistent: true });
channel.consume("orders", async msg => {
  if (!msg) return;
  try { await handleIdempotently(JSON.parse(msg.content.toString())); channel.ack(msg); }
  catch { channel.nack(msg, false, false); }
});
```
Diagram: Producer -> Exchange --routing key/binding--> Queue -> Consumer -> ack/nack

Example

// amqplib-style example channel.publish("events", "order.created", Buffer.from(JSON.stringify(event)), { persistent: true }); channel.consume("orders", async msg => { if (!msg) return; try { await handleIdempotently(JSON.parse(msg.content.toString())); channel.ack(msg); } catch { channel.nack(msg, false, false); } });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q72RabbitMQ Topology and Queue Types

When should you use a topic exchange?

A topic exchange matches dot-separated routing keys against patterns, where * matches one segment and # matches zero or more segments.

Answer

A topic exchange matches dot-separated routing keys against patterns, where * matches one segment and # matches zero or more segments. It is useful when consumers subscribe to categories such as order.created or order.*. Avoid uncontrolled wildcard subscriptions that accidentally receive sensitive or excessive traffic.

Syntax

Publish/consume example:
```ts
channel.publish("events", "order.created", Buffer.from(JSON.stringify(event)), { persistent: true });
channel.consume("orders", async msg => {
  if (!msg) return;
  try { await handleIdempotently(JSON.parse(msg.content.toString())); channel.ack(msg); }
  catch { channel.nack(msg, false, false); }
});
```
Diagram: Producer -> Exchange --routing key/binding--> Queue -> Consumer -> ack/nack

Example

// amqplib-style example channel.publish("events", "order.created", Buffer.from(JSON.stringify(event)), { persistent: true }); channel.consume("orders", async msg => { if (!msg) return; try { await handleIdempotently(JSON.parse(msg.content.toString())); channel.ack(msg); } catch { channel.nack(msg, false, false); } });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q73RabbitMQ Topology and Queue Types

When should you use a fanout exchange?

A fanout exchange routes a copy of each message to every bound queue and ignores the routing key.

Answer

A fanout exchange routes a copy of each message to every bound queue and ignores the routing key. It is useful for broadcast notifications where multiple independent consumers need the same event. Each subscriber needs a separate queue if it must receive and process its own copy.

Syntax

Publish/consume example:
```ts
channel.publish("events", "order.created", Buffer.from(JSON.stringify(event)), { persistent: true });
channel.consume("orders", async msg => {
  if (!msg) return;
  try { await handleIdempotently(JSON.parse(msg.content.toString())); channel.ack(msg); }
  catch { channel.nack(msg, false, false); }
});
```
Diagram: Producer -> Exchange --routing key/binding--> Queue -> Consumer -> ack/nack

Example

// amqplib-style example channel.publish("events", "order.created", Buffer.from(JSON.stringify(event)), { persistent: true }); channel.consume("orders", async msg => { if (!msg) return; try { await handleIdempotently(JSON.parse(msg.content.toString())); channel.ack(msg); } catch { channel.nack(msg, false, false); } });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q74RabbitMQ Topology and Queue Types

What are quorum queues?

RabbitMQ quorum queues use replicated state based on a majority of members to improve data safety and availability across node failures.

Answer

RabbitMQ quorum queues use replicated state based on a majority of members to improve data safety and availability across node failures. They have different performance and operational characteristics from classic queues. Size clusters and monitor quorum health, disk latency, and leader changes, and understand that a majority must remain available for progress.

Syntax

Publish/consume example:
```ts
channel.publish("events", "order.created", Buffer.from(JSON.stringify(event)), { persistent: true });
channel.consume("orders", async msg => {
  if (!msg) return;
  try { await handleIdempotently(JSON.parse(msg.content.toString())); channel.ack(msg); }
  catch { channel.nack(msg, false, false); }
});
```
Diagram: Producer -> Exchange --routing key/binding--> Queue -> Consumer -> ack/nack

Example

// amqplib-style example channel.publish("events", "order.created", Buffer.from(JSON.stringify(event)), { persistent: true }); channel.consume("orders", async msg => { if (!msg) return; try { await handleIdempotently(JSON.parse(msg.content.toString())); channel.ack(msg); } catch { channel.nack(msg, false, false); } });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q75RabbitMQ Topology and Queue Types

What are exclusive and auto-delete queues?

An exclusive queue is tied to its declaring connection, while an auto-delete queue is removed after its consumers are gone under the queue's lifecycle rules.

Answer

An exclusive queue is tied to its declaring connection, while an auto-delete queue is removed after its consumers are gone under the queue's lifecycle rules. They are useful for temporary reply queues or transient subscriptions, but not for durable business work that must survive client disconnects.

Syntax

Publish/consume example:
```ts
channel.publish("events", "order.created", Buffer.from(JSON.stringify(event)), { persistent: true });
channel.consume("orders", async msg => {
  if (!msg) return;
  try { await handleIdempotently(JSON.parse(msg.content.toString())); channel.ack(msg); }
  catch { channel.nack(msg, false, false); }
});
```
Diagram: Producer -> Exchange --routing key/binding--> Queue -> Consumer -> ack/nack

Example

// amqplib-style example channel.publish("events", "order.created", Buffer.from(JSON.stringify(event)), { persistent: true }); channel.consume("orders", async msg => { if (!msg) return; try { await handleIdempotently(JSON.parse(msg.content.toString())); channel.ack(msg); } catch { channel.nack(msg, false, false); } });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q76Flow Control and Backpressure

What is backpressure in messaging?

Backpressure prevents producers or consumers from overwhelming downstream capacity.

Answer

Backpressure prevents producers or consumers from overwhelming downstream capacity. It can be implemented with bounded queues, broker prefetch, rate limits, paused Kafka partitions, or upstream demand signals. Without it, latency and memory usage grow until the system becomes unstable.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q77Flow Control and Backpressure

How do you prevent an in-memory queue from exhausting memory?

Use a bounded queue, apply producer blocking or rejection when full, and expose queue depth and wait time as metrics.

Answer

Use a bounded queue, apply producer blocking or rejection when full, and expose queue depth and wait time as metrics. Define a policy for overload rather than silently dropping important work. Persist work in a broker when it must survive process restarts and size limits based on realistic message sizes.

Syntax

Publish/consume example:
```ts
channel.publish("events", "order.created", Buffer.from(JSON.stringify(event)), { persistent: true });
channel.consume("orders", async msg => {
  if (!msg) return;
  try { await handleIdempotently(JSON.parse(msg.content.toString())); channel.ack(msg); }
  catch { channel.nack(msg, false, false); }
});
```
Diagram: Producer -> Exchange --routing key/binding--> Queue -> Consumer -> ack/nack

Example

// amqplib-style example channel.publish("events", "order.created", Buffer.from(JSON.stringify(event)), { persistent: true }); channel.consume("orders", async msg => { if (!msg) return; try { await handleIdempotently(JSON.parse(msg.content.toString())); channel.ack(msg); } catch { channel.nack(msg, false, false); } });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q78Flow Control and Backpressure

How should consumer concurrency be tuned?

Increase concurrency gradually while measuring throughput, latency, error rate, CPU, memory, and downstream saturation.

Answer

Increase concurrency gradually while measuring throughput, latency, error rate, CPU, memory, and downstream saturation. More workers can reduce broker backlog but overload databases or external APIs. Respect ordering constraints and use bounded concurrency rather than spawning unbounded tasks for every message.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q79Flow Control and Backpressure

What is load shedding?

Load shedding deliberately rejects or drops lower-priority work when capacity is insufficient, protecting critical functions from cascading failure.

Answer

Load shedding deliberately rejects or drops lower-priority work when capacity is insufficient, protecting critical functions from cascading failure. It is appropriate only when the business semantics permit it, such as best-effort telemetry. For durable business events, prefer backpressure, buffering, or explicit rejection to silent loss.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q80Flow Control and Backpressure

How do you size a queue backlog?

Estimate backlog growth as incoming rate minus processing rate over time, then include average payload size, retention, retry traffic, and recovery throughput.

Answer

Estimate backlog growth as incoming rate minus processing rate over time, then include average payload size, retention, retry traffic, and recovery throughput. A backlog is recoverable only if consumers can process faster than new arrivals after the incident. Set capacity and alert thresholds based on recovery objectives, not just normal traffic.

Syntax

Publish/consume example:
```ts
channel.publish("events", "order.created", Buffer.from(JSON.stringify(event)), { persistent: true });
channel.consume("orders", async msg => {
  if (!msg) return;
  try { await handleIdempotently(JSON.parse(msg.content.toString())); channel.ack(msg); }
  catch { channel.nack(msg, false, false); }
});
```
Diagram: Producer -> Exchange --routing key/binding--> Queue -> Consumer -> ack/nack

Example

// amqplib-style example channel.publish("events", "order.created", Buffer.from(JSON.stringify(event)), { persistent: true }); channel.consume("orders", async msg => { if (!msg) return; try { await handleIdempotently(JSON.parse(msg.content.toString())); channel.ack(msg); } catch { channel.nack(msg, false, false); } });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q81Observability and Operations

Which metrics matter for Kafka?

Important Kafka metrics include consumer lag, records in and out, request latency, under-replicated partitions, offline partitions, ISR shrink events, disk usage, and error rates.

Answer

Important Kafka metrics include consumer lag, records in and out, request latency, under-replicated partitions, offline partitions, ISR shrink events, disk usage, and error rates. Track them by topic and consumer group where possible. Pair metrics with logs and traces so operators can locate the slow stage.

Syntax

Producer example:
```ts
await producer.send({ topic: "orders", messages: [{ key: orderId, value: JSON.stringify(event) }] });
```
Consumer example:
```ts
await consumer.run({ eachMessage: async ({ message }) => {
  const event = JSON.parse(message.value?.toString() ?? "{}");
  await handleIdempotently(event);
} });
```
Diagram: Producer -> Topic partition -> Consumer group -> Handler -> Offset commit

Example

// KafkaJS-style example await producer.send({ topic: "orders", messages: [{ key: order.id, value: JSON.stringify({ eventId, orderId: order.id }) }] });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q82Observability and Operations

Which metrics matter for RabbitMQ?

Monitor ready and unacknowledged message counts, publish and delivery rates, consumer count, redelivery rate, connection and channel churn, disk and memory alarms, and quorum health.

Answer

Monitor ready and unacknowledged message counts, publish and delivery rates, consumer count, redelivery rate, connection and channel churn, disk and memory alarms, and quorum health. Queue depth alone cannot distinguish slow processing from absent consumers. Alert on message age and sustained imbalance as well.

Syntax

Publish/consume example:
```ts
channel.publish("events", "order.created", Buffer.from(JSON.stringify(event)), { persistent: true });
channel.consume("orders", async msg => {
  if (!msg) return;
  try { await handleIdempotently(JSON.parse(msg.content.toString())); channel.ack(msg); }
  catch { channel.nack(msg, false, false); }
});
```
Diagram: Producer -> Exchange --routing key/binding--> Queue -> Consumer -> ack/nack

Example

// amqplib-style example channel.publish("events", "order.created", Buffer.from(JSON.stringify(event)), { persistent: true }); channel.consume("orders", async msg => { if (!msg) return; try { await handleIdempotently(JSON.parse(msg.content.toString())); channel.ack(msg); } catch { channel.nack(msg, false, false); } });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q83Observability and Operations

How do you trace a message across services?

Propagate a correlation ID and distributed trace context in message headers, then create producer and consumer spans linked through the messaging operation.

Answer

Propagate a correlation ID and distributed trace context in message headers, then create producer and consumer spans linked through the messaging operation. Record event ID and relevant destination metadata while avoiding sensitive payloads. Sampling and context propagation should be consistent across services.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q84Observability and Operations

What should a message-processing log contain?

Useful structured logs include event ID, message type, destination, attempt number, correlation ID, processing duration, outcome, and error category.

Answer

Useful structured logs include event ID, message type, destination, attempt number, correlation ID, processing duration, outcome, and error category. Avoid logging credentials or full sensitive payloads. Use consistent fields so operators can query a single event across producers, brokers, consumers, and retry paths.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q85Observability and Operations

How do you detect a stuck consumer?

Look for growing lag or queue age combined with no successful completions, stalled offsets, repeated errors, or absent heartbeats.

Answer

Look for growing lag or queue age combined with no successful completions, stalled offsets, repeated errors, or absent heartbeats. Distinguish a slow but progressing consumer from a deadlocked one. Alerts should include the affected group or queue, oldest-message age, and a runbook for safe recovery.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q86Security and Governance

How should brokers be secured?

Secure brokers with authenticated clients, encrypted transport, least-privilege authorization, network restrictions, and managed credentials.

Answer

Secure brokers with authenticated clients, encrypted transport, least-privilege authorization, network restrictions, and managed credentials. Rotate secrets and audit administrative access. Security configuration must cover producers, consumers, connectors, schema registries, and monitoring tools rather than only the broker listener.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q87Security and Governance

What is Kafka ACL authorization?

Kafka ACLs restrict which principals can perform operations on resources such as topics, consumer groups, and transactional IDs.

Answer

Kafka ACLs restrict which principals can perform operations on resources such as topics, consumer groups, and transactional IDs. Grant only the actions required by each service and separate administrative identities from application identities. Validate ACLs during deployment to avoid broad wildcard permissions.

Syntax

Producer example:
```ts
await producer.send({ topic: "orders", messages: [{ key: orderId, value: JSON.stringify(event) }] });
```
Consumer example:
```ts
await consumer.run({ eachMessage: async ({ message }) => {
  const event = JSON.parse(message.value?.toString() ?? "{}");
  await handleIdempotently(event);
} });
```
Diagram: Producer -> Topic partition -> Consumer group -> Handler -> Offset commit

Example

// KafkaJS-style example await producer.send({ topic: "orders", messages: [{ key: order.id, value: JSON.stringify({ eventId, orderId: order.id }) }] });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q88Security and Governance

How do you protect sensitive event data?

Minimize sensitive fields, classify data, encrypt transport and storage, restrict topic access, and define retention and deletion policies.

Answer

Minimize sensitive fields, classify data, encrypt transport and storage, restrict topic access, and define retention and deletion policies. Avoid putting secrets in headers or logs because metadata often spreads widely. If downstream consumers do not need a field, do not publish it.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q89Security and Governance

How do you prevent message spoofing?

Authenticate producers, authorize publication to specific destinations, validate message schemas and business invariants, and protect credentials.

Answer

Authenticate producers, authorize publication to specific destinations, validate message schemas and business invariants, and protect credentials. A consumer should not trust a payload merely because it came through a broker; validate tenant, ownership, and allowed state transitions before applying side effects.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q90Security and Governance

What governance is needed for event contracts?

Event governance should define ownership, naming, schema compatibility, retention, data classification, deprecation, and consumer discovery.

Answer

Event governance should define ownership, naming, schema compatibility, retention, data classification, deprecation, and consumer discovery. Automated schema checks and contract tests reduce accidental breaking changes. Governance should enable teams to evolve safely without requiring every change to be centrally approved.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q91Testing Messaging Systems

How do you unit-test a message handler?

Unit-test a handler by supplying representative payloads and mocking external dependencies, then assert the business result and failure classification.

Answer

Unit-test a handler by supplying representative payloads and mocking external dependencies, then assert the business result and failure classification. Keep broker mechanics outside the core domain logic where practical. Include duplicate deliveries, invalid payloads, transient failures, and permanent failures in the test cases.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q92Testing Messaging Systems

How do you integration-test Kafka consumers?

Integration tests should run against a real or containerized Kafka broker when broker behavior matters.

Answer

Integration tests should run against a real or containerized Kafka broker when broker behavior matters. Publish records, wait for observable processing outcomes, and verify offset, retry, and serialization behavior without relying on arbitrary sleeps. Use isolated topic names and clean up resources reliably.

Syntax

Producer example:
```ts
await producer.send({ topic: "orders", messages: [{ key: orderId, value: JSON.stringify(event) }] });
```
Consumer example:
```ts
await consumer.run({ eachMessage: async ({ message }) => {
  const event = JSON.parse(message.value?.toString() ?? "{}");
  await handleIdempotently(event);
} });
```
Diagram: Producer -> Topic partition -> Consumer group -> Handler -> Offset commit

Example

// KafkaJS-style example await producer.send({ topic: "orders", messages: [{ key: order.id, value: JSON.stringify({ eventId, orderId: order.id }) }] });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q93Testing Messaging Systems

How do you test RabbitMQ routing?

Create test exchanges, queues, and bindings, publish messages with matching and nonmatching routing keys, and assert which queues receive them.

Answer

Create test exchanges, queues, and bindings, publish messages with matching and nonmatching routing keys, and assert which queues receive them. Include publisher confirms, unroutable messages, acknowledgement failures, and dead-letter behavior. Use isolated virtual hosts or unique names to avoid test interference.

Syntax

Publish/consume example:
```ts
channel.publish("events", "order.created", Buffer.from(JSON.stringify(event)), { persistent: true });
channel.consume("orders", async msg => {
  if (!msg) return;
  try { await handleIdempotently(JSON.parse(msg.content.toString())); channel.ack(msg); }
  catch { channel.nack(msg, false, false); }
});
```
Diagram: Producer -> Exchange --routing key/binding--> Queue -> Consumer -> ack/nack

Example

// amqplib-style example channel.publish("events", "order.created", Buffer.from(JSON.stringify(event)), { persistent: true }); channel.consume("orders", async msg => { if (!msg) return; try { await handleIdempotently(JSON.parse(msg.content.toString())); channel.ack(msg); } catch { channel.nack(msg, false, false); } });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q94Testing Messaging Systems

What is a contract test for events?

A contract test verifies that producer output matches the agreed schema and semantic expectations consumed by downstream services.

Answer

A contract test verifies that producer output matches the agreed schema and semantic expectations consumed by downstream services. It can validate required fields, event types, and compatibility against representative consumers. Schema compatibility alone is not enough if a field's meaning changes without a shape change.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q95Testing Messaging Systems

How do you test retry and dead-letter flows?

Inject a controlled failure and assert the attempt count, delay tier, dead-letter destination, and preserved event identity.

Answer

Inject a controlled failure and assert the attempt count, delay tier, dead-letter destination, and preserved event identity. Test that permanent failures do not retry indefinitely and that replay is safe. Prefer deterministic clocks or test hooks over long real-time waits.

Syntax

Bounded retry example:
```ts
const delayMs = Math.min(60_000, 1_000 * 2 ** attempt);
if (isTransient(error) && attempt < MAX_ATTEMPTS) {
  await scheduleRetry(event, delayMs);
} else {
  await publishDeadLetter(event, { reason: classify(error), attempt });
}
```
Diagram: Consume -> Classify error -> Retry with backoff -> Success / Dead-letter after limit

Example

const delayMs = Math.min(60_000, 1_000 * 2 ** attempt); if (isTransient(error) && attempt < MAX_ATTEMPTS) { await scheduleRetry(event, delayMs + Math.random() * 250); } else { await publishDeadLetter(event, { reason: classify(error), attempt }); }

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.

Advanced Questions

Architecture, optimization, and design trade-offs.

Q61Kafka Transactions and Stream Processing

What are Kafka transactions useful for?

Kafka transactions can atomically publish records to multiple Kafka partitions and commit consumed offsets as part of the same Kafka transaction.

Answer

Kafka transactions can atomically publish records to multiple Kafka partitions and commit consumed offsets as part of the same Kafka transaction. This supports consume-transform-produce workflows without exposing partial output to read-committed consumers. The guarantee does not automatically include external databases or HTTP services.

Syntax

Producer example:
```ts
await producer.send({ topic: "orders", messages: [{ key: orderId, value: JSON.stringify(event) }] });
```
Consumer example:
```ts
await consumer.run({ eachMessage: async ({ message }) => {
  const event = JSON.parse(message.value?.toString() ?? "{}");
  await handleIdempotently(event);
} });
```
Diagram: Producer -> Topic partition -> Consumer group -> Handler -> Offset commit

Example

// KafkaJS-style example await producer.send({ topic: "orders", messages: [{ key: order.id, value: JSON.stringify({ eventId, orderId: order.id }) }] });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q62Kafka Transactions and Stream Processing

What is read_committed isolation in Kafka?

A read_committed consumer reads only records from committed transactions and skips aborted transactional records.

Answer

A read_committed consumer reads only records from committed transactions and skips aborted transactional records. It is useful when downstream consumers must not observe output from failed Kafka transactions. Consumers using read_uncommitted can see transactional records before commit, so isolation should match the application's guarantee.

Syntax

Producer example:
```ts
await producer.send({ topic: "orders", messages: [{ key: orderId, value: JSON.stringify(event) }] });
```
Consumer example:
```ts
await consumer.run({ eachMessage: async ({ message }) => {
  const event = JSON.parse(message.value?.toString() ?? "{}");
  await handleIdempotently(event);
} });
```
Diagram: Producer -> Topic partition -> Consumer group -> Handler -> Offset commit

Example

// KafkaJS-style example await producer.send({ topic: "orders", messages: [{ key: order.id, value: JSON.stringify({ eventId, orderId: order.id }) }] });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q63Kafka Transactions and Stream Processing

What is a stream-processing topology?

A stream-processing topology connects sources, transformations, joins, aggregations, and sinks into a continuous computation.

Answer

A stream-processing topology connects sources, transformations, joins, aggregations, and sinks into a continuous computation. Stateful operations require storage and recovery strategies, and event-time processing may need to handle late data. Design for replay, partitioning, state growth, and observable processing lag.

Syntax

Producer example:
```ts
await producer.send({ topic: "orders", messages: [{ key: orderId, value: JSON.stringify(event) }] });
```
Consumer example:
```ts
await consumer.run({ eachMessage: async ({ message }) => {
  const event = JSON.parse(message.value?.toString() ?? "{}");
  await handleIdempotently(event);
} });
```
Diagram: Producer -> Topic partition -> Consumer group -> Handler -> Offset commit

Example

// KafkaJS-style example await producer.send({ topic: "orders", messages: [{ key: order.id, value: JSON.stringify({ eventId, orderId: order.id }) }] });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q64Kafka Transactions and Stream Processing

What is a Kafka Streams state store?

A state store holds local or persistent state used by a Kafka Streams application for operations such as aggregation, joins, and deduplication.

Answer

A state store holds local or persistent state used by a Kafka Streams application for operations such as aggregation, joins, and deduplication. Changelog topics can help restore state after failure. State size, restoration time, key distribution, and local disk capacity affect recovery and operational behavior.

Syntax

Producer example:
```ts
await producer.send({ topic: "orders", messages: [{ key: orderId, value: JSON.stringify(event) }] });
```
Consumer example:
```ts
await consumer.run({ eachMessage: async ({ message }) => {
  const event = JSON.parse(message.value?.toString() ?? "{}");
  await handleIdempotently(event);
} });
```
Diagram: Producer -> Topic partition -> Consumer group -> Handler -> Offset commit

Example

// KafkaJS-style example await producer.send({ topic: "orders", messages: [{ key: order.id, value: JSON.stringify({ eventId, orderId: order.id }) }] });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q65Kafka Transactions and Stream Processing

What are event time and processing time?

Event time is when the event occurred in the source domain, while processing time is when the stream processor handles it.

Answer

Event time is when the event occurred in the source domain, while processing time is when the stream processor handles it. Delays and out-of-order arrival can make them differ substantially. Event-time windows often use watermarks or grace periods to balance correctness for late events against output latency.

Syntax

Producer example:
```ts
await producer.send({ topic: "orders", messages: [{ key: orderId, value: JSON.stringify(event) }] });
```
Consumer example:
```ts
await consumer.run({ eachMessage: async ({ message }) => {
  const event = JSON.parse(message.value?.toString() ?? "{}");
  await handleIdempotently(event);
} });
```
Diagram: Producer -> Topic partition -> Consumer group -> Handler -> Offset commit

Example

// KafkaJS-style example await producer.send({ topic: "orders", messages: [{ key: order.id, value: JSON.stringify({ eventId, orderId: order.id }) }] });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q96Distributed Workflows and Sagas

What is a saga?

A saga coordinates a business transaction across multiple services as a sequence of local transactions and compensating actions.

Answer

A saga coordinates a business transaction across multiple services as a sequence of local transactions and compensating actions. Each step commits independently, and failures trigger retries or compensations rather than a single global database rollback. Sagas require explicit state, idempotent steps, timeouts, and operational recovery.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q97Distributed Workflows and Sagas

What is a compensating transaction?

A compensating transaction semantically reverses or offsets an earlier completed step, such as releasing a reservation after a payment fails.

Answer

A compensating transaction semantically reverses or offsets an earlier completed step, such as releasing a reservation after a payment fails. It is not always a literal rollback because external effects may be irreversible. Design compensation as a business operation with its own idempotency and failure handling.

Syntax

Transactional outbox example:
```sql
BEGIN;
UPDATE orders SET status = 'CREATED' WHERE id = :order_id;
INSERT INTO outbox(event_id, event_type, payload)
VALUES (:event_id, 'OrderCreated', :payload);
COMMIT;
```
Diagram: Business transaction -> Outbox table -> Relay/CDC -> Broker -> Idempotent consumer

Example

-- Outbox rows are written in the same transaction as the business change BEGIN; UPDATE orders SET status = 'CREATED' WHERE id = :order_id; INSERT INTO outbox(event_id, event_type, payload) VALUES (:event_id, 'OrderCreated', :payload); COMMIT;

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q98Distributed Workflows and Sagas

How do you make saga steps idempotent?

Give each step a stable operation ID, persist its status with a uniqueness constraint, and make repeated commands return the known result instead of applying the action again.

Answer

Give each step a stable operation ID, persist its status with a uniqueness constraint, and make repeated commands return the known result instead of applying the action again. Record transitions atomically and handle duplicate events. Compensation should also have a stable identity and safe retry policy.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q99Distributed Workflows and Sagas

How do you handle a saga timeout?

A timeout should move the workflow into an explicit state where the coordinator checks whether the step succeeded, retries safely, or initiates compensation.

Answer

A timeout should move the workflow into an explicit state where the coordinator checks whether the step succeeded, retries safely, or initiates compensation. A timed-out response may hide a successful remote action, so reconcile using operation IDs before compensating. Alert on workflows that exceed their expected duration.

Syntax

Bounded retry example:
```ts
const delayMs = Math.min(60_000, 1_000 * 2 ** attempt);
if (isTransient(error) && attempt < MAX_ATTEMPTS) {
  await scheduleRetry(event, delayMs);
} else {
  await publishDeadLetter(event, { reason: classify(error), attempt });
}
```
Diagram: Consume -> Classify error -> Retry with backoff -> Success / Dead-letter after limit

Example

const delayMs = Math.min(60_000, 1_000 * 2 ** attempt); if (isTransient(error) && attempt < MAX_ATTEMPTS) { await scheduleRetry(event, delayMs + Math.random() * 250); } else { await publishDeadLetter(event, { reason: classify(error), attempt }); }

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q100Distributed Workflows and Sagas

When is a saga preferable to a distributed transaction?

A saga is often preferable when services own separate databases, operations span long periods, or global locks and distributed transaction support are impractical.

Answer

A saga is often preferable when services own separate databases, operations span long periods, or global locks and distributed transaction support are impractical. It trades atomic rollback for eventual consistency and business compensation. Use it only when intermediate states and compensation are acceptable to the domain.

Syntax

Transactional outbox example:
```sql
BEGIN;
UPDATE orders SET status = 'CREATED' WHERE id = :order_id;
INSERT INTO outbox(event_id, event_type, payload)
VALUES (:event_id, 'OrderCreated', :payload);
COMMIT;
```
Diagram: Business transaction -> Outbox table -> Relay/CDC -> Broker -> Idempotent consumer

Example

-- Outbox rows are written in the same transaction as the business change BEGIN; UPDATE orders SET status = 'CREATED' WHERE id = :order_id; INSERT INTO outbox(event_id, event_type, payload) VALUES (:event_id, 'OrderCreated', :payload); COMMIT;

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q101Advanced Reliability Patterns

What is the inbox pattern?

The inbox pattern records incoming event IDs durably before or alongside business processing so duplicate deliveries can be detected.

Answer

The inbox pattern records incoming event IDs durably before or alongside business processing so duplicate deliveries can be detected. The inbox record and business update should share a transaction when possible. It complements an outbox, which records outgoing publication intent, and supports reliable service boundaries.

Syntax

Transactional outbox example:
```sql
BEGIN;
UPDATE orders SET status = 'CREATED' WHERE id = :order_id;
INSERT INTO outbox(event_id, event_type, payload)
VALUES (:event_id, 'OrderCreated', :payload);
COMMIT;
```
Diagram: Business transaction -> Outbox table -> Relay/CDC -> Broker -> Idempotent consumer

Example

-- Outbox rows are written in the same transaction as the business change BEGIN; UPDATE orders SET status = 'CREATED' WHERE id = :order_id; INSERT INTO outbox(event_id, event_type, payload) VALUES (:event_id, 'OrderCreated', :payload); COMMIT;

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q102Advanced Reliability Patterns

What is a transactional inbox/outbox combination?

A transactional inbox/outbox service atomically records the incoming event as handled, updates local business state, and writes outgoing events to an outbox.

Answer

A transactional inbox/outbox service atomically records the incoming event as handled, updates local business state, and writes outgoing events to an outbox. A relay later publishes the outbox rows. This avoids losing local state transitions and outgoing event intent, while stable IDs and idempotent consumers handle possible redelivery.

Syntax

Transactional outbox example:
```sql
BEGIN;
UPDATE orders SET status = 'CREATED' WHERE id = :order_id;
INSERT INTO outbox(event_id, event_type, payload)
VALUES (:event_id, 'OrderCreated', :payload);
COMMIT;
```
Diagram: Business transaction -> Outbox table -> Relay/CDC -> Broker -> Idempotent consumer

Example

-- Outbox rows are written in the same transaction as the business change BEGIN; UPDATE orders SET status = 'CREATED' WHERE id = :order_id; INSERT INTO outbox(event_id, event_type, payload) VALUES (:event_id, 'OrderCreated', :payload); COMMIT;

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q103Advanced Reliability Patterns

How do you handle a database commit followed by broker acknowledgement failure?

If the database transaction commits but acknowledgement fails, the broker may redeliver the message.

Answer

If the database transaction commits but acknowledgement fails, the broker may redeliver the message. The consumer should recognize the event ID as already applied and acknowledge the duplicate safely. This is why deduplication state must be committed atomically with the business change.

Syntax

Transactional outbox example:
```sql
BEGIN;
UPDATE orders SET status = 'CREATED' WHERE id = :order_id;
INSERT INTO outbox(event_id, event_type, payload)
VALUES (:event_id, 'OrderCreated', :payload);
COMMIT;
```
Diagram: Business transaction -> Outbox table -> Relay/CDC -> Broker -> Idempotent consumer

Example

-- Outbox rows are written in the same transaction as the business change BEGIN; UPDATE orders SET status = 'CREATED' WHERE id = :order_id; INSERT INTO outbox(event_id, event_type, payload) VALUES (:event_id, 'OrderCreated', :payload); COMMIT;

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q104Advanced Reliability Patterns

How do you handle broker publish timeout with an unknown outcome?

A publish timeout may mean the broker never accepted the message or accepted it but the acknowledgement was lost.

Answer

A publish timeout may mean the broker never accepted the message or accepted it but the acknowledgement was lost. Retry with stable event identity and producer idempotence where available, and make consumers idempotent. Do not interpret a timeout as proof of failure.

Syntax

Bounded retry example:
```ts
const delayMs = Math.min(60_000, 1_000 * 2 ** attempt);
if (isTransient(error) && attempt < MAX_ATTEMPTS) {
  await scheduleRetry(event, delayMs);
} else {
  await publishDeadLetter(event, { reason: classify(error), attempt });
}
```
Diagram: Consume -> Classify error -> Retry with backoff -> Success / Dead-letter after limit

Example

const delayMs = Math.min(60_000, 1_000 * 2 ** attempt); if (isTransient(error) && attempt < MAX_ATTEMPTS) { await scheduleRetry(event, delayMs + Math.random() * 250); } else { await publishDeadLetter(event, { reason: classify(error), attempt }); }

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q105Advanced Reliability Patterns

How do you design replay-safe consumers?

Replay-safe consumers separate event ingestion from irreversible side effects, use stable IDs and version-aware business rules, and record processing state.

Answer

Replay-safe consumers separate event ingestion from irreversible side effects, use stable IDs and version-aware business rules, and record processing state. Replaying historical data should not resend notifications or charge payments unless explicitly intended. Provide replay modes, rate limits, and audit logs.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q106Performance and Capacity

How do you increase Kafka throughput?

Increase throughput by tuning batch size and linger, using compression, distributing keys across partitions, and ensuring broker disks and networks are not bottlenecks.

Answer

Increase throughput by tuning batch size and linger, using compression, distributing keys across partitions, and ensuring broker disks and networks are not bottlenecks. Scale partitions and consumers only after measuring the limiting stage. More partitions increase overhead and can complicate ordering and recovery.

Syntax

Producer example:
```ts
await producer.send({ topic: "orders", messages: [{ key: orderId, value: JSON.stringify(event) }] });
```
Consumer example:
```ts
await consumer.run({ eachMessage: async ({ message }) => {
  const event = JSON.parse(message.value?.toString() ?? "{}");
  await handleIdempotently(event);
} });
```
Diagram: Producer -> Topic partition -> Consumer group -> Handler -> Offset commit

Example

// KafkaJS-style example await producer.send({ topic: "orders", messages: [{ key: order.id, value: JSON.stringify({ eventId, orderId: order.id }) }] });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q107Performance and Capacity

How do you reduce end-to-end message latency?

Reduce latency by minimizing unnecessary hops, tuning batching and acknowledgements to the required durability, keeping handlers efficient, and avoiding saturated downstream services.

Answer

Reduce latency by minimizing unnecessary hops, tuning batching and acknowledgements to the required durability, keeping handlers efficient, and avoiding saturated downstream services. Measure publish-to-completion latency separately from broker request latency. Aggressive batching may improve throughput but add waiting time.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q108Performance and Capacity

How do you estimate Kafka partition count?

Estimate partition count from target throughput per partition, required consumer parallelism, key distribution, and operational overhead, then validate with load tests.

Answer

Estimate partition count from target throughput per partition, required consumer parallelism, key distribution, and operational overhead, then validate with load tests. A partition count that is too low limits parallelism; too many partitions increase metadata, file, recovery, and controller overhead. Revisit the estimate as workloads evolve.

Syntax

Producer example:
```ts
await producer.send({ topic: "orders", messages: [{ key: orderId, value: JSON.stringify(event) }] });
```
Consumer example:
```ts
await consumer.run({ eachMessage: async ({ message }) => {
  const event = JSON.parse(message.value?.toString() ?? "{}");
  await handleIdempotently(event);
} });
```
Diagram: Producer -> Topic partition -> Consumer group -> Handler -> Offset commit

Example

// KafkaJS-style example await producer.send({ topic: "orders", messages: [{ key: order.id, value: JSON.stringify({ eventId, orderId: order.id }) }] });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q109Performance and Capacity

How do you handle large messages?

Prefer storing large objects in object storage and publishing a reference with integrity metadata rather than sending huge payloads through the broker.

Answer

Prefer storing large objects in object storage and publishing a reference with integrity metadata rather than sending huge payloads through the broker. If large messages are unavoidable, validate broker limits, memory pressure, network timeouts, and retry cost. References need access control and lifecycle management.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q110Performance and Capacity

What is batching and when can it hurt?

Batching groups messages to reduce network and broker overhead, improving throughput.

Answer

Batching groups messages to reduce network and broker overhead, improving throughput. It can increase latency while the batch fills and may enlarge retry units. Choose batch settings based on traffic volume and latency objectives, and test behavior during low-volume periods as well as peak load.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q111Multi-Tenant and Multi-Region Messaging

How do you isolate tenants in a messaging platform?

Tenant isolation can use separate topics or queues, authorization policies, quotas, and tenant-aware metadata.

Answer

Tenant isolation can use separate topics or queues, authorization policies, quotas, and tenant-aware metadata. Shared destinations reduce operational overhead but increase the risk of noisy neighbors and accidental data exposure. Validate tenant identity from trusted context and monitor per-tenant usage.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q112Multi-Tenant and Multi-Region Messaging

What should be considered in cross-region event replication?

Cross-region replication introduces network latency, replication lag, conflict risk, and failure-mode complexity.

Answer

Cross-region replication introduces network latency, replication lag, conflict risk, and failure-mode complexity. Decide whether the remote region is for disaster recovery, active-active processing, or analytics because each has different consistency requirements. Define ownership, failover, and duplicate handling before enabling bidirectional writes.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q113Multi-Tenant and Multi-Region Messaging

How do you avoid duplicate processing during failover?

Use stable event IDs, idempotent handlers, clear partition or queue ownership, and a failover procedure that avoids two active consumers performing the same irreversible work.

Answer

Use stable event IDs, idempotent handlers, clear partition or queue ownership, and a failover procedure that avoids two active consumers performing the same irreversible work. Replication may replay records after a cutover. Reconcile offsets and business state before resuming full traffic.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q114Multi-Tenant and Multi-Region Messaging

How do you define a disaster-recovery objective for messaging?

Define recovery point objective, recovery time objective, retention, replication lag tolerance, and the expected replay volume.

Answer

Define recovery point objective, recovery time objective, retention, replication lag tolerance, and the expected replay volume. Test restoration and failover regularly, including credentials, schemas, connectors, and consumer offsets. A replicated broker is not a complete DR plan unless applications can resume safely.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q115Multi-Tenant and Multi-Region Messaging

How do you prevent a noisy tenant from starving others?

Use per-tenant quotas, priority lanes where supported, bounded concurrency, and separate destinations for workloads with very different service levels.

Answer

Use per-tenant quotas, priority lanes where supported, bounded concurrency, and separate destinations for workloads with very different service levels. Measure arrival rate, backlog age, and processing cost per tenant. Isolation should match the required fairness and the cost of operating separate resources.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q116Design and Architecture Scenarios

Design reliable order-event processing.

Use an order service that commits the order and an outbox record in one transaction, then publishes OrderCreated.

Answer

Use an order service that commits the order and an outbox record in one transaction, then publishes OrderCreated. Consumers such as billing and fulfillment use event IDs for deduplication and maintain explicit state transitions. Monitor outbox age, consumer lag, retries, and dead-letter queues; define compensation for partial workflow failure.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q117Design and Architecture Scenarios

Design a notification system using pub/sub.

Publish domain events to a durable topic and let email, SMS, and push consumers maintain independent subscriptions.

Answer

Publish domain events to a durable topic and let email, SMS, and push consumers maintain independent subscriptions. Each channel consumer should use idempotency keys, rate limits, retry policies, and dead-letter handling. Store delivery status separately and avoid letting a failing channel block unrelated channels.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q118Design and Architecture Scenarios

Design a payment-processing consumer that must not double-charge.

Require a stable payment operation ID, use the payment provider's idempotency feature, and persist the operation state transactionally.

Answer

Require a stable payment operation ID, use the payment provider's idempotency feature, and persist the operation state transactionally. A message redelivery should return the recorded outcome rather than create a new charge. Reconcile ambiguous timeouts and alert on operations stuck in an unknown state.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q119Design and Architecture Scenarios

Design an event pipeline for analytics.

Publish domain events to a retained Kafka topic, validate schemas, and consume them into analytical storage through replayable processing.

Answer

Publish domain events to a retained Kafka topic, validate schemas, and consume them into analytical storage through replayable processing. Use event IDs to deduplicate, event time for windowed metrics, and checkpoints or offsets for recovery. Separate analytics failures from transactional application paths and monitor lag and data quality.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q120Design and Architecture Scenarios

How would you migrate from a queue-based system to Kafka?

Inventory message contracts, routing rules, ordering needs, retention, retry behavior, and consumer ownership first.

Answer

Inventory message contracts, routing rules, ordering needs, retention, retry behavior, and consumer ownership first. Use a controlled dual-publish or bridge strategy with stable event IDs and compare outputs before cutover. Avoid uncontrolled dual writes; provide rollback, lag monitoring, and a clear authority for each message stream.

Syntax

Producer example:
```ts
await producer.send({ topic: "orders", messages: [{ key: orderId, value: JSON.stringify(event) }] });
```
Consumer example:
```ts
await consumer.run({ eachMessage: async ({ message }) => {
  const event = JSON.parse(message.value?.toString() ?? "{}");
  await handleIdempotently(event);
} });
```
Diagram: Producer -> Topic partition -> Consumer group -> Handler -> Offset commit

Example

// KafkaJS-style example await producer.send({ topic: "orders", messages: [{ key: order.id, value: JSON.stringify({ eventId, orderId: order.id }) }] });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q121Governance, Cost, and Lifecycle

How should event retention be chosen?

Retention should reflect replay needs, compliance obligations, storage cost, and downstream recovery windows.

Answer

Retention should reflect replay needs, compliance obligations, storage cost, and downstream recovery windows. Kafka retention by time or size is different from queue deletion after acknowledgement. Document whether historical replay is supported and ensure required consumers can recover before data expires.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q122Governance, Cost, and Lifecycle

What is log compaction in Kafka?

Log compaction retains the latest value for each key over time, making a topic useful for state snapshots or changelog streams.

Answer

Log compaction retains the latest value for each key over time, making a topic useful for state snapshots or changelog streams. It does not mean every intermediate event remains available indefinitely. Tombstones and cleanup timing matter, so compaction is unsuitable when every historical transition must be preserved.

Syntax

Producer example:
```ts
await producer.send({ topic: "orders", messages: [{ key: orderId, value: JSON.stringify(event) }] });
```
Consumer example:
```ts
await consumer.run({ eachMessage: async ({ message }) => {
  const event = JSON.parse(message.value?.toString() ?? "{}");
  await handleIdempotently(event);
} });
```
Diagram: Producer -> Topic partition -> Consumer group -> Handler -> Offset commit

Example

// KafkaJS-style example await producer.send({ topic: "orders", messages: [{ key: order.id, value: JSON.stringify({ eventId, orderId: order.id }) }] });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q123Governance, Cost, and Lifecycle

How do you deprecate an event safely?

Identify all producers and consumers, announce the timeline, add replacement fields or event versions, and monitor adoption before removing old behavior.

Answer

Identify all producers and consumers, announce the timeline, add replacement fields or event versions, and monitor adoption before removing old behavior. Avoid changing event meaning in place. Contract tests and consumer inventory help verify that no critical dependency is silently left behind.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q124Governance, Cost, and Lifecycle

How do you control messaging platform cost?

Control cost by right-sizing retention and replication, compressing payloads, limiting unnecessary fan-out, batching efficiently, and removing abandoned topics and queues.

Answer

Control cost by right-sizing retention and replication, compressing payloads, limiting unnecessary fan-out, batching efficiently, and removing abandoned topics and queues. Balance savings against recovery and durability requirements. Use per-team ownership and usage dashboards to make costs attributable.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.
Q125Governance, Cost, and Lifecycle

What operational runbooks should messaging teams maintain?

Runbooks should cover consumer lag, queue buildup, broker disk pressure, under-replicated partitions, credential rotation, dead-letter replay, schema failures, and disaster recovery.

Answer

Runbooks should cover consumer lag, queue buildup, broker disk pressure, under-replicated partitions, credential rotation, dead-letter replay, schema failures, and disaster recovery. Include diagnostic commands, safe remediation steps, escalation contacts, and post-incident checks. Test runbooks during exercises rather than only during outages.

Syntax

Event contract example:
```ts
type DomainEvent<T> = {
  eventId: string;
  eventType: string;
  occurredAt: string;
  correlationId: string;
  data: T;
};
```
Example: `OrderCreated` is published after the order transaction commits.
Diagram: Domain change -> Event envelope -> Broker -> Independent subscribers

Example

type DomainEvent<T> = { eventId: string; eventType: string; occurredAt: string; correlationId: string; data: T; }; await publish({ eventId, eventType, occurredAt: new Date().toISOString(), correlationId, data });

Key Points

  • Define the guarantee and failure boundary explicitly.
  • Use stable event IDs and idempotent processing where duplicates are possible.
  • Monitor backlog, processing latency, and failure/retry rates.

Share this question bank

Send this page to someone preparing for an interview.