0

I have two Frontends consuming JSON from two different Backends using the JSON Web Token. These backends act on the same database.

In the db for example I have the Driver, Customer and Trip tables. The customer or the driver can cancel a trip only if it has not been canceled beforehand by one of them. Some transactions are recorded during a cancellation.

How to prevent having a double execution in this case when simultaneously, the customer and the driver launch a request for trip cancellation?

Am usin' Spring Boot (RESTful) and Spring JPA.

Any help will be greatly appreciated.

Edit: Assuming these backends are A & B, Customer is requesting cancellation from the backend A, and Driver from B.

dm_tr
  • 4,265
  • 1
  • 6
  • 30
  • Database concurrency control, uding transactions, should ensure this. – Raedwald Dec 20 '20 at 17:20
  • Does this answer your question? [What is a database transaction?](https://stackoverflow.com/questions/974596/what-is-a-database-transaction) – Raedwald Dec 20 '20 at 17:22
  • No, it does not! – dm_tr Dec 20 '20 at 17:26
  • what you need to do is to edit your question to explain *why* that does not answer your question. Demonstrate that you do, in fact, know what a *transaction* is, and explain why database transactions are not the answer to your problem. – Raedwald Dec 20 '20 at 17:44
  • 1
    Indeed, database transaction does not solve it. Database transaction is supposed to work under a unique thread with a request from a specific user. But in my case, requests are submitted from two different users on two different services (These services work separately) – dm_tr Dec 20 '20 at 17:56

1 Answers1

1

Use optimistic locking. Your code would look as follows:

@Entity
public class Trip {

    @Version
    @NotNull
    private Long version;

    ...

}

It works as follows. Each change modifies the version. Suppose two users (or two services) loaded the same version of the trip. Now they both try to cancel it, i.e. they both try to modify it. Besides changes they both send the version. The JPA checks if the version in the update statement is the same as in the database. So the first request wins and will be executed. During the execution the version will be incremented.

Now the 2nd request arrives and wants also to cancel the trip. The JPA will see that the version attribute in the update statement is older (less) than the version value in database. Thus the 2nd request will not be executed and an OptimisticLockException will be thrown.

You can catch this exception and inform the user that the data were change in the meanwhile and suggest user to reload the data. The user reloads the data and sees that the trip has already been cancelled.

mentallurg
  • 4,967
  • 5
  • 28
  • 36