About Skills Projects Blog Contact View my CV ↗ Español
Kafka + Flink hands-on: a real-time streaming pipeline

Kafka + Flink hands-on: a real-time streaming pipeline

Kafka and Flink from the ground up: topics, partitions, exactly-once, windows, watermarks, state and checkpoints in a real log pipeline.

By Omar Flores
Table of Contents

It is 18:10 on a Friday. The incident dashboard shows the last error fourteen minutes ago, but support has already received three tickets. The job feeding the dashboard runs every five minutes and takes seven. Nobody understands why the “real-time” system is always late.

The problem is not the dashboard. You are simulating real time with batch: group, wait, query, repeat. When volume grows, the window stretches. Kafka and Flink solve a different problem: they move events as a log and process them as they arrive, with state and with a notion of time that does not depend on the server clock.


Kafka in five concepts (and one that matters more)

A topic is an append-only log: producers write at the end and consumers read from a position. Each topic is split into partitions, the unit of parallelism and ordering. Every message has an offset inside its partition. Producers write and consumers read in groups.

The sentence that matters: Kafka guarantees order within a partition, not within a topic. If two events for the same order land in different partitions, they can be processed in any order. The message key decides the partition; choosing the key is a design decision, not a detail.

Consumers in the same consumer group split the partitions. With 6 partitions and 3 consumers, each reads 2. Add a fourth and the group rebalances. A consumer cannot read a partition another member of the same group already owns, and two different groups can read the same topic without stepping on each other.

Kafka retains messages by time or size, not by whether they were read. That enables replay: if a pipeline fails, you return to an earlier offset and rebuild. That replay capability is the foundation of Flink’s fault tolerance.

The topic: where performance is decided

A topic with too few partitions limits parallelism. One with too many adds metadata overhead and rebalances. For a log pipeline, starting with 6 or 8 partitions is reasonable; in production, use replication factor 3 and min.insync.replicas=2.

This compose starts Kafka in KRaft mode, without ZooKeeper, with two listeners: one for containers and one for your machine.

services:
  kafka:
    image: apache/kafka:4.4.0
    ports:
      - "9092:9092"
    environment:
      KAFKA_NODE_ID: 1
      KAFKA_PROCESS_ROLES: broker,controller
      KAFKA_LISTENERS: INTERNAL://:29092,EXTERNAL://:9092,CONTROLLER://:9093
      KAFKA_ADVERTISED_LISTENERS: INTERNAL://kafka:29092,EXTERNAL://localhost:9092
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: CONTROLLER:PLAINTEXT,INTERNAL:PLAINTEXT,EXTERNAL:PLAINTEXT
      KAFKA_INTER_BROKER_LISTENER_NAME: INTERNAL
      KAFKA_CONTROLLER_LISTENER_NAMES: CONTROLLER
      KAFKA_CONTROLLER_QUORUM_VOTERS: 1@kafka:9093
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
      KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1
      KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1
      CLUSTER_ID: MkU3OEVBNTcwNTJENDM2Qk

Create the topic:

docker compose exec kafka /opt/kafka/bin/kafka-topics.sh \
  --bootstrap-server localhost:9092 \
  --create --topic app-logs \
  --partitions 6 --replication-factor 1

--describe shows leaders, replicas and ISR. If a broker falls out of the ISR, that topic is at risk; in production, acks=all does not save you if the replicas are not in sync.

Producers and consumers: the contract almost nobody writes

The producer decides the key, batch size, compression and acks. Since Kafka 3.0, enable.idempotence=true and acks=all are the defaults; if you lower acks to 1 for latency, you lose the guarantee that the message survives the leader’s failure.

Send test events with the key equal to the service:

docker compose exec -it kafka /opt/kafka/bin/kafka-console-producer.sh \
  --bootstrap-server localhost:9092 \
  --topic app-logs \
  --property parse.key=true \
  --property key.separator=:
checkout:{"event_time":"2026-12-05 10:00:00","service":"checkout","level":"ERROR","duration_ms":1834}
checkout:{"event_time":"2026-12-05 10:00:02","service":"checkout","level":"INFO","duration_ms":120}
catalog:{"event_time":"2026-12-05 10:00:03","service":"catalog","level":"ERROR","duration_ms":45}

The console consumer verifies that the topic has data:

docker compose exec kafka /opt/kafka/bin/kafka-console-consumer.sh \
  --bootstrap-server localhost:9092 \
  --topic app-logs \
  --from-beginning

In a real consumer, disable auto-commit and commit the offset after processing. Commit before and a crash loses the message; commit after and a crash reprocesses it. That choice is the difference between at-most-once and at-least-once, and it is why exactly-once needs more than commitSync.

Exactly-once: the phrase you need to take apart

There are three guarantees: at-most-once (may lose), at-least-once (may duplicate) and exactly-once (processed once). The third is the most expensive and the most misunderstood.

