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

(Tuis.) #1
Architectural Scalability | 175

ActiveRecord, or if you are tuning performance and ActiveRecord’s advanced fea-
tures are too heavy.


One such example,SqlBypass, is provided for you. It provides the necessary subset of
ActiveRecord to handle sessions. Activate it by manually changing the session class:


CGI::Session::ActiveRecordStore.session_class =
CGI::Session::ActiveRecordStore::SqlBypass

Of course, you can easily write your own classes that talk to the session database, and
plug them in by this mechanism. The RDoc on CGI::Session::ActiveRecordStore
explains the exact requirements.


MemCacheStore


The MemCacheStore is a grown-up version of the DRbStore (a very simple central-
ized in-memory session store). It uses Danga Interactive’smemcacheddaemon to store
sessions. (memcachedis discussed in detail in Chapter 4.) For scalability purposes,
memcached is usually preferable to the DRbStore, except in very small settings.


To activate the MemCacheStore, you must install the ruby-memcache gem (gem
install ruby-memcache). Then, start up a memcached server on an appropriate
machine. This command will tell memcached to use up to 512 MB of RAM, listen on
port 11211 (the default memcached port), and daemonize itself:


memcached -d -m 512 -p 11211

Then, set the Rails session store to the MemCacheStore:


config.action_controller.session_store = :mem_cache_store

Any options can be set with thesessionmethod. For example, you can specify multi-
ple memcached servers to balance requests:


class ApplicationController
session :cache => MemCache.new('10.0.0.13:11211', '10.0.0.14:11211')
end

By default, memcached acts as a cache. It takes a-m argument that specifies
how much memory to use, and if it hits that limit it will start deleting the oldest
records to make room for new ones. This is usually undesirable for session storage. If
you use memcached for session storage, ensure that you have enough memory in the
cache to hold all current sessions.


Depending on your tolerance for lost sessions, you may want to consider running
memcached with the-Moption. This option tells memcached to return an error when
the memory is full, rather than deleting items from the cache.


Remember that memcached stores data in memory only.* If you stop the
memcached process, you instantly lose all sessions. There is a new session store,



  • Storing persistent data in memcached is actually a slight abuse of what it was designed for, but it’s really darn
    fast so no one complains.

Free download pdf