To use transactions in MongoDB you have to start a session first. When you have many transactions, you can either reuse an existing session or create a new one for every transaction.
I benchmarked (code below) both options and the result is puzzling me. Using a fresh session for each transaction seems to be significantly faster (~2 to 3 times faster) than using a single session for all transactions.
Can anybody explain why this is so? How do sessions work under the hood? What are their implications? What costs do the imply (and when and why)? I really want to understand and I am grateful for any pointers.
Stopwatch sw = new Stopwatch();
coll1.InsertOne(new BsonDocument { { "Seq", 0 } });
sw.Start();
for (int i = 1; i <= reps; i++) {
using (var session = client.StartSession()) {
session.StartTransaction();
coll1.InsertOne(session: session, document: new BsonDocument { { "Seq", i } });
session.CommitTransaction();
}
}
sw.Stop();
Console.WriteLine($"{reps / sw.Elapsed.TotalSeconds} OP/s with fresh sessions.");
coll2.InsertOne(new BsonDocument { { "Seq", 0 } });
sw.Restart();
using (var session = client.StartSession()) {
for (int i = 1; i <= reps; i++) {
session.StartTransaction();
coll2.InsertOne(session: session, document: new BsonDocument { { "Seq", i } });
session.CommitTransaction();
}
}
sw.Stop();
Console.WriteLine($"{reps / sw.Elapsed.TotalSeconds} OP/s with common session.");
I also tried running the single session code first giving me the same result.
MongoDB's server sessions, or logical sessions, are the underlying framework used by client sessions to support Causal Consistency and retryable writes.
Developers should add application logic that can catch and retry a transaction that aborts due to temporary exceptions, such as an MVCC write conflict, a transient network failure or a primary replica election. With retryable writes, the MongoDB drivers will automatically retry the commit statement of the transaction.
MongoDB does lock a document that is being modified by a transaction. However, other sessions that attempt to modify that document do not block. Rather, their transaction is aborted, and they are required to retry the transaction.
From the documentation.
Isolation
Operations within a causally consistent session are not isolated from operations outside the session. If a concurrent write operation interleaves between the session’s write and read operations, the session’s read operation may return results that reflect a write operation that occurred after the session’s write operation.
It means that operations of different sessions could go in parallel without frequent blocking.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With