Our program is using Queue. Multiple consumers are processing messages.
Consumers do the following:
- Receive on or off status message from the Queue.
- Get the latest status from the repository.
- Compare the state of the repository and the state received from the message.
- If the on/off status is different, update the data. (At this time, other related data are also updated.)
Assuming that this process is handled by multiple consumers, the following problems are expected.
- Producer sends messages 1: on, 2: off, and 3: on.
- Consumer A receives message #1 and stores message #1 in the storage because there is no latest data.
- Consumer A receives message #2.
- At this time, consumer B receives message #3 at the same time.
- Consumers A and B read the latest data from the storage at the same time (message 1).
- Consumer B finishes processing first. Don't update the repository as the on/off state is unchanged.(1: on, 3: on)
- Then consumer A finishes the processing. The on/off state has changed, so it processes and saves the work. (1: on, 2: off)
In normal case, the latest data remaining in the DB should be on.
(This is because the message was sent in the order of on -> off -> on.)
However, according to the above scenario, off remains the latest data.
Is there any good way to solve this problem? For reference, the queue we use is using AWS Amazon MQ and the storage is using AWS dynamoDB. And using Spring Boot.