⚙️ Kafka Stream Processing

This skill helps you design and implement Kafka stream processing pipelines, covering producers, consumers, Kafka Streams, connectors, and deployment patterns.

QUICK INSTALL
npx playbooks add skill manutej/luxor-claude-marketplace --skill kafka-stream-processing

Kafka Stream Processing instructions

Kafka Stream Processing

A comprehensive skill for building event-driven applications with Apache Kafka. Master producers, consumers, Kafka Streams, connectors, schema registry, and production deployment patterns for real-time data processing at scale.

When to Use This Skill

Use this skill when:

  • Building event-driven microservices architectures
  • Processing real-time data streams and event logs
  • Implementing publish-subscribe messaging systems
  • Creating data pipelines for analytics and ETL
  • Building streaming data applications with stateful processing
  • Integrating heterogeneous systems with Kafka Connect
  • Implementing change data capture (CDC) patterns
  • Building real-time dashboards and monitoring systems
  • Processing IoT sensor data at scale
  • Implementing event sourcing and CQRS patterns
  • Building distributed systems requiring guaranteed message delivery
  • Creating real-time recommendation engines
  • Processing financial transactions with exactly-once semantics
  • Building log aggregation and monitoring pipelines

Core Concepts

Apache Kafka Architecture

Kafka is a distributed streaming platform designed for high-throughput, fault-tolerant, real-time data processing.

Key Components:

  1. Topics: Named categories for organizing messages
  2. Partitions: Ordered, immutable sequences of records within topics
  3. Brokers: Kafka servers that store and serve data
  4. Producers: Applications that publish records to topics
  5. Consumers: Applications that read records from topics
  6. Consumer Groups: Coordinated consumers sharing workload
  7. ZooKeeper/KRaft: Cluster coordination (ZooKeeper legacy, KRaft modern)

Design Principles:

Kafka Design Philosophy:
  - High Throughput: Millions of messages per second
  - Low Latency: Single-digit millisecond latency
  - Durability: Replicated, persistent storage
  - Scalability: Horizontal scaling via partitions
  - Fault Tolerance: Automatic failover and recovery
  - Message Delivery Semantics: At-least-once, exactly-once support

Topics and Partitions

Topics are logical channels for data streams. Each topic is divided into partitions for parallelism and scalability.

# Create a topic with 20 partitions and replication factor 3
$ bin/kafka-topics.sh --bootstrap-server localhost:9092 --create --topic my_topic_name \
--partitions 20 --replication-factor 3 --config x=y

Partition Characteristics:

  • Ordered: Messages within a partition are strictly ordered
  • Immutable: Records cannot be modified after written
  • Append-only: New records appended to partition end
  • Retention: Configurable retention by time or size
  • Replication: Each partition replicated across brokers

Adding Partitions:

# Increase partition count (cannot decrease)
$ bin/kafka-topics.sh --bootstrap-server localhost:9092 --alter --topic my_topic_name \
--partitions 40

Note: Adding partitions doesn't redistribute existing data and may affect consumers using custom partitioning.

Stream Partitions and Tasks

<h3>Stream Partitions and Tasks</h3>
<p> The messaging layer of Kafka partitions data for storing and transporting it. Kafka Streams partitions data for processing it. In both cases, this partitioning is what enables data locality, elasticity, scalability, high performance, and fault tolerance. Kafka Streams uses the concepts of <b>partitions</b> and <b>tasks</b> as logical units of its parallelism model based on Kafka topic partitions. There are close links between Kafka Streams and Kafka in the context of parallelism: </p>
<ul>
<li>Each <b>stream partition</b> is a totally ordered sequence of data records and maps to a Kafka <b>topic partition</b>.</li>
<li>A <b>data record</b> in the stream maps to a Kafka <b>message</b> from that topic.</li>
<li>The <b>keys</b> of data records determine the partitioning of data in both Kafka and Kafka Streams, i.e., how data is routed to specific partitions within topics.</li>
</ul>
<p> An application's processor topology is scaled by breaking it into multiple tasks. More specifically, Kafka Streams creates a fixed number of tasks based on the input stream partitions for the application, with each task assigned a list of partitions from the input streams (i.e., Kafka topics). The assignment of partitions to tasks never changes so that each task is a fixed unit of parallelism of the application. Tasks can then instantiate their own processor topology based on the assigned partitions; they also maintain a buffer for each of its assigned partitions and process messages one-at-a-time from these record buffers. As a result stream tasks can be processed independently and in parallel without manual intervention. </p>
<p> Slightly simplified, the maximum parallelism at which your application may run is bounded by the maximum number of stream tasks, which itself is determined by maximum number of partitions of the input topic(s) the application is reading from. For example, if your input topic has 5 partitions, then you can run up to 5 applications instances. These instances will collaboratively process the topic's data. If you run a larger number of app instances than partitions of the input topic, the "excess" app instances will launch but remain idle; however, if one of the busy instances goes down, one of the idle instances will resume the former's work. </p>
<p> It is important to understand that Kafka Streams is not a resource manager, but a library that "runs" anywhere its stream processing application runs. Multiple instances of the application are executed either on the same machine, or spread across multiple machines and tasks can be distributed automatically by the library to those running application instances. The assignment of partitions to tasks never changes; if an application instance fails, all its assigned tasks will be automatically restarted on other instances and continue to consume from the same stream partitions. </p>

