Skip to content

Commit 076fc21

Browse files
committed
docs: update microservices idempotent consumer
1 parent acb40e1 commit 076fc21

File tree

7 files changed

+67
-47
lines changed

7 files changed

+67
-47
lines changed

Diff for: microservices-distributed-tracing/README.md

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
11
---
2-
title: "Microservices Distributed Tracing Pattern: Enhancing Visibility in Service Communication"
3-
shortTitle: Distributed Tracing in Microservices
2+
title: "Microservices Distributed Tracing Pattern In Java: Enhancing Visibility in Service Communication"
3+
shortTitle: Microservices Distributed Tracing
44
description: "Learn how the Distributed Tracing pattern enhances visibility into service communication across microservices. Discover its benefits, implementation examples, and best practices."
55
category: Architectural
66
language: en
77
tag:
88
- Cloud distributed
99
- Microservices
1010
- Resilience
11-
- Scalability
1211
- Observability
12+
- Scalability
1313
- System health
1414
---
1515

Diff for: microservices-idempotent-consumer/README.md

+58-34
Original file line numberDiff line numberDiff line change
@@ -1,53 +1,56 @@
11
---
2-
title: "Idempotent Consumer Pattern in Java: Ensuring Reliable Message Processing"
3-
shortTitle: Idempotent Consumer
2+
title: "Microservices Idempotent Consumer Pattern in Java: Ensuring Reliable Message Processing"
3+
shortTitle: Microservices Idempotent Consumer
44
description: "Learn about the Idempotent Consumer pattern in Java. Discover how it ensures reliable and consistent message processing, even in cases of duplicate messages."
5-
category: Structural
5+
category: Messaging
66
language: en
77
tag:
8+
- Asynchronous
9+
- Decoupling
810
- Event-driven
11+
- Messaging
12+
- Microservices
13+
- Resilience
14+
- Retry
915
---
1016

1117
## Also known as
1218

13-
* Idempotency Pattern
19+
* Idempotent Subscriber
20+
* Repeatable Message Consumer
21+
* Safe Consumer
1422

1523
## Intent of Idempotent Consumer Pattern
1624

17-
The Idempotent Consumer pattern is used to handle duplicate messages in distributed systems, ensuring that multiple processing of the same message does not cause undesired side effects. This pattern guarantees that the same message can be processed repeatedly with the same outcome, which is critical in ensuring reliable communication and data consistency in systems where message duplicates are possible.
25+
Ensure that consuming the same message multiple times does not cause unintended side effects in a microservices-based architecture.
1826

1927
## Detailed Explanation of Idempotent Consumer Pattern with Real-World Examples
2028

21-
### Real-world Example
29+
Real-world example
2230

2331
> In a payment processing system, ensuring that payment messages are idempotent prevents duplicate transactions. For example, if a user’s payment message is accidentally processed twice, the system should recognize the second message as a duplicate and prevent it from executing a second time. By storing unique identifiers for each processed message, such as a transaction ID, the system can skip any duplicate messages. This ensures that a user is not charged twice for the same transaction, maintaining system integrity and customer satisfaction.
2432
25-
### In Plain Words
33+
In plain words
2634

2735
> The Idempotent Consumer pattern prevents duplicate messages from causing unintended side effects by ensuring that processing the same message multiple times results in the same outcome. This makes message processing safe in distributed systems where duplicates may occur.
2836
29-
### Wikipedia says
3037

31-
> In computing, idempotence is the property of certain operations in mathematics and computer science whereby they can be applied multiple times without changing the result beyond the initial application.
38+
Wikipedia says
3239

33-
## When to Use the Idempotent Consumer Pattern
40+
> In computing, idempotence is the property of certain operations in mathematics and computer science whereby they can be applied multiple times without changing the result beyond the initial application.
3441
35-
The Idempotent Consumer pattern is particularly useful in scenarios:
42+
Flowchart
3643

37-
* When messages can be duplicated due to network retries or communication issues.
38-
* In distributed systems where message ordering is not guaranteed, making deduplication necessary to avoid repeated processing.
39-
* In financial or critical systems, where duplicate processing would have significant side effects.
44+
![Microservices Idempotent Consumer flowchart](./etc/microservices-idempotent-consumer-flowchart.png)
4045

41-
## Real-World Applications of Idempotent Consumer Pattern
46+
## Programmatic example of Idempotent Consumer Pattern
4247

43-
* Payment processing systems that avoid duplicate transactions.
44-
* E-commerce systems to prevent multiple entries of the same order.
45-
* Inventory management systems to prevent multiple entries when updating stock levels.
48+
In this Java example, we have an idempotent service that creates and updates orders. The `create` method is idempotent, meaning multiple calls with the same order ID return the same result without duplicates. For state changes (like starting or completing an order), the service checks whether the transition is valid and throws an exception if it’s not allowed. The `RequestStateMachine` ensures that order statuses move forward in a valid sequence (e.g., PENDING → STARTED → COMPLETED).
4649

47-
## Programmatic example of Idempotent Consumer Pattern
48-
In this Java example, we have an idempotent service that offers functionality to create and update (start, complete, etc.) orders. The service ensures that the **create order** operation is idempotent, meaning that performing it multiple times with the same order ID will lead to the same result without creating duplicates. For state transitions (such as starting or completing an order), the service enforces valid state changes and throws exceptions if an invalid transition is attempted. The state machine governs the valid order status transitions, ensuring that statuses progress in a defined and consistent sequence.
4950
### RequestService - Managing Idempotent Order Operations
50-
The `RequestService` class is responsible for handling the creation and state transitions of orders. The `create` method is designed to be idempotent, ensuring that it either returns an existing order or creates a new one without any side effects if invoked multiple times with the same order ID.
51+
52+
The `RequestService` class provides methods to create and transition an order. The `create` method returns an existing order if it already exists, making it idempotent.
53+
5154
```java
5255
public class RequestService {
5356
// Idempotent: ensures that the same request is returned if it already exists
@@ -76,8 +79,11 @@ public class RequestService {
7679
}
7780
}
7881
```
82+
7983
### RequestStateMachine - Managing Order Transitions
80-
The `RequestStateMachine` ensures that state transitions occur in a valid order. It handles the progression of an order's status, ensuring the correct sequence (e.g., from `PENDING` to `STARTED` to `COMPLETED`).
84+
85+
The `RequestStateMachine` enforces valid state changes. If a requested transition is not allowed based on the current status, an exception is thrown.
86+
8187
```java
8288
public class RequestStateMachine {
8389

@@ -102,9 +108,10 @@ public class RequestStateMachine {
102108
}
103109
}
104110
```
111+
105112
### Main Application - Running the Idempotent Consumer Example
106113

107-
In the main application, we demonstrate how the `RequestService` can be used to perform idempotent operations. Whether the order creation or state transition is invoked once or multiple times, the result is consistent and does not produce unexpected side effects.
114+
Here, we demonstrate how `RequestService` can be called multiple times without creating duplicate orders. We also show how invalid transitions (like trying to start an order twice) result in exceptions, while valid transitions proceed normally.
108115

109116
```java
110117
Request req = requestService.create(UUID.randomUUID());
@@ -127,32 +134,49 @@ req = requestService.complete(req.getUuid());
127134
// Log the final status of the Request to confirm it's been completed
128135
LOGGER.info("Request: {}", req);
129136
```
137+
130138
Program output:
139+
131140
```
132141
19:01:54.382 INFO [main] com.iluwatar.idempotentconsumer.App : Nb of requests : 1
133142
19:01:54.395 ERROR [main] com.iluwatar.idempotentconsumer.App : Cannot start request twice!
134143
19:01:54.399 INFO [main] com.iluwatar.idempotentconsumer.App : Request: Request(uuid=2d5521ef-6b6b-4003-9ade-81e381fe9a63, status=COMPLETED)
135144
```
145+
146+
## When to Use the Idempotent Consumer Pattern
147+
148+
* When messages can arrive more than once due to network glitches or retries
149+
* When microservices must guarantee consistent state changes regardless of duplicates
150+
* When fault-tolerant event-driven communication is critical to system reliability
151+
* When horizontal scaling requires stateless consumer operations
152+
153+
## Real-World Applications of Idempotent Consumer Pattern
154+
155+
* Payment processing systems that receive duplicate charge events
156+
* E-commerce order services that handle duplicate purchase requests
157+
* Notification services that retry failed message deliveries
158+
* Distributed transaction systems where duplicated events are common
159+
136160
## Benefits and Trade-offs of the Idempotent Consumer Pattern
137161

138-
### Benefits
162+
Benefits
139163

140-
* **Reliability**: Ensures that messages can be processed without unwanted side effects from duplicates.
141-
* **Consistency**: Maintains data integrity by ensuring that duplicate messages do not cause redundant updates or actions.
142-
* **Fault Tolerance**: Handles message retries gracefully, preventing them from causing errors.
164+
* Prevents duplicate side effects
165+
* Increases reliability under repeated or delayed messages
166+
* Simplifies error handling and retry logic
143167

144-
### Trade-offs
168+
Trade-offs
145169

146-
* **State Management**: Requires storing processed message IDs, which can add memory overhead.
147-
* **Complexity**: Implementing deduplication mechanisms can increase the complexity of the system.
148-
* **Scalability**: In high-throughput systems, maintaining a large set of processed messages can impact performance and resource usage.
170+
* Requires careful design to track processed messages
171+
* Can add overhead for maintaining idempotency tokens or state
172+
* May require additional storage or database transactions
149173

150174
## Related Patterns in Java
151175

152-
* [Retry Pattern](https://java-design-patterns.com/patterns/retry/): Works well with the Idempotent Consumer pattern to handle failed messages.
153-
* [Circuit Breaker Pattern](https://java-design-patterns.com/patterns/circuitbreaker/): Often used alongside idempotent consumers to prevent repeated failures from causing overload.
176+
* Outbox Pattern: Uses a dedicated table or storage to reliably publish events and handle deduplication at the source.
154177

155178
## References and Credits
156179

180+
* [Building Microservices](https://amzn.to/3UACtrU)
157181
* [Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions](https://amzn.to/4dznP2Y)
158-
* [Designing Data-Intensive Applications](https://amzn.to/3UADv7Q)
182+
* [Microservices Patterns: With examples in Java](https://amzn.to/3UyWD5O)
Loading

Diff for: microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/RequestService.java

+2-5
Original file line numberDiff line numberDiff line change
@@ -44,18 +44,15 @@ public RequestService(
4444
}
4545

4646
/**
47-
* Creates a new Request or returns an existing one by it's UUID. This operation is idempotent:
47+
* Creates a new Request or returns an existing one by its UUID. This operation is idempotent:
4848
* performing it once or several times successively leads to an equivalent result.
4949
*
5050
* @param uuid The unique identifier for the Request.
5151
* @return Return existing Request or save and return a new Request.
5252
*/
5353
public Request create(UUID uuid) {
5454
Optional<Request> optReq = requestRepository.findById(uuid);
55-
if (!optReq.isEmpty()) {
56-
return optReq.get();
57-
}
58-
return requestRepository.save(new Request(uuid));
55+
return optReq.orElseGet(() -> requestRepository.save(new Request(uuid)));
5956
}
6057

6158
/**

Diff for: microservices-idempotent-consumer/src/test/java/com/iluwatar/idempotentconsumer/AppTest.java

+2-2
Original file line numberDiff line numberDiff line change
@@ -39,12 +39,12 @@
3939
class AppTest {
4040

4141
@Test
42-
void main() {
42+
void testMain() {
4343
assertDoesNotThrow(() -> App.main(new String[] {}));
4444
}
4545

4646
@Test
47-
void run() throws Exception {
47+
void testRun() throws Exception {
4848
RequestService requestService = Mockito.mock(RequestService.class);
4949
RequestRepository requestRepository = Mockito.mock(RequestRepository.class);
5050
UUID uuid = UUID.randomUUID();

Diff for: microservices-idempotent-consumer/src/test/java/com/iluwatar/idempotentconsumer/RequestServiceTests.java

+1-2
Original file line numberDiff line numberDiff line change
@@ -43,11 +43,10 @@
4343
class RequestServiceTests {
4444
private RequestService requestService;
4545
@Mock private RequestRepository requestRepository;
46-
private RequestStateMachine requestStateMachine;
4746

4847
@BeforeEach
4948
void setUp() {
50-
requestStateMachine = new RequestStateMachine();
49+
RequestStateMachine requestStateMachine = new RequestStateMachine();
5150
requestService = new RequestService(requestRepository, requestStateMachine);
5251
}
5352

Diff for: microservices-idempotent-consumer/src/test/java/com/iluwatar/idempotentconsumer/RequestStateMachineTests.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ class RequestStateMachineTests {
3535
private RequestStateMachine requestStateMachine;
3636

3737
@BeforeEach
38-
public void setUp() {
38+
void setUp() {
3939
requestStateMachine = new RequestStateMachine();
4040
}
4141

0 commit comments

Comments
 (0)