0
0
Ruby on Railsframework~15 mins

Page and action caching in Ruby on Rails - Deep Dive

Choose your learning style9 modes available
Overview - Page and action caching
What is it?
Page and action caching are techniques in Rails to store the output of web pages or controller actions so they can be quickly served without running the full code again. Page caching saves the entire HTML page as a static file, while action caching stores the result of a controller action but still runs filters like authentication. Both help speed up websites by reducing repeated work.
Why it matters
Without caching, every visitor causes the server to run all the code to build pages, which can slow down the site and use more resources. Caching makes websites faster and more responsive, improving user experience and saving server costs. It is especially important for pages that don’t change often but get many visitors.
Where it fits
Before learning caching, you should understand how Rails controllers and views work to generate pages dynamically. After mastering caching, you can explore more advanced caching like fragment caching, Russian doll caching, and HTTP caching to optimize performance further.
Mental Model
Core Idea
Caching saves the final output of web pages or actions so the server can reuse it instantly instead of rebuilding it every time.
Think of it like...
Imagine a bakery that bakes fresh bread for every customer order. Page caching is like baking a large batch in advance and just handing out ready bread, so customers don’t wait. Action caching is like preparing the dough and proofing it, but still checking the customer’s preferences before baking.
┌───────────────┐       ┌───────────────┐
│ User Request  │──────▶│ Check Cache   │
└───────────────┘       └───────────────┘
         │                      │
         │ Cache Hit            │ Cache Miss
         ▼                      ▼
┌───────────────┐       ┌───────────────┐
│ Serve Cached  │       │ Run Controller│
│ Page/Action   │       │ and Render    │
└───────────────┘       └───────────────┘
                                │
                                ▼
                      ┌───────────────┐
                      │ Store Output  │
                      │ in Cache      │
                      └───────────────┘
Build-Up - 7 Steps
1
FoundationWhat is caching in Rails
🤔
Concept: Caching means saving the result of work so it can be reused later without repeating the work.
In Rails, when a user visits a page, the server runs code to build the page. Caching saves the final page or action result so next time it can be sent immediately without running code again.
Result
Pages load faster because the server skips rebuilding the page.
Understanding caching as saving work output helps grasp why it speeds up websites.
2
FoundationDifference between page and action caching
🤔
Concept: Page caching saves the full HTML page as a static file, while action caching saves the controller action result but still runs filters.
Page caching stores the entire page on disk and serves it directly, bypassing Rails completely. Action caching stores the action output but still runs before and after filters like authentication.
Result
Page caching is faster but less flexible; action caching allows checks before serving cached content.
Knowing the difference helps choose the right caching method based on security and flexibility needs.
3
IntermediateHow to enable page caching in Rails
🤔
Concept: Page caching requires setting up a cache directory and telling Rails which pages to cache.
You add `caches_page :action_name` in your controller to cache that action’s page. Rails saves the HTML output in the public directory. When a request comes, the web server serves the static file directly.
Result
The cached page is served instantly without hitting Rails code.
Seeing how Rails saves static files clarifies why page caching is so fast.
4
IntermediateHow action caching works with filters
🤔Before reading on: do you think action caching skips all controller filters or still runs some? Commit to your answer.
Concept: Action caching stores the action output but still runs filters like authentication before serving cached content.
You add `caches_action :action_name` in your controller. When a request comes, Rails runs filters (like checking if user is logged in) before serving the cached output. This keeps security intact.
Result
Cached content is served only after filters pass, balancing speed and control.
Understanding that filters still run prevents security mistakes when using action caching.
5
IntermediateWhen to expire cached pages or actions
🤔Before reading on: do you think cached pages expire automatically or need manual clearing? Commit to your answer.
Concept: Cached pages and actions do not update automatically; you must expire them when data changes.
You use methods like `expire_page` or `expire_action` to delete cached files when content changes. This ensures users see fresh data.
Result
Cache stays accurate and does not serve outdated pages.
Knowing cache expiration is manual helps avoid stale content bugs.
6
AdvancedLimitations and risks of page caching
🤔Before reading on: do you think page caching works well with user-specific content? Commit to your answer.
Concept: Page caching cannot handle user-specific or dynamic content because it serves the same static file to everyone.
If your page shows different info per user (like login status), page caching will serve wrong content. Also, it bypasses Rails filters, so security checks are skipped.
Result
Page caching is best for public, static pages only.
Recognizing these limits prevents security and personalization errors.
7
ExpertModern alternatives and deprecation notes
🤔Before reading on: do you think Rails still recommends page and action caching in latest versions? Commit to your answer.
Concept: Rails has deprecated built-in page and action caching in favor of more flexible caching like fragment caching and HTTP caching.
Modern Rails apps use fragment caching to cache parts of pages and HTTP caching headers to let browsers cache content. Gems like 'actionpack-page_caching' provide legacy support but are not recommended for new apps.
Result
Developers use safer, more flexible caching methods that work well with dynamic content and security.
Knowing the evolution of caching in Rails guides learners to use current best practices.
Under the Hood
Page caching works by saving the full HTML output of a controller action as a static file in the public directory. When a request matches that page, the web server (like Nginx or Apache) serves the static file directly, bypassing Rails entirely. Action caching stores the rendered output in Rails cache stores but still runs controller filters before serving cached content. This means Rails processes the request partially to maintain security and logic before returning cached data.
Why designed this way?
Page caching was designed to maximize speed by letting the web server serve static files without Rails overhead. Action caching was created to keep security and filters active while still speeding up response times. Over time, these methods showed limits with dynamic content and security, leading Rails to favor fragment and HTTP caching for more flexible, maintainable performance improvements.
┌───────────────┐
│ User Request  │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Web Server    │
│ (Nginx/Apache)│
└──────┬────────┘
       │
       │ Cached Page Exists?
       ├─────Yes─────▶ Serve Static File
       │
       └─────No─────▶ Pass to Rails
                      │
                      ▼
             ┌─────────────────┐
             │ Rails Controller │
             │ Runs Filters     │
             │ Runs Action      │
             └────────┬────────┘
                      │
                      ▼
             ┌─────────────────┐
             │ Render Response │
             └─────────────────┘
                      │
                      ▼
             ┌─────────────────┐
             │ Store Cache     │
             └─────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does page caching run controller filters like authentication before serving cached pages? Commit yes or no.
Common Belief:Page caching runs all controller filters before serving cached pages, so it is secure for user-specific content.
Tap to reveal reality
Reality:Page caching bypasses Rails entirely and does not run any filters, so it cannot protect user-specific or sensitive content.
Why it matters:Using page caching on pages with private data can expose sensitive information to all users.
Quick: Do cached pages update automatically when underlying data changes? Commit yes or no.
Common Belief:Cached pages automatically update whenever the data they show changes.
Tap to reveal reality
Reality:Cached pages remain the same until manually expired or cleared; they do not update automatically.
Why it matters:Failing to expire caches leads to users seeing outdated or incorrect information.
Quick: Is action caching always faster than page caching? Commit yes or no.
Common Belief:Action caching is always faster than page caching because it still runs filters.
Tap to reveal reality
Reality:Page caching is faster because it serves static files without running Rails code; action caching runs filters and Rails code before serving cached output.
Why it matters:Choosing action caching expecting maximum speed can lead to slower responses than page caching.
Quick: Does Rails still include page and action caching by default in the latest versions? Commit yes or no.
Common Belief:Rails includes page and action caching as built-in features in all recent versions.
Tap to reveal reality
Reality:Rails removed built-in page and action caching in newer versions, recommending fragment and HTTP caching instead.
Why it matters:Trying to use deprecated caching methods can cause compatibility issues and maintenance problems.
Expert Zone
1
Page caching requires careful cache expiration strategies to avoid serving stale or incorrect content, especially in multi-user environments.
2
Action caching can be combined with conditional GET requests to improve performance while maintaining security filters.
3
Using external cache stores (like Memcached or Redis) for action caching improves scalability but requires understanding cache invalidation complexities.
When NOT to use
Avoid page caching for any pages that show user-specific or dynamic content. Instead, use fragment caching or HTTP caching headers. Action caching is less common now; prefer fragment caching for partial page caching and rely on HTTP caching for client-side performance.
Production Patterns
In production, developers often use fragment caching to cache reusable parts of views and HTTP caching headers to let browsers cache static assets. Page caching is used only for fully static public pages served by the web server. Action caching is rare but may be used in legacy apps requiring filter checks with cached content.
Connections
HTTP Caching
Builds-on
Understanding server-side caching like page and action caching helps grasp how HTTP caching headers control browser caching, completing the performance picture.
Fragment Caching
Alternative approach
Knowing the limits of page and action caching clarifies why fragment caching is preferred for caching parts of pages with dynamic content.
Operating System File Caching
Similar pattern
Just like OS caches frequently accessed files in memory to speed up access, page caching stores static pages to serve them faster, showing a shared principle of caching across computing.
Common Pitfalls
#1Caching pages that show user-specific data without expiration.
Wrong approach:class ProductsController < ApplicationController caches_page :show def show @product = Product.find(params[:id]) @user = current_user end end
Correct approach:class ProductsController < ApplicationController before_action :authenticate_user! def show @product = Product.find(params[:id]) end # Use fragment caching for parts that can be cached safely end
Root cause:Misunderstanding that page caching serves the same static file to all users, ignoring user-specific content.
#2Not expiring cached pages after data changes.
Wrong approach:class ArticlesController < ApplicationController caches_page :index def update @article = Article.find(params[:id]) @article.update(article_params) redirect_to articles_path end end
Correct approach:class ArticlesController < ApplicationController caches_page :index def update @article = Article.find(params[:id]) @article.update(article_params) expire_page action: :index redirect_to articles_path end end
Root cause:Forgetting that cached pages do not update automatically and require manual expiration.
#3Using deprecated page caching methods in modern Rails apps.
Wrong approach:class HomeController < ApplicationController caches_page :index end
Correct approach:class HomeController < ApplicationController # Use fragment caching or HTTP caching instead end
Root cause:Not knowing that Rails removed built-in page caching support in recent versions.
Key Takeaways
Page and action caching save server work by storing full pages or action results to serve faster.
Page caching serves static files directly, skipping Rails filters, so it is only safe for public, static pages.
Action caching runs filters before serving cached content, balancing speed and security but is less common now.
Cached content does not update automatically; you must expire caches manually to avoid stale data.
Modern Rails favors fragment and HTTP caching over page and action caching for flexible, secure performance.