Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Identity cache inside transaction #533

Open
DharmaPriya-V opened this issue Mar 30, 2023 · 1 comment
Open

Identity cache inside transaction #533

DharmaPriya-V opened this issue Mar 30, 2023 · 1 comment

Comments

@DharmaPriya-V
Copy link

DharmaPriya-V commented Mar 30, 2023

Identity cache gem does not fetch from the cache store when fetch method was used inside any transaction, this is to avoid inconsistency in cache data as the changes will be commited at the end of transaction.

But they might be use case where we only load and not do updation. One way to solve this having a transaction which is not joinable to parent transaction. Usually identity_cache has should_use_cache? method which decides to fetch from cache or DB. should_use_cache? checks for any open transaction which is joinable, if so it make the DB call instead of fetching from cache. But if we wrap the fetch call inside transaction which is new and not joinable , then we can make use of advantage of the cache store and can save query at many places.

In the below code, fetch is happening inside the new transaction which is not joinable, should_use_cache? method returns true in this case and fetch from cache store.

Sample code:

ApplicationRecord.transaction do
    ApplicationRecord.transaction(requires_new: true, joinable: false) do
        ApplicationRecord.fetch(1)
     end
end
@dylanahsmith
Copy link
Contributor

should_use_cache? checks for any open transaction which is joinable

This is only meant to exclude the transaction that wraps tests to rollback the test state.

Ideally, Active Record would have the concept of a read-only transaction. This could be used to inform the database of the transaction being read-only (e.g. mysql supports START TRANSACTION READ ONLY), but it could also be enforced as part of the Active Record abstraction (i.e. when raw queries aren't being used).

If you want to workaround this limitation, then you could introduce a read-only scope at the application level, then override should_use_cache? to use the cache in this case. Although, don't do this when reading from a database replica, since that can result in a cache invalidation being replaced with stale data.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants