Welcome!

Ruby-On-Rails Authors: Liz McMillan, Pat Romanski, Elizabeth White, Hovhannes Avoyan, Yeshim Deniz

Related Topics: Java IoT, Industrial IoT, Microservices Expo, Open Source Cloud, Machine Learning , Ruby-On-Rails

Java IoT: Blog Post

Russian Doll Caching

Rails 4 is out featuring Russian Doll caching (aka Cache Digests)

Rails 4 is out featuring Russian Doll caching (aka Cache Digests). In this article, I apply Russian Doll caching to one of my poorer performing
Rails 3 pages using the cache_digests gem.

ActionView templates are great. They are easy to code, manage and extend but the one thing they are not is fast...at least not out of the box.

In this article, I'll be using TraceView to time ActionView performance. If you haven't used TraceView before, checkout my previous article Instrumenting Ruby on Rails with TraceView.

ActionView Is Slow; Pitfalls Ahead
ActionView puts forth a great development pattern of views and partials that is easy to understand, implement and maintain but that comes at a cost: The rendering process is complex and slow.

russian-doll-caching-render

The screenshot above shows the timings for the Users#show URL on Gameface. The page in question is fairly straight forward containing four components: a topbar, sidebar, user details and a listing of game characters.

With no caching at all, the ActionView layer averages roughly ~365ms for this URL. This represents over 80% of average request processing time and dwarfs all of the other layers combined.

russian-doll-caching-trace

In terms of performance, ActionView is a weapon of mass destruction and is the low-hanging fruit for improvement.

Russian Doll Caching
Russian Doll caching is a type of nested fragment caching that auto expires fragments when object timestamps change.

You still make the same calls as previous fragment caching schemes in Rails:

1 2 3 4 5 6 7 8 9 10 11 - cache @user do (user view data) - cache [ 'details', @user ] do (user details view data) - cache [ 'characters', @user ] do - @user.characters.each do |character| - cache character do (character view data)

With Russian Doll caching (AKA cache digests) unique cache keys are formed using an md5 stamp based on the timestamp of the object being cached:

1 2 views/users/3-20130530135425/7a1bb8bb15b02ee7aa69cec1d5f6f630 views/details/users/3-20130530135425/6f28ec6d31e7e3b73a575777d59e63ca

The advantage of this is that when objects are updated and outer fragments are automatically invalidated, nested fragments can be re-used. (russian dolls)

A key requirement to this is that children objects should update the timestamps of their parent object by using ActiveRecord touch option. This will allow for automatic cache invalidation and avoid serving stale content.

1 2 3 class Character < ActiveRecord::Base belongs_to :user, touch: true end

For a more thorough explanation of Russian Doll Caching, see Ryan Bates cache digests episode or this explanation from Remarkable Labs.

Cache Friendly Page Layouts
When caching, it's best to avoid caching logged-in content since the same caches will get served to all users regardless of any logged in status.

For effective (and less problematic) fragment caching, designing the page well to separate out logged in content is critical.

Below is the layout for the Gameface profile view before re-design. Logged in specific content and links are sprinkled throughout the page making it hard to divide it up into cache-able fragments.

russian-doll-caching-uncachable

Properly caching this page as-is would be complicated and inefficient since we would have to tip-toe around logged-in content.

The Redesign
To fix this, I re-organized the page to group the logged-in specific content into one specific area. With logged-in content out of the way, we are then free to cache the rest of the page in well-defined fragments.

russian-doll-caching-cachable

The Results
With the page re-design and Russian Doll fragment caching applied to the large majority of the page, we now average a much better ~120ms for ActionView on that URL. A reduction of 265ms or 67% in average processing time.

russian-doll-caching-result

On top of the performance improvement, we also get automatic cache invalidation as object timestamps are updated. This greatly simplifies the whole system by not requiring cache sweepers or other tricks to invalidate stale caches.

Summary
Russian Doll caching is a small but significant improvement over prior caching in Rails. When used effectively, it can greatly reduce server side ActionView processing and automatically expire stale fragments.

