Unsure if I am understanding pessimistic locking functionality correctly

Hi @MattN42

Yes, the saga row in a database is locked before the handler executed. In most cases (happy cases) this guarantees that only one thread in one process on one host can execute the message handling logic. This is not a 100% guarantee, though. It might happen that this thread that started executed saga logic happens to be on a machine that loses connectivity with the DB server. Once the DB detects lost connection it may release the locks held on that row and another thread on another machine can start executing.

This is why the NHibernate persister uses optimistic concurrency (in addition to pessimistic) to make sure that only one of these threads can successfully persist the state change.

You can think about is like this: optimistic concurrency is for correctness, pessimistic concurrency is for performance. It is important because when a saga row is locked for processing one message, other messages for that saga wait on that lock. They are not sent for retries but wait in-memory for their turn. This makes allows the NHibernate saga persister to handle 100s of messages per second in a single saga instance. If pessimistic concurrency was not in place, all these other messages would fail and would be subject to retries, grinding the system to halt.

2 Likes