By WebNest Studio Engineering Team
Spring Boot Tutorial
Event-Driven Microservices with Spring Cloud Stream
Writing Kafka or RabbitMQ code directly ties your services to one broker's API. Spring Cloud Stream lets you write messaging logic as plain Java functions — Supplier, Function and Consumer beans — and binds them to broker destinations through configuration. The same code runs on Kafka, RabbitMQ, Pulsar or cloud brokers by swapping the binder dependency.
This lesson builds an order-processing flow across services with Spring Cloud Stream: producing events with StreamBridge, consuming and transforming them with functional beans, consumer groups and partitioning, error handling with dead-letter queues, and testing with the test binder.
Functional Bindings
Declare a @Bean of type Consumer<OrderPlaced> named reserveStock, and Spring Cloud Stream creates an input binding reserveStock-in-0. A Function<A, B> gets both -in-0 and -out-0 bindings — it consumes, transforms and publishes. Map bindings to topics/exchanges with spring.cloud.stream.bindings.<binding>.destination. If several functions exist, list them in spring.cloud.function.definition.
Publishing from Business Code
To send an event from a REST controller or service method (not on a schedule), inject StreamBridge and call streamBridge.send("orders-out-0", event). Messages are serialised as JSON by default, with a contentType header.
Consumer Groups and Partitions
Set group on an input binding so that multiple instances of the same service share the work (each message is processed by one instance), while different services each receive every message. Partitioning by a key (such as order id) keeps related events in order and on the same instance.
Error Handling
Failed messages are retried (maxAttempts, back-off settings on the consumer binding). After retries, enable a dead-letter queue (enableDlq on Kafka or RabbitMQ binder properties) so a poison message is parked for inspection instead of blocking the stream. As always with messaging, consumers must be idempotent.
Examples
Dependencies and bindings configuration
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-stream</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-stream-binder-kafka</artifactId> <!-- or -binder-rabbit -->
</dependency>
# inventory-service application.yml
spring:
cloud:
function:
definition: reserveStock
stream:
kafka:
binder:
brokers: localhost:9092
bindings:
reserveStock-in-0:
destination: orders.placed
group: inventory-service
consumer:
max-attempts: 3
reserveStock-out-0:
destination: stock.reserved
Created binding reserveStock-in-0 -> topic orders.placed (group inventory-service)
Created binding reserveStock-out-0 -> topic stock.reserved
Producing with StreamBridge and processing with a Function
// order-service
public record OrderPlaced(String orderId, List<Line> lines) {}
public record Line(String sku, int qty) {}
@RestController
public class OrderController {
private final StreamBridge streamBridge;
public OrderController(StreamBridge streamBridge) {
this.streamBridge = streamBridge;
}
@PostMapping("/api/orders")
public ResponseEntity<Void> place(@RequestBody OrderPlaced order) {
// (save the order first — ideally via an outbox)
streamBridge.send("orders.placed", order);
return ResponseEntity.accepted().build();
}
}
// inventory-service: consumes OrderPlaced, emits StockReserved
public record StockReserved(String orderId, boolean success) {}
@Configuration
public class InventoryFunctions {
@Bean
Function<OrderPlaced, StockReserved> reserveStock(StockService stock) {
return order -> {
boolean ok = stock.tryReserve(order.orderId(), order.lines()); // idempotent by orderId
return new StockReserved(order.orderId(), ok);
};
}
}
// notification-service
@Bean
Consumer<StockReserved> notifyCustomer(Notifier notifier) {
return event -> notifier.stockResult(event.orderId(), event.success());
}
POST /api/orders {"orderId":"WN-10231","lines":[{"sku":"HD-NAVY-M","qty":1}]} -> 202 Accepted
inventory-service: reserved stock for WN-10231
notification-service: "Good news! Your order WN-10231 is confirmed."
Testing with the test binder
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-stream-test-binder</artifactId>
<scope>test</scope>
</dependency>
@SpringBootTest
@Import(TestChannelBinderConfiguration.class)
class ReserveStockTest {
@Autowired InputDestination input;
@Autowired OutputDestination output;
@Autowired JsonMapper json;
@Test
void reservesStockAndPublishesResult() throws Exception {
input.send(MessageBuilder.withPayload(
new OrderPlaced("WN-1", List.of(new Line("HD-NAVY-M", 1)))).build(), "orders.placed");
Message<byte[]> result = output.receive(1000, "stock.reserved");
StockReserved event = json.readValue(result.getPayload(), StockReserved.class);
assertThat(event.success()).isTrue();
}
}
ReserveStockTest > reservesStockAndPublishesResult() PASSED (no broker needed)
Common Mistakes
- Forgetting spring.cloud.function.definition when several function beans exist, so none are bound.
- Omitting the consumer group, so every instance of a service processes every message.
- Publishing events before the database transaction commits, or without an outbox, causing inconsistencies.
- Non-idempotent consumers that double-process redelivered messages.
- Not configuring a DLQ, letting a poison message block a partition or queue.
Exercise
Using the lesson's Dependencies and bindings configuration example, create a small implementation or design sketch that demonstrates Spring Cloud Stream binds Supplier/Function/Consumer beans to broker destinations by configuration.. Add a test case or scenario that would catch Forgetting spring.cloud.function.definition when several function beans exist, so none are bound., and describe the expected result.
Show hints
- Start with Functional Bindings and compare your approach with Dependencies and bindings configuration. Identify the decision or behavior the lesson recommends.
- Walk through your scenario step by step. Confirm that it follows Spring Cloud Stream binds Supplier/Function/Consumer beans to broker destinations by configuration. and that it would catch the failure described by Forgetting spring.cloud.function.definition when several function beans exist, so none are bound..
Quick quiz
1. Which choice is a mistake to avoid in Event-Driven Microservices with Spring Cloud Stream?
- A. Spring Cloud Stream binds Supplier/Function/Consumer beans to broker destinations by configuration.
- B. Forgetting spring.cloud.function.definition when several function beans exist, so none are bound.
- C. Omitting the consumer group, so every instance of a service processes every message.
Show answer
B. Avoid this approach: Forgetting spring.cloud.function.definition when several function beans exist, so none are bound. The lesson recommends: Spring Cloud Stream binds Supplier/Function/Consumer beans to broker destinations by configuration.
Interview questions
How would you apply the guidance in Functional Bindings to a real task, and what failure would you guard against?
Show answer
Spring Cloud Stream binds Supplier/Function/Consumer beans to broker destinations by configuration. Apply this in Functional Bindings; the example Dependencies and bindings configuration shows one way to do it. Avoid Forgetting spring.cloud.function.definition when several function beans exist, so none are bound. and explain how your implementation or design prevents that failure.
Key Points to Remember
- Spring Cloud Stream binds Supplier/Function/Consumer beans to broker destinations by configuration.
- Binders (Kafka, RabbitMQ, ...) make messaging code broker-independent.
- StreamBridge sends events from business code; bindings named <function>-in-0/-out-0.
- Consumer groups share work across instances; partitions preserve per-key ordering.
- Configure retries and DLQs, keep consumers idempotent, and test with the test binder.
Practice in the playground
Write and run your own code for this topic, or start from the exercise or an example. Runs plain Java 17. Frameworks such as Spring, and databases, are not available here. Your code for each topic is kept in this browser.
Run the examples
Change an input, predict the result, then compare it with the output. Explain why the result changes.
These examples need a JDK project with their libraries on your computer, so they can be copied but not run here. Codelab runs Python, FastAPI backends with SQLite, plain Java 17 and HTML/CSS/JavaScript.
Written by
WebNest Studio Engineering Team
Practical lessons from developers working with Java, Python, React, databases and production systems.
Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering