What is Memcache in Ruby on Rails?

svg viewer

Background

Caching is a process of storing data generated by new requests in order to serve similar requests in the future more swiftly. When developing a web-application, caching serves as an essential tool to manage requests and speed-up the response time. Through caching, web sites running on a single server with a single database can sustain a load of thousands of concurrent users.

Memcache is one of the different caching systems. Memcache caches objects in RAM to speed up access to the content. Content is directly fetched from memory instead of from an external data source. One of the most popular memcache servers is provided by Danga, an open-source software.

Memcache in Ruby on Rails

Ruby on Rails uses the Danga server coupled with Dallia high-performance Ruby client to serve memcache to provide centralized caching for the application. This memcache cache store can offer a single, shared server to provide high performance, high availability, and fast access to content. To initialize, the developer needs to input all the addresses of memcache servers; otherwise, it will be initialized on the localhost using the default port, which is not ideal for sites that generate a massive amount of requests.

Installing memcache on Ruby on Rails

This installation setup is for Ubuntu.

Step 1

Use the following command to install memcache:

sudo apt install memcached
svg viewer
svg viewer

Step 2 (optional)

If you already have rubygems installed on your system, skip this step. Otherwise, install rubygems using the follwing command:

sudo apt-get install rubygems

Step 3

Install Dalli using the following command:

sudo gem install dalli

After that, add the following: line in your gemfile:

gem 'dalli'

Finally, execute this command:

bundle install
svg viewer

Working with memcache

In order to open up a connection to memcache using Dalli, use the following dummy code:

require 'dalli'

options = { :username => 'username', :password => 'password' }
mc = Dalli::Client.new('hostname:port', options)

To make this snippet of code compatible with your code, change :username, :password, and hostname:port according to the variables in your bucket.

Reading and writing data on memcache is straight forward. Observe the following code snippet:

mc.set('drink', 'tea')
value = mc.get('drink')
puts value

The above code will store key-value pairs in memcache. The key is drink and it has a value of tea. Use the .set() method to place a key-value pair on memcache and use the .get() method to retrieve a value using a key from the memcache.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved