I was asked this question in a recent interview which I could not answer so was hoping to get some answers. I might not have got the question correctly maybe because I lack the understanding of the concepts like - database cluster, multiple JVM synchronization, load balancing. I will try my best to recall the question. Here it is:
1. There are two instances of an application (let's say A1 & A2) running on two different JVMs and two instances of a similar database (D1 & D2).
2. The application instances will try to insert a record in a DB instance. What I mean is that A1 will insert in D1 and A2 will insert in D2.
3. A server load balancer decides which of these app instances will run at a given time and this load balancer is a typical server load balancer not under our control.
Problem : At a given time only on of these application instances should be allowed to do a insert in a corresponding DB. This is required to avoid both the app instances to run at the same time and insert the same record in its database instances. How to achieve this ?
Wrong answers I gave:
1. Synchronize the code (Not possible because the app are running on different JVMs)
2. Try some database lock (Not possible because these two database instances can't talk to each other)
Hope I have explained the problem clearly. I have also attached an ugly looking architecture image. Thanks in advance for all replies.
Who receives the input; load balancer or both the instance?
If load balancer receives it and delegates to one of the instance, then is not the whole question becomes pointless?
If both the instance receives the input, then what the load balancer is for?
In a typical clustered environment the request actually comes to the load balancer and gets delegated to a specific instance bearing minimal load at current time. Therefore if a load balancer is in place, then the whole given scenario becomes useless, since the situation can never occur!!
If there is no load balancer and request comes to both the instances, only then the question makes sense. In such a scenario, the best choice would be to use JMX communication between two instances to sync up and decide who will handle the persistence operation.