Skip to main content

Spring Cloud Stream on Boot 4: Functional Kafka and RabbitMQ Binders

One Supplier, Function and Consumer pipeline run on Kafka and on RabbitMQ with Spring Cloud Stream 5.1 on Spring Boot 4.2, by changing one profile. Real transcripts for the test binder, partitioning (murmur2, not hashCode), RabbitMQ’s queue-per-partition trap, dead-letter queues on both binders, and the wiring mistakes with their actual error messages.

If you have written Kafka code with Spring, you have a KafkaTemplate in your service and a @KafkaListener on the other side. If you have written RabbitMQ code, you have a RabbitTemplate and a @RabbitListener. Both work, and both bake the broker into your business logic. Moving a service from one to the other means rewriting every class that sends or receives.

Spring Cloud Stream is the layer that removes that coupling. You write ordinary java.util.function beans — a Supplier that produces, a Function that transforms, a Consumer that receives — and a library called a binder connects them to Kafka or RabbitMQ based on configuration. This post builds one small order-to-invoice pipeline, runs it on both brokers by changing a single Spring profile, and then spends most of its length on the places where “same code, different broker” turns out to be only mostly true: partitioning, dead-letter queues, and a few wiring mistakes that cost me real time.

Everything below was run. The code is in the cloud-stream module of the spring-messaging-demo repository, and every console block in this article is copied from a file in that module’s output/ folder, written by the test suite against real Kafka and RabbitMQ brokers started with Testcontainers.

Versions tested. Spring Boot 4.2.0 (GA 19 November 2026), Spring Cloud 2026.0.0 with Spring Cloud Stream and Spring Cloud Function 5.1.0, spring-kafka 4.2.0 with kafka-clients 4.4.0, spring-amqp 4.2.0, Apache Kafka 4.4.0 and RabbitMQ 4.4.1 (the apache/kafka:4.4.0 and rabbitmq:4-management images), Testcontainers 2.0.5, Temurin JDK 25.0.5.1. Versions were read from maven-metadata.xml on Maven Central and from the Spring Cloud 2026.0.0 BOM, which sets spring-boot.version to 4.2.0. I could not find a release announcement for 2026.0.0; its Maven Central artifacts are dated 19 November 2026.

Your business logic should not know which broker it runs on

Four words carry the whole framework, and each is simple once you see what it replaces.

  • A function bean is your code: a Supplier<T>, Function<A,B> or Consumer<T>.
  • A binding is one input or output of a function. Its name is generated: the function name, then -in- or -out-, then an index starting at 0. So bill-in-0 is the first (and only) input of bill.
  • A destination is where the binding points: a Kafka topic or a RabbitMQ exchange. You choose it in configuration.
  • A binder is the plug-in that makes destinations real on one specific broker. Kafka and RabbitMQ each have one.
One function bean per step, one binding per function input and outputorderSourceSupplier beanpriceOrderFunction beanbillConsumer beandestinationordersdestinationinvoicesorderSource-out-0priceOrder-in-0priceOrder-out-0bill-in-0The binder (Kafka or RabbitMQ) turns each destination into a topic or an exchange and each binding into a producer or consumer.It is the only part of the system that knows which broker is underneath.Binding names are the function name plus -in- or -out- plus an index: bill-in-0 is the first input of bill.
The figure to hold in your head: your code is the three blue boxes. Everything else is configuration that the binder reads.

The diagram is the whole architecture. Notice what is not in the blue boxes: no topic names, no serializers, no connection factories. That is the promise, and the rest of the article is about testing it.

Going deeper

Three beans, no broker: the smallest thing that works

This is the entire application logic, from Pipeline.java. The supplier is polled by the framework once a second and emits one order per call; the function prices an order into an invoice; the consumer bills it, and throws on a negative total so that later sections have a poison message to work with.

    /**
     * Polled by the framework (every second by default), one order per call. A supplier that returns
     * {@code null} sends nothing, which is how {@code demo.max-orders} makes the demos finite (0 = unbounded).
     */
    @Bean
    public Supplier<Order> orderSource(@Value("${demo.max-orders:0}") int maxOrders) {
        AtomicInteger n = new AtomicInteger();
        return () -> {
            int i = n.incrementAndGet();
            if (maxOrders > 0 && i > maxOrders) {
                return null;
            }
            return new Order("o-" + i, CUSTOMERS.get(i % CUSTOMERS.size()), 1 + i % 3, 9.5);
        };
    }

    /** Input and output are both typed; the framework converts JSON to and from the records. */
    @Bean
    public Function<Order, Invoice> priceOrder() {
        return order -> new Invoice(order.orderId(), order.customerId(), order.quantity() * order.unitPrice());
    }

    /** A negative total is the "poison" in the dead-letter demos: this consumer throws on it. */
    @Bean
    public Consumer<Invoice> bill() {
        return invoice -> {
            log.info("bill attempt for {}", invoice.orderId());
            if (invoice.total() < 0) {
                throw new IllegalArgumentException("Refusing to bill " + invoice.orderId() + ": negative total");
            }
            log.info("billed {} for {}", invoice.orderId(), invoice.total());
        };
    }

Two details are easy to miss. A supplier that returns null sends nothing, which is how the demo.max-orders property makes every demo in this post finite. And the function is typed: Function<Order, Invoice>. The framework converts JSON bytes to an Order on the way in and an Invoice to JSON on the way out, so there is no serializer code anywhere.

You can prove all of that without a broker. The test binder (artifact spring-cloud-stream-test-binder) replaces Kafka and RabbitMQ with in-memory destinations. This helper from Test01TestBinderTest.java starts the real application on it, and the function test sends JSON into orders and reads from invoices:

    private static ConfigurableApplicationContext start(String... args) {
        return new SpringApplicationBuilder(TestChannelBinderConfiguration.getCompleteConfiguration(CloudStreamApplication.class))
                .web(WebApplicationType.NONE).run(args);
    }
    void function() {
        try (Transcript t = new Transcript("01-test-binder-function");
                ConfigurableApplicationContext ctx = start("--spring.cloud.function.definition=priceOrder")) {
            InputDestination in = ctx.getBean(InputDestination.class);
            OutputDestination out = ctx.getBean(OutputDestination.class);
            t.line("$ function definition = priceOrder   (binder: test, no broker)");
            in.send(json("{\"orderId\":\"o-1\",\"customerId\":\"alice\",\"quantity\":2,\"unitPrice\":9.5}"), "orders");
            Message<byte[]> reply = out.receive(2000, "invoices");
            t.line("in  orders   : {\"orderId\":\"o-1\",\"customerId\":\"alice\",\"quantity\":2,\"unitPrice\":9.5}");
            t.line("out invoices : %s", new String(reply.getPayload()));
            t.line("out contentType header: %s", reply.getHeaders().get("contentType"));
            assertThat(new String(reply.getPayload())).isEqualTo("{\"orderId\":\"o-1\",\"customerId\":\"alice\",\"total\":19.0}");
        }
    }

Transcript 01-test-binder-function.txt:

$ function definition = priceOrder   (binder: test, no broker)
in  orders   : {"orderId":"o-1","customerId":"alice","quantity":2,"unitPrice":9.5}
out invoices : {"orderId":"o-1","customerId":"alice","total":19.0}
out contentType header: application/json

The supplier test lets the poller run at 100 ms with five orders allowed, and prints what the test binder received (02-test-binder-supplier.txt):

$ function definition = orderSource, poller fixed-delay = 100 ms, demo.max-orders = 5
polled #1: {"orderId":"o-1","customerId":"bob","quantity":2,"unitPrice":9.5}
   headers: [contentType, id, scst_partition, timestamp]  scst_partition=0
polled #2: {"orderId":"o-2","customerId":"carol","quantity":3,"unitPrice":9.5}
   headers: [contentType, id, scst_partition, timestamp]  scst_partition=2

Look at scst_partition=0 on the first message. The binder has already worked out a partition number before any broker is involved. The partitioning section below is about where that number comes from.

A throwing consumer does not throw at the caller. The third test sends a good invoice and then a poison one to bill (03-test-binder-consumer.txt):
$ function definition = bill   (max-attempts=3, back-off 200 ms)
good invoice sent -> log lines containing 'bill attempt for o-1': 1
poison invoice sent -> attempts: 3
send() returned normally

The poison message was attempted three times (the configured max-attempts: 3), the framework logged an exhausted-retry error, and send() returned normally. A test that expects an exception from the sender will wait forever. Count attempts instead, as this one does.

Going deeper: what the test binder is, and where it stops

The test binder is a binder like any other, registered by importing TestChannelBinderConfiguration. Because the cloud-stream module has both real binders on its classpath, this is a useful result: the test binder was used in every test above even though Kafka and RabbitMQ binders were present, with no default-binder set. Everything it proves is about your functions and your binding configuration: names, conversion, partition headers, retry counts. It proves nothing about a real broker, which is why the Kafka and RabbitMQ sections below use real ones.

The test binder passes InputDestination and OutputDestination beans to the test. They address a destination by its configured name, not by binding name, so a destination that has no binding yields a bare NullPointerException rather than a helpful message (the next section shows that exact failure).

Going deeper

From a function name to a topic: bindings, destinations and groups

The beans have no idea where they send or receive. All of that lives in application.yml, and it is the only configuration that is the same for every broker:

  cloud:
    function:
      # The functions to bind, separated by semicolons. Left empty, nothing was bound to 'orders' (output/09).
      definition: orderSource;priceOrder;bill
    stream:
      poller:
        fixed-delay: 1000
      bindings:
        orderSource-out-0:
          destination: orders
          producer:
            partition-key-expression: payload.customerId
            partition-count: 3
        priceOrder-in-0:
          destination: orders
          group: pricing
        priceOrder-out-0:
          destination: invoices
        bill-in-0:
          destination: invoices
          group: billing
          consumer:
            max-attempts: 3
            back-off-initial-interval: 200
            back-off-multiplier: 1.0

Read it from the top. spring.cloud.function.definition lists which functions to bind. Each binding then gets a destination. orders appears twice because the supplier writes to it and priceOrder reads from it — they are connected by sharing a name, not by anything in the Java. The group on the two input bindings is the one new concept that matters for scaling: all instances of the application that use the same group split the messages between them, which is how you run three copies of priceOrder without pricing every order three times. On Kafka that is a consumer group; on RabbitMQ it becomes part of a durable queue name.

If you forget spring.cloud.function.definition, nothing tells you. With three function beans and the property empty, the test binder had no channel for orders at all (09-no-function-definition.txt):
$ three function beans (orderSource, priceOrder, bill), spring.cloud.function.definition left empty
beans of type Function: [functionRouter, priceOrder], Supplier: [orderSource], Consumer: [bill]
send threw NullPointerException: Cannot invoke "org.springframework.messaging.SubscribableChannel.send(org.springframework.messaging.Message)" because the return value of "org.springframework.cloud.stream.binder.test.InputDestination.getChannelByName(String)" is null

The application starts cleanly; the symptom is only that nothing flows. When a stream is silent, check the definition property before anything else.

Going deeper

  • Producing and consuming messages in the reference docs
  • Retry settings (max-attempts, back-off) are binding-level and the same on both brokers, which is why they sit in this file; the dead-letter settings are not, and sit in the profile files (see the dead-letter section)

Switch one profile, change the broker

The broker-specific blocks are two small files. application-kafka.yml sets the default binder, three consumer threads and a dead-letter topic:

spring:
  cloud:
    stream:
      default-binder: kafka
      bindings:
        priceOrder-in-0:
          consumer:
            concurrency: 3
      kafka:
        bindings:
          bill-in-0:
            consumer:
              enable-dlq: true
              dlq-name: invoices.billing.dlq

and application-rabbit.yml does the same job for RabbitMQ. It is longer, and every extra line is explained by a later section, so I will show it now and refer back to it:

spring:
  cloud:
    stream:
      default-binder: rabbit
      bindings:
        priceOrder-out-0:
          producer:
            # Rabbit routes through an exchange: a message published before the group's queue exists is
            # dropped. required-groups makes the producer declare the consumer queue itself.
            required-groups: billing
        priceOrder-in-0:
          consumer:
            # Rabbit has no consumer groups across partitions: every instance owns exactly one partition queue.
            partitioned: true
            instance-count: 3
            instance-index: 0
      rabbit:
        bindings:
          priceOrder-out-0:
            producer:
              # The producer declares the consumer's queue for required-groups, so it must declare it with
              # the same arguments as the consumer does, or the broker answers PRECONDITION_FAILED.
              auto-bind-dlq: true
          bill-in-0:
            consumer:
              auto-bind-dlq: true
              republish-to-dlq: true

Both starters are on the classpath of the same project (pom.xml), and the profile picks one. The application code does not name either broker. A script checks that mechanically (13-binder-free.txt):

$ grep -rilE 'kafka|rabbit' src/main/java | wc -l
0
$ grep -rilE 'kafka|rabbit' src/main/resources
src/main/resources/application-kafka.yml
src/main/resources/application-rabbit.yml

Now run the same jar twice, against a real broker each time, changing only --spring.profiles.active (the script is run-on-broker.sh). Kafka first (11-run-kafka.txt):

com.ankurm.cloudstream.Pipeline          : billed o-1 for 19.0
com.ankurm.cloudstream.Pipeline          : billed o-2 for 28.5
com.ankurm.cloudstream.Pipeline          : billed o-3 for 9.5
com.ankurm.cloudstream.Pipeline          : billed o-4 for 19.0
com.ankurm.cloudstream.Pipeline          : billed o-5 for 28.5
com.ankurm.cloudstream.Pipeline          : billed o-6 for 9.5
com.ankurm.cloudstream.Pipeline          : billed o-7 for 19.0
com.ankurm.cloudstream.Pipeline          : billed o-8 for 28.5

Eight orders in, eight billed. Now RabbitMQ (12-run-rabbit.txt):

com.ankurm.cloudstream.Pipeline          : billed o-1 for 19.0
com.ankurm.cloudstream.Pipeline          : billed o-4 for 19.0
com.ankurm.cloudstream.Pipeline          : billed o-5 for 28.5
com.ankurm.cloudstream.Pipeline          : billed o-8 for 28.5

Four of eight. Same jar, same code, same --demo.max-orders=8, no error anywhere. Hold on to that: the missing four are the subject of the next section.

Two binders on the classpath need a default. This module deliberately ships both. Without spring.cloud.stream.default-binder (or a binder on every binding) the context refuses to start (08-two-binders-no-default.txt):
$ both binder starters on the classpath, no spring.cloud.stream.default-binder, no per-binding binder
BeanCreationException: Error creating bean with name 'functionInitializer' defined in class path resource [org/springframework/cloud/stream/function/FunctionConfiguration.class]: A default binder has been requested, but there is more than one binder available for 'org.springframework.messaging.MessageChannel' : kafka,rabbit, and no default binder has been set.

Real services usually have one binder on the classpath and never see this. It is the price of demonstrating both in one project.

Going deeper: the Rabbit binder makes your worker a web server

The jar runs on port 8080 unless you stop it. The Rabbit binder depends on spring-boot-starter-webflux through spring-cloud-stream-binder-rabbit-core, and Boot sees WebFlux on the classpath and starts a reactive web server. The first time I ran the packaged jar the symptom was “Web server failed to start. Port 8080 was already in use” — from an application that serves no HTTP. The dependency path (14-webflux-path.txt):

com.ankurm:cloud-stream-demo:jar:1.0
\- org.springframework.cloud:spring-cloud-starter-stream-rabbit:jar:5.1.0:compile
   \- org.springframework.cloud:spring-cloud-stream-binder-rabbit:jar:5.1.0:compile
      \- org.springframework.cloud:spring-cloud-stream-binder-rabbit-core:jar:5.1.0:compile
         \- org.springframework.boot:spring-boot-starter-webflux:jar:4.2.0:compile

The fix is one property, already set in application.yml: spring.main.web-application-type: none. If your service genuinely wants HTTP endpoints, drop that line and expect the Rabbit binder to be the reason WebFlux is there.

Going deeper

Partitioning: same key, same partition, and what Rabbit has to fake

Partitioning is how a stream scales without losing order. Messages with the same key always go to the same partition, and one consumer owns each partition, so all orders for one customer are processed by one thread, in sequence. The producer side is two lines in application.yml above: partition-key-expression: payload.customerId says what the key is, and partition-count: 3 says how many partitions to spread over.

On Kafka, partitions are native. The binder created the topics for me, with the partition counts the configuration implied, and then I read every record back with a plain Kafka consumer (Test02KafkaPipelineTest.java, transcript 04-kafka-pipeline.txt):

$ profile kafka, supplier capped at 12 orders (demo.max-orders=12), broker apache/kafka:4.4.0
billed lines in the application log: 12
topic invoices-k2 created by the binder with 1 partition(s)
topic orders-k2 created by the binder with 3 partition(s)
consumer group 'pricing': 3 members (concurrency=3), partitions per member [1, 1, 1]
records on orders-k2 by partition (customer of each record):
  partition 0: [bob, alice, bob, alice, bob, alice]
  partition 1: [dave, dave, dave]
  partition 2: [carol, carol, carol]
records that carry a Kafka message key: 0
alice: in 1 partition(s), actually partition 0; murmur2 % 3 = 0, hashCode % 3 = 0
bob: in 1 partition(s), actually partition 0; murmur2 % 3 = 0, hashCode % 3 = 1
carol: in 1 partition(s), actually partition 2; murmur2 % 3 = 2, hashCode % 3 = 1
dave: in 1 partition(s), actually partition 1; murmur2 % 3 = 1, hashCode % 3 = 2
Kafka: 12 orders, 3 partitions on topic orderspartition 0alice, bob6 records (alice x3, bob x3)consumer thread 1 of 3partition 1dave3 recordsconsumer thread 2 of 3partition 2carol3 recordsconsumer thread 3 of 3partition = murmur2(customerId bytes) & 0x7fffffff, modulo 3The same customer always lands in the same partition, so one consumer sees that customer in order.
Partition 0 holds two customers and partition 1 and 2 one each: hashing does not promise an even spread, only a stable one.

Three things in that transcript are worth reading slowly.

The group has three members. concurrency: 3 in the Kafka profile gave one application three consumer threads, each assigned one partition. This is Kafka doing the work; you configured nothing per partition.

The Kafka record key is empty. “Records that carry a Kafka message key: 0”. partition-key-expression chooses a partition, it does not set the record key. If you need the key on the record (for log compaction, or for a downstream consumer that reads it), that is a separate binder property on the Kafka side, which this module does not exercise.

The reference page and the jar disagree about the formula. The documentation’s partitioning page states the default as key.hashCode() % partitionCount. The transcript shows what actually happened: bob.hashCode() % 3 would be 1, and bob is in partition 0. The test asserts that the real partition equals Kafka’s own murmur2 hash of the key bytes modulo 3, and it does for all four customers. The accordion below reads the same thing out of the jar.

The practical consequence: if some other producer needs to land in the same partition as this one (a non-Spring service, say), copy the murmur2 behaviour, not the documented hashCode formula.

Now the payoff of the “four of eight” from the last section. RabbitMQ has no partitions inside a queue. The binder fakes them: one queue per partition, named destination.group-index, and each application instance consumes exactly one of those queues, chosen by instance-index. The Rabbit profile above sets instance-count: 3 and instance-index: 0, so one running copy owns queue 0 and nothing owns the other two. The reference docs say this directly for RabbitMQ: “there is a queue for each partition, with the queue name containing the instance index.” Kafka, by contrast, needs none of these properties while its default rebalancing is on.

Test04RabbitPipelineTest.java runs the pipeline three ways against one RabbitMQ broker and asks the broker itself what exists (06-rabbit-partitions.txt):

$ profile rabbit, 12 orders: alice, bob, carol, dave x 3, partition-count=3, consumer instance-count=3 instance-index=0

run A, no required-groups on the orders producer: billed 6 of 12
queues on the broker (name, messages, consumers):
  orders-r4a.pricing-0	0	1

run B, required-groups=pricing on the orders producer: billed 6 of 12
queues on the broker (name, messages, consumers):
  orders-r4b.pricing-0	0	1
  orders-r4b.pricing-1	3	0
  orders-r4b.pricing-2	3	0

run C, plus instance-index 1 and 2: billed 12 of 12
queues on the broker (name, messages, consumers):
  orders-r4b.pricing-0	0	1
  orders-r4b.pricing-1	0	1
  orders-r4b.pricing-2	0	1
RabbitMQ: one queue per partition, one consumer instance per queueexchangeorders-r4borders-r4b.pricing-00 waiting, instance 0 consumesorders-r4b.pricing-13 waiting, no consumerorders-r4b.pricing-23 waiting, no consumerRun B of the transcript: six orders consumed, six waiting for instances that are not running.Start instance-index 1 and 2 and both queues drain.
On RabbitMQ a partition is a queue, and a queue with no consumer is just a place where messages wait.

Run A is the surprise. Six of twelve orders were billed and the broker has a single queue, pricing-0. The queues for partitions 1 and 2 were never created, because on RabbitMQ the consumer declares its queue and this consumer only owns index 0. A message routed to a partition with no queue has nowhere to go. Those six orders are in no queue at all, which is exactly what the eight-order jar run showed.

Run B adds required-groups=pricing on the producer. Now the producer declares the partition queues itself, and the unconsumed messages wait: three each in pricing-1 and pricing-2. Run C starts two more application contexts with instance-index 1 and 2, and both queues drain; twelve of twelve billed. That, and not a bigger concurrency, is how a partitioned RabbitMQ stream scales: more instances, each told which partition it is.

required-groups has a hidden second half. When the producer declares the consumer’s queue, it must declare it with the same arguments the consumer will use. The consumer side has auto-bind-dlq: true, which adds a dead-letter exchange argument to the queue. A producer that declares the same queue without it gets this from the broker (10-rabbit-required-groups-mismatch.txt):
$ rabbit profile, but the producer binding priceOrder-out-0 has required-groups=billing and auto-bind-dlq=false
reply-code=406, reply-text=PRECONDITION_FAILED - inequivalent arg 'x-dead-letter-exchange' for queue 'invoices-<run>.billing' in vhost '/': received the value 'DLX' of type 'longstr' but current is none

That is why application-rabbit.yml sets auto-bind-dlq: true on the producer binding priceOrder-out-0 as well. The error appears in the log; the application keeps running with a binding that cannot declare its queue. Whichever side declares the queue first wins, and the other side is the one that fails.

Going deeper: reading the default partition selector out of the jar

When documentation and observation disagree, I decompile. The default selector is the nested class PartitionHandler$DefaultPartitionSelector in spring-cloud-stream-5.1.0.jar (partition-selector.sh, output 15-partition-selector.txt):

$ javap -p -c PartitionHandler$DefaultPartitionSelector   (selectPartition and the murmur2 call)
public int selectPartition(java.lang.Object, int);
Code:
0: aload_1
1: invokevirtual #7                  // Method java/lang/Object.toString:()Ljava/lang/String;
4: getstatic     #11                 // Field java/nio/charset/StandardCharsets.UTF_8:Ljava/nio/charset/Charset;
7: invokevirtual #17                 // Method java/lang/String.getBytes:(Ljava/nio/charset/Charset;)[B
10: astore_3
11: aload_0
12: aload_3
13: invokevirtual #23                 // Method murmur2:([B)I
16: ldc           #29                 // int 2147483647
18: iand
19: ireturn

It converts the key to a string, takes the UTF-8 bytes, runs them through a murmur2 method, and masks off the sign bit with 0x7fffffff (that is the ldc 2147483647; iand). The partition handler then takes the result modulo partition-count. This is the same algorithm Kafka’s default partitioner uses for keyed records, which is probably why the transcript matches Utils.murmur2 from kafka-clients. One consequence follows directly from the first two instructions: it is the string form of the key that is hashed, so a numeric key 42 and a string key "42" land together.

Going deeper

Going deeper

Poison messages: dead-letter queues on both binders

A poison message is one that will never succeed however many times you retry it. The consumer throws, the framework retries three times with a short back-off, and then it has to do something with the message. If it does nothing, that message sits at the front of its partition and every later message waits behind it. The standard answer is a dead-letter queue (DLQ): after the retries are exhausted, move the message to a side destination and keep going. Each binder has its own switch for it, which is why these are in the profile files and not in application.yml.

On Kafka the switch is enable-dlq, and the DLQ is a topic. Test03KafkaDlqTest.java sends a good invoice, a poison one, then another good one, and then reads the DLQ topic directly (05-kafka-dlq.txt):