Kafka achieves exactly-once inside Kafka with two pieces: an idempotent producer, which deduplicates retries with an ID and a sequence number, and transactions, which group writes to multiple partitions into one atomic unit. Consumers read with isolation.level=read_committed so they do not see records from aborted transactions.

That does not cover your database, your payments API, or the email you send at the end of the pipeline. For an external sink you need a distributed transaction, an idempotent sink, or a deduplication key. Flink handles Kafka-to-Kafka with checkpoints and a two-phase commit sink; for everything else, the responsibility is still yours.

The right question is not “do I have exactly-once?”. It is “what happens if this event is processed twice?”. If the answer is “I charge twice”, the problem is not Kafka.

Flink runs a distributed job with a JobManager that coordinates and TaskManagers that process. Each operator has a parallelism; TaskManager slots limit how many operators run at once. State lives in the TaskManager and is backed up in checkpoints.

Add these two entries under services: in the previous compose. The Kafka connector is not part of the distribution; download it and mount it in /opt/flink/lib.

mkdir -p lib
curl -fL -o lib/flink-sql-connector-kafka-5.1.0-2.3.jar \
  https://repo.maven.apache.org/maven2/org/apache/flink/flink-sql-connector-kafka/5.1.0-2.3/flink-sql-connector-kafka-5.1.0-2.3.jar
  jobmanager:
    image: flink:2.3.0-scala_2.12
    command: jobmanager
    ports:
      - "8081:8081"
    volumes:
      - ./lib/flink-sql-connector-kafka-5.1.0-2.3.jar:/opt/flink/lib/flink-sql-connector-kafka-5.1.0-2.3.jar
    environment:
      - |
        FLINK_PROPERTIES=
        jobmanager.rpc.address: jobmanager

  taskmanager:
    image: flink:2.3.0-scala_2.12
    command: taskmanager
    depends_on:
      - jobmanager
    volumes:
      - ./lib/flink-sql-connector-kafka-5.1.0-2.3.jar:/opt/flink/lib/flink-sql-connector-kafka-5.1.0-2.3.jar
    environment:
      - |
        FLINK_PROPERTIES=
        jobmanager.rpc.address: jobmanager
        taskmanager.numberOfTaskSlots: 2

The UI at http://localhost:8081 shows jobs, checkpoints and backpressure. If it does not load, the JobManager did not start; read the logs before touching the job.

Windows and watermarks: when time arrives out of order

An event-time window groups by when the fact happened, not when it arrived. An event from 10:00 may arrive at 10:03; with processing time, you count it in the wrong window.

A watermark is a promise: “I do not expect events older than this instant”. Flink generates it from event timestamps. forBoundedOutOfOrderness(5s) tolerates five seconds of disorder; anything older that arrives after the watermark is dropped unless you configure allowed lateness.

In Flink SQL, the watermark is declared on the table:

CREATE TABLE app_logs (
  event_time TIMESTAMP(3),
  service STRING,
  level STRING,
  duration_ms INT,
  WATERMARK FOR event_time AS event_time - INTERVAL '5' SECOND
) WITH (
  'connector' = 'kafka',
  'topic' = 'app-logs',
  'properties.bootstrap.servers' = 'kafka:29092',
  'properties.group.id' = 'flink-service-health',
  'scan.startup.mode' = 'earliest-offset',
  'format' = 'json'
);

SELECT window_start, window_end, service,
       SUM(CASE WHEN level = 'ERROR' THEN 1 ELSE 0 END) AS errors
FROM TUMBLE(TABLE app_logs, DESCRIPTOR(event_time), INTERVAL '1' MINUTE)
GROUP BY window_start, window_end, service;

The window emits when the watermark crosses its end. If a topic partition is idle, the global watermark stalls; withIdleness in the DataStream API or checking source parallelism avoids that block.

State and checkpoints: what keeps a restart from duplicating data

Windows and aggregates need state. Flink stores it per key and organizes it into key groups, which allows the job to rescale and redistribute state. For large state, RocksDB; for small state, the in-memory backend.

A checkpoint is a consistent snapshot of state and input offsets. Flink injects barriers into the stream, waits for every operator to receive them, and writes state to durable storage. If the job fails, it restores the last checkpoint and resumes from the saved offsets.

StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.enableCheckpointing(30_000);
env.getCheckpointConfig().setCheckpointingConsistencyMode(CheckpointingMode.EXACTLY_ONCE);
env.getCheckpointConfig().setMinPauseBetweenCheckpoints(15_000);
env.getCheckpointConfig().setCheckpointTimeout(120_000);
env.getCheckpointConfig().setMaxConcurrentCheckpoints(1);

Configuration config = new Configuration();
config.set(CheckpointingOptions.CHECKPOINT_STORAGE, "filesystem");
config.set(CheckpointingOptions.CHECKPOINTS_DIRECTORY, "s3://my-bucket/flink/checkpoints");
env.configure(config);

State also expires. Without TTL, a ValueState per user grows forever; with TTL, Flink cleans up keys nobody updated. That detail is the difference between a job that runs for months and one that dies from memory.

The full pipeline: logs in real time

Paste the source from the window section and this sink into job.sql. The sink uses Kafka transactions so writes are committed only when the checkpoint completes.

CREATE TABLE service_health (
  window_start TIMESTAMP(3),
  window_end TIMESTAMP(3),
  service STRING,
  errors BIGINT,
  avg_ms DOUBLE
) WITH (
  'connector' = 'kafka',
  'topic' = 'service-health',
  'properties.bootstrap.servers' = 'kafka:29092',
  'format' = 'json',
  'sink.delivery-guarantee' = 'exactly-once',
  'sink.transactional-id-prefix' = 'service-health-'
);

INSERT INTO service_health
SELECT window_start, window_end, service,
       SUM(CASE WHEN level = 'ERROR' THEN 1 ELSE 0 END) AS errors,
       AVG(duration_ms) AS avg_ms
FROM TUMBLE(TABLE app_logs, DESCRIPTOR(event_time), INTERVAL '1' MINUTE)
GROUP BY window_start, window_end, service;

Put these SET statements at the top of job.sql:

SET 'execution.checkpointing.interval' = '30s';
SET 'execution.checkpointing.mode' = 'EXACTLY_ONCE';

In the demo, checkpoints stay in the JobManager; in production, use S3 or HDFS.

docker compose cp job.sql jobmanager:/tmp/job.sql
docker compose exec jobmanager ./bin/sql-client.sh -f /tmp/job.sql

Read the output with read_committed so you do not see aborted transaction records:

docker compose exec kafka /opt/kafka/bin/kafka-console-consumer.sh \
  --bootstrap-server localhost:9092 \
  --topic service-health \
  --isolation-level read_committed \
  --from-beginning

If everything works, a JSON object with errors and avg_ms per service appears every minute. Keep sending events so the watermark advances. If nothing appears, check the watermark, the event timestamps and whether the topic has data in the partition you are looking at.

Performance: the numbers that matter

Do not optimize by intuition. Look at consumer lag, checkpoint duration, backpressure and CPU before touching configuration.

Symptom Likely cause What to do
Lag grows Too few partitions or a hot key More partitions or rekey
Slow checkpoints Large state or backpressure TTL, incremental RocksDB, more parallelism
High latency Conservative watermark or large batch Tune tolerated disorder and linger.ms
Duplicates At-least-once sink Transactions or an idempotent sink
Restart loop Checkpoint timeout or sink down Backoff, longer timeout, fix the sink

Job parallelism cannot exceed the topic’s partitions if you want every subtask to read one. With 6 partitions and parallelism 12, half the subtasks sit idle. The rule is simple: size partitions by throughput and parallelism by partitions.

Checkpoint interval is a trade-off: more frequent checkpoints reduce replay, but add overhead. 30 to 60 seconds is a good starting point; for large state, use incremental checkpoints and fast storage.

Common mistakes and when not to use this

  1. Choosing the key as the event ID. Events land in arbitrary partitions and you lose per-entity order. Use the ID of the entity you need to order.
  2. Creating one topic per user. Thousands of topics, metadata and rebalances. Partition by key, not by entity.
  3. Committing the offset before processing. A crash and the message disappears. Commit after.
  4. Ignoring the watermark. A window that never closes is usually an idle partition or badly parsed timestamps.
  5. Keeping state without TTL. The job grows until the checkpoint takes longer than the interval.
  6. Using exactly-once with a sink outside the transaction. The guarantee ends where Kafka ends.
  7. Looking only at the UI. Consumer lag and checkpoint duration matter more than a green job.
  8. Scaling the job before scaling partitions. More parallelism over 6 partitions accelerates nothing.

Kafka and Flink are not the answer to everything. If you have 20 events per minute and a dashboard that refreshes hourly, a cron job and a table are enough. If you need ad hoc queries over years of history, a warehouse is better. If the problem is request-response, a transactional database wins. And if you cannot operate a cluster with on-call, use a managed service before running Kafka and Flink by hand.

Checklist before production

  • The topic has enough partitions for peak load and a key that avoids hot partitions.
  • Replication factor 3 and min.insync.replicas=2 in production.
  • acks=all and idempotence enabled on producers.
  • Retention sized for the replay you need.
  • Schema contract and backward compatibility.
  • Consumer offsets committed after processing.
  • Watermark measured with real data, not a guessed value.
  • Checkpoints on durable storage, with retention and alerts.
  • State with TTL and size limits.
  • Alerts on lag, checkpoint duration and backpressure.
  • Failure test: kill a TaskManager and verify there are no duplicates.
  • Runbook for rebalances, restarts and savepoint deployments.

Kafka gives you the log. Flink gives you the state. The guarantee that an event is processed once is not something you buy: you design it, with checkpoints, transactions and an uncomfortable question about every side effect.