Message Delivery Semantics

Design:
  - The Producer: Design considerations.
  - The Consumer: Design considerations.
  - Message Delivery Semantics: At-least-once, at-most-once, exactly-once.
  - Using Transactions for atomic operations.

At-Least-Once Delivery:

  • Producer retries until acknowledgment received
  • Consumer commits offset after processing
  • Risk: Duplicate processing on failures
  • Use case: When duplicates are acceptable or idempotent processing

At-Most-Once Delivery:

  • Consumer commits offset before processing
  • No producer retries
  • Risk: Message loss on failures
  • Use case: When data loss acceptable (e.g., metrics)

Exactly-Once Semantics (EOS):

  • Transactional writes with idempotent producers
  • Consumer reads committed messages only
  • Use case: Financial transactions, critical data processing

Producer Load Balancing

ProducerClient:
  publish(topic: str, message: bytes, partition_key: Optional[str] = None)
    topic: The topic to publish the message to.
    message: The message payload to send.
    partition_key: Optional key to determine the partition. If None, random partitioning is used.

  get_metadata(topic: str) -> dict
    topic: The topic to get metadata for.
    Returns: A dictionary containing broker information and partition leader details.

The producer directs data to the partition leader broker without a routing tier. Kafka nodes provide metadata to producers for directing requests to the correct partition leaders. Producers can implement custom partitioning logic or use random distribution.

Producers

Kafka producers publish records to topics with configurable reliability and performance characteristics.

Producer API

Producer API:
  - send(record): Sends a record to a Kafka topic.
    - Parameters:
      - record: The record to send, including topic, key, and value.
    - Returns: A Future representing the result of the send operation.
  - flush(): Forces any buffered records to be sent.
  - close(): Closes the producer, releasing any resources.
  - metrics(): Returns metrics about the producer.

  Configuration:
  - bootstrap.servers: A list of host/port pairs to use for establishing the initial connection to the Kafka cluster.
  - key.serializer: The serializer class for key that implements the org.apache.kafka.common.serialization.Serializer interface.
  - value.serializer: The serializer class for value that implements the org.apache.kafka.common.serialization.Serializer interface.
  - acks: The number of acknowledgments the producer requires the leader to have received before considering a request complete.
  - linger.ms: The producer groups together any records that arrive in between request transmissions into a single batched request.
  - batch.size: The producer will attempt to batch records together into fewer requests whenever multiple records are being sent to the same partition.

Producer Configuration

Essential Settings:

  1. bootstrap.servers: Kafka cluster connection string
  • Format: host1:9092,host2:9092,host3:9092
  • Use multiple brokers for fault tolerance
  1. key.serializer / value.serializer: Data serialization
  • org.apache.kafka.common.serialization.StringSerializer
  • org.apache.kafka.common.serialization.ByteArraySerializer
  • Custom serializers for complex types
  1. acks: Acknowledgment level
  • 0: No acknowledgment (fire and forget)
  • 1: Leader acknowledgment only
  • all / -1: All in-sync replicas acknowledge (strongest durability)
  1. retries: Retry count for failed sends
  • Default: 2147483647 (Integer.MAX_VALUE)
  • Set to 0 to disable retries
  1. enable.idempotence: Exactly-once semantics
  • true: Enables idempotent producer (prevents duplicates)
  • false: Default behavior

Performance Tuning:

  1. linger.ms: Batching delay
  • Default: 0 (send immediately)
  • Higher values (5-100ms) increase throughput via batching
  • Trade-off: Latency vs throughput
  1. batch.size: Batch size in bytes
  • Default: 16384 (16KB)
  • Larger batches improve throughput
  • Maximum single batch size per partition
  1. compression.type: Message compression
  • Options: none, gzip, snappy, lz4, zstd
  • Reduces network bandwidth and storage
  • CPU overhead for compression/decompression
  1. buffer.memory: Total producer buffer memory
  • Default: 33554432 (32MB)
  • Memory for buffering unsent records
  • Producer blocks when buffer full

Producer Example (Java)

import org.apache.kafka.clients.producer.*;
import org.apache.kafka.common.serialization.StringSerializer;
import java.util.Properties;

public class SimpleProducer {
    public static void main(String[] args) {
        Properties props = new Properties();
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        props.put(ProducerConfig.ACKS_CONFIG, "all");
        props.put(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, true);
        props.put(ProducerConfig.LINGER_MS_CONFIG, 10);
        props.put(ProducerConfig.BATCH_SIZE_CONFIG, 32768);

        try (KafkaProducer<String, String> producer = new KafkaProducer<>(props)) {
            ProducerRecord<String, String> record =
                new ProducerRecord<>("my-topic", "key1", "Hello Kafka!");

            // Async send with callback
            producer.send(record, (metadata, exception) -> {
                if (exception != null) {
                    System.err.println("Error producing: " + exception);
                } else {
                    System.out.printf("Sent to partition %d, offset %d%n",
                        metadata.partition(), metadata.offset());
                }
            });
        }
    }
}

Producer Best Practices

  1. Use Batching: Configure linger.ms and batch.size for throughput
  2. Enable Idempotence: Set enable.idempotence=true for reliability
  3. Handle Errors: Implement proper callback error handling
  4. Use Compression: Enable compression for large messages
  5. Partition Keys: Use meaningful keys for ordered processing
  6. Close Producers: Always close producers in finally blocks
  7. Monitor Metrics: Track producer metrics (record-send-rate, compression-rate)
  8. Resource Pools: Reuse producer instances when possible

Consumers

Kafka consumers read records from topics, supporting both individual and group-based consumption.

Consumer Groups

Consumer groups enable parallel processing with automatic load balancing and fault tolerance.

Key Concepts:

  • Group ID: Unique identifier for consumer group
  • Partition Assignment: Each partition consumed by one consumer in group
  • Rebalancing: Automatic reassignment when consumers join/leave
  • Offset Management: Group tracks committed offsets per partition

Consumer Group Monitoring:

# List consumer groups
$ bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --list

# Describe consumer group members with partition assignments
$ bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --describe --group my-group --members --verbose
CONSUMER-ID HOST CLIENT-ID #PARTITIONS ASSIGNMENT
consumer1-3fc8d6f1-581a-4472-bdf3-3515b4aee8c1 /127.0.0.1 consumer1 2 topic1(0), topic2(0)
consumer4-117fe4d3-c6c1-4178-8ee9-eb4a3954bee0 /127.0.0.1 consumer4 1 topic3(2)
consumer2-e76ea8c3-5d30-4299-9005-47eb41f3d3c4 /127.0.0.1 consumer2 3 topic2(1), topic3(0,1)
consumer3-ecea43e4-1f01-479f-8349-f9130b75d8ee /127.0.0.1 consumer3 0 -

Consumer Configuration

Essential Settings:

  1. bootstrap.servers: Kafka cluster connection
  2. group.id: Consumer group identifier
  3. key.deserializer / value.deserializer: Data deserialization
  4. enable.auto.commit: Automatic offset commits
  • true: Auto-commit offsets periodically
  • false: Manual offset management
  1. auto.offset.reset: Behavior when no offset found
  • earliest: Start from beginning
  • latest: Start from end
  • none: Throw exception

Consumer-Specific Kafka Streams Defaults:

Parameter Name: max.poll.records
Corresponding Client: Consumer
Streams Default: 100

Parameter Name: client.id
Corresponding Client: -
Streams Default: <application.id>-<random-UUID>

Parameter Name: enable.auto.commit
Description: Controls whether the consumer automatically commits offsets. When true, the consumer will automatically commit offsets periodically based on the poll interval.
Default Value: true

Consumer Example (Java)

import org.apache.kafka.clients.consumer.*;
import org.apache.kafka.common.serialization.StringDeserializer;
import java.time.Duration;
import java.util.*;

public class SimpleConsumer {
    public static void main(String[] args) {
        Properties props = new Properties();
        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        props.put(ConsumerConfig.GROUP_ID_CONFIG, "my-consumer-group");
        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
        props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");

        try (KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props)) {
            consumer.subscribe(Collections.singletonList("my-topic"));

            while (true) {
                ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100));

                for (ConsumerRecord<String, String> record : records) {
                    System.out.printf("Partition: %d, Offset: %d, Key: %s, Value: %s%n",
                        record.partition(), record.offset(), record.key(), record.value());

                    // Process record
                    processRecord(record);
                }

                // Manual commit after processing batch
                consumer.commitSync();
            }
        }
    }

    private static void processRecord(ConsumerRecord<String, String> record) {
        // Business logic here
    }
}

Consumer Offset Management

Offset Commit Strategies:

  1. Auto-commit (default):
  • Simple but risky for at-least-once delivery
  • May commit before processing completes
  1. Manual Synchronous Commit:
  • Blocks until commit succeeds
  • Guarantees offset committed before continuing
  • Lower throughput
  1. Manual Asynchronous Commit:
  • Non-blocking commit
  • Higher throughput
  • Handle failures in callback
  1. Hybrid Approach:
  • Async commits during processing
  • Sync commit before rebalance/shutdown
// Async commit with callback
consumer.commitAsync((offsets, exception) -> {
    if (exception != null) {
        System.err.println("Commit failed: " + exception);
    }
});

// Sync commit for reliability
try {
    consumer.commitSync();
} catch (CommitFailedException e) {
    System.err.println("Commit failed: " + e);
}

Consumer Best Practices

  1. Choose Right Auto-commit: Disable for at-least-once semantics
  2. Handle Rebalancing: Implement ConsumerRebalanceListener
  3. Process Efficiently: Minimize poll() call duration
  4. Graceful Shutdown: Close consumers properly
  5. Monitor Lag: Track consumer lag metrics
  6. Partition Assignment: Understand assignment strategies
  7. Thread Safety: Kafka consumers are NOT thread-safe
  8. Error Handling: Retry logic for transient failures

Kafka Streams

Kafka Streams is a client library for building real-time streaming applications with stateful processing.

Kafka Streams Architecture

Processor Topology:

There are two special processors in the topology:
<ul>
<li><b>Source Processor</b>: A special type of stream processor that does not have any upstream processors. It produces an input stream to its topology from one or multiple Kafka topics by consuming records from these topics and forwarding them to its down-stream processors.</li>
<li><b>Sink Processor</b>: A special type of stream processor that does not have down-stream processors. It sends any received records from its up-stream processors to a specified Kafka topic.</li>
</ul>
Note that in normal processor nodes other remote systems can also be accessed while processing the current record. Therefore the processed results can either be streamed back into Kafka or written to an external system.

Sub-topologies:

Applications are decomposed into sub-topologies connected by repartition topics. Each sub-topology can scale independently.

KStream vs KTable vs GlobalKTable

KStream: Immutable stream of records

import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.kstream.KStream;

StreamsBuilder builder = new StreamsBuilder();
KStream<String, Long> wordCounts = builder.stream(
    "word-counts-input-topic", /* input topic */
    Consumed.with(
        Serdes.String(), /* key serde */
        Serdes.Long() /* value serde */
    )
);

KTable: Changelog stream (latest value per key)

import org.apache.kafka.streams.StreamsBuilder;

StreamsBuilder builder = new StreamsBuilder();
builder.table("input-topic");

GlobalKTable: Fully replicated table available to all instances

KTable: Each application instance gets data from only 1 partition.
GlobalKTable: Each application instance gets data from all partitions.

Writing Streams to Kafka

KStream<String, Long> stream = ...;
// Write

Related Skills

Get the best new skills
in your inbox

Weekly roundup of top Claude Code skills, MCP servers, and AI coding tips.