blog by OSO

How to Use Kafka Streams Processor API for Complex Enterprise Applications

Sion Smith
Sion Smith 3 September 2025
OSO guide to using the Kafka Streams Processor API for complex enterprise applications, with white title text on a navy panel and a lime Blogs label.

Updated October 2026: We have updated every code example to the current Processor API (the processor.api package, with Record and typed output) introduced in Kafka 2.7. The old Processor<K, V> interface, context.forward(key, value, To.child(...)) and the transformer methods were deprecated and then removed in Kafka 4.0, so the original examples no longer compile on current versions. We also now use prefixScan() for composite keys and mention the stream-table join grace period added in Kafka 3.6.

When you build mission-critical streaming applications for supply chain management, financial services or real-time business intelligence, the Kafka Streams DSL (Domain Specific Language) often reaches its limits sooner than expected. The DSL excels at straightforward transformations and standard joins. Complex enterprise scenarios that need custom state management, reconciliation logic and fine-grained control over data lifecycles need the Processor API’s imperative control.

Why use the Processor API instead of the DSL?

The difference lies in the programming model. The DSL is declarative: you describe what you want and the framework decides how to do it. That works brilliantly for standard operations, but becomes restrictive when the business logic needs precise control over state and processing order.

The Processor API is imperative: you write each processing step yourself. That suits enterprise Java teams who are used to explicit control flow:

  • Familiar code. State store access is plain get(), put() and delete() calls, so code reviews don’t need streaming specialists.
  • Flexible state stores. You can attach as many state stores as you need to a processor, with any key design, instead of the stores a DSL join creates for you.
  • Custom keys. Composite keys, such as customer ID plus order ID, allow both single lookups and prefix scans across related records.
Choose the Processor API whenStick with the DSL when
You need custom state management across several streamsYou need straightforward maps, filters and transformations
Events arrive in an unpredictable order and must be reconciledJoins follow predictable timing
Data retention depends on business events, not time windowsWindowed aggregations fit the problem
You need composite keys and prefix scansThe team is new to stream processing

You don’t have to choose one or the other for a whole application: KStream#process() lets you drop a custom processor into a DSL topology.

When do Kafka Streams DSL joins hit their limits?

Out-of-order reference data

Consider enriching order events with product information using a KStream to KTable join. The product data sits in a KTable while orders flow through a KStream. The join looks up the table when each order arrives. If the product data isn’t there yet, an inner join drops the order and a left join emits it without the product data.

Kafka 3.6 added an optional grace period for stream-table joins on versioned tables (KIP-923), which buffers stream records for a fixed time to handle small delays. It doesn’t help when reference data comes from legacy batch systems hours later. With the Processor API, you can hold incomplete orders in a state store and complete them whenever the reference data arrives.

Too many state stores

Complex business processes often chain several enrichments: orders joined with inventory, then shipping details, then delivery confirmations. Each DSL join creates its own state stores, and often repartition topics, and intermediate results carry earlier data forward into the next store. That means more memory and disk, duplicated data and a topology that is harder to operate.

With the Processor API, one processor can manage a single state store that accumulates information from all of these streams, keyed by the business ID.

Fixed time windows

Stream-to-stream joins need a fixed window. Container shipping is a good example of why that hurts: the average journey might take three months, but exceptions can stretch it to six months or more. A short window loses legitimate late events; a very long one makes the state stores huge. The Processor API lets you keep records until a business event, such as delivery, says they are complete.

How do you implement a Processor API state store pattern?

The core pattern replaces chains of joins with processors that read, update and write one state store organised by a business key such as the order ID. Here is a simple order enrichment processor using the current API:

public class OrderEnrichmentProcessor implements Processor<String, Order, String, EnrichedOrder> {
    private ProcessorContext<String, EnrichedOrder> context;
    private KeyValueStore<String, OrderState> orderStore;

    @Override
    public void init(ProcessorContext<String, EnrichedOrder> context) {
        this.context = context;
        this.orderStore = context.getStateStore("order-state-store");
    }

    @Override
    public void process(Record<String, Order> record) {
        String orderId = record.key();
        OrderState state = orderStore.get(orderId);
        if (state == null) {
            state = new OrderState();
        }

        state.setOrder(record.value());
        state.setLastUpdated(record.timestamp());
        orderStore.put(orderId, state);

        context.forward(record.withValue(state.toEnrichedOrder()));
    }
}

Each processor contains simple get, update and put logic. Wire the processors and their state stores into a topology:

Topology topology = new Topology();
topology.addSource("orders-source", "orders")
        .addProcessor("order-enrichment", OrderEnrichmentProcessor::new, "orders-source")
        .addStateStore(
            Stores.keyValueStoreBuilder(
                Stores.persistentKeyValueStore("order-state-store"),
                Serdes.String(), orderStateSerde),
            "order-enrichment")
        .addSink("enriched-sink", "enriched-orders", "order-enrichment");

How do you handle race conditions with composite keys?

A credit-based discount system shows the pattern. Customers earn credits by returning products and get discounts on later orders. Orders and credit updates can arrive in either order. Instead of rejecting early orders or building retry topics, the processor stores orders it can’t price yet under a composite key, customer ID plus order ID, and releases them when credit arrives.

Because orders and credit updates share the customer ID as their partitioning key, they reach the same task. The input topics must be co-partitioned: the same number of partitions and the same key.

public class DiscountProcessor implements Processor<String, Object, String, PricedOrder> {
    private ProcessorContext<String, PricedOrder> context;
    private KeyValueStore<String, CustomerBalance> balanceStore;
    private KeyValueStore<String, PendingOrder> pendingOrderStore;

    @Override
    public void init(ProcessorContext<String, PricedOrder> context) {
        this.context = context;
        this.balanceStore = context.getStateStore("balance-store");
        this.pendingOrderStore = context.getStateStore("pending-order-store");
        // Release orders that have waited too long, every 10 minutes
        context.schedule(Duration.ofMinutes(10), PunctuationType.WALL_CLOCK_TIME,
            this::releaseStaleOrders);
    }

    @Override
    public void process(Record<String, Object> record) {
        Object value = record.value();
        if (value instanceof Order) {
            processOrder(record, (Order) value);
        } else if (value instanceof CreditUpdate) {
            processCreditUpdate(record, (CreditUpdate) value);
        }
    }

    private void processOrder(Record<String, Object> record, Order order) {
        String customerId = record.key();
        CustomerBalance balance = balanceStore.get(customerId);

        if (balance != null && balance.getCredits() >= order.getRequiredCredits()) {
            balance.useCredits(order.getRequiredCredits());
            balanceStore.put(customerId, balance);
            context.forward(new Record<>(order.getOrderId(), order.applyDiscount(),
                record.timestamp()), "discounted-orders");
        } else {
            // Not enough credit yet: park the order under a composite key
            String pendingKey = customerId + "-" + order.getOrderId();
            pendingOrderStore.put(pendingKey, new PendingOrder(order, record.timestamp()));
        }
    }

    private void processCreditUpdate(Record<String, Object> record, CreditUpdate update) {
        String customerId = record.key();
        CustomerBalance balance = balanceStore.get(customerId);
        if (balance == null) {
            balance = new CustomerBalance(customerId, 0);
        }
        balance.addCredit(update.getAmount());

        List<String> released = new ArrayList<>();
        try (KeyValueIterator<String, PendingOrder> pending =
                 pendingOrderStore.prefixScan(customerId + "-", new StringSerializer())) {
            while (pending.hasNext()) {
                KeyValue<String, PendingOrder> entry = pending.next();
                Order order = entry.value.getOrder();
                if (balance.getCredits() >= order.getRequiredCredits()) {
                    balance.useCredits(order.getRequiredCredits());
                    context.forward(new Record<>(order.getOrderId(), order.applyDiscount(),
                        record.timestamp()), "discounted-orders");
                    released.add(entry.key);
                }
            }
        }
        released.forEach(pendingOrderStore::delete);
        balanceStore.put(customerId, balance);
    }

    private void releaseStaleOrders(long now) {
        long cutoff = now - Duration.ofHours(2).toMillis();
        List<String> expired = new ArrayList<>();
        try (KeyValueIterator<String, PendingOrder> all = pendingOrderStore.all()) {
            while (all.hasNext()) {
                KeyValue<String, PendingOrder> entry = all.next();
                if (entry.value.getReceivedAt() < cutoff) {
                    Order order = entry.value.getOrder();
                    context.forward(new Record<>(order.getOrderId(), order.withoutDiscount(), now),
                        "regular-orders");
                    expired.add(entry.key);
                }
            }
        }
        expired.forEach(pendingOrderStore::delete);
    }
}

The processor forwards to two named child nodes, discounted-orders and regular-orders, which you add as sinks in the topology with the processor as their parent. A single credit update can release dozens of pending orders, all found through the prefix scan rather than a full-store iteration. Downstream systems receive consistent, already-reconciled events.

How do you manage state store lifecycles?

One of the most powerful parts of the Processor API is programmatic control over how long state lives. Instead of time-based expiry, you implement business-driven clean-up with punctuations: scheduled callbacks that scan the store and remove records that are finished.

public class OrderMonitoringProcessor implements Processor<String, OrderEvent, String, OrderState> {
    private ProcessorContext<String, OrderState> context;
    private KeyValueStore<String, OrderState> orderStore;

    @Override
    public void init(ProcessorContext<String, OrderState> context) {
        this.context = context;
        this.orderStore = context.getStateStore("order-monitoring-store");
        context.schedule(Duration.ofHours(1), PunctuationType.WALL_CLOCK_TIME,
            this::cleanUpOrders);
    }

    @Override
    public void process(Record<String, OrderEvent> record) {
        OrderState state = orderStore.get(record.key());
        if (state == null) {
            state = new OrderState(record.key());
        }
        state.updateWith(record.value());
        if (record.value().getType() == EventType.DELIVERED) {
            state.markCompleted();
        }
        orderStore.put(record.key(), state);
        context.forward(record.withValue(state));
    }

    private void cleanUpOrders(long now) {
        long sixMonthsAgo = now - Duration.ofDays(180).toMillis();
        List<String> finished = new ArrayList<>();
        try (KeyValueIterator<String, OrderState> all = orderStore.all()) {
            while (all.hasNext()) {
                KeyValue<String, OrderState> entry = all.next();
                if (entry.value.isCompleted() || entry.value.getLastUpdated() < sixMonthsAgo) {
                    finished.add(entry.key);
                }
            }
        }
        finished.forEach(orderStore::delete);
    }
}

Orders can be removed after delivery, customer records after account closure and temporary holds after a grace period. The stores stay manageable while keeping data for as long as the business process needs it.

Multi-stream reconciliation

Business process monitoring often joins data from five, ten or more systems, each publishing at different rates and latencies. The OSO engineers have built supply chain trackers where processors for ERP, transport management, warehouse management and finance events all update one state store per business process. Each processor knows how to interpret its system’s events, and downstream systems see the complete, evolving picture.

Manual intervention

Real processes need overrides: support teams release orders, adjust balances or trigger special handling. Add a control topic, keyed and partitioned like the business events, as another source for the processor. An admin UI or API can then publish control events that the processor applies to the same state.

What should you consider for performance and operations?

  • Store type. In-memory stores give the lowest lookup latency but must fit in memory and be rebuilt from the changelog after a restart. RocksDB stores hold much larger datasets with a modest memory footprint.
  • Restore time. Large stores lengthen restarts and rebalances. Standby replicas (num.standby.replicas) keep warm copies on other instances.
  • Lookups per event. Denormalising data inside the store uses more space but avoids several lookups for each event.
  • Co-partitioning. Streams that share a processor and store must use the same key and partition count, so related events reach the same task. This lets one application process events from dozens of topics.
  • Iterators. Always close store iterators (try-with-resources), and collect keys to delete rather than deleting while you iterate.
  • Testing. Use TopologyTestDriver to test processors with realistic event orders and timings, including late and out-of-order data.

What are the practical takeaways?

Start with a clear picture of your state store access patterns, design composite keys for the lookups you need, handle errors and late data explicitly, and plan data lifecycles from day one. Prototype complex scenarios with both the DSL and the Processor API to see the trade-offs. The Processor API takes more effort up front, but for complex enterprise use cases it often produces simpler, more maintainable production systems.

Key takeaway: Use the Kafka Streams Processor API when the DSL can’t express your logic: out-of-order events, many streams feeding one state, composite keys with prefix scans, and business-driven retention through punctuations. Write new code against the processor.api interfaces, because Kafka 4.0 removed the old Processor API.

Frequently asked questions

What is the Kafka Streams Processor API?

It is the low-level Kafka Streams API for defining processing logic node by node. You implement processors that receive each record, read and write state stores, forward records to child nodes and schedule punctuations. The DSL itself is built on top of it.

When should I use the Processor API instead of the Kafka Streams DSL?

Use it when you need custom state management, reconciliation of events that arrive out of order, composite keys, or data retention driven by business events. For standard transformations, joins with predictable timing and windowed aggregations, the DSL is simpler.

Was the old Kafka Streams Processor API removed?

Yes. Kafka 2.7 introduced the new typed API in the processor.api package, and the old Processor interface, To.child forwarding and the transform methods were deprecated and then removed in Kafka 4.0. Use Processor with four type parameters and Record instead.

Can I mix the Processor API with the DSL?

Yes. KStream#process() and processValues() add a custom processor to a DSL topology, and you can connect state stores to it by name. Many applications use the DSL for simple steps and a custom processor for the complex logic.

How do you clean up state stores in the Processor API?

Schedule a punctuation with context.schedule(), using wall-clock or stream time, and scan the store for records that are complete or too old. Collect their keys, close the iterator, then delete them.

Build complex Kafka Streams applications with OSO

Talk to OSO's Kafka engineers about designing Processor API topologies, state stores and reconciliation logic for your enterprise streaming applications.

CONTACT US