3. Agenda
1.Why do we need to do this?
2.What is a Conditional GET request?
3.How do we do it?
4.How does it work?
4. The Problem:
We build apps quickly. Apps consume a lot
of data (JSON in this example). Often, a lot of
the data doesn’t change very often, but it’s
easier to just fetch all the things all the time,
because cache invalidation is hard.
5. Then, one day we need to
scale. And one of the
strategies we decide to use
is to cache some responses.
6. Problems
• Page and action cacheing have been
moved from Rails 4 into gems
• Fragment cacheing requires memory,
and often things like Redis or
memcached.
• Buggy
8. Conditional requests
Part of the HTTP standard that
allows browsers to ask servers if
anything has changed, or not.
Request headers can be used by both the client and the server
to determine if any new data is present. If no new data is
present, the server can return a 304. If new data is available, it
can render the new data.
9. Time-Based
class PokemonsController < ApplicationController
def index
pokemons = Pokemon.all.includes(:pokemon_type)
expires_in 1.minute
render json: pokemons
end
end
10. Etags
class PokemonsController < ApplicationController
def index
pokemons = Pokemon.all.includes(:pokemon_type)
if stale? etag: pokemons
render json: pokemons
end
end
end
11.
12. Last Modified
class PokemonsController < ApplicationController
def index
pokemons = Pokemon.all.includes(:pokemon_type)
if stale? last_modified: pokemons.maximum(:updated_at)
render json: pokemons
end
end
end
13. Last Modified + Etag
class PokemonsController < ApplicationController
def index
pokemons = Pokemon.all.includes(:pokemon_type)
if stale? pokemons
render json: pokemons
end
end
end