We took a previously un-cached URL with a poor page layout that was averaging ~365ms of processing in ActionView and reduced that number to ~120ms for a 67% performance improvement.

Additional Considerations
When using fragment caching, note which backing cache store you are using. The default cache store in Rails is the filesystem but you can get even greater performance by backing your cache store with memcache or redis instead.

See the redis-rails gem as an example.

Next Up
Coming soon, I'll revisit this page under Rails 4 to further explore performance improvements over Rails 3.

Cheatsheet
Separate out logged-in content from agnostic content for best cache coverage. Page design affects caching efficiency.

When possible, always call cache with the object being cached. Cache keys and their eventual invalidation will be keyed off of the timestamp on the object being cached.

1 2 3 4 5 - cache @user do (user view data) - cache [ 'details', @user ] do (user details view data)

To cache an index of objects, you have to revert to manually passing in theexpires_in option since there is no single object timestamp to key off of.

1 2 - cache [ 'user list', expires_in: 30.minutes ] do (user list view data)

Update belongs_to model relationships with touch: true so that parent fragment caches can be invalidated when children are updated.

Collect timing data before and after to quantify and validate changes.

More Stories By Peter Giacomo Lombardo

A Rubyist and Linux addict for over a decade, Peter mainly develops in Ruby and JavaScript (as well as PHP and Perl). He is the creator of numerous software tools and applications, most recently Password Pusher, a Ruby on Rails application to communicate passwords over the web and Gameface, a social networking platform for gamers using Rails 3. When he's not creating his own applications, he helps develop and maintain the infrastructure at OurStage and manages the Ruby community for AppNeta.