$ profile kafka, function definition = bill, enable-dlq=true, max-attempts=3
bill attempts: o-1=1 o-2=3 o-3=1
billed: o-1=1 o-2=0 o-3=1 (o-3 was behind the poison record on the same partition)
DLQ topic invoices-k3.billing.dlq holds 1 record(s)
payload: {"orderId":"o-2","customerId":"bob","total":-1.0}
header x-original-topic = invoices-k3
header x-original-partition = 0
header x-original-offset = 1
header x-original-timestamp = (epoch millis, omitted)
header x-original-timestamp-type = CreateTime
header x-exception-fqcn = org.springframework.messaging.MessagingException
header x-exception-message = error occurred in message handler [org.springframework.cloud.stream.function.FunctionConfi...
header x-exception-stacktrace = org.springframework.messaging.MessagingException: Retry policy for operation 'org.springfr...
   stack trace mentions the real cause (IllegalArgumentException: Refusing to bill o-2): true

The ordering is the point. o-3 was billed once even though it sat behind the poison o-2: three attempts on o-2, then the record moved to invoices-k3.billing.dlq, then o-3 went through. The DLQ record keeps the original payload and carries x-original-topic, partition and offset, so you can find the source.

One thing to know before you build alerting on it: x-exception-fqcn says MessagingException, not IllegalArgumentException. The consumer exception is wrapped by the framework, and the stack-trace header is where the real cause is, as the last line of the transcript confirms.

On RabbitMQ the switch is auto-bind-dlq, and there are two behaviours depending on republish-to-dlq. Test05RabbitDlqTest.java runs the same poison message under both and reads the DLQ through the management API (07-rabbit-dlq.txt):

$ profile rabbit, function definition = bill, auto-bind-dlq=true, max-attempts=3

--- republish-to-dlq=true (what application-rabbit.yml sets) ---
bill attempts for the poison invoice: 3
queues (name, messages, consumers):
  invoices-<run>.billing	0	1
  invoices-<run>.billing.dlq	1	0
DLQ payload: {"orderId":"p-r5a","customerId":"alice","total":-1.0}
DLQ header names: [retry-count, x-exception-message, x-exception-stacktrace, x-original-exchange, x-original-routingKey]
  x-exception-message = Retry policy for operation 'org.springframework.integration.amqp.inbound.AmqpInboundChannelAdapter$Listener$$Lambda/0x...' exhausted; aborting execution
  x-original-exchange = invoices-<run>
  x-original-routingKey = invoices-<run>
DLQ header has x-exception-stacktrace: true

--- republish-to-dlq=false (broker-side dead lettering only) ---
bill attempts for the poison invoice: 3
queues (name, messages, consumers):
  invoices-<run>.billing	0	1
  invoices-<run>.billing.dlq	1	0
DLQ payload: {"orderId":"p-r5b","customerId":"alice","total":-1.0}
DLQ header names: [x-death, x-first-death-exchange, x-first-death-queue, x-first-death-reason, x-last-death-exchange, x-last-death-queue, x-last-death-reason]
  x-first-death-queue = invoices-<run>.billing
  x-first-death-reason = rejected
  x-death: reason=rejected queue=invoices-<run>.billing count=1
DLQ header has x-exception-stacktrace: false

Both put the poison payload in invoices-<run>.billing.dlq. What differs is the evidence you get. With republish-to-dlq: true the binder itself republishes the message, and adds x-exception-message and x-exception-stacktrace. With false the broker dead-letters it on rejection, and all you get is RabbitMQ’s own x-death bookkeeping — reason rejected, no exception text at all. The second is lighter; the first is the one you want at 3 a.m. when someone asks why the message died.

Going deeper: the comparison in one table
Kafka binderRabbitMQ binder
Switchenable-dlq: trueauto-bind-dlq: true
DLQ is atopic, named by dlq-namequeue named destination.group.dlq
Exception evidenceheaders: fqcn, message, stack tracesame headers only with republish-to-dlq: true; otherwise x-death
Where the source is recordedx-original-topic/partition/offsetx-original-exchange, x-original-routingKey
Retries before dead-letteringbinding-level max-attempts, same on both (3 attempts observed above, as configured)

The Kafka column is from 05-kafka-dlq.txt and the Rabbit column from 07-rabbit-dlq.txt. This module does not replay dead letters; I did not exercise any replay mechanism, so treat the DLQ as a holding place that a process or a person has to drain.

Going deeper

What actually changes when you switch binders

Collecting what the transcripts showed, the Java did not change at all, and the configuration changed in these places:

ConcernKafkaRabbitMQWhere shown
Partitionsreal topic partitions, created by the binderone queue per partitionpartitioning
Scaling a partitioned consumerconcurrency, or more instances; rebalancing is automaticone instance per instance-index, set by youpartitioning
A partition with no consumermessages wait in the loglost unless required-groups declares the queuerun A and B
Dead lettersenable-dlqauto-bind-dlq plus republish-to-dlq for exception headersdead letters
Extra dependenciesnone surprisingpulls in WebFluxswitching profiles

So “change one profile” is true for the beans and false for the topology. The business code is portable. The partitioning and failure-handling configuration is not, and the first time you will notice is an eight-order test that bills four.

Should you use Spring Cloud Stream at all?

Use it when the broker is a deployment detail; skip it when the broker is the design. It earns its place for event-driven services where the logic is “take a message, do something, maybe emit another” and you want it testable with no broker at all (the test binder section) or movable between brokers. It is a poor fit when the broker’s own features are the point: Kafka transactions across topics, Kafka Streams state stores, RabbitMQ’s exchange types and per-message TTL. The binders expose many of those as properties, but every one you reach for is a place where “portable” stops being true, as the Rabbit partition section showed. And if you will only ever run Kafka, plain Spring Kafka has fewer moving parts, one less abstraction to debug, and the same @KafkaListener your team already knows.

Run it yourself

Clone the repository, and from the cloud-stream directory with JDK 25 and Docker available, run run-all.sh to regenerate every file in output/. The tests assert the same numbers they print, so if a later Spring Cloud release changes any behaviour shown here, the build fails rather than the article quietly going stale.

Further reading

No Comments yet!

This site uses Akismet to reduce spam. Learn how your comment data is processed.