caching - How do I cache external api response per user in rails? -


i have rails 4.1 application wherein have bookings section. in section have multiple sub sections such hotels, vacation rentals etc.

in each of these sections fetching data relevant apis user can sort , filter.

i cache response per user once have got data, filtering & sorting quick cached data , time not wasted on making trip other site.

however 1 issue users can without logging in.

i have setup memcached store caches data fine first user but, when second user comes data first user gets overwritten.

how can cache data per user(logggd/unlogged) ? (i willing change cache store provided don't have spend work)

rails supports per user "caches" out of box. called session. default rails uses cookies storage can swap storage use memcached or redis bypass ~4kb size limit imposed on cookies browser.

to use rails memcached storage backend use dalli gem:

# gemfile gem 'dalli'  # config/environments/production.rb config.cache_store = :dalli_store 

this let store pretty by:

session[:foo] = bar 

and session values can fetched long user retains cookie containing session id.

an alternate approach if want keep performance benefits of using cookiestore sessions use session id part of key used cache request in memcached give each user individual cache.

you can session id calling session.id in controller.

require 'dalli' options = { :namespace => "app_v1", :compress => true } dc = dalli::client.new('localhost:11211', options) cache_key = 'foo-' + session.id  @data = dc.fetch(cache_key)   do_some_api_call end 

you can view fragments , regular rails low level cache well. note models not session aware.

see:


Comments