Stream processing

Filter, join and aggregate payment events as they arrive, with Kafka Streams in Quarkus and with Apache Flink SQL.

Updated CompTech Team

A consumer that only writes each record to a database is not a stream processor. Stream processing is the filter, the join and the total you compute while the record is on its way, and the new topic those results go to. Two libraries cover the lab: Kafka Streams, inside the service that already owns the payments code, and Apache Flink, when the job is large enough to be its own system.

Both read the payments topic from Kafka on OpenShift and write a five-minute total per account.

Prerequisites

  • The payments topic, keyed by account, with a parseable amount
  • A Quarkus project for the Kafka Streams service, deployed like any other pod
  • For Flink, the Flink Kubernetes operator on the same cluster, and a FlinkDeployment that can reach the bootstrap Service

Kafka Streams

The topology is the program. Quarkus starts it with the application. State lives in a local store and, for a windowed aggregate, also in a changelog topic so another pod can take over after a rebalance.

@ApplicationScoped
public class Totals {
    @Produces
    public Topology topology() {
        var builder = new StreamsBuilder();
        builder.stream("payments", Consumed.with(Serdes.String(), new JsonSerde<>(Payment.class)))
            .filter((account, payment) -> payment.amount() > 0)
            .groupByKey()
            .windowedBy(TimeWindows.ofSizeWithNoGrace(Duration.ofMinutes(5)))
            .aggregate(
                () -> 0L,
                (account, payment, sum) -> sum + payment.amount(),
                Materialized.with(Serdes.String(), Serdes.Long()))
            .toStream()
            .selectKey((window, total) -> window.key())
            .to("payment-totals", Produced.with(Serdes.String(), Serdes.Long()));
        return builder.build();
    }
}
quarkus.kafka-streams.bootstrap-servers=lab-kafka-bootstrap.kafka.svc:9092
quarkus.kafka-streams.application-id=payment-totals
quarkus.kafka-streams.topics=payments,payment-totals

application-id is the consumer group and the prefix of the changelog topics. Changing it makes the job start again from the reset policy. filter drops a non-positive amount before it affects a total. The window is five minutes of event time, with no grace, so a late record is dropped rather than reopening yesterday's window. Add grace when the producers do not get the record to Kafka immediately.

Create payment-totals as a KafkaTopic with the same partition count as payments. A change-log join needs co-partitioning: the same count and the same key. Joining payments to account-balance on the account id works when both topics have six partitions and both are keyed by account. A join on a key you did not partition by is a full copy, not a join.

Scale the Deployment and the assignment moves. The local store is rebuilt from the changelog. That rebuild is why the changelog topics must have the same replication and the same min.insync.replicas as the topics you care about. An application-id you reuse for a second, unrelated topology will corrupt both. One topology, one id.

Flink SQL

The same total in Flink SQL, for a job the data team should be able to read without the Quarkus repository:

CREATE TABLE payments (
  account STRING,
  amount BIGINT,
  ts TIMESTAMP(3),
  WATERMARK FOR ts AS ts - INTERVAL '5' SECOND
) WITH (
  'connector' = 'kafka',
  'topic' = 'payments',
  'properties.bootstrap.servers' = 'lab-kafka-bootstrap.kafka.svc:9092',
  'properties.group.id' = 'flink-payment-totals',
  'format' = 'json',
  'scan.startup.mode' = 'earliest-offset'
);

INSERT INTO payment_totals
SELECT account,
       window_start,
       SUM(amount) AS total
FROM TABLE(TUMBLE(TABLE payments, DESCRIPTOR(ts), INTERVAL '5' MINUTES))
GROUP BY account, window_start, window_end;

payment_totals is another Kafka table with 'connector' = 'kafka'. The watermark says records may arrive five seconds late and still count. That is the grace period the Streams job set to zero. Pick one definition of "late" and use it in both, or they will disagree by the records in between.

Submit the SQL as a FlinkDeployment session job, or as a SQL file the Flink operator runs. The checkpoint directory must be on durable storage. A checkpoint is what makes a restart continue rather than recompute from the beginning. Store it on the same S3-compatible bucket the rest of the platform uses.

Which one

Kafka Streams Flink
Runs as A pod in the application Deployment Its own cluster, its own checkpoints
State RocksDB plus a changelog topic Flink state backend, checkpointed
Fits Logic the service team owns, joins across a few topics Large state, SQL as the interface, many jobs on one runtime
Exactly-once sink to Kafka The Streams transactional producer Checkpoints, with a transactional Kafka sink

Do not run both on the same topic writing the same payment-totals keys. Pick one topology per result. The delivery rules still apply to whatever consumes payment-totals.

What's next

  1. A total is an input to a model in Kafka for AI.
  2. The source of payments is often the outbox, not a hand-written producer.
  3. Consumer lag on payment-totals is an alert in monitoring.