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

Prevent spurious SQL query execution via ActiveSupport::Cache events #188

Merged

Conversation

leoarnold
Copy link
Contributor

When using a simple Rails view template like

<% cache User.all do %>
  some content here
<% end %>

we noticed that a spurious SQL query

SELECT "users".* FROM "users"

was executed both on cache miss and on cache hit.

Since the very point of fragment caching is to prevent this kind of queries, we investigated and found out that they were caused by meta_request.

Rather than just stating the cache key used, events from ActiveSupport::Cache provide all original objects which contributed to the calculation of the cache key. This included User.all from the template.

When meta_request checks whether this object is encodable to JSON

User.all.as_json(methods: [:duration])

unintentionally triggers the spurious SQL query.

We fix this by sanitizing the event payload and replacing the inputs of the cache key calculation with their final result.

When using a simple Rails view template like

```erb
<% cache User.all do %>
  some content here
<% end %>
```

we noticed that a spurious SQL query

```sql
SELECT "users".* FROM "users"
```

was executed both on cache miss and on cache hit.

Since the very point of [fragment caching][1] is to prevent this kind
of queries, we investigated and found out that they were caused by
`meta_request`.

Rather than just stating the cache key used, events from `ActiveSupport::Cache`
provide all original objects which contributed to the calculation of
the cache key. This included `User.all` from the template.

When `meta_request` checks whether this object is encodable to JSON

```ruby
User.all.as_json(methods: [:duration])
```

unintentionally triggers the spurious SQL query.

We fix this by sanitizing the event payload and replacing the inputs
of the cache key calculation with their final result.

[1]: https://guides.rubyonrails.org/caching_with_rails.html#fragment-caching
@dejan
Copy link
Owner

dejan commented Apr 12, 2024

Thanks!

@dejan dejan merged commit 0b2eaf7 into dejan:master Apr 12, 2024
@leoarnold leoarnold deleted the leoarnold/meta_request/fragment-caching branch April 16, 2024 09:00
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

Successfully merging this pull request may close these issues.

None yet

2 participants