title: How to cache a rails api controller
body: <p>I'm seeing some performance issues in my application and was wondering whether my cache was working properly or if I misunderstood / misconfigured anything. I'm using <a href="https://github.com/fast-jsonapi/fast_jsonapi" rel="nofollow noreferrer">fast-jsonapi</a> for serialization which comes with a built-in caching option.</p>
  
  <p>Let's say:</p>
  
  <pre class="lang-rb prettyprint-override"><code>class BooksController &lt; ApplicationController
  ...
    def index
      @books = Books.includes(:author, :publisher).with_attached_cover.all
      BookSerializer.new(@book, { include: [:author, :publisher]}).serializable_hash.to_json
    end
  ...
  end
  </code></pre>
  
  <p>and</p>
  
  <pre class="lang-rb prettyprint-override"><code>class BookSerializer
    include FastJsonapi::ObjectSerializer
    cache_options store: Rails.cache, namespace: 'fast-jsonapi', expires_in: 24.hours
  
    belongs_to :author
    belongs_to :publisher
  
    attributes :all_the_book_attributes_im_too_lazy_to_list
  end
  </code></pre>
  
  <p>also let's assume I have around 5000 books of 2000 authors and 100 publishers, so I would expect caching to make a big difference in performance. </p>
  
  <p>However, in fact I'm seeing my database hit the same way with or without caching enabled and really slow response times. Further, when checking my cache it only seems to be caching each individual book but not the serialized hash as a whole. </p>
  
  <p>Now I'm wondering whether I completely missed the purpose of caching in a serializer or if I need to add some additional layer in my controller? If yes, is there a solution to do so in a DRY way? Would it conflict with the cache of the serializer? What is the purpose of a cache in a serializer then anyway?</p>
  
  <p>I know that there are multiple ways/layers of cache I can use. I'm just not sure which ones to combine and whether to prevent any conflicts between those layers.</p>