Fragment caching for expensive JSON serialization

14565
0

Serializing complex ActiveRecord objects to JSON can consume significant CPU time, especially when rendering collections with nested associations. Fragment caching stores rendered JSON fragments in Redis keyed by a cache key that includes the record's cache_key_with_version, which automatically invalidates when the record updates. This approach delivers massive performance gains for read-heavy endpoints—instead of serializing hundreds of records on every request, I serve cached fragments and only serialize changed records. The cache key must include all dependencies, so I use touch: true on associations to invalidate parent caches when children change. For endpoints with heavy traffic, this can reduce response times from seconds to milliseconds.