Kafka Advanced
This chapter distinguishes processing guarantees, builds atomic read-process-write flows, secures broker traffic and authorization, defines actionable telemetry, and connects external systems without custom polling loops.
- Explain Exactly-once semantics by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Security & monitoring by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Kafka Connect by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Kafka Streams vs Flink by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Alert rule reference by naming its input, guarantee, internal lifecycle, important failure, and proof.
How to use this chapter
For Kafka Advanced, read the explanations first and predict every example before running it. Keep a learning repository containing code, tests, command output, and the short written submission. The roadmap checklist at the end audits coverage; the chapter itself follows the distributed learning arc appropriate to this subject.
The problem this chapter solves
This chapter distinguishes processing guarantees, builds atomic read-process-write flows, secures broker traffic and authorization, defines actionable telemetry, and connects external systems without custom polling loops.
It decouples services in time, supports high-throughput event streams, and lets multiple independent consumer groups derive different views from the same facts.
Learning outcomes
- Explain Exactly-once semantics by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Security & monitoring by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Kafka Connect by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Kafka Streams vs Flink by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Alert rule reference by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Trace the chapter's complete execution path and identify where memory, I/O, concurrency, persistence, or rendering cost accumulates.
- Build the worked example, make one failure visible, and defend the design in a review.
Chapter progression
The order below is intentional: later sections depend on guarantees established earlier.
Runtime or system overview
A record key is mapped to a partition, sent to that partition's leader, appended to the log, and replicated to followers. A consumer group assigns each partition to at most one active member. Offsets are application progress, not record identities. Durability depends on acknowledgments, replication, ISR, and broker settings working together. In Kafka Advanced, use that execution model to decide where the chapter's validation, state ownership, cleanup, and evidence belong.
Execution trace
- The producer validates and serializes a versioned record, hashes its key to a partition, batches it, and sends it to that partition's leader under the configured acknowledgment policy.
- The broker appends the record at the next partition offset and replicates it; durability depends on acknowledgments, in-sync replicas, and minimum-ISR settings together.
- A group member polls assigned partitions, deserializes the record, checks event identity, and performs its bounded idempotent side effect.
- Recoverable progress advances only after the corresponding effect is durable, or a Kafka transaction atomically publishes output and offsets for Kafka-to-Kafka work.
- Tests inject duplicate delivery, rebalance, poison data, broker interruption, and lag while asserting ordering only within the declared key scope.
Memory and performance lens
Producers batch records in client buffers; consumers fetch batches into memory. Oversized messages, unlimited in-flight requests, slow processing, and large poll batches cause pressure. Broker page cache is central to throughput; Kafka is designed around sequential disk I/O and zero-copy transfer where possible. For Kafka Advanced, connect those costs to the concrete operations in the topic sections rather than assuming the friendly surface syntax is cheap.
When tuning Kafka Advanced, measure publish-to-complete latency, retries, duplicate effects, oldest work age, queue depth or partition lag, throughput, and recovery time rather than optimizing from source-code appearance.
1. Exactly-once semantics
The Exactly-once semantics unit begins with at-most-once/at-least-once/exactly-once: Processing guarantees describe where duplicates or loss can occur; Kafka transactions can atomically publish output records and consumed offsets within Kafka. Use Kafka EOS for Kafka-to-Kafka flows and idempotent sinks for external effects. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
Guarantees before APIs: Exactly-once semantics
| Concept | Meaning | Engineering decision |
|---|---|---|
| at-most-once/at-least-once/exactly-once | Processing guarantees describe where duplicates or loss can occur; Kafka transactions can atomically publish output records and consumed offsets within Kafka. | Use Kafka EOS for Kafka-to-Kafka flows and idempotent sinks for external effects. |
| idempotent producers | Producer settings balance latency, throughput, ordering, and durability. | Enable idempotence, use stable keys, and handle delivery callbacks. |
| transactions: atomic read-process-write | Processing guarantees describe where duplicates or loss can occur; Kafka transactions can atomically publish output records and consumed offsets within Kafka. | Use Kafka EOS for Kafka-to-Kafka flows and idempotent sinks for external effects. |
| EOS Python transactional API | Processing guarantees describe where duplicates or loss can occur; Kafka transactions can atomically publish output records and consumed offsets within Kafka. | Use Kafka EOS for Kafka-to-Kafka flows and idempotent sinks for external effects. |
Message and failure lifecycle: Exactly-once semantics
at-most-once/at-least-once/exactly-once. An idempotent transactional producer uses a transactional ID and epoch; consumers using read_committed hide aborted writes.
idempotent producers. Records accumulate per partition, are compressed and sent in batches. acks=all waits for the configured replica condition; idempotence uses producer IDs and sequence numbers to suppress retry duplicates within Kafka.
transactions: atomic read-process-write. An idempotent transactional producer uses a transactional ID and epoch; consumers using read_committed hide aborted writes.
EOS Python transactional API. An idempotent transactional producer uses a transactional ID and epoch; consumers using read_committed hide aborted writes.
Read these as one system: at-most-once/at-least-once/exactly-once establishes the starting contract, idempotent producers changes how that contract is executed or represented, and EOS Python transactional API exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
A recoverable implementation slice: Exactly-once semantics
1event = {"event_id": event_id, "type": "at_most_once_at_least_once_exactly_once.v1", "payload": payload}2producer.produce(topic, key=entity_id, value=encode(event), on_delivery=delivered)3producer.poll(0)This Exactly-once semantics slice makes at-most-once/at-least-once/exactly-once observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward EOS Python transactional API, predict its behavior for empty, invalid, repeated, and large input.
Duplicate, ordering, and outage traps: Exactly-once semantics
| Risk | Why it matters |
|---|---|
| at-most-once/at-least-once/exactly-once | EOS does not make an arbitrary HTTP call or database write exactly once. |
| idempotent producers | acks=all is not sufficient if replication or minimum ISR is misconfigured. |
| transactions: atomic read-process-write | EOS does not make an arbitrary HTTP call or database write exactly once. |
| EOS Python transactional API | EOS does not make an arbitrary HTTP call or database write exactly once. |
Failure-recovery drill: Exactly-once semantics
- Foundation: implement or demonstrate at-most-once/at-least-once/exactly-once with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine at-most-once/at-least-once/exactly-once with idempotent producers. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for EOS Python transactional API. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
2. Security & monitoring
The Security & monitoring unit begins with SSL encryption + SASL (PLAIN/SCRAM-SHA-256): TLS protects transport, SASL authenticates clients, ACLs authorize operations, and telemetry reveals durability and latency risk. Use unique principals, least privilege, certificate rotation, and lag/ISR alerts. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
Guarantees before APIs: Security & monitoring
| Concept | Meaning | Engineering decision |
|---|---|---|
| SSL encryption + SASL (PLAIN/SCRAM-SHA-256) | TLS protects transport, SASL authenticates clients, ACLs authorize operations, and telemetry reveals durability and latency risk. | Use unique principals, least privilege, certificate rotation, and lag/ISR alerts. |
| ACLs with kafka-acls.sh | TLS protects transport, SASL authenticates clients, ACLs authorize operations, and telemetry reveals durability and latency risk. | Use unique principals, least privilege, certificate rotation, and lag/ISR alerts. |
| Prometheus JMX exporter | TLS protects transport, SASL authenticates clients, ACLs authorize operations, and telemetry reveals durability and latency risk. | Use unique principals, least privilege, certificate rotation, and lag/ISR alerts. |
| Grafana key metrics: consumer lag/under-replicated/latency | A consumer group divides partitions so one member owns a partition at a time; committed offsets represent recoverable progress. | Commit only after the corresponding side effects are durable and make the handler idempotent. |
Message and failure lifecycle: Security & monitoring
SSL encryption + SASL (PLAIN/SCRAM-SHA-256). Brokers evaluate a principal's operation against resource patterns. JMX exporters expose controller, broker, replica, request, and group measurements.
ACLs with kafka-acls.sh. Brokers evaluate a principal's operation against resource patterns. JMX exporters expose controller, broker, replica, request, and group measurements.
Prometheus JMX exporter. Brokers evaluate a principal's operation against resource patterns. JMX exporters expose controller, broker, replica, request, and group measurements.
Grafana key metrics: consumer lag/under-replicated/latency. Polling drives heartbeats and fetches. Rebalances revoke and reassign ownership. Commit-before-processing risks loss; commit-after-processing permits duplicates.
Read these as one system: SSL encryption + SASL (PLAIN/SCRAM-SHA-256) establishes the starting contract, ACLs with kafka-acls.sh changes how that contract is executed or represented, and Grafana key metrics: consumer lag/under-replicated/latency exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
A recoverable implementation slice: Security & monitoring
1event = {"event_id": event_id, "type": "ssl_encryption_sasl_plain_scram_sha_256.v1", "payload": payload}2producer.produce(topic, key=entity_id, value=encode(event), on_delivery=delivered)3producer.poll(0)This Security & monitoring slice makes SSL encryption + SASL (PLAIN/SCRAM-SHA-256) observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward Grafana key metrics: consumer lag/under-replicated/latency, predict its behavior for empty, invalid, repeated, and large input.
Duplicate, ordering, and outage traps: Security & monitoring
| Risk | Why it matters |
|---|---|
| SSL encryption + SASL (PLAIN/SCRAM-SHA-256) | Encryption without hostname verification or authorization is incomplete. |
| ACLs with kafka-acls.sh | Encryption without hostname verification or authorization is incomplete. |
| Prometheus JMX exporter | Encryption without hostname verification or authorization is incomplete. |
| Grafana key metrics: consumer lag/under-replicated/latency | Slow processing beyond poll limits causes rebalances and duplicate work. |
Failure-recovery drill: Security & monitoring
- Foundation: implement or demonstrate SSL encryption + SASL (PLAIN/SCRAM-SHA-256) with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine SSL encryption + SASL (PLAIN/SCRAM-SHA-256) with ACLs with kafka-acls.sh. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for Grafana key metrics: consumer lag/under-replicated/latency. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
3. Kafka Connect
The Kafka Connect unit begins with JDBC source connector (PostgreSQL→Kafka): Kafka Connect runs standardized source and sink connectors with distributed configuration, offsets, tasks, and converters. Use Connect for well-supported integration patterns and manage schemas explicitly. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
Guarantees before APIs: Kafka Connect
| Concept | Meaning | Engineering decision |
|---|---|---|
| JDBC source connector (PostgreSQL→Kafka) | Kafka Connect runs standardized source and sink connectors with distributed configuration, offsets, tasks, and converters. | Use Connect for well-supported integration patterns and manage schemas explicitly. |
| JDBC sink + S3 sink connectors | Kafka Connect runs standardized source and sink connectors with distributed configuration, offsets, tasks, and converters. | Use Connect for well-supported integration patterns and manage schemas explicitly. |
| connector JSON configuration | Kafka Connect runs standardized source and sink connectors with distributed configuration, offsets, tasks, and converters. | Use Connect for well-supported integration patterns and manage schemas explicitly. |
| REST API for connector management | Kafka Connect runs standardized source and sink connectors with distributed configuration, offsets, tasks, and converters. | Use Connect for well-supported integration patterns and manage schemas explicitly. |
Message and failure lifecycle: Kafka Connect
JDBC source connector (PostgreSQL→Kafka). Workers coordinate connectors and task assignments; source offsets track extraction progress and sink tasks consume Kafka partitions.
JDBC sink + S3 sink connectors. Workers coordinate connectors and task assignments; source offsets track extraction progress and sink tasks consume Kafka partitions.
connector JSON configuration. Workers coordinate connectors and task assignments; source offsets track extraction progress and sink tasks consume Kafka partitions.
REST API for connector management. Workers coordinate connectors and task assignments; source offsets track extraction progress and sink tasks consume Kafka partitions.
Read these as one system: JDBC source connector (PostgreSQL→Kafka) establishes the starting contract, JDBC sink + S3 sink connectors changes how that contract is executed or represented, and REST API for connector management exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
A recoverable implementation slice: Kafka Connect
1event = {"event_id": event_id, "type": "jdbc_source_connector_postgresql_kafka.v1", "payload": payload}2producer.produce(topic, key=entity_id, value=encode(event), on_delivery=delivered)3producer.poll(0)This Kafka Connect slice makes JDBC source connector (PostgreSQL→Kafka) observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward REST API for connector management, predict its behavior for empty, invalid, repeated, and large input.
Duplicate, ordering, and outage traps: Kafka Connect
| Risk | Why it matters |
|---|---|
| JDBC source connector (PostgreSQL→Kafka) | A connector does not automatically solve source consistency, deletes, or sink idempotency. |
| JDBC sink + S3 sink connectors | A connector does not automatically solve source consistency, deletes, or sink idempotency. |
| connector JSON configuration | A connector does not automatically solve source consistency, deletes, or sink idempotency. |
| REST API for connector management | A connector does not automatically solve source consistency, deletes, or sink idempotency. |
Failure-recovery drill: Kafka Connect
- Foundation: implement or demonstrate JDBC source connector (PostgreSQL→Kafka) with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine JDBC source connector (PostgreSQL→Kafka) with JDBC sink + S3 sink connectors. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for REST API for connector management. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
4. Kafka Streams vs Flink
The Kafka Streams vs Flink unit begins with embedded library vs independent processing cluster: Kafka Streams is an embedded JVM library tightly integrated with Kafka partitions and changelogged local state; Flink is an independent distributed engine with richer event-time, state, and multi-source processing. Choose Streams for Kafka-centric topologies owned with an application, and Flink for large, stateful, event-time pipelines needing an operational processing cluster. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
Guarantees before APIs: Kafka Streams vs Flink
| Concept | Meaning | Engineering decision |
|---|---|---|
| embedded library vs independent processing cluster | Kafka Streams is an embedded JVM library tightly integrated with Kafka partitions and changelogged local state; Flink is an independent distributed engine with richer event-time, state, and multi-source processing. | Choose Streams for Kafka-centric topologies owned with an application, and Flink for large, stateful, event-time pipelines needing an operational processing cluster. |
| event-time windows and watermarks | Kafka Streams is an embedded JVM library tightly integrated with Kafka partitions and changelogged local state; Flink is an independent distributed engine with richer event-time, state, and multi-source processing. | Choose Streams for Kafka-centric topologies owned with an application, and Flink for large, stateful, event-time pipelines needing an operational processing cluster. |
| local state stores and changelogs | Kafka Streams is an embedded JVM library tightly integrated with Kafka partitions and changelogged local state; Flink is an independent distributed engine with richer event-time, state, and multi-source processing. | Choose Streams for Kafka-centric topologies owned with an application, and Flink for large, stateful, event-time pipelines needing an operational processing cluster. |
| Flink checkpoints and savepoints | Kafka Streams is an embedded JVM library tightly integrated with Kafka partitions and changelogged local state; Flink is an independent distributed engine with richer event-time, state, and multi-source processing. | Choose Streams for Kafka-centric topologies owned with an application, and Flink for large, stateful, event-time pipelines needing an operational processing cluster. |
| choice by topology/operations/state/latency | Kafka Streams is an embedded JVM library tightly integrated with Kafka partitions and changelogged local state; Flink is an independent distributed engine with richer event-time, state, and multi-source processing. | Choose Streams for Kafka-centric topologies owned with an application, and Flink for large, stateful, event-time pipelines needing an operational processing cluster. |
Message and failure lifecycle: Kafka Streams vs Flink
embedded library vs independent processing cluster. Streams tasks follow Kafka partition assignment and restore RocksDB state from changelogs. Flink operators checkpoint distributed state and use watermarks to decide event-time completeness; savepoints support controlled upgrades.
event-time windows and watermarks. Streams tasks follow Kafka partition assignment and restore RocksDB state from changelogs. Flink operators checkpoint distributed state and use watermarks to decide event-time completeness; savepoints support controlled upgrades.
local state stores and changelogs. Streams tasks follow Kafka partition assignment and restore RocksDB state from changelogs. Flink operators checkpoint distributed state and use watermarks to decide event-time completeness; savepoints support controlled upgrades.
Flink checkpoints and savepoints. Streams tasks follow Kafka partition assignment and restore RocksDB state from changelogs. Flink operators checkpoint distributed state and use watermarks to decide event-time completeness; savepoints support controlled upgrades.
choice by topology/operations/state/latency. Streams tasks follow Kafka partition assignment and restore RocksDB state from changelogs. Flink operators checkpoint distributed state and use watermarks to decide event-time completeness; savepoints support controlled upgrades.
Read these as one system: embedded library vs independent processing cluster establishes the starting contract, event-time windows and watermarks changes how that contract is executed or represented, and choice by topology/operations/state/latency exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
A recoverable implementation slice: Kafka Streams vs Flink
1event = {"event_id": event_id, "type": "embedded_library_vs_independent_processing.v1", "payload": payload}2producer.produce(topic, key=entity_id, value=encode(event), on_delivery=delivered)3producer.poll(0)This Kafka Streams vs Flink slice makes embedded library vs independent processing cluster observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward choice by topology/operations/state/latency, predict its behavior for empty, invalid, repeated, and large input.
Duplicate, ordering, and outage traps: Kafka Streams vs Flink
| Risk | Why it matters |
|---|---|
| embedded library vs independent processing cluster | Neither engine fixes bad keys, unbounded state, or undefined late-event policy. |
| event-time windows and watermarks | Neither engine fixes bad keys, unbounded state, or undefined late-event policy. |
| local state stores and changelogs | Neither engine fixes bad keys, unbounded state, or undefined late-event policy. |
| Flink checkpoints and savepoints | Neither engine fixes bad keys, unbounded state, or undefined late-event policy. |
| choice by topology/operations/state/latency | Neither engine fixes bad keys, unbounded state, or undefined late-event policy. |
Failure-recovery drill: Kafka Streams vs Flink
- Foundation: implement or demonstrate embedded library vs independent processing cluster with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine embedded library vs independent processing cluster with event-time windows and watermarks. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for choice by topology/operations/state/latency. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
5. Alert rule reference
The Alert rule reference unit begins with consumer lag age and growth: A consumer group divides partitions so one member owns a partition at a time; committed offsets represent recoverable progress. Commit only after the corresponding side effects are durable and make the handler idempotent. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
Guarantees before APIs: Alert rule reference
| Concept | Meaning | Engineering decision |
|---|---|---|
| consumer lag age and growth | A consumer group divides partitions so one member owns a partition at a time; committed offsets represent recoverable progress. | Commit only after the corresponding side effects are durable and make the handler idempotent. |
| under-replicated partitions | An under-replicated partition has fewer in-sync replicas than its configured replication factor, indicating reduced redundancy or a lagging/offline broker. | Alert on sustained non-zero counts, correlate with offline partitions, disk/network saturation, and broker changes, then restore replica health before another failure. |
| offline partitions and ISR shrink | A Kafka topic is split into ordered partitions whose records have monotonically increasing offsets. Retention removes old segments; compaction retains the latest value per key. | Choose keys for ordering and partitions for required parallelism and future load. |
| request latency and failed produce/fetch rate | Kafka request latency and failed produce/fetch rates reveal whether clients and brokers can append and retrieve records within the workload's service objective. | Alert on sustained tail latency or error-rate deviation together with queue time, ISR, disk, network, client timeouts, and consumer lag. |
Message and failure lifecycle: Alert rule reference
consumer lag age and growth. Polling drives heartbeats and fetches. Rebalances revoke and reassign ownership. Commit-before-processing risks loss; commit-after-processing permits duplicates.
under-replicated partitions. The leader tracks follower fetch progress and removes replicas from the ISR when they fall outside configured thresholds. Kafka exposes cluster counts through broker metrics and administrative APIs.
offline partitions and ISR shrink. Each partition has a leader and replicas. The in-sync replica set tracks followers sufficiently caught up; KRaft stores cluster metadata in a Raft quorum.
request latency and failed produce/fetch rate. Broker request queues, processing, replication waits, network transfer, client retries, and timeouts contribute to end-to-end latency; metrics must be sliced by request type and broker.
Read these as one system: consumer lag age and growth establishes the starting contract, under-replicated partitions changes how that contract is executed or represented, and request latency and failed produce/fetch rate exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
A recoverable implementation slice: Alert rule reference
1message = consumer.poll(1.0); handle(message); consumer.commit(message=message, asynchronous=False)This Alert rule reference slice makes consumer lag age and growth observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward request latency and failed produce/fetch rate, predict its behavior for empty, invalid, repeated, and large input.
Duplicate, ordering, and outage traps: Alert rule reference
| Risk | Why it matters |
|---|---|
| consumer lag age and growth | Slow processing beyond poll limits causes rebalances and duplicate work. |
| under-replicated partitions | Treating a transient count as harmless without duration and affected-partition context can leave the cluster one failure away from unavailability or loss. |
| offline partitions and ISR shrink | Offsets are only unique within a partition; compaction does not preserve every intermediate event. |
| request latency and failed produce/fetch rate | Averages hide affected partitions and tail failures; retry traffic can make throughput look healthy while user-visible latency collapses. |
Failure-recovery drill: Alert rule reference
- Foundation: implement or demonstrate consumer lag age and growth with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine consumer lag age and growth with under-replicated partitions. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for request latency and failed produce/fetch rate. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
Complete worked example
This example integrates the chapter rather than demonstrating an isolated method.
1producer.init_transactions()2while True:3 records = consumer.consume(num_messages=100, timeout=1.0)4 if not records:5 continue6 producer.begin_transaction()7 try:8 for record in records:9 producer.produce("validated.v1", key=record.key(), value=validate(record.value()))10 producer.send_offsets_to_transaction(offsets_after(records), consumer.consumer_group_metadata())11 producer.commit_transaction()12 except Exception:13 producer.abort_transaction()14 raiseExpected result
1Output records and input offsets become visible atomically to read_committed consumers.Line-by-line reading
| Line | Code | Explanation |
|---|---|---|
| 1 | producer.init_transactions() | Implements the next python statement in the example's data flow. |
| 2 | while True: | Repeats while the condition remains true; the body must make progress toward termination. |
| 3 | records = consumer.consume(num_messages=100, timeout=1.0) | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 4 | if not records: | Evaluates the condition and enters this branch only when it is truthy. |
| 5 | continue | Implements the next python statement in the example's data flow. |
| 6 | producer.begin_transaction() | Implements the next python statement in the example's data flow. |
| 7 | try: | Defines failure translation or cleanup that must run around the protected operation. |
| 8 | for record in records: | Consumes the iterable one item at a time through the iterator protocol. |
| 9 | producer.produce("validated.v1", key=record.key(), value=validate(record.value())) | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 10 | producer.send_offsets_to_transaction(offsets_after(records), consumer.consumer_group_metadata()) | Implements the next python statement in the example's data flow. |
| 11 | producer.commit_transaction() | Implements the next python statement in the example's data flow. |
| 12 | except Exception: | Defines failure translation or cleanup that must run around the protected operation. |
| 13 | producer.abort_transaction() | Implements the next python statement in the example's data flow. |
| 14 | raise | Stops the happy path with a deliberate exception carrying the boundary failure. |
Step-by-step execution
- The producer validates and serializes a versioned record, hashes its key to a partition, batches it, and sends it to that partition's leader under the configured acknowledgment policy.
- The broker appends the record at the next partition offset and replicates it; durability depends on acknowledgments, in-sync replicas, and minimum-ISR settings together.
- A group member polls assigned partitions, deserializes the record, checks event identity, and performs its bounded idempotent side effect.
- Recoverable progress advances only after the corresponding effect is durable, or a Kafka transaction atomically publishes output and offsets for Kafka-to-Kafka work.
- Tests inject duplicate delivery, rebalance, poison data, broker interruption, and lag while asserting ordering only within the declared key scope.
Common mistakes and professional corrections
| Area | Common failure | Better engineering choice |
|---|---|---|
| Exactly-once semantics | EOS does not make an arbitrary HTTP call or database write exactly once. | Use Kafka EOS for Kafka-to-Kafka flows and idempotent sinks for external effects. |
| Security & monitoring | Encryption without hostname verification or authorization is incomplete. | Use unique principals, least privilege, certificate rotation, and lag/ISR alerts. |
| Kafka Connect | A connector does not automatically solve source consistency, deletes, or sink idempotency. | Use Connect for well-supported integration patterns and manage schemas explicitly. |
| Kafka Streams vs Flink | Neither engine fixes bad keys, unbounded state, or undefined late-event policy. | Choose Streams for Kafka-centric topologies owned with an application, and Flink for large, stateful, event-time pipelines needing an operational processing cluster. |
| Alert rule reference | Slow processing beyond poll limits causes rebalances and duplicate work. | Commit only after the corresponding side effects are durable and make the handler idempotent. |
Interview and review notes
- Define the central abstraction without naming a library function.
- Trace one request, call, query, message, render, or state transition from input to observable result.
- Compare two alternatives from this chapter by guarantee, cost, and failure behavior.
- Explain the most likely production bug and the test or metric that reveals it.
- State what remains authoritative after process loss, retry, reconnect, or deployment.
Practice set
Easy
- Define every bold term in the concept tables in one precise sentence.
- Reproduce the focused examples and annotate the value or state after each important line.
- Explain the chapter progression diagram aloud in two minutes.
Medium
- Replace one convenient default with an explicit policy for validation, timeout, ordering, pagination, cleanup, or error handling.
- Write a negative test for each topic group.
- Compare the measured behavior before and after one justified change.
Hard
- Combine all topic groups into one thin vertical slice.
- Inject a realistic failure at the most important external boundary and prove recovery.
- Write a one-page design note covering ownership, trade-offs, security, observability, and rollback.
Chapter submission
Submit:
- source code or reproducible commands;
- automated tests plus one deliberately failing-before-fix test;
- captured output, query plan, trace, screenshot, or metric;
- a 300–500 word explanation of the execution flow and one rejected alternative;
- a short README with setup, versions, limitations, and cleanup steps.
- Continue with the Production Kafka System project workshop.
Self-review rubric
| Dimension | Beginning | Competent | Professional |
|---|---|---|---|
| Explanation | Names APIs | Explains behavior | Connects guarantees, internals, and trade-offs |
| Implementation | Happy path only | Validated and tested | Clear ownership, failure recovery, and cleanup |
| Evidence | Manual claim | Repeatable output | Tests plus meaningful measurement or inspection |
| Communication | Steps missing | Reproducible README | Decisions, limits, and alternatives are explicit |
Roadmap coverage checklist
- To do: Exactly-once semantics: at-most-once/at-least-once/exactly-once
- To do: Exactly-once semantics: idempotent producers
- To do: Exactly-once semantics: transactions: atomic read-process-write
- To do: Exactly-once semantics: EOS Python transactional API
- To do: Security & monitoring: SSL encryption + SASL (PLAIN/SCRAM-SHA-256)
- To do: Security & monitoring: ACLs with kafka-acls.sh
- To do: Security & monitoring: Prometheus JMX exporter
- To do: Security & monitoring: Grafana key metrics: consumer lag/under-replicated/latency
- To do: Kafka Connect: JDBC source connector (PostgreSQL→Kafka)
- To do: Kafka Connect: JDBC sink + S3 sink connectors
- To do: Kafka Connect: connector JSON configuration
- To do: Kafka Connect: REST API for connector management
- To do: Kafka Streams vs Flink: embedded library vs independent processing cluster
- To do: Kafka Streams vs Flink: event-time windows and watermarks
- To do: Kafka Streams vs Flink: local state stores and changelogs
- To do: Kafka Streams vs Flink: Flink checkpoints and savepoints
- To do: Kafka Streams vs Flink: choice by topology/operations/state/latency
- To do: Alert rule reference: consumer lag age and growth
- To do: Alert rule reference: under-replicated partitions
- To do: Alert rule reference: offline partitions and ISR shrink
- To do: Alert rule reference: request latency and failed produce/fetch rate
Quick revision
- Exactly-once semantics: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Security & monitoring: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Kafka Connect: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Kafka Streams vs Flink: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Alert rule reference: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Re-read the worked-example execution trace instead of memorizing isolated syntax.
- If you cannot name the owner of state and cleanup, the design is not yet complete.
Mastery check
How well can you recall this?
Finished this lesson?