# Should we cancel read-only transactions before (or instead of) committing them?

**URL:** <https://forums.foundationdb.org/t/should-we-cancel-read-only-transactions-before-or-instead-of-committing-them/4670>\
**Category:** Using FoundationDB\
**Created:** [October 23, 2024, 12:11pm UTC](https://forums.foundationdb.org/t/should-we-cancel-read-only-transactions-before-or-instead-of-committing-them/4670 "2024-10-23T12:11:07Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![miridius](https://sea1.discourse-cdn.com/foundationdb/user_avatar/forums.foundationdb.org/miridius/32/1500_2.png) [@miridius](https://forums.foundationdb.org/u/miridius)\
**Post date:** [October 23, 2024, 12:11pm UTC](https://forums.foundationdb.org/t/should-we-cancel-read-only-transactions-before-or-instead-of-committing-them/4670/1 "2024-10-23T12:11:07Z")

</div>

In our app we make heavy use of transactions which we know are read-only. The [JavaDocs](https://apple.github.io/foundationdb/javadoc/com/apple/foundationdb/Transaction.html) advise using commit even on read-only transactions to make sure they don’t get GC’ed too early, since that would cancel in-progress reads.

Would it be reasonable or even beneficial to call `cancel` instead of `commit` once we’re done with the transaction?

---

<div class="post-metadata">

**Author:** ![alloc](https://sea1.discourse-cdn.com/foundationdb/user_avatar/forums.foundationdb.org/alloc/32/9_2.png) [@alloc](https://forums.foundationdb.org/u/alloc)\
**Post date:** [October 29, 2024, 4:57pm UTC](https://forums.foundationdb.org/t/should-we-cancel-read-only-transactions-before-or-instead-of-committing-them/4670/2 "2024-10-29T16:57:53Z")

</div>

I’m not as familiar as perhaps I should be on all of the details regarding garbage collection of outstanding reads when there are outstanding reads. I think the more general advice would be to avoid calling `commit()` (or `cancel()`) until all reads you care about have completed. The advice in the Javadoc comment also seems to predict a world where we rely on the JVM garbage collector to free up native resources, which was once the case (using a `finalizer`–gasp!) but now the advice is for callers to manually call `close()` on their transactions. If you have any reads that have not completed and you call `close()` on the transaction, then those outstanding reads will generally not succeed. But they also shouldn’t be cleaned up until `close()` is called.

One most notable thing I will add about `commit()` call on a read-only transaction is that it is executed entirely locally. If the transaction determines that it is read-only (that is, it has no mutations or write conflict ranges), then the `commit()` call will return “success” immediately without having to make a network call, so the cost of calling `commit()` is fairly low.
