Advanced Rails - Building Industrial-Strength Web Apps in Record Time

(Tuis.) #1
Architectural Scalability | 179

In this example, we assume that the barcode for a particular piece of text never
changes, so we don’t have to worry about cache expiration. In the real world, we
would want to expire old entries so as not to fill up all available RAM or disk space.
If we are using memcached as a fragment cache store, we do not have to worry about
this; memcached keeps the cache to the size we ask it to by throwing away the old-
est entries when it fills up.


Fragment cache stores. Like the various session stores, there are several fragment cache
stores that can hold your cached data. The default is the memory store, which is the
simplest and requires no options. It stores the fragments in the server’s memory
space. Each Mongrel or FastCGI listener will have its own fragment cache.


The FileStore, as its name implies, stores fragments in a filesystem directory. When
configured, it takes one argument, the path to the cache directory:


config.action_controller.fragment_cache_store = :file_store,
"/var/rails/fragment_cache"

The DRbStore (fragment_cache_store = :drb_store) requires a running DRb server to
store the fragments. It takes a single configuration argument: the URI of the DRb server
(druby://drb_server_name:9192/). Finally, the MemCacheStore (:mem_cache_store) uses
a memcached server. Its argument is the hostname or I Paddress of the server run-
ning memcached.


It is technically possible to use the same memcached server for session storage and
caching, as session IDs and fragment cache names are not likely to collide (Mem-
CacheStore session keys begin withsession:). However, this is not recommended.
Sessions and fragment caching have fundamentally different needs, and it is not terri-
bly difficult to set up multiple memcached servers (use the-poption to specify a port
number). I recommend keeping separate concerns separated.


Cache stores have more flexibility than session stores when scaling upward. Though
a session must always be reliably available to all of the application servers, you don’t
lose anything from a fragment cache miss (except a small performance penalty as you
have to regenerate the content). Therefore, you could theoretically decide to give
each application server its own memory fragment cache. Although this is usually a
bad idea (it expands the total amount of memory required), it can make sense if the
information to be cached is partitioned along application server boundaries.


Fragment cache helper.The most typical use for fragment caching is in caching an
expensive-to-calculate part of a page that must be displayed often. In most cases,
there is other dynamic information on the page (even something as simple as a block
showing the current user’s login name), so the whole page cannot be cached with
either page caching or action caching.

Free download pdf