Here is the situation, I have 3 instances, one is a manager, for assigning job, and two is worker, doing to job. Let say the user need to withdraw something, and workflow is like follow:
Request sent
Manager assign job, depends on worker instance loading
worker do the work (reduce the num in db)
tell the manager instance job is finished!
All things work, but two instance may have two withdraw in same account, it may have some problems, to make a negative number…. So, it have some problems there. Well, you can say add an execute channel or queue or something that only execute one database’s write function….
But the problem is when I have more and more instance, only with one instance for writing, that may reduce the productivity, any recommends? Thanks.
How do you do it?
By carefully designing the operations to be atomic, and doing all of the relevant checks, accesses and updates as part of the atomic action.
Now you mention that you have a database as part of the implementation technology. Assuming that it is a transactional database, you should be mapping each of these atomic operations to a transaction. So, to build on your description:
withdrawal > 0.balance - withdrawal >= 0On the other hand, if there was no database involved, and you were simply updating in-memory objects, then you’d create an
Accountclass that had a synchronized method for doing a withdrawal that did steps 3.3 through 3.5 of the above, and have the worker call the method with the relevant parameters.