Skip to content

Commit 3cea274

Browse files
committed
added idempotent consumer pattern
1 parent 7c8802e commit 3cea274

File tree

11 files changed

+723
-0
lines changed

11 files changed

+723
-0
lines changed

idempotent-consumer/README.md

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
---
2+
title: "Idempotent Consumer Pattern in Java: Ensuring Reliable Message Processing"
3+
shortTitle: Idempotent Consumer
4+
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: Messaging
6+
language: en
7+
tag:
8+
- Messaging
9+
- Fault tolerance
10+
- Event-driven
11+
- Reliability
12+
---
13+
14+
## Also known as
15+
16+
* Idempotency Pattern
17+
18+
## Intent of Idempotent Consumer Pattern
19+
20+
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.
21+
22+
## Detailed Explanation of Idempotent Consumer Pattern with Real-World Examples
23+
24+
### Real-world Example
25+
26+
> 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.
27+
28+
### In Plain Words
29+
30+
> 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.
31+
32+
### Wikipedia says
33+
34+
> 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.
35+
36+
## Detailed Explanation with Real-World Example Diagram
37+
38+
![Idempotent Consumer Diagram](./etc/idempotent_consumer.png)
39+
40+
The diagram shows the flow in which the consumer processes the first message and skips the duplicate using the unique transaction ID stored in memory or a persistent storage.
41+
42+
## When to Use the Idempotent Consumer Pattern
43+
44+
The Idempotent Consumer pattern is particularly useful in scenarios:
45+
46+
* When messages can be duplicated due to network retries or communication issues.
47+
* In distributed systems where message ordering is not guaranteed, making deduplication necessary to avoid repeated processing.
48+
* In financial or critical systems, where duplicate processing would have significant side effects.
49+
50+
## Real-World Applications of Idempotent Consumer Pattern
51+
52+
* Payment processing systems that avoid duplicate transactions.
53+
* E-commerce systems to prevent multiple entries of the same order.
54+
* Inventory management systems to prevent multiple entries when updating stock levels.
55+
56+
## Benefits and Trade-offs of the Idempotent Consumer Pattern
57+
58+
### Benefits
59+
60+
* **Reliability**: Ensures that messages can be processed without unwanted side effects from duplicates.
61+
* **Consistency**: Maintains data integrity by ensuring that duplicate messages do not cause redundant updates or actions.
62+
* **Fault Tolerance**: Handles message retries gracefully, preventing them from causing errors.
63+
64+
### Trade-offs
65+
66+
* **State Management**: Requires storing processed message IDs, which can add memory overhead.
67+
* **Complexity**: Implementing deduplication mechanisms can increase the complexity of the system.
68+
* **Scalability**: In high-throughput systems, maintaining a large set of processed messages can impact performance and resource usage.
69+
70+
## Related Patterns in Java
71+
72+
* [Retry Pattern](https://java-design-patterns.com/patterns/retry/): Works well with the Idempotent Consumer pattern to handle failed messages.
73+
* [Circuit Breaker Pattern](https://java-design-patterns.com/patterns/circuitbreaker/): Often used alongside idempotent consumers to prevent repeated failures from causing overload.
74+
75+
## References and Credits
76+
77+
* [Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions](https://amzn.to/4dznP2Y)
78+
* [Designing Data-Intensive Applications](https://amzn.to/3UADv7Q)

idempotent-consumer/pom.xml

Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<!--
3+
4+
This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
5+
6+
The MIT License
7+
Copyright © 2014-2022 Ilkka Seppälä
8+
9+
Permission is hereby granted, free of charge, to any person obtaining a copy
10+
of this software and associated documentation files (the "Software"), to deal
11+
in the Software without restriction, including without limitation the rights
12+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13+
copies of the Software, and to permit persons to whom the Software is
14+
furnished to do so, subject to the following conditions:
15+
16+
The above copyright notice and this permission notice shall be included in
17+
all copies or substantial portions of the Software.
18+
19+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25+
THE SOFTWARE.
26+
27+
-->
28+
<project xmlns="http://maven.apache.org/POM/4.0.0"
29+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
30+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
31+
<modelVersion>4.0.0</modelVersion>
32+
<parent>
33+
<groupId>com.iluwatar</groupId>
34+
<artifactId>java-design-patterns</artifactId>
35+
<version>1.26.0-SNAPSHOT</version>
36+
</parent>
37+
38+
<artifactId>idempotent-consumer</artifactId>
39+
<dependencyManagement>
40+
<dependencies>
41+
<dependency>
42+
<groupId>org.springframework.boot</groupId>
43+
<artifactId>spring-boot-dependencies</artifactId>
44+
<type>pom</type>
45+
<version>3.2.3</version>
46+
<scope>import</scope>
47+
</dependency>
48+
<dependency>
49+
<groupId>org.hibernate</groupId>
50+
<artifactId>hibernate-core</artifactId>
51+
<version>6.4.4.Final</version>
52+
</dependency>
53+
</dependencies>
54+
</dependencyManagement>
55+
<dependencies>
56+
<!-- Spring Boot Dependencies -->
57+
58+
<!-- Spring Boot Data JPA for database access -->
59+
<dependency>
60+
<groupId>org.springframework.boot</groupId>
61+
<artifactId>spring-boot-starter-data-jpa</artifactId>
62+
</dependency>
63+
64+
<!-- Testing Dependencies -->
65+
<dependency>
66+
<groupId>org.springframework.boot</groupId>
67+
<artifactId>spring-boot-starter-test</artifactId>
68+
<scope>test</scope>
69+
</dependency>
70+
71+
<!-- JUnit Jupiter Engine for testing -->
72+
<dependency>
73+
<groupId>org.junit.jupiter</groupId>
74+
<artifactId>junit-jupiter-engine</artifactId>
75+
<scope>test</scope>
76+
</dependency>
77+
78+
<!-- Mockito for mocking in tests -->
79+
<dependency>
80+
<groupId>org.mockito</groupId>
81+
<artifactId>mockito-core</artifactId>
82+
<scope>test</scope>
83+
</dependency>
84+
85+
<!-- H2 for mocking database -->
86+
<dependency>
87+
<groupId>com.h2database</groupId>
88+
<artifactId>h2</artifactId>
89+
<scope>runtime</scope>
90+
</dependency>
91+
92+
</dependencies>
93+
94+
95+
<build>
96+
<plugins>
97+
<!-- Maven Assembly Plugin for creating a single distributable JAR -->
98+
<plugin>
99+
<groupId>org.apache.maven.plugins</groupId>
100+
<artifactId>maven-assembly-plugin</artifactId>
101+
<executions>
102+
<execution>
103+
<phase>package</phase>
104+
<goals>
105+
<goal>single</goal>
106+
</goals>
107+
<configuration>
108+
<descriptorRefs>
109+
<descriptorRef>jar-with-dependencies</descriptorRef>
110+
</descriptorRefs>
111+
<archive>
112+
<manifest>
113+
<!-- Define the main class for the executable JAR -->
114+
<mainClass>com.iluwatar.idempotentconsumer.App</mainClass>
115+
</manifest>
116+
</archive>
117+
</configuration>
118+
</execution>
119+
</executions>
120+
</plugin>
121+
122+
<!-- Other plugins as needed -->
123+
124+
</plugins>
125+
</build>
126+
</project>
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
/*
2+
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
3+
*
4+
* The MIT License
5+
* Copyright © 2014-2022 Ilkka Seppälä
6+
*
7+
* Permission is hereby granted, free of charge, to any person obtaining a copy
8+
* of this software and associated documentation files (the "Software"), to deal
9+
* in the Software without restriction, including without limitation the rights
10+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11+
* copies of the Software, and to permit persons to whom the Software is
12+
* furnished to do so, subject to the following conditions:
13+
*
14+
* The above copyright notice and this permission notice shall be included in
15+
* all copies or substantial portions of the Software.
16+
*
17+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23+
* THE SOFTWARE.
24+
*/
25+
package com.iluwatar.idempotentconsumer;
26+
27+
import java.util.UUID;
28+
import lombok.extern.slf4j.Slf4j;
29+
import org.springframework.boot.CommandLineRunner;
30+
import org.springframework.boot.SpringApplication;
31+
import org.springframework.boot.autoconfigure.SpringBootApplication;
32+
import org.springframework.context.annotation.Bean;
33+
34+
/**
35+
* The main entry point for the idempotent-consumer application.
36+
* This application demonstrates the use of the Idempotent Consumer
37+
* pattern which ensures that a message is processed exactly once
38+
* in scenarios where the same message can be delivered multiple times.
39+
*
40+
* @see <a href="https://en.wikipedia.org/wiki/Idempotence">Idempotence (Wikipedia)</a>
41+
* @see <a href="https://camel.apache.org/components/latest/eips/idempotentConsumer-eip.html">Idempotent Consumer Pattern (Apache Camel)</a>
42+
*/
43+
@SpringBootApplication
44+
@Slf4j
45+
public class App {
46+
public static void main(String[] args) {
47+
SpringApplication.run(App.class, args);
48+
}
49+
/**
50+
* The starting point of the CommandLineRunner
51+
* where the main program is run.
52+
*
53+
* @param requestService idempotent request service
54+
* @param requestRepository request jpa repository
55+
*/
56+
@Bean
57+
public CommandLineRunner run(RequestService requestService, RequestRepository requestRepository) {
58+
return args -> {
59+
Request req = requestService.create(UUID.randomUUID());
60+
requestService.create(req.getUuid());
61+
requestService.create(req.getUuid());
62+
LOGGER.info("Nb of requests : {}", requestRepository.count()); // 1, processRequest is idempotent
63+
req = requestService.start(req.getUuid());
64+
try {
65+
req = requestService.start(req.getUuid());
66+
} catch (InvalidNextStateException ex) {
67+
LOGGER.error("Cannot start request twice!");
68+
}
69+
req = requestService.complete(req.getUuid());
70+
LOGGER.info("Request: {}", req);
71+
};
72+
}
73+
}
74+
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/*
2+
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
3+
*
4+
* The MIT License
5+
* Copyright © 2014-2022 Ilkka Seppälä
6+
*
7+
* Permission is hereby granted, free of charge, to any person obtaining a copy
8+
* of this software and associated documentation files (the "Software"), to deal
9+
* in the Software without restriction, including without limitation the rights
10+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11+
* copies of the Software, and to permit persons to whom the Software is
12+
* furnished to do so, subject to the following conditions:
13+
*
14+
* The above copyright notice and this permission notice shall be included in
15+
* all copies or substantial portions of the Software.
16+
*
17+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23+
* THE SOFTWARE.
24+
*/
25+
package com.iluwatar.idempotentconsumer;
26+
27+
/**
28+
* This exception is thrown when an invalid transition is attempted in the Statemachine
29+
* for the request status. This can occur when attempting to move to a state that is not valid
30+
* from the current state.
31+
*/
32+
public class InvalidNextStateException extends RuntimeException {
33+
public InvalidNextStateException(String s) {
34+
super(s);
35+
}
36+
}
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/*
2+
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
3+
*
4+
* The MIT License
5+
* Copyright © 2014-2022 Ilkka Seppälä
6+
*
7+
* Permission is hereby granted, free of charge, to any person obtaining a copy
8+
* of this software and associated documentation files (the "Software"), to deal
9+
* in the Software without restriction, including without limitation the rights
10+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11+
* copies of the Software, and to permit persons to whom the Software is
12+
* furnished to do so, subject to the following conditions:
13+
*
14+
* The above copyright notice and this permission notice shall be included in
15+
* all copies or substantial portions of the Software.
16+
*
17+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23+
* THE SOFTWARE.
24+
*/
25+
package com.iluwatar.idempotentconsumer;
26+
27+
import jakarta.persistence.Entity;
28+
import jakarta.persistence.Id;
29+
import java.util.UUID;
30+
import lombok.Data;
31+
import lombok.NoArgsConstructor;
32+
33+
/**
34+
* The {@code Request} class represents a request with a unique UUID and a status.
35+
* The status of a request can be one of four values: PENDING, STARTED, COMPLETED, or INERROR.
36+
*/
37+
@Entity
38+
@NoArgsConstructor
39+
@Data
40+
public class Request {
41+
enum Status {
42+
PENDING,
43+
STARTED,
44+
COMPLETED,
45+
INERROR
46+
}
47+
48+
@Id
49+
private UUID uuid;
50+
private Status status;
51+
52+
public Request(UUID uuid) {
53+
this(uuid, Status.PENDING);
54+
}
55+
56+
public Request(UUID uuid, Status status) {
57+
this.uuid = uuid;
58+
this.status = status;
59+
}
60+
}

0 commit comments

Comments
 (0)