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.