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
IoT is at the core or many Digital Transformation initiatives with the goal of re-inventing a company's business model. We all agree that collecting relevant IoT data will result in massive amounts of data needing to be stored. However, with the rapid development of IoT devices and ongoing business model transformation, we are not able to predict the volume and growth of IoT data. And with the lack of IoT history, traditional methods of IT and infrastructure planning based on the past do not app...
Internet-of-Things discussions can end up either going down the consumer gadget rabbit hole or focused on the sort of data logging that industrial manufacturers have been doing forever. However, in fact, companies today are already using IoT data both to optimize their operational technology and to improve the experience of customer interactions in novel ways. In his session at @ThingsExpo, Gordon Haff, Red Hat Technology Evangelist, shared examples from a wide range of industries – including en...
To get the most out of their data, successful companies are not focusing on queries and data lakes, they are actively integrating analytics into their operations with a data-first application development approach. Real-time adjustments to improve revenues, reduce costs, or mitigate risk rely on applications that minimize latency on a variety of data sources. Jack Norris reviews best practices to show how companies develop, deploy, and dynamically update these applications and how this data-first...
Intelligent Automation is now one of the key business imperatives for CIOs and CISOs impacting all areas of business today. In his session at 21st Cloud Expo, Brian Boeggeman, VP Alliances & Partnerships at Ayehu, will talk about how business value is created and delivered through intelligent automation to today’s enterprises. The open ecosystem platform approach toward Intelligent Automation that Ayehu delivers to the market is core to enabling the creation of the self-driving enterprise.
"We're a cybersecurity firm that specializes in engineering security solutions both at the software and hardware level. Security cannot be an after-the-fact afterthought, which is what it's become," stated Richard Blech, Chief Executive Officer at Secure Channels, in this SYS-CON.tv interview at @ThingsExpo, held November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA.
Consumers increasingly expect their electronic "things" to be connected to smart phones, tablets and the Internet. When that thing happens to be a medical device, the risks and benefits of connectivity must be carefully weighed. Once the decision is made that connecting the device is beneficial, medical device manufacturers must design their products to maintain patient safety and prevent compromised personal health information in the face of cybersecurity threats. In his session at @ThingsExpo...
SYS-CON Events announced today that Grape Up 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. Grape Up is a software company specializing in cloud native application development and professional services related to Cloud Foundry PaaS. With five expert teams that operate in various sectors of the market across the U.S. and Europe, Grape Up works with a variety of customers from emergi...
Detecting internal user threats in the Big Data eco-system is challenging and cumbersome. Many organizations monitor internal usage of the Big Data eco-system using a set of alerts. This is not a scalable process given the increase in the number of alerts with the accelerating growth in data volume and user base. Organizations are increasingly leveraging machine learning to monitor only those data elements that are sensitive and critical, autonomously establish monitoring policies, and to detect...
SYS-CON Events announced today that Massive Networks 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. Massive Networks mission is simple. To help your business operate seamlessly with fast, reliable, and secure internet and network solutions. Improve your customer's experience with outstanding connections to your cloud.
Everything run by electricity will eventually be connected to the Internet. Get ahead of the Internet of Things revolution and join Akvelon expert and IoT industry leader, Sergey Grebnov, in his session at @ThingsExpo, for an educational dive into the world of managing your home, workplace and all the devices they contain with the power of machine-based AI and intelligent Bot services for a completely streamlined experience.
Because IoT devices are deployed in mission-critical environments more than ever before, it’s increasingly imperative they be truly smart. IoT sensors simply stockpiling data isn’t useful. IoT must be artificially and naturally intelligent in order to provide more value In his session at @ThingsExpo, John Crupi, Vice President and Engineering System Architect at Greenwave Systems, will discuss how IoT artificial intelligence (AI) can be carried out via edge analytics and machine learning techn...
With tough new regulations coming to Europe on data privacy in May 2018, Calligo will explain why in reality the effect is global and transforms how you consider critical data. EU GDPR fundamentally rewrites the rules for cloud, Big Data and IoT. In his session at 21st Cloud Expo, Adam Ryan, Vice President and General Manager EMEA at Calligo, will examine the regulations and provide insight on how it affects technology, challenges the established rules and will usher in new levels of diligence a...
In the enterprise today, connected IoT devices are everywhere – both inside and outside corporate environments. The need to identify, manage, control and secure a quickly growing web of connections and outside devices is making the already challenging task of security even more important, and onerous. In his session at @ThingsExpo, Rich Boyer, CISO and Chief Architect for Security at NTT i3, discussed new ways of thinking and the approaches needed to address the emerging challenges of security i...
SYS-CON Events announced today that Datera, that offers a radically new data management architecture, has been named "Exhibitor" of 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. Datera is transforming the traditional datacenter model through modern cloud simplicity. The technology industry is at another major inflection point. The rise of mobile, the Internet of Things, data storage and Big...
An increasing number of companies are creating products that combine data with analytical capabilities. Running interactive queries on Big Data requires complex architectures to store and query data effectively, typically involving data streams, an choosing efficient file format/database and multiple independent systems that are tied together through custom-engineered pipelines. In his session at @BigDataExpo at @ThingsExpo, Tomer Levi, a senior software engineer at Intel’s Advanced Analytics ...
SYS-CON Events announced today that Datera 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. Datera offers a radically new approach to data management, where innovative software makes data infrastructure invisible, elastic and able to perform at the highest level. It eliminates hardware lock-in and gives IT organizations the choice to source x86 server nodes, with business model option...
With 10 simultaneous tracks, keynotes, general sessions and targeted breakout classes, Cloud Expo and @ThingsExpo are two of the most important technology events of the year. Since its launch over eight years ago, Cloud Expo and @ThingsExpo have presented a rock star faculty as well as showcased hundreds of sponsors and exhibitors! In this blog post, I provide 7 tips on how, as part of our world-class faculty, you can deliver one of the most popular sessions at our events. But before reading the...
SYS-CON Events announced today that CA Technologies has been named "Platinum Sponsor" of SYS-CON's 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. CA Technologies helps customers succeed in a future where every business - from apparel to energy - is being rewritten by software. From planning to development to management to security, CA creates software that fuels transformation for companies in the applic...
In his session at 21st Cloud Expo, Carl J. Levine, Senior Technical Evangelist for NS1, will objectively discuss how DNS is used to solve Digital Transformation challenges in large SaaS applications, CDNs, AdTech platforms, and other demanding use cases. Carl J. Levine is the Senior Technical Evangelist for NS1. A veteran of the Internet Infrastructure space, he has over a decade of experience with startups, networking protocols and Internet infrastructure, combined with the unique ability to it...
SYS-CON Events announced today that GrapeUp, the leading provider of rapid product development at the speed of business, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Grape Up is a software company, specialized in cloud native application development and professional services related to Cloud Foundry PaaS. With five expert teams that operate in various sectors of the market acr...