Skip to content

Inconsistent ActiveRecord Query Caching Between Master and Replica Connections #17

@aks

Description

@aks

There is a problem with Rails caching and fresh_connection.

  1. fresh_connection maintains a replica connection pool, consisting of multiple connection instances, separate from the master connection pool, also one or more connection instances.

  2. The ActiveRecord Query Cache module inserts itself as class methods into the AbstractAdapter, but maintains the actual query cache as an instance variable on the connection instance.

These two facts means that the query caches for the "master" connections are separate from that of the "replica" connections. So, the AR::Base methods of update, insert, and delete methods, which clear the cache attached to a given connection, do not clear the corresponding cache in the other pool connections.

So, when a read-only query for an AR model object is diverted to a replica connection, it's cache is likely (guaranteed) to be out-of-date from a recent update to that same object on the master connection.

For example:

c = Contact.find_by login: 'my-email@sample.com'  # replica connection
c.update address: new_address   # update the address
c.save   # master connection query cache cleared, replica connection unchanged!
...
c = Contact.find_by login: 'my-email@sample.com' # out-of-date replica connection cache retrieved
c.address       # -- almost guaranteed to be incorrect!! 

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions