NHibernate second-level cache invalidation behavior with async sessions in version 5.3+
25.5K reputation · 15 Oct 2022, 04:30 UTC
The goal is to decide whether NHibernate’s second‑level cache can be trusted to provide repeatable reads when multiple async ISession instances share the same session factory in a repeatable development or test environment.
In NHibernate 5.3+ the async ISession uses FlushMode.Auto, which does not automatically clear the second‑level cache when another thread commits a change. Consequently, a subsequent async read may return a stale cached value unless the cache provider is transactional (e.g., RedisCache) or the application manually evicts the affected entries. This leaves developers with an unresolved choice: rely on the cache and risk stale data, implement manual eviction after each async write, or adopt a transactional cache provider. Should the second‑level cache be considered stale‑safe for async reads? Is manual eviction required after every async write to guarantee consistency? Does switching to a transactional cache provider eliminate the need for application‑level cache management?