Recently, I encountered an online bug. Accessing a specific interface will cause occasional exceptions. After checking the log, it is found that an error is reported during the operation of mongodb. The error information is as follows:
error message: Command failed with error 251 (NoSuchTransaction): 'Given transaction number 115 does not match any in-progress transactions. The active transaction number is 114' on server xx.xx.xx.xx:xxxx. The full response is {"errorLabels": ["TransientTransactionError"], "ok": 0.0, "errmsg": "Given transaction number 115 does not match any in-progress transactions. The active transaction number is 114", "code": 251, "codeName": "NoSuchTransaction"}
Through searching and troubleshooting, the problem was located to be due to processing MongoDB operations where two requests in the same transaction are sent to the DB at the same time, with the probability of generating the following scenario.
1. request 1 and request 2 are sent to Mongo at the same time and start execution
2. Request 1 is still executing and request 2 has completed
3. Since request 1 is not yet completed, the transaction has not really started at DB level, so request 2 cannot end normally (that is why the error states that transaction id 115 cannot be found, because the transaction is not yet registered in DB), resulting in transaction rollback and throwing exceptions
4. request 1 execution is complete, but the transaction has been rolled back, the operation is invalid
Reviewing the code, we found that the reason why two requests are sent to DB at the same time is that the zipWith() method is used for data merging. The feature of this method is that it will request two data to be merged to the database at the same time, which will trigger the aforementioned problem when operating Mongo.
The solution is very simple, just use the zipWhen() method instead. zipWhen will block and wait for the first data requested to arrive before requesting the second data, which perfectly circumvents this problem.