<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Haris Masood on Medium]]></title>
        <description><![CDATA[Stories by Haris Masood on Medium]]></description>
        <link>https://medium.com/@syedharismasood4?source=rss-bf563d438b2b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*KX2ZlH1kutILlpOIVGx9hA.jpeg</url>
            <title>Stories by Haris Masood on Medium</title>
            <link>https://medium.com/@syedharismasood4?source=rss-bf563d438b2b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 11:32:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@syedharismasood4/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building Reliable Microservices with the Transactional Outbox Pattern in Spring Boot]]></title>
            <link>https://medium.com/@syedharismasood4/building-reliable-microservices-with-the-transactional-outbox-pattern-in-spring-boot-952d96f8b534?source=rss-bf563d438b2b------2</link>
            <guid isPermaLink="false">https://medium.com/p/952d96f8b534</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[transactional-outbox]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Haris Masood]]></dc:creator>
            <pubDate>Mon, 10 Jun 2024 08:56:08 GMT</pubDate>
            <atom:updated>2024-06-13T10:36:13.640Z</atom:updated>
            <content:encoded><![CDATA[<p>In microservices based architectures one of the biggest challenge is to avoid data inconsistency across microservices. Data inconsistency can occur due to many reasons, one such reason is the <strong>Dual Write</strong> problem, which we will discuss in this article.</p><h3>Problem Statement</h3><p>The <strong>Dual Write</strong> problem occurs when a piece of code tries to write to two different data sources i.e. a database and a message queue in a single transaction and one of those writes fail leaving the system in an inconsistent state. In order to better understand the problem, let’s consider the following piece of code:</p><pre>    @Transactional<br>    public User createUser(UserRequestDto userRequestDto) {<br>        User user = userRequestDtoMapper.mapToUserEntity(userRequestDto);<br><br>        user = userRepository.save(user); // Write to the database<br><br>        kafkaTemplate.send(topic, user); // Write to the message queue<br><br>        return user;<br>    }</pre><p>Although the above code snippet apparently seems fine, but after having a closer look at it, we can find out that there are some issues with that. The first one is what if the Kafka broker became temporarily unavailable during the transaction? Yes, as you might think we can simply roll-back transaction, well yes we can, but wait is it a good practice to roll-back the entire transaction due to a temporary failure of an external system? Definitely the answer would be no.</p><p>The second problem which is not so easy to detect by looking at the code is, what if transaction fails to commit? Well again you might think that this isn’t going to happen, well on your local machine it’s true that this scenario will hardly occur, but on production there are thousands of reasons that can cause the database commit to fail. If you are still not convinced then this <a href="https://stackoverflow.com/questions/3960189/can-a-commit-statement-in-sql-ever-fail-how">stackoverflow</a> thread might convince you otherwise. And if this failure occurs then we’ll end up in an inconsistent state because the message will be sent before the transaction is rolled-back. So, essentially user will not be persisted in the database but message will be published indicating that user was created when in reality it was not.</p><h3>Solution</h3><p>In order to solve this problem we have two solutions one is to implement distributed transaction pattern like <strong>Saga</strong>. But, the problem is that it’s a bit difficult to implement and maintain. The good news is we can avoid distributed transactions (in most cases) by using <strong>Transactional Outbox Pattern</strong>.</p><h3><strong>Transactional Outbox Pattern</strong></h3><p>The idea of Transactional Outbox is that in order to avoid <strong>Dual Write</strong> problem instead of writing to two different data sources we must write to only one i.e. our database in a single transaction, so we can roll-back the entire transaction in case of failures as a single unit without side effects. So, essentially we are creating a local transaction instead of a distributed one. In this way we will always end up in a consistent state. In order to implement this pattern we have to create a new table called <strong>outbox </strong>and instead of writing directly to a queue we will write the message in this table. And create a separate <strong>Message Relay Service (MRS) </strong>which will poll undelivered messages and deliver them in batches. Another advantage of this pattern is that since messages are stored in the <strong>outbox </strong>table, we can also easily <strong>replay</strong> messages incase required. Diagrammatically this can be viewed as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*7RoBit1tKmTRZ9lUVOVJrA.png" /></figure><h3><strong>Implementation</strong></h3><p>This demo assumes that you have following tools installed on your local machine:</p><ul><li>Java 17</li><li>Maven</li><li>Mysql 8</li><li>Kafka</li></ul><p>To initialise Spring Boot project use <a href="https://start.spring.io/#!type=maven-project&amp;language=java&amp;platformVersion=3.3.0&amp;packaging=jar&amp;jvmVersion=17&amp;groupId=com.example.microservices&amp;artifactId=transactional-outbox-pattern&amp;name=transactional-outbox-pattern&amp;description=Demo%20project%20for%20transactional%20outbox%20pattern&amp;packageName=com.example.microservices&amp;dependencies=data-jpa,web,validation,liquibase,kafka,kafka-streams,mysql">this</a> initialiser. Once the project is setup create the following liquibase migration files inside resources folder:</p><p><strong>db/changelog/2024/05/changelog</strong></p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;databaseChangeLog<br>        xmlns=&quot;http://www.liquibase.org/xml/ns/dbchangelog&quot;<br>        xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;<br>        xsi:schemaLocation=&quot;http://www.liquibase.org/xml/ns/dbchangelog<br>                      http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-4.27.xsd&quot;&gt;<br><br><br>    &lt;includeAll path=&quot;db/changelog/2024/05/migrations&quot;/&gt;<br><br>&lt;/databaseChangeLog&gt;</pre><p><strong>db/changelog/2024/05/migrations/2024–05–27–01-create-order-table.sql</strong></p><pre>CREATE TABLE `user` (<br>  `id` int NOT NULL AUTO_INCREMENT,<br>  `firstname` varchar(45) NOT NULL,<br>  `lastname` varchar(45) DEFAULT NULL,<br>  `address` varchar(100) DEFAULT NULL,<br>  `dob` date NOT NULL,<br>  `email` varchar(255) NOT NULL,<br>  `created_date` timestamp NULL DEFAULT NULL,<br>  `last_modified_date` timestamp NULL DEFAULT NULL,<br>  PRIMARY KEY (`id`),<br>  UNIQUE KEY `email_UNIQUE` (`email`)<br>) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;</pre><p><strong>db/changelog/2024/05/migrations/2024–05–27–02-create-outbox-table.sql</strong></p><pre>CREATE TABLE `outbox` (<br>  `id` int NOT NULL AUTO_INCREMENT,<br>  `aggregate` varchar(10) NOT NULL,<br>  `message` text NOT NULL,<br>  `is_delivered` tinyint NOT NULL DEFAULT &#39;0&#39;,<br>  `created_date` timestamp NOT NULL,<br>  `last_modified_date` timestamp NOT NULL,<br>  PRIMARY KEY (`id`)<br>) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;</pre><p>We have created two tables one for storing users called <strong>user</strong>, and other one for storing messages called <strong>outbox</strong>. There are many ways to structure your outbox table, the structure we’ve used above contains <strong>id</strong>, <strong>aggregate</strong> (name of an aggregate which initiated the message, in our case it’ll be USER), <strong>message</strong> (contains the actual content of a message), <strong>is_delivered</strong> (0 for undelivered message and 1 for delivered), <strong>created_date</strong>, <strong>last_modified_date</strong>. But again there is no fixed structure for creating the outbox table, choose structure that works best for you.</p><p>Next, create entities and repositories for these tables:</p><pre>package com.example.microservices.entity;<br><br>import jakarta.persistence.Column;<br>import jakarta.persistence.Entity;<br>import jakarta.persistence.EntityListeners;<br>import jakarta.persistence.GeneratedValue;<br>import jakarta.persistence.GenerationType;<br>import jakarta.persistence.Id;<br>import org.springframework.data.annotation.CreatedDate;<br>import org.springframework.data.annotation.LastModifiedDate;<br>import org.springframework.data.jpa.domain.support.AuditingEntityListener;<br><br>import java.time.LocalDate;<br>import java.time.LocalDateTime;<br><br>@Entity<br>@EntityListeners(AuditingEntityListener.class)<br>public class User {<br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    @Column(name = &quot;id&quot;, nullable = false)<br>    private Long id;<br><br>    @Column(name = &quot;firstname&quot;, nullable = false, length = 45)<br>    private String firstname;<br><br>    @Column(name = &quot;lastname&quot;, length = 45)<br>    private String lastname;<br><br>    @Column(name = &quot;dob&quot;, nullable = false)<br>    private LocalDate dob;<br><br>    @Column(name = &quot;address&quot;, nullable = true, length = 100)<br>    private String address;<br><br>    @Column(name = &quot;email&quot;, nullable = false, unique = true)<br>    private String email;<br><br>    @CreatedDate<br>    @Column(name = &quot;created_date&quot;)<br>    private LocalDateTime createdDate;<br><br>    @LastModifiedDate<br>    @Column(name = &quot;last_modified_date&quot;)<br>    private LocalDateTime lastModifiedDate;<br><br>    private static final String USER_AGGREGATE = &quot;USER&quot;;<br><br>    public User() {<br>    }<br><br>    public User(String firstname, String lastname, LocalDate dob, String address, String email) {<br>        this.firstname = firstname;<br>        this.lastname = lastname;<br>        this.dob = dob;<br>        this.address = address;<br>        this.email = email;<br>    }<br><br>    public LocalDateTime getLastModifiedDate() {<br>        return lastModifiedDate;<br>    }<br><br>    public void setLastModifiedDate(LocalDateTime lastModifiedDate) {<br>        this.lastModifiedDate = lastModifiedDate;<br>    }<br><br>    public LocalDateTime getCreatedDate() {<br>        return createdDate;<br>    }<br><br>    public void setCreatedDate(LocalDateTime createdDate) {<br>        this.createdDate = createdDate;<br>    }<br><br>    public String getEmail() {<br>        return email;<br>    }<br><br>    public void setEmail(String email) {<br>        this.email = email;<br>    }<br><br>    public LocalDate getDob() {<br>        return dob;<br>    }<br><br>    public void setDob(LocalDate dob) {<br>        this.dob = dob;<br>    }<br><br>    public String getLastname() {<br>        return lastname;<br>    }<br><br>    public void setLastname(String lastname) {<br>        this.lastname = lastname;<br>    }<br><br>    public String getFirstname() {<br>        return firstname;<br>    }<br><br>    public void setFirstname(String firstname) {<br>        this.firstname = firstname;<br>    }<br><br>    public Long getId() {<br>        return id;<br>    }<br><br>    public void setId(Long id) {<br>        this.id = id;<br>    }<br><br>    public String getAddress() {<br>        return address;<br>    }<br><br>    public void setAddress(String address) {<br>        this.address = address;<br>    }<br>}</pre><pre>package com.example.microservices.entity;<br><br>import com.example.microservices.constant.Aggregate;<br>import jakarta.persistence.Column;<br>import jakarta.persistence.Entity;<br>import jakarta.persistence.EntityListeners;<br>import jakarta.persistence.EnumType;<br>import jakarta.persistence.Enumerated;<br>import jakarta.persistence.GeneratedValue;<br>import jakarta.persistence.GenerationType;<br>import jakarta.persistence.Id;<br>import org.springframework.data.annotation.CreatedDate;<br>import org.springframework.data.annotation.LastModifiedDate;<br>import org.springframework.data.jpa.domain.support.AuditingEntityListener;<br><br>import java.time.LocalDateTime;<br><br>@Entity<br>@EntityListeners(AuditingEntityListener.class)<br>public class Outbox {<br><br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    @Column(name = &quot;id&quot;, nullable = false)<br>    private Long id;<br><br>    @Enumerated(EnumType.STRING)<br>    @Column(name = &quot;aggregate&quot;)<br>    private Aggregate aggregate;<br><br><br>    @Column(name = &quot;message&quot;, length = 500)<br>    private String message;<br><br>    @Column(name = &quot;is_delivered&quot;, nullable = false)<br>    private Boolean isDelivered = false;<br><br>    @CreatedDate<br>    @Column(name = &quot;created_date&quot;)<br>    private LocalDateTime createdDate;<br><br>    @LastModifiedDate<br>    @Column(name = &quot;last_modified_date&quot;)<br>    private LocalDateTime lastModifiedDate;<br><br><br>    public Outbox() {<br>    }<br><br>    public Outbox(Aggregate aggregate, String message, Boolean isDelivered) {<br>        this.aggregate = aggregate;<br>        this.message = message;<br>        this.isDelivered = isDelivered;<br>    }<br><br>    public Boolean getIsDelivered() {<br>        return isDelivered;<br>    }<br><br>    public void setIsDelivered(Boolean isDelivered) {<br>        this.isDelivered = isDelivered;<br>    }<br><br>    public LocalDateTime getLastModifiedDate() {<br>        return lastModifiedDate;<br>    }<br><br>    public void setLastModifiedDate(LocalDateTime lastModifiedDate) {<br>        this.lastModifiedDate = lastModifiedDate;<br>    }<br><br>    public LocalDateTime getCreatedDate() {<br>        return createdDate;<br>    }<br><br>    public void setCreatedDate(LocalDateTime createdDate) {<br>        this.createdDate = createdDate;<br>    }<br><br>    public String getMessage() {<br>        return message;<br>    }<br><br>    public void setMessage(String message) {<br>        this.message = message;<br>    }<br><br>    public Long getId() {<br>        return id;<br>    }<br><br>    public void setId(Long id) {<br>        this.id = id;<br>    }<br><br>    public Aggregate getAggregate() {<br>        return aggregate;<br>    }<br><br>    public void setAggregate(Aggregate aggregate) {<br>        this.aggregate = aggregate;<br>    }<br>}</pre><pre>package com.example.microservices.repository;<br><br>import com.example.microservices.entity.User;<br>import org.springframework.data.jpa.repository.JpaRepository;<br>import org.springframework.stereotype.Repository;<br><br>@Repository<br>public interface UserRepository extends JpaRepository&lt;User, Long&gt; {<br><br>}</pre><pre>package com.example.microservices.repository;<br><br>import com.example.microservices.entity.Outbox;<br>import org.springframework.data.jpa.repository.JpaRepository;<br>import org.springframework.stereotype.Repository;<br><br>import java.util.List;<br><br>@Repository<br>public interface OutboxRepository extends JpaRepository&lt;Outbox, Long&gt; {<br><br>}</pre><p>Next, create a rest controller and a request DTO for creating users:</p><pre>package com.example.microservices.controller;<br><br>import com.example.microservices.dto.UserRequestDto;<br>import com.example.microservices.entity.User;<br>import com.example.microservices.service.UserService;<br>import jakarta.validation.Valid;<br>import org.springframework.web.bind.annotation.PostMapping;<br>import org.springframework.web.bind.annotation.RequestBody;<br>import org.springframework.web.bind.annotation.RequestMapping;<br>import org.springframework.web.bind.annotation.RestController;<br><br>@RestController<br>@RequestMapping(&quot;/api/v1/users&quot;)<br>public class UserController {<br><br>    private UserService userService;<br><br>    public UserController(UserService userService) {<br>        this.userService = userService;<br>    }<br><br>    @PostMapping<br>    public User createUser(@RequestBody @Valid UserRequestDto userRequestDto) {<br>        return userService.createUser(userRequestDto);<br>    }<br><br>}</pre><pre>package com.example.microservices.dto;<br><br>import com.example.microservices.entity.User;<br>import jakarta.validation.constraints.Email;<br>import jakarta.validation.constraints.NotNull;<br><br>import java.time.LocalDate;<br><br>public class UserRequestDto {<br><br>    @NotNull<br>    private String firstName;<br>    private String lastName;<br>    private String address;<br>    @NotNull<br>    private LocalDate dob;<br>    @Email<br>    private String email;<br><br><br>    public String getFirstName() {<br>        return firstName;<br>    }<br><br>    public void setFirstName(String firstName) {<br>        this.firstName = firstName;<br>    }<br><br>    public String getLastName() {<br>        return lastName;<br>    }<br><br>    public void setLastName(String lastName) {<br>        this.lastName = lastName;<br>    }<br><br>    public String getAddress() {<br>        return address;<br>    }<br><br>    public void setAddress(String address) {<br>        this.address = address;<br>    }<br><br>    public LocalDate getDob() {<br>        return dob;<br>    }<br><br>    public void setDob(LocalDate dob) {<br>        this.dob = dob;<br>    }<br><br>    public String getEmail() {<br>        return email;<br>    }<br><br>    public void setEmail(String email) {<br>        this.email = email;<br>    }<br>}</pre><p>Finally create a service class to handle user creation logic along with associated mapper classes and an enum for the aggregate:</p><pre>package com.example.microservices.constant;<br><br>public enum Aggregate {<br>    USER<br>}</pre><pre>package com.example.microservices.mapper;<br><br>import com.example.microservices.constant.Aggregate;<br>import com.example.microservices.entity.Outbox;<br>import com.example.microservices.entity.User;<br>import com.fasterxml.jackson.core.JsonProcessingException;<br>import com.fasterxml.jackson.databind.ObjectMapper;<br>import org.springframework.stereotype.Component;<br><br>@Component<br>public class UserMapper {<br><br>    private final ObjectMapper objectMapper;<br><br>    public UserMapper(ObjectMapper objectMapper) {<br>        this.objectMapper = objectMapper;<br>    }<br><br>    public Outbox mapToOutBoxEntity(User user) throws JsonProcessingException {<br>        return new Outbox(<br>                Aggregate.USER,<br>                objectMapper.writeValueAsString(user),<br>                false<br>        );<br>    }<br>}</pre><pre>package com.example.microservices.mapper;<br><br>import com.example.microservices.dto.UserRequestDto;<br>import com.example.microservices.entity.User;<br>import org.springframework.stereotype.Component;<br><br>@Component<br>public class UserRequestDtoMapper {<br><br>    public User mapToUserEntity(UserRequestDto userRequestDto) {<br>        return new User(<br>                userRequestDto.getFirstName(),<br>                userRequestDto.getLastName(),<br>                userRequestDto.getDob(),<br>                userRequestDto.getAddress(),<br>                userRequestDto.getEmail()<br>        );<br>    }<br><br>}</pre><pre>package com.example.microservices.service;<br><br>import com.example.microservices.dto.UserRequestDto;<br>import com.example.microservices.entity.Outbox;<br>import com.example.microservices.entity.User;<br>import com.example.microservices.mapper.UserMapper;<br>import com.example.microservices.mapper.UserRequestDtoMapper;<br>import com.example.microservices.repository.OutboxRepository;<br>import com.example.microservices.repository.UserRepository;<br>import org.springframework.stereotype.Service;<br>import org.springframework.transaction.annotation.Transactional;<br><br>@Service<br>public class UserService {<br><br>    private final UserRepository userRepository;<br>    private final OutboxRepository outboxRepository;<br>    private final UserRequestDtoMapper userRequestDtoMapper;<br>    private final UserMapper userMapper;<br><br><br>    public UserService(UserRepository userRepository, OutboxRepository outboxRepository,<br>                       UserRequestDtoMapper userRequestDtoMapper, UserMapper userMapper) {<br>        this.userRepository = userRepository;<br>        this.outboxRepository = outboxRepository;<br>        this.userRequestDtoMapper = userRequestDtoMapper;<br>        this.userMapper = userMapper;<br>    }<br><br>    @Transactional<br>    public User createUser(UserRequestDto userRequestDto) {<br>        try {<br>            User user = userRequestDtoMapper.mapToUserEntity(userRequestDto);<br><br>            user = userRepository.save(user);<br><br>            Outbox outbox = userMapper.mapToOutBoxEntity(user);<br><br>            outboxRepository.save(outbox); // This time saving message in a table instead of directly publishing<br><br>            return user;<br><br>        } catch (Exception e) {<br>            throw new RuntimeException(e);<br>        }<br>    }<br><br>}</pre><p>As can be seen in the <strong>createUser</strong> method we are now storing message in the outbox table instead of directly publishing message as before. This way if transaction fails the entire operation is rolled back and no message will be published, which will ensure consistency in our system.</p><p>Our first part is completed, but the question arises how will we actually publish the messages. Here comes the <strong>Message Relay Service (MRS) </strong>as already described above.</p><h3>Message Relay Service (MRS)</h3><p>There are multiple ways to implement <strong>MRS</strong>. Few of them are:</p><ul><li>Create a job that will run periodically and poll the outbox table for undelivered messages and deliver them in batches.</li><li>Use CDC (change data capture) tools like <a href="https://debezium.io/">Debezium</a> to automatically publish messages whenever data is inserted in the outbox table.</li></ul><p>While both of these techniques are perfectly fine, but for this demo we will focus on the first one. We’ll create a job, but before that we have to add a query method in our outbox repository which we created previously to find the top 10 undelivered messages:</p><pre>package com.example.microservices.repository;<br><br>import com.example.microservices.entity.Outbox;<br>import org.springframework.data.jpa.repository.JpaRepository;<br>import org.springframework.stereotype.Repository;<br><br>import java.util.List;<br><br>@Repository<br>public interface OutboxRepository extends JpaRepository&lt;Outbox, Long&gt; {<br><br>    List&lt;Outbox&gt; findTop10ByIsDelivered(boolean status);<br><br>}</pre><p>Now we can go ahead and create our job:</p><pre>package com.example.microservices.task;<br><br>import com.example.microservices.entity.Outbox;<br>import com.example.microservices.entity.User;<br>import com.example.microservices.repository.OutboxRepository;<br>import com.fasterxml.jackson.core.JsonProcessingException;<br>import com.fasterxml.jackson.databind.ObjectMapper;<br>import org.springframework.beans.factory.annotation.Value;<br>import org.springframework.kafka.core.KafkaTemplate;<br>import org.springframework.scheduling.annotation.Scheduled;<br>import org.springframework.stereotype.Component;<br>import org.springframework.transaction.annotation.Transactional;<br><br>import java.util.List;<br><br>@Component<br>public class OutboxProcessorTask {<br><br>    private final OutboxRepository outboxRepository;<br>    private final KafkaTemplate&lt;String, Object&gt; kafkaTemplate;<br>    private final String topic;<br>    private final ObjectMapper objectMapper;<br><br>    public OutboxProcessorTask(OutboxRepository outboxRepository,<br>                               KafkaTemplate&lt;String, Object&gt; kafkaTemplate, @Value(&quot;${kafka.topic.user}&quot;) String topic, ObjectMapper objectMapper) {<br>        this.outboxRepository = outboxRepository;<br>        this.kafkaTemplate = kafkaTemplate;<br>        this.topic = topic;<br>        this.objectMapper = objectMapper;<br>    }<br><br>    @Scheduled(fixedRate = 5000)<br>    @Transactional<br>    public void process() throws JsonProcessingException {<br>        System.out.println(&quot;Task executed&quot;);<br><br>        List&lt;Outbox&gt; outboxes = outboxRepository.findTop10ByIsDelivered(false);<br><br>        for (Outbox outbox : outboxes) {<br>            kafkaTemplate.send(topic,  objectMapper.readValue(outbox.getMessage(), User.class));<br>            outbox.setIsDelivered(true);<br>        }<br>    }<br><br>}</pre><p>The above job does the following:</p><ol><li><strong>Scheduled</strong> annotation marks the method to be executed as a job, <strong>fixedRate </strong>parameter sets this job to be run after every five seconds.</li><li>Fetches top 10 messages from the outbox table whose is_delivered column is false.</li><li>Iterate through the messages, in each iteration publish message and set is_delivered field as true.</li></ol><p>Notice that this job is transactional as well, so if something goes wrong during processing all the messages in that batch will be retried again in next execution.</p><h3>TESTING</h3><p>It’s time for testing. First of all we have to start our Kafka server and consumer. Run the following commands inside your directory where you have downloaded Kafka:</p><pre># Start the ZooKeeper service<br>$ bin/zookeeper-server-start.sh config/zookeeper.properties<br><br># Start the Kafka broker service<br>$ bin/kafka-server-start.sh config/server.properties</pre><p>Once your Kafka server is up, run the following commands in a separate tab to start a Kafka consumer, which will subscribe to user-events topic:</p><pre># Create user-events topic<br>$ bin/kafka-topics.sh --create --topic user-events --bootstrap-server <br>  localhost:9092<br><br># Start a consumer<br>$ bin/kafka-console-consumer.sh --topic user-events --from-beginning <br>  --bootstrap-server localhost:9092</pre><p>Now that our Kafka server is up and ready to consume events, we can start our Spring Boot application by running the following command inside our project directory:</p><pre>mvn spring-boot:run</pre><p>This will start our application, after application is started we can observe in the logs that <strong>“Task executed”</strong> is printed after every five seconds, this log confirms that our job is running properly.</p><p>Now let’s call our API using curl:</p><pre>curl --location &#39;localhost:8085/api/v1/users&#39; \<br>--header &#39;Content-Type: application/json&#39; \<br>--data-raw &#39;{<br>    &quot;firstName&quot;: &quot;Haris&quot;,<br>    &quot;lastName&quot;: &quot;Masood&quot;,<br>    &quot;dob&quot;: &quot;2024-05-27&quot;,<br>    &quot;address&quot;: &quot;test address&quot;,<br>    &quot;email&quot;: &quot;haris@test.com&quot; <br>}&#39;</pre><p>To verify that our message was successfully published and consumed, head back to the consumer tab and you can see the message printed there.</p><p>Let’s also inquire our database:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dGCDRNcosTykPDSfpWZoig.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4_NpRfTaKjA_XJgmznqO3g.png" /></figure><p>As, we can see from the above screenshots both user and outbox tables are populated. Also, is_delivered column of the outbox table is set to 1 which further confirms that our message is published correctly.</p><h3>Things To Consider</h3><p>While implementing the <strong>Transactional Outbox Pattern</strong> we need to consider a few things. In message delivery there are three semantics:</p><ul><li>At least once delivery</li><li>At most once delivery</li><li>Best effort delivery</li></ul><p>This pattern provides <strong>at least once delivery</strong> semantic meaning that messages can be delivered more than once in some cases, because the <strong>MRS</strong> will retry all the messages in next execution if there was some exception during the processing of a batch. Due to this reason we have to make our consumers idempotent.</p><p>The other thing to consider is that, this pattern deals with producing end of our system. We should make our consuming end reliable by using techniques like retry and dead letter queues.</p><p>The third thing is that this pattern if implemented correctly can remove the need for implementing and managing complex distributed transactions. However, there can be cases where eventual consistency is absolutely not desirable, in those cases Saga pattern should be considered.</p><p>And lastly at some point the outbox table will grow too large, so we must write some sort of a cleaning job that will delete delivered messages periodically.</p><h3>Conclusion</h3><p>As we’ve seen that the <strong>Transactional Outbox Pattern</strong> is a very powerful pattern to mitigate data inconsistency issues in microservices architecture. It’s also not very difficult to understand and implement. The source code for this article can be found on <a href="https://github.com/SyedHaris/transactional-outbox-demo">Github</a>.</p><h3>References</h3><ul><li><a href="https://codeopinion.com/outbox-pattern-reliably-save-state-publish-events/">https://codeopinion.com/outbox-pattern-reliably-save-state-publish-events/</a></li><li><a href="https://thorben-janssen.com/outbox-pattern-hibernate/">https://thorben-janssen.com/outbox-pattern-hibernate/</a></li><li><a href="https://spring.io/blog/2023/10/24/a-use-case-for-transactions-adapting-to-transactional-outbox-pattern">https://spring.io/blog/2023/10/24/a-use-case-for-transactions-adapting-to-transactional-outbox-pattern</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=952d96f8b534" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>