@ThingsExpo Stories
As businesses evolve, they need technology that is simple to help them succeed today and flexible enough to help them build for tomorrow. Chrome is fit for the workplace of the future — providing a secure, consistent user experience across a range of devices that can be used anywhere. In her session at 21st Cloud Expo, Vidya Nagarajan, a Senior Product Manager at Google, will take a look at various options as to how ChromeOS can be leveraged to interact with people on the devices, and formats th...
SYS-CON Events announced today that Yuasa System will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Yuasa System is introducing a multi-purpose endurance testing system for flexible displays, OLED devices, flexible substrates, flat cables, and films in smartphones, wearables, automobiles, and healthcare.
Organizations do not need a Big Data strategy; they need a business strategy that incorporates Big Data. Most organizations lack a road map for using Big Data to optimize key business processes, deliver a differentiated customer experience, or uncover new business opportunities. They do not understand what’s possible with respect to integrating Big Data into the business model.
Enterprises have taken advantage of IoT to achieve important revenue and cost advantages. What is less apparent is how incumbent enterprises operating at scale have, following success with IoT, built analytic, operations management and software development capabilities – ranging from autonomous vehicles to manageable robotics installations. They have embraced these capabilities as if they were Silicon Valley startups. As a result, many firms employ new business models that place enormous impor...
SYS-CON Events announced today that Taica will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Taica manufacturers Alpha-GEL brand silicone components and materials, which maintain outstanding performance over a wide temperature range -40C to +200C. For more information, visit http://www.taica.co.jp/english/.
SYS-CON Events announced today that Dasher Technologies will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Dasher Technologies, Inc. ® is a premier IT solution provider that delivers expert technical resources along with trusted account executives to architect and deliver complete IT solutions and services to help our clients execute their goals, plans and objectives. Since 1999, we'v...
Recently, REAN Cloud built a digital concierge for a North Carolina hospital that had observed that most patient call button questions were repetitive. In addition, the paper-based process used to measure patient health metrics was laborious, not in real-time and sometimes error-prone. In their session at 21st Cloud Expo, Sean Finnerty, Executive Director, Practice Lead, Health Care & Life Science at REAN Cloud, and Dr. S.P.T. Krishnan, Principal Architect at REAN Cloud, will discuss how they b...
SYS-CON Events announced today that MIRAI Inc. will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. MIRAI Inc. are IT consultants from the public sector whose mission is to solve social issues by technology and innovation and to create a meaningful future for people.
SYS-CON Events announced today that TidalScale, a leading provider of systems and services, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. TidalScale has been involved in shaping the computing landscape. They've designed, developed and deployed some of the most important and successful systems and services in the history of the computing industry - internet, Ethernet, operating s...
SYS-CON Events announced today that IBM has been named “Diamond Sponsor” of SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California.
Join IBM November 1 at 21st Cloud Expo at the Santa Clara Convention Center in Santa Clara, CA, and learn how IBM Watson can bring cognitive services and AI to intelligent, unmanned systems. Cognitive analysis impacts today’s systems with unparalleled ability that were previously available only to manned, back-end operations. Thanks to cloud processing, IBM Watson can bring cognitive services and AI to intelligent, unmanned systems. Imagine a robot vacuum that becomes your personal assistant tha...
SYS-CON Events announced today that TidalScale will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. TidalScale is the leading provider of Software-Defined Servers that bring flexibility to modern data centers by right-sizing servers on the fly to fit any data set or workload. TidalScale’s award-winning inverse hypervisor technology combines multiple commodity servers (including their ass...
As hybrid cloud becomes the de-facto standard mode of operation for most enterprises, new challenges arise on how to efficiently and economically share data across environments. In his session at 21st Cloud Expo, Dr. Allon Cohen, VP of Product at Elastifile, will explore new techniques and best practices that help enterprise IT benefit from the advantages of hybrid cloud environments by enabling data availability for both legacy enterprise and cloud-native mission critical applications. By rev...
Infoblox delivers Actionable Network Intelligence to enterprise, government, and service provider customers around the world. They are the industry leader in DNS, DHCP, and IP address management, the category known as DDI. We empower thousands of organizations to control and secure their networks from the core-enabling them to increase efficiency and visibility, improve customer service, and meet compliance requirements.
With major technology companies and startups seriously embracing Cloud strategies, now is the perfect time to attend 21st Cloud Expo October 31 - November 2, 2017, at the Santa Clara Convention Center, CA, and June 12-14, 2018, at the Javits Center in New York City, NY, and learn what is going on, contribute to the discussions, and ensure that your enterprise is on the right path to Digital Transformation.
Amazon is pursuing new markets and disrupting industries at an incredible pace. Almost every industry seems to be in its crosshairs. Companies and industries that once thought they were safe are now worried about being “Amazoned.”. The new watch word should be “Be afraid. Be very afraid.” In his session 21st Cloud Expo, Chris Kocher, a co-founder of Grey Heron, will address questions such as: What new areas is Amazon disrupting? How are they doing this? Where are they likely to go? What are th...
SYS-CON Events announced today that N3N will exhibit at SYS-CON's @ThingsExpo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. N3N’s solutions increase the effectiveness of operations and control centers, increase the value of IoT investments, and facilitate real-time operational decision making. N3N enables operations teams with a four dimensional digital “big board” that consolidates real-time live video feeds alongside IoT sensor data a...
In his Opening Keynote at 21st Cloud Expo, John Considine, General Manager of IBM Cloud Infrastructure, will lead you through the exciting evolution of the cloud. He'll look at this major disruption from the perspective of technology, business models, and what this means for enterprises of all sizes. John Considine is General Manager of Cloud Infrastructure Services at IBM. In that role he is responsible for leading IBM’s public cloud infrastructure including strategy, development, and offering ...
Digital transformation is changing the face of business. The IDC predicts that enterprises will commit to a massive new scale of digital transformation, to stake out leadership positions in the "digital transformation economy." Accordingly, attendees at the upcoming Cloud Expo | @ThingsExpo at the Santa Clara Convention Center in Santa Clara, CA, Oct 31-Nov 2, will find fresh new content in a new track called Enterprise Cloud & Digital Transformation.
Most technology leaders, contemporary and from the hardware era, are reshaping their businesses to do software. They hope to capture value from emerging technologies such as IoT, SDN, and AI. Ultimately, irrespective of the vertical, it is about deriving value from independent software applications participating in an ecosystem as one comprehensive solution. In his session at @ThingsExpo, Kausik Sridhar, founder and CTO of Pulzze Systems, will discuss how given the magnitude of today's applicati...