Dushyant Singh
Dushyant Singh

Reputation: 405

How to make sure that DB transaction happens only one time?

How to make sure that a particular DB transaction happens only once. I am making a payment request from my mobile (more than once), but the backend should only execute only one. Once the request is executed its status is marked as COMPLETED. But in case of multiple request, before one request gets completed another starts is execution so the payment is done twice before the status to be marked COMPLETED. How to solve this problem? I am using Java as backend. How can synchronize() help to solve this problem?

Upvotes: 2

Views: 423

Answers (2)

Shirin Safaeian
Shirin Safaeian

Reputation: 960

This is a known issue as Double Post.

Preventing parallel access to the method with Synchronize and lock will not help you, as the requests will be proceed in series.

Using client Side methods may help, but is not enough, as many things may happen at client side.

If you want to prevent it at Server Side (this is the correct way to do), you can add a hidden field to the client form (some unique hash string) and send it to the server with every request. In the Server side component, you can check if a request with that hash is already received, and if so, return an error code to client.

You can also persist the hash with your Data and make it a unique field, so the first request that reach your database will be persisted, and the others will see unique field errors.

Upvotes: 0

Kims
Kims

Reputation: 425

You can try to add a lock around the code. That way only one thread can enter at any given time. If you make one request, then the other request have to wait until the request is finish.

Upvotes: 1

Related Questions