Consider the following two Mongoid domain models, Widget and Gadget.

widget.rb
1
2
3
4
5
6
class Widget
  include Mongoid::Document

  field :name
  has_many :gadgets
end
gadget.rb
1
2
3
4
5
6
7
8
class Gadget
  include Mongoid::Document

  field :name
  field :extras

  belongs_to :widget
end

And an API call that returns a collection of widgets.

1
2
3
get 'widgets' do
  Widget.all.as_json
end

Given many widgets, the API makes a subquery to fetch the corresponding gadgets for each widget.

Introducing mongoid-cached-json. This library mitigates several frequent problems with such code.

  • Adds a declarative way of specifying a subset of fields to be returned part of as_json.
  • Avoids a large amount of subqueries by caching document JSONs participating in the parent-child relationship.
  • Provides a consistent strategy for restricting child documents' fields from being returned via the parent JSON.

Using Mongoid::CachedJson we were able to cut our JSON API average response time by about a factor of 10. Find it on Github.

Categories: api, caching, mongoid


Comments