VKR
VKR

Reputation: 339

MongoDB multiple threads updating same document at same time

I am using Atlas MongoDB as database (created cluster with MongoDB version 4.2) and using spring Data MongoDB jar(2.2.0 RELEASE) to do insert and update Operations. I have single collection with thousands of documents in it. I had a custom unique key (Id) for each document.

Update scenario - first I need to read the document from DB and do some logic with new incoming document against db document and do final update. (read -> logic -> update). It is working fine with single thread but its not working with multiple threads updating same document. Each time I receive second message/thread for same document, I want previous thread to be committed before I read it.

Is there any Transaction atomicity consistency levels (acid properties) in MongoDB or SpringData MongoDB to handle this.

Steps:

  Application receives inputMessage.
  Read the existing document from DB
  execute the logic.
  Update DB.

2021-01-12 20:08:00.952 [org.springframework.kafka.KafkaListenerEndpointContainer#1-96-C-1] INFO inputMessage is {"flight":{"event":"ETA","fltNum":"1111"})

2021-01-12 20:08:00.961 [org.springframework.kafka.KafkaListenerEndpointContainer#1-96-C-1] INFO flight Data updated.

2021-01-12 20:08:00.979 [org.springframework.kafka.KafkaListenerEndpointContainer#1-137-C-1] INFO inputMessage is {"flight":{"event":"FLTPLN","fltNum":"1111"}}

2021-01-12 20:08:00.986 [org.springframework.kafka.KafkaListenerEndpointContainer#1-42-C-1] INFO inputMessage is {"flight":{"event":"LOADPLAN","fltNum":"1111"}}

2021-01-12 20:08:00.993 [org.springframework.kafka.KafkaListenerEndpointContainer#1-137-C-1] INFO - flight Data updated

2021-01-12 20:08:00.996 [org.springframework.kafka.KafkaListenerEndpointContainer#1-42-C-1] INFO - flight Data updated

Here thread 1-96-C-1 completed successfully. Problem with thread 1-137-C-1 and 1-42-C-1.

Here 1-137-C-1 came first and it will read the existing document from DB(that is committed by 1-96-C-1). Before 1-137-C-1 update the db, we received 1-42-C-1. Now 1-42-C-1 also read the data committed by 1-96-C-1 because 1-137-C-1 not yet updated.

I don't want this, even we received 1-42-C-1, it need to be wait until 1-137-C-1 completes the update.

Upvotes: 0

Views: 2780

Answers (1)

Gibbs
Gibbs

Reputation: 22956

Here, the problem is second request may be executed first before the first request due to network delay or so many other reasons which would make the requests out of order.

Its not related to mongodb. Mongodb provides document level concurrency.

You need to have a way to identify the previous thread requests status in the application.

Upvotes: 1

Related Questions