问题
Having carefully reading the online documentation, I still have a lot of questions about two phase commit in MongoDB.
In the section Recovering from Failure Scenarios, why are there only two classes of failures? In my thinking failure can happen in any of these step so there should be a lot more than two classes here. For example what if, (in Apply Transaction to Both Accounts section), after updating account A the database server failed. That means account A lost some money without anything happen on account B. And we would have inconsistent transaction?
回答1:
In my thinking failure can happen in any of these step so there should be a lot more than two classes here.
The key thing to remember here is that the documentation is NOT a definitive guide on two phase commits, in reality two phase commits are technically impossible in MongoDB and I would strongly recommend you get an ACID tech if you want to perform them.
You must remember that there are certain fail scenarios that you cannot counter due to this not being within the server itself. Instead the whole existance of two phase commits is only client side as such it is quite flimsy compared to say TTL monitoring.
after updating account A the database server failed. That means account A lost some money without anything happen on account B. And we would have inconsistent transaction?
In support of Philipps answer the original transaction between account A and B would still be pending in this case, it will only be moved to finished/completed once account B has been updated.
This means the transaction cannot be marked as completed until it is.
Instead of using MongoDB for a scenario that it isn't really designed for I would recommend using something that is designed for your scenario.
回答2:
When the application or database suddenly crashes between applying the transaction to A and applying the transaction to B, there will still be a transaction with state:"pending"
in the global transaction collection. Your recovery script which you run after a crash should notice this, check the two accounts, and see that there is a pending transaction in one, but not the other account. It now knows everything it needs to know to either rollback the transaction or try to complete it.
Yes, writing a recovery script which is that smart isn't easy. But transactions in a database system not designed for them is always hard. Sometimes you can work around requiring transactions in MongoDB by designing your documents in a way that fields which need to be updated together are always in the same document, but there isn't always a sane way to do this. When your use-case absolutely needs transactions, protect your sanity and use a relational database.
回答3:
the online document may not be perfect. in fact you do need to rollback operations on A and B
来源:https://stackoverflow.com/questions/19851659/two-phase-commit-in-mongodb