Preventing insertion of duplicate records on concurrent hits on RESTApi Stateless Application

Viewed 278

I have spent days in finding a solution to a problem. I have a stateless spring boot application. take example of Payment (table) application using Spring boot. Following are the preventions and functionalities that I have to keep in mind while creating RESTApi.

Preventions

  • I am not allowed to manage requests in Queue.
  • Making unique keys is not an option.

Required Functionality

  • USE RDBMS like MySQL

  • App must allow simultaneous insertion. (There may be hundreds of users inserting at the same time)

  • There must not be duplicate records (No duplicate record for same user)

  • High Performance (Low response time)

I have tried other ways like multithreading or using synchronized method but this takes a lot time to process the request. I cannot keep user in waiting.

Basically I want to achieve a general solution for preventing concurrent requests at programming level.

Your Response will be highly appreciated.

1 Answers

You can use @Version annotation. You can use optimistic lock to avoid same row transaction commit to database.

@Entity
public class Entity {
   @Version
   long version;
}

But you have to add version column to database tables. If you can not use queue and you can not modify database tables. You have only one chance. Simply use redis or hazelcast distributed lock but it will cost you a lot.

Related