<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Swaathi Kakarla</title>
    <description>The latest articles on Forem by Swaathi Kakarla (@imswaathik).</description>
    <link>https://forem.com/imswaathik</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F304686%2Fc8de13f1-4ab7-41f5-811d-798b847e03a2.jpg</url>
      <title>Forem: Swaathi Kakarla</title>
      <link>https://forem.com/imswaathik</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/imswaathik"/>
    <language>en</language>
    <item>
      <title>Pattern Matching In Elixir</title>
      <dc:creator>Swaathi Kakarla</dc:creator>
      <pubDate>Mon, 24 Aug 2020 15:53:07 +0000</pubDate>
      <link>https://forem.com/imswaathik/pattern-matching-in-elixir-3n83</link>
      <guid>https://forem.com/imswaathik/pattern-matching-in-elixir-3n83</guid>
      <description>&lt;p&gt;If you’re someone who’s sick of writing huge IF and CASE statements, you’re not alone. As a relative newbie to functional languages, pattern matching is something I really enjoyed. It’s a great way to write idiomatic code - without the need for those long nested conditional statements.&lt;/p&gt;

&lt;p&gt;Pattern matching is definitely not something new. It’s existed for decades as a powerful functional programming technique. I personally enjoy the way Elixir implements it, so much so that I always look out for ways to use it.&lt;/p&gt;

&lt;p&gt;So, what is pattern matching? The name reveals as much - it’s a way to process and extract data based on its structure. With it, the “=” operator works more like a matching operator than an assignment operator. Let me show you what I mean.&lt;/p&gt;

&lt;h3&gt;
  
  
  It’s not the assignment operator anymore!
&lt;/h3&gt;

&lt;p&gt;With pattern matching, the “=” operator is used to match values on either side. For example, if you were to do,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;iex(1)&amp;gt; 4 = 5
** (MatchError) no match of right hand side value: 5
You get a “MatchError” exception. Here, Elixir is not trying to assign the value of “5” to “4”, but rather seeing if they’re equal.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you’re associating this with the common “==” parameter, well you’re almost there. Technically MatchError could be equated to false, but the error information gives us more detail into what is exactly not matching. More on this down below!&lt;/p&gt;

&lt;p&gt;Let’s see what happens when we try it with a variable.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;iex(4)&amp;gt; x = 4
4

iex(5)&amp;gt; 5 = x + 1
5

iex(6)&amp;gt; 5 = x + 2
** (MatchError) no match of right hand side value: 6
In the first statement, x gets assigned the value of 4 because x is nil/null/empty.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the second statement, x retains the value of 4 and since both sides match, we get no error.&lt;/p&gt;

&lt;p&gt;However in the last statement, a MatchError is raised.&lt;/p&gt;

&lt;p&gt;What’s really great is that you can use this across different data types,&lt;/p&gt;

&lt;p&gt;Here’s another example,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;iex(7)&amp;gt; [1, x, 5] = [1, 10, 5]
[1, 10, 5]
iex(8)&amp;gt; x
10
This is incredibly useful in parsing JSON responses,

iex(9)&amp;gt; %{topic: x} = %{name: "Swaathi", company: "Skcript", topic: "Elixir", source: "Internet"}
%{company: "Skcript", name: "Swaathi", source: "Internet", topic: "Elixir"}
iex(10)&amp;gt; x
"Elixir"
It works great with nested lists too!
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Matching in case statements
&lt;/h3&gt;

&lt;p&gt;Pattern matching in case statements makes the code so much more idiomatic. For example,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;iex(6)&amp;gt; case {4, 5, 6} do
...(6)&amp;gt; {4, 5} -&amp;gt; "One"
...(6)&amp;gt; {4, 5, x} -&amp;gt; "X is #{x}"
...(6)&amp;gt; _ -&amp;gt; "Three"
...(6)&amp;gt; end
"X is 6"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can see that not only the pattern is matched, but the missing element is also assigned to the variable “X”.&lt;/p&gt;

&lt;p&gt;You can pattern match in if statements too - but it’s really frowned upon in the Elixir world. Generally if statements are less idiomatic and extremely limited as compared to case statements so you’ll see them used only in really rare scenarios.&lt;/p&gt;

&lt;h3&gt;
  
  
  Control the flow of logic
&lt;/h3&gt;

&lt;p&gt;As someone who used to worship OO programming, I tried to bring most of those concepts into the functional world. I quickly realized the error in my ways.&lt;/p&gt;

&lt;p&gt;Let’s take an example of a payment library. In the OOP world, there would be shared state across objects and a function for each payment method. Something like this,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Payment
  attr_accessor :amount
  def initialize(amount)
    self.amount = amount
  end

  def pay_with_paypal(username, password)
    ...
  end

  def pay_with_card(number, expires_on, cvv)
    ...
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And then to execute, I would have called this,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;p = Payment.new(100)
p.pay_with_paypal(“xxx”, “xxx”)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Or,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;p.pay_with_card(“xxx”, “xxx”, “xxx”)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now my OOP brain would convert this into FP like so,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;defmodule Payments do
  def pay_with_paypal(login: login, password: password) do
    ...
  end

  def pay_with_card(number: number, expires: expires, code: code) do
    ...
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Well looks about right, no?&lt;/p&gt;

&lt;p&gt;Not exactly. In Elixir, you can pattern match in functions too! This proves to be extremely useful when the function that needs to be executed is dependent on the parameters passed. The more idiomatic way to write this code would be,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;defmodule Payments do
  def pay(:paypal, login: login, password: password) do
    ...
  end
  def pay(:card, number: number, expires: expires, code: code) do
    ...
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here your function name remains the same (since you’re trying to pay at the end of the day), and the function that gets executed will be based on the first parameter.&lt;/p&gt;

&lt;p&gt;Like so,&lt;/p&gt;

&lt;p&gt;Payments.pay(:paypal, login: "xxx", password: "xxx")&lt;br&gt;
What’s great about pattern matching in functions is that you can extract the parameter value as and when you’re determining what function to execute.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def run(%{state: "ready"}, ctx) do
  ...
end

def run(%{state: "pending"}, %{initialized: false } = ctx) do
  ...
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the first function, the value of ctx could just about be anything, however the second function will only get executed when the second parameter matches the pattern of “{initialized: false}” (when “initialized” is false).&lt;/p&gt;

&lt;p&gt;It doesn’t end there. You can tag on “guard” statements too to functions!&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def run(%{state: "ready", data: data}, ctx) when length(data) &amp;gt; 0 do
  ...
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now this function will execute only when “state” is ready AND the length of “data” is greater than zero. How useful is that! (Now you might start realizing why if statements are frowned upon.)&lt;/p&gt;

&lt;p&gt;If the calling function matches none of these statements, Elixir will throw an error. However if you want to catch that too, you can just do this.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def run(_, _) do 
  ...
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here the “underscore” parameter acts as a catchall and will execute when none of the other functions match. Be careful to place this at the very end as the order of matching is top to bottom.&lt;/p&gt;

&lt;h3&gt;
  
  
  Conclusion
&lt;/h3&gt;

&lt;p&gt;Pattern matching is a great way to write idiomatic functional code. It’s a powerful tenant of functional programming that makes it a joy to write conditional statements. Once you master it, you can clean up your code and optimize it in tons of places!&lt;/p&gt;

</description>
      <category>elixir</category>
    </item>
    <item>
      <title>Concurrency In The Erlang VM</title>
      <dc:creator>Swaathi Kakarla</dc:creator>
      <pubDate>Thu, 25 Jun 2020 07:26:17 +0000</pubDate>
      <link>https://forem.com/imswaathik/concurrency-in-the-erlang-vm-272k</link>
      <guid>https://forem.com/imswaathik/concurrency-in-the-erlang-vm-272k</guid>
      <description>&lt;p&gt;&lt;a href="https://codesync.global/media/how-erlang-got-its-name-concurrency-before-erlang/=1592766229543000"&gt;Erlang&lt;/a&gt; is often referred to as the “concurrency oriented programming language”.&lt;/p&gt;

&lt;p&gt;How did it get this name? How can a language created in the 80s for the telecom industry help us now?&lt;/p&gt;

&lt;p&gt;Erlang or &lt;em&gt;Erlang/OTP&lt;/em&gt; (Open Telecom Platform) was built in 1986 at Ericsson to handle the growing telephone user base. It was designed with the aim of improving the development of telephony applications. It is great for building distributed, fault tolerant and highly available systems.&lt;/p&gt;

&lt;p&gt;So, what relevance does a technology built in the 80s have for us? It turns out that all the reasons for which Erlang was built for is extremely useful for web servers today. We need applications to be fast and reliable - and we want it now! Fortunately that’s possible with Phoenix, the web framework built on top of Elixir (a modern language built on top of Erlang). It has great features like hot code swapping and &lt;a href="https://github.com/phoenixframework/phoenix_live_view"&gt;real time views&lt;/a&gt; - without JS!&lt;/p&gt;

&lt;p&gt;How is all that possible? It’s largely due to how the language was built to be concurrent from bottom up - thanks to BEAM, the Erlang VM.&lt;/p&gt;

&lt;p&gt;Before we go any further, let’s recap a few concepts from CS 101 - the Operating System!&lt;/p&gt;

&lt;h2&gt;
  
  
  Concurrency
&lt;/h2&gt;

&lt;p&gt;In order to understand why concurrency in the Erlang VM is so special, we need to understand how the operating system processes instructions/programs. &lt;/p&gt;

&lt;p&gt;The CPU is responsible for the working of a machine. It’s sole responsibility is to execute processes. Now a process is an isolated block of execution. They have their own memory, context and file descriptors. A process is then made up of many threads or the over used definition “&lt;em&gt;a lightweight process&lt;/em&gt;”.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--F_Piq0kf--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/njlhn6cavj6tun4y5yn9.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--F_Piq0kf--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/njlhn6cavj6tun4y5yn9.png" alt="OS Process and Threads"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The CPU is responsible for executing these processes in the most efficient format. It can execute processes one after the other. This is known as “sequential execution”. This is the most basic and oldest method of execution. It’s also pretty useless for us today - even the refrigerators we use today can do more!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--JtQh0-tA--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/zi1s3beg9jpoca6m6q9m.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--JtQh0-tA--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/zi1s3beg9jpoca6m6q9m.jpg" alt="Sequential Processing"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You might think that since your modern day computer allows you to do more than one thing at a time, the CPU is executing processes in parallel. Something like this,&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--w6v_hnhg--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/o49b41n1u6lbtdg33yjf.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--w6v_hnhg--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/o49b41n1u6lbtdg33yjf.jpg" alt="Parallelism"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;However this is far from the truth. We are quite far from true parallelism. There’s a whole &lt;a href="https://devblogs.microsoft.com/pfxteam/most-common-performance-issues-in-parallel-programs/=1592766229547000"&gt;plethora of bugs&lt;/a&gt; that crop up when we try to go down this path.&lt;/p&gt;

&lt;p&gt;The next best thing is concurrency. Concurrent execution means breaking up processes into multiple tiny bits and switching between them while executing. This happens so fast that it gives the user the illusion of multiple processes being executed at the same time - while cleverly circumventing the problems of parallelism.&lt;/p&gt;

&lt;p&gt;It looks something like this,&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--tjVxVDWa--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/8zix5k1050jegbgccvzo.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--tjVxVDWa--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/8zix5k1050jegbgccvzo.jpg" alt="Concurrency"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You can see that the CPU switches between process 1 and 2. This is known as context switching. It is a pretty heavy task as the CPU needs to store all the information and state of a process to memory before switching - and then load it back when it needs to execute again. However we’ve worked on this problem for so many years that we’ve got insanely good at it.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;One last thing …&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;The speed of program execution is dependent on the CPU clock cycles. The faster the processor, the faster your computer is. Moore’s law states that the number of transistors on an affordable CPU would double every two years. However if you’ve noticed, processors haven’t been getting that much faster in the past few years. That’s because we’ve hit a physical &lt;a href="https://www.theverge.com/2018/7/19/17590242/intel-50th-anniversary-moores-law-history-chips-processors-future"&gt;bump in the road&lt;/a&gt;. This happened when we realized going much higher than 4GHz is very difficult and futile. Speed of light actually became a constraint! This is when we decided to do multi-core processing instead. We scaled horizontally, instead of vertically. We added more cores, instead of making a single core powerful.&lt;/p&gt;

&lt;blockquote&gt;
  Okay I know we’ve covered a lot of material here. But what’s relevant for you to remember is that context switching is heavy and that we’ve moved on to multi-core processing now. Let’s see what tricks Erlang has up its sleeve that makes it the concurrency oriented language.
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  Concurrency Models
&lt;/h2&gt;

&lt;p&gt;In the previous section we deduced that concurrency is the best way forward to achieve multiprocessing. Over the years various languages have introduced different algorithms to achieve concurrency. Let’s have a look at three of the most significant ones relevant to our topic of discussion.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Shared Memory Model&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This is a commonly used model in popular programming languages like Java and C#. It involves different processes accessing the same block of memory to store and communicate with each other. It allows for context switching to be less heavier. &lt;/p&gt;

&lt;p&gt;Though this sounds great in theory, it causes some unfriendly situations when two or more processes try to access the same shared memory block. It leads to situations like deadlocks. In order to overcome this, we have mutexes,locks and synchronization. However this makes the system more complex and difficult to scale. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--oSeR3b2---/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/zv5hy9mfle9nxecej6rf.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--oSeR3b2---/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/zv5hy9mfle9nxecej6rf.png" alt="Shared Memory"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Actor Model&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This is the model used by Erlang and Rust to achieve concurrency. It depends on isolating processes as much as possible and reducing communication between them to message passing. Each process is known as an actor. &lt;/p&gt;

&lt;p&gt;Actors communicate with each other by sending messages. Messages can be sent at any time and are non-blocking. These messages are then stored in the receiving actors mailbox. In order to read messages, actors have to perform a blocking read action.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--XlLO-KKs--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/xryfhuhdjbxotuck78e7.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--XlLO-KKs--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/xryfhuhdjbxotuck78e7.png" alt="Actor Model"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Communicating Sequential Processes&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This is a highly efficient concurrent model used by Go. It’s similar to the actor model in that it uses message passing. However unlike in the actor model where only receiving messages is blocking, CSP requires both actions to be blocking. &lt;/p&gt;

&lt;p&gt;In CSP, a separate store called the channel is used to transfer incoming and outgoing messages. Processes don’t communicate with each other directly, but with the channel layer in between.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--dlkSuLzf--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/q2eev659egahzmvfz4to.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--dlkSuLzf--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/q2eev659egahzmvfz4to.png" alt="CSP"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Actor Model
&lt;/h2&gt;

&lt;p&gt;Let’s take a deeper look into the actor model.&lt;/p&gt;

&lt;p&gt;An actor is a primitive form of concurrency. Each actor has an identity that other actors can use to send and receive messages from. When messages are received, they are stored in the actors mailbox. An actor must make an explicit attempt to read contents of the mailbox. Each actor is completely isolated from others and shares no memory between them. This completely eradicates the need for complex synchronization mechanisms or locks.&lt;/p&gt;

&lt;p&gt;An actor can do three things when it receives a message,&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Create more actors&lt;/strong&gt; &lt;span&gt;&lt;/span&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Send messages to other actors&lt;/strong&gt; &lt;span&gt;&lt;/span&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Designate what to do with the next message&lt;/strong&gt; &lt;span&gt;&lt;/span&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The first two are pretty straightforward. Let’s look at it’s representation on a code level.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--ylf2mwOA--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/2a3ihkokhxvirmmwlw8a.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--ylf2mwOA--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/2a3ihkokhxvirmmwlw8a.png" alt="Elixir Code"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You can see here that spawning a new process in Elixir - is exactly that. Unlike other languages which use a multithreaded approach to deal with concurrency, Elixir uses threads.&lt;/p&gt;

&lt;p&gt;The key thing to remember is that these are Erlang threads which are much more lightweight than their OS counterparts. On average, Erlang processes are &lt;a href="http://blog.plataformatec.com.br/2018/04/elixir-processes-and-this-thing-called-otp/=1592766229553000"&gt;2000 times&lt;/a&gt; more lightweight than OS processes. There could be hundreds of thousands of Erlang processes in a system and all would be well.&lt;/p&gt;

&lt;p&gt;Erlang threads also have a PID attached to them. Using this PID, you can extract information about the memory it occupies, functions it’s running and much more. Using the PID, you can also send messages to processes and communicate.&lt;/p&gt;

&lt;p&gt;Let’s take a look at the final responsibility of an actor - designation.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--ylf2mwOA--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/2a3ihkokhxvirmmwlw8a.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--ylf2mwOA--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/2a3ihkokhxvirmmwlw8a.png" alt="Elixir Code"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You can see here that each process also has its own internal state. Everytime we send a message to the process, it does not restart the function with default values, rather it is able to retain information of the state of the running process. Inherently each actor is able to access it’s own set of memory, and keep track of it.&lt;/p&gt;

&lt;p&gt;These three properties allow Erlang processes to be very lightweight. It eradicates the need for complex synchronization techniques and does not take up too much memory space for interprocess communication. All this contributes to high availability.&lt;/p&gt;

&lt;blockquote&gt;
  At this point of time, it’s a great idea to watch this &lt;a href="https://www.youtube.com/watch?v%3DELwEdb_pD0k"&gt;quick 4 minute video of the actor model&lt;/a&gt;. After all, a picture is worth a thousand words, and a video even more!  

  If you’ve got the time and want something much more in detail, &lt;a href="https://www.youtube.com/watch?v=7erJ1DV_Tlo"&gt;have a look at this video&lt;/a&gt; where the creator of the Actor Model explains all that I’ve said in such an eloquent way.
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  BEAM
&lt;/h2&gt;

&lt;p&gt;Well after so many topics, we’ve finally come to the actual Erlang VM - BEAM!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--khuzs9c2--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://media1.tenor.com/images/e5acbf1cf1c0ad287cdca3251c384a9f/tenor.gif%3Fitemid%3D11313969" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--khuzs9c2--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://media1.tenor.com/images/e5acbf1cf1c0ad287cdca3251c384a9f/tenor.gif%3Fitemid%3D11313969" alt="BEAM Me Up Scotty"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The &lt;a href="https://blog.lelonek.me/elixir-on-erlang-vm-demystified-320557d09e1f"&gt;BEAM VM was built&lt;/a&gt; to be able to both compile Erlang/Elixir files into bytecode (.beam) files as well as to schedule Erlang processes on the CPU. This level of control gives a huge advantage to efficiently and concurrently run processes.&lt;/p&gt;

&lt;p&gt;When the VM starts, it’s first step is to start the Scheduler. It is responsible for running each Erlang process concurrently on the CPU. Since the processes are all maintained and scheduled by BEAM, we have more control over what happens when a process fails (fault tolerance) and are able to more efficiently use memory and perform better context switching.&lt;/p&gt;

&lt;p&gt;BEAM also takes full advantage of the hardware. It starts a Scheduler for each available core allowing processes to run freely and efficiently, while still being able to communicate with each other.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--abjJbL9p--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/c9xdsxv2d0x39jidqaqd.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--abjJbL9p--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/c9xdsxv2d0x39jidqaqd.png" alt="BEAM VM"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;BEAM allows Erlang to spawn thousands of processes and achieve high levels of concurrency. There is an awesome conversation on HackerNews about how the idea that thousands of processes lead to efficient concurrency.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--41bPN7sB--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/a76rwf4kzdjbkcvscc8r.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--41bPN7sB--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/a76rwf4kzdjbkcvscc8r.png" alt="HN Snippet"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Have a &lt;a href="https://news.ycombinator.com/item?id%3D10028227"&gt;read&lt;/a&gt;!&lt;/p&gt;

&lt;h2&gt;
  
  
  Contributing Characteristics
&lt;/h2&gt;

&lt;p&gt;Stay calm, we’re almost at the end!&lt;/p&gt;

&lt;p&gt;Erlang concurrency is largely due to the Actor model and BEAM. However, there are many other constructs that ensure stability as well. I’m going to give you small pointers that you can pick up for further reading.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Supervisors&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;There is a special Erlang process called the Supervisor. It’s goal is to figure out what to do when a process fails. It helps it reset to an initial value so that it can be sent for processing once again. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Fault Tolerance&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Joe Armstrong, (late) creator of Erlang, said the infamous line, “Let it crash”. He &lt;a href="https://thenewstack.io/why-erlang-joe-armstrongs-legacy-of-fault-tolerant-computing/=1592766229560000"&gt;designed&lt;/a&gt; the fault tolerant language not with the goal of preventing errors from happening, but to build structures that handle error scenarios. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--673mja4G--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/e63xt2ftrtvr482soiyx.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--673mja4G--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/e63xt2ftrtvr482soiyx.png" alt="HN Snippet"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The entire thread is heartwarming, &lt;a href="https://news.ycombinator.com/item?id%3D19708379"&gt;give it a read&lt;/a&gt;!  &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Distribution&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Finally Erlang makes it extremely easy to build distributed systems. Each Erlang instance can act as a node in different devices and communicate just as easily as spawning processes. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. No GIL!&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Unlike other interpreted languages, most famously Ruby and Python, Erlang does not have to worry about the Global Interpreter Lock. The GIL ensures that only one Ruby/Python thread runs per process on the CPU. This is a huge blow to concurrency.&lt;/p&gt;

&lt;p&gt;App servers like Passenger try to overcome this by creating multiple OS processors and run it on multiple cores. However as we saw before, OS threads are expensive to manage.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Erlang is a beautifully constructed and well throughout language. It’s truly passed the test of time and is so much more relevant in recent times.&lt;/p&gt;

</description>
      <category>erlang</category>
      <category>elixir</category>
      <category>concurrency</category>
      <category>multiprocessing</category>
    </item>
    <item>
      <title>Rails is Fast: Optimize Your View Performance</title>
      <dc:creator>Swaathi Kakarla</dc:creator>
      <pubDate>Wed, 29 Jan 2020 15:13:44 +0000</pubDate>
      <link>https://forem.com/appsignal/rails-is-fast-optimize-your-view-performance-1klf</link>
      <guid>https://forem.com/appsignal/rails-is-fast-optimize-your-view-performance-1klf</guid>
      <description>&lt;p&gt;In this post, we'll look into tried and true methods of improving Rails view performance. Specifically, I will focus on database efficiency, view manipulation, and caching.&lt;/p&gt;

&lt;p&gt;I think the phrase "premature optimization is the root of all evil" has been taken a little out of context. I've often heard developers use this during code reviews when simple optimization techniques are pointed out. You know the famous, "I'll get it working and then optimize it" - then test it - then debug it - then test it again, and so on!&lt;/p&gt;

&lt;p&gt;Well, thankfully, there are some simple and effective performance and optimization techniques that you can use from the moment you start writing code.&lt;/p&gt;

&lt;p&gt;Throughout the post, we will stick to a basic Rails app, make improvements on it and compare results.&lt;/p&gt;

&lt;p&gt;The basic Rails app has the following models:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;Person (has many addresses)&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;name:string&lt;/li&gt;
&lt;li&gt;votes_count:integer&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;

&lt;p&gt;Profile (belongs to Person)&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;address:string&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This is what our Person model looks like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ruby"&gt;&lt;code&gt;&lt;span class="c1"&gt;# == Schema Information&lt;/span&gt;
&lt;span class="c1"&gt;#&lt;/span&gt;
&lt;span class="c1"&gt;# Table name: people&lt;/span&gt;
&lt;span class="c1"&gt;#&lt;/span&gt;
&lt;span class="c1"&gt;#  id          :integer          not null, primary key&lt;/span&gt;
&lt;span class="c1"&gt;#  name        :string&lt;/span&gt;
&lt;span class="c1"&gt;#  votes_count :integer&lt;/span&gt;
&lt;span class="c1"&gt;#  created_at  :datetime         not null&lt;/span&gt;
&lt;span class="c1"&gt;#  updated_at  :datetime         not null&lt;/span&gt;
&lt;span class="c1"&gt;#&lt;/span&gt;

&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Person&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="no"&gt;ApplicationRecord&lt;/span&gt;
  &lt;span class="c1"&gt;# Relationships&lt;/span&gt;
  &lt;span class="n"&gt;has_many&lt;/span&gt; &lt;span class="ss"&gt;:profiles&lt;/span&gt;

  &lt;span class="c1"&gt;# Validations&lt;/span&gt;
  &lt;span class="n"&gt;validates_presence_of&lt;/span&gt; &lt;span class="ss"&gt;:name&lt;/span&gt;
  &lt;span class="n"&gt;validates_uniqueness_of&lt;/span&gt; &lt;span class="ss"&gt;:name&lt;/span&gt;

  &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;vote!&lt;/span&gt;
    &lt;span class="n"&gt;update&lt;/span&gt; &lt;span class="ss"&gt;votes_count: &lt;/span&gt;&lt;span class="n"&gt;votes_count&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
  &lt;span class="k"&gt;end&lt;/span&gt;
&lt;span class="k"&gt;end&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is the code for our Profile model:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ruby"&gt;&lt;code&gt;&lt;span class="c1"&gt;# == Schema Information&lt;/span&gt;
&lt;span class="c1"&gt;#&lt;/span&gt;
&lt;span class="c1"&gt;# Table name: profiles&lt;/span&gt;
&lt;span class="c1"&gt;#&lt;/span&gt;
&lt;span class="c1"&gt;#  id         :integer          not null, primary key&lt;/span&gt;
&lt;span class="c1"&gt;#  address    :text&lt;/span&gt;
&lt;span class="c1"&gt;#  person_id  :integer&lt;/span&gt;
&lt;span class="c1"&gt;#  created_at :datetime         not null&lt;/span&gt;
&lt;span class="c1"&gt;#  updated_at :datetime         not null&lt;/span&gt;
&lt;span class="c1"&gt;#&lt;/span&gt;

&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Profile&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="no"&gt;ApplicationRecord&lt;/span&gt;
  &lt;span class="c1"&gt;# Relationships&lt;/span&gt;
  &lt;span class="n"&gt;belongs_to&lt;/span&gt; &lt;span class="ss"&gt;:person&lt;/span&gt;

  &lt;span class="c1"&gt;# Validations&lt;/span&gt;
  &lt;span class="n"&gt;validates_presence_of&lt;/span&gt; &lt;span class="ss"&gt;:address&lt;/span&gt;
&lt;span class="k"&gt;end&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There's also a seed file to populate 1000 people. We can do this with ease by utilizing &lt;a href="https://github.com/faker-ruby/faker"&gt;Faker gem&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;We're now going to create an action called "home" in ApplicationController.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ruby"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;home&lt;/span&gt;
  &lt;span class="vi"&gt;@people&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="no"&gt;Person&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;all&lt;/span&gt;
&lt;span class="k"&gt;end&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The code for our home.html.erb is as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ruby"&gt;&lt;code&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;ul&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="sx"&gt;% @people.each &lt;/span&gt;&lt;span class="k"&gt;do&lt;/span&gt; &lt;span class="o"&gt;|&lt;/span&gt;&lt;span class="n"&gt;person&lt;/span&gt;&lt;span class="o"&gt;|&lt;/span&gt; &lt;span class="sx"&gt;%&amp;gt;
    &amp;lt;li id="&amp;lt;%= person.id %&amp;gt;&lt;/span&gt;&lt;span class="s2"&gt;"&amp;gt;&amp;lt;%= render person %&amp;gt;&amp;lt;/li&amp;gt;
  &amp;lt;% end %&amp;gt;
&amp;lt;/ul&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's do a dry run and measure the performance of our page against this.&lt;/p&gt;

&lt;p&gt;That page took a whopping 1066.7ms to load. Not good! This is what we will aim to reduce.&lt;/p&gt;

&lt;h2&gt;
  
  
  Database Queries
&lt;/h2&gt;

&lt;p&gt;The first step to building a performant application is to maximize resource utilization. Most Rails apps render something from the database onto the views, so let's try to optimize database calls first!&lt;/p&gt;

&lt;p&gt;For the purpose of this demonstration, I'm going to use a MySQL database.&lt;/p&gt;

&lt;p&gt;Let's look at how that initial load of 1066ms breaks down.&lt;/p&gt;

&lt;p&gt;414.7 to execute 'controllers/application_controller#home'&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;...
(0.1ms)  SELECT "profiles"."address" FROM "profiles" WHERE "profiles"."person_id" = ?  [["person_id", 996]]
Rendered people/_person.html.erb (1.5ms)
(0.2ms)  SELECT "profiles"."address" FROM "profiles" WHERE "profiles"."person_id" = ?  [["person_id", 997]]
Rendered people/_person.html.erb (2.3ms)
(0.1ms)  SELECT "profiles"."address" FROM "profiles" WHERE "profiles"."person_id" = ?  [["person_id", 998]]
Rendered people/_person.html.erb (2.1ms)
(0.2ms)  SELECT "profiles"."address" FROM "profiles" WHERE "profiles"."person_id" = ?  [["person_id", 999]]
Rendered people/_person.html.erb (2.3ms)
(0.2ms)  SELECT "profiles"."address" FROM "profiles" WHERE "profiles"."person_id" = ?  [["person_id", 1000]]
Rendered people/_person.html.erb (2.0ms)
Rendered application/home.html.erb within layouts/application (890.5ms)

Completed 200 OK in 1066ms (Views: 890.5ms | ActiveRecord: 175.4ms)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;519.2 and 132.8 to render "application/home.html.erb" and "people/_person.html.erb" partials.&lt;/p&gt;

&lt;p&gt;Did you notice anything weird?&lt;/p&gt;

&lt;p&gt;We made one database call in the controller, but every partial makes its own database call as well! Introducing, the N+1 query problem.&lt;/p&gt;

&lt;h3&gt;
  
  
  1.  N+1 Queries
&lt;/h3&gt;

&lt;p&gt;This is a very popular and simple optimization technique—but it deserves the first mention since this mistake is so prevalent.&lt;/p&gt;

&lt;p&gt;Let's see what "people/_person.html.erb" does:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ruby"&gt;&lt;code&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;ul&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;li&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="no"&gt;Name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="sx"&gt;%= person.name %&amp;gt;
  &amp;lt;/li&amp;gt;
  &amp;lt;li&amp;gt;
    Addresses:
      &amp;lt;ul&amp;gt;
        &amp;lt;% person.profiles.each do |profile| %&amp;gt;
          &amp;lt;li&amp;gt;&amp;lt;%=&lt;/span&gt; &lt;span class="n"&gt;profile&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;address&lt;/span&gt; &lt;span class="sx"&gt;%&amp;gt;&amp;lt;/li&amp;gt;&lt;/span&gt;
        &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="sx"&gt;% end &lt;/span&gt;&lt;span class="o"&gt;%&amp;gt;&lt;/span&gt;
      &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="sr"&gt;/ul&amp;gt;
  &amp;lt;/&lt;/span&gt;&lt;span class="n"&gt;li&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;
&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="sr"&gt;/ul&amp;gt;

&amp;lt;%= button_to "Vote &lt;/span&gt;&lt;span class="si"&gt;#{&lt;/span&gt;&lt;span class="n"&gt;person&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;votes_count&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="sr"&gt;", vote_person_path(person) %&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Basically, it queries the database for that person's profiles and renders each one out. So it does N queries (where N is the number of people) and the 1 query we did in the controller—thus, N+1.&lt;/p&gt;

&lt;p&gt;To optimize this, make use of the MySQL database joins and the Rails ActiveRecord includes functions.&lt;/p&gt;

&lt;p&gt;Let's change the controller to match the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ruby"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;home&lt;/span&gt;
  &lt;span class="vi"&gt;@people&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="no"&gt;Person&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;all&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;includes&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="ss"&gt;:profiles&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;end&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;All the people are loaded by 1 MySQL query, and all their respective queries are loaded in another. Bringing N+1 to just 2 queries.&lt;/p&gt;

&lt;p&gt;Let's look at how this increases performance!&lt;/p&gt;

&lt;p&gt;It took us only 936ms to load the page. You can see below that the "application_controller#home" action does 2 MySQL queries.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Rendered people/_person.html.erb (0.3ms)
Rendered people/_person.html.erb (0.2ms)
Rendered people/_person.html.erb (0.3ms)
Rendered people/_person.html.erb (0.3ms)
Rendered people/_person.html.erb (0.3ms)
Rendered people/_person.html.erb (0.3ms)
Rendered people/_person.html.erb (0.3ms)
Rendered people/_person.html.erb (0.2ms)

Rendered application/home.html.erb within layouts/application (936.0ms)
Completed 200 OK in 936ms (Views: 927.1ms | ActiveRecord: 9.3ms)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  2.  Load Only What You Will Use
&lt;/h3&gt;

&lt;p&gt;This is how the homepage looks.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--uCbv54ou--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/v1/images/blog/2020-01/image10.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--uCbv54ou--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/v1/images/blog/2020-01/image10.png" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You can see we only need the address, nothing else. But in the "_person.html.erb" partial we load the profile object. Let's see how we can make that change.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ruby"&gt;&lt;code&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;li&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="no"&gt;Addresses&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
  &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;ul&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="sx"&gt;% person.profiles.pluck(:address).each &lt;/span&gt;&lt;span class="k"&gt;do&lt;/span&gt; &lt;span class="o"&gt;|&lt;/span&gt;&lt;span class="n"&gt;address&lt;/span&gt;&lt;span class="o"&gt;|&lt;/span&gt; &lt;span class="sx"&gt;%&amp;gt;
      &amp;lt;li&amp;gt;&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="sx"&gt;%= address %&amp;gt;&amp;lt;/li&amp;gt;
    &amp;lt;% end %&amp;gt;
  &amp;lt;/ul&amp;gt;
&amp;lt;/li&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For a more in-depth look at N+1 queries, read &lt;a href="https://blog.appsignal.com/2018/04/24/active-record-performance-the-n-1-queries-antipattern.html"&gt;ActiveRecord performance: the N+1 queries antipattern&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;ProTip: You can create a &lt;a href="https://www.rubyguides.com/2019/10/scopes-in-ruby-on-rails/"&gt;scope&lt;/a&gt; for this and add it to the "models/profile.rb" file. Raw database queries in your view files aren't of much use.&lt;/p&gt;

&lt;h3&gt;
  
  
  3.  Move All Database Calls to the Controller
&lt;/h3&gt;

&lt;p&gt;Let's say, in the future of this make-believe application, you'd like to display the total number of users on the home page.&lt;/p&gt;

&lt;p&gt;Simple! Let's make a call in the view that looks like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ruby"&gt;&lt;code&gt;&lt;span class="c1"&gt;# of People: &amp;lt;%= @people.count %&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Okay, that's simple enough.&lt;/p&gt;

&lt;p&gt;There's another requirement—you need to create a UI element that displays the page progress. Let's now divide the number of people on the page by the total count.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ruby"&gt;&lt;code&gt;&lt;span class="no"&gt;Progress&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="sx"&gt;%= index / @people.count %&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Unfortunately, your colleague doesn't know that you've already made this query and they proceed to make it again and again in the views.&lt;/p&gt;

&lt;p&gt;Had your controller looked like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ruby"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;home&lt;/span&gt;
  &lt;span class="vi"&gt;@people&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="no"&gt;Person&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;all&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;includes&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="ss"&gt;:profiles&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
  &lt;span class="vi"&gt;@people_count&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="vi"&gt;@people&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;count&lt;/span&gt;
&lt;span class="k"&gt;end&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It would have been easier to reuse already calculated variables.&lt;/p&gt;

&lt;p&gt;Though this does not contribute to a direct improvement in page load speeds, it prevents multiple calls to the database from various view pages and helps you prepare for optimizations that you can perform later, such as caching.&lt;/p&gt;

&lt;h3&gt;
  
  
  4.  Paginate Wherever You Can!
&lt;/h3&gt;

&lt;p&gt;Just like loading only what you need, it also helps to only show what you need! With pagination, views render a portion of the information and keep the rest to load on demand. This shaves off a lot of milliseconds! The &lt;a href="https://github.com/mislav/will_paginate"&gt;will_paginate&lt;/a&gt; and &lt;a href="https://github.com/kaminari/kaminari"&gt;kaminari&lt;/a&gt; gems do this for you in minutes.&lt;/p&gt;

&lt;p&gt;One annoyance that this causes is that users have to keep clicking on "Next Page". For that, you can also look at "&lt;a href="https://www.sitepoint.com/infinite-scrolling-rails-basics/"&gt;Infinite Scrolling&lt;/a&gt;" to give your users a much better experience.&lt;/p&gt;

&lt;h2&gt;
  
  
  Avoiding HTML Reloads
&lt;/h2&gt;

&lt;p&gt;In a traditional Rails app, HTML view rendering takes a lot of time. Fortunately, there are measures you can take to reduce this.&lt;/p&gt;

&lt;h3&gt;
  
  
  1.  Turbolinks
&lt;/h3&gt;

&lt;p&gt;This comes wrapped up in your standard Rails app. Turbolinks is a JavaScript library that works everywhere (even without Rails, like on static pages) and degrades gracefully on unsupported browsers.&lt;/p&gt;

&lt;p&gt;It &lt;a href="https://blog.appsignal.com/2018/05/23/speeding-up-your-apps-navigation-with-turbolinks.html"&gt;converts every link into an AJAX request&lt;/a&gt; and replaces the entire body of the page via JS. This greatly improves performance as it doesn't have to reload the CSS, JS and images.&lt;/p&gt;

&lt;p&gt;However, when writing custom JS you'll have to take extra precaution to write "Turbolinks safe JS". Read more about this &lt;a href="https://thoughtbot.com/upcase/videos/turbolinks"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  2.  Use AJAX Requests
&lt;/h3&gt;

&lt;p&gt;In the same vein as Turbolinks, you can convert some of your links and buttons into AJAX requests as well. The difference here is that you get to control what HTML gets replaced rather than replacing the whole body as Turbolinks does.&lt;/p&gt;

&lt;p&gt;Let's see AJAX in action!&lt;/p&gt;

&lt;p&gt;In the sample app, there's a "Vote" button for each user. Let's measure how long it takes to do that action.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Started POST "/people/1/vote" for 127.0.0.1 at 2020-01-21 14:50:49 +0530
Processing by PeopleController#vote as HTML
  Person Load (0.3ms)  SELECT  "people".* FROM "people" WHERE "people"."id" = ? LIMIT ?  [["id", 1], ["LIMIT", 1]]
   (0.1ms)  begin transaction
  Person Exists (4.5ms)  SELECT  1 AS one FROM "people" WHERE "people"."name" = ? AND ("people"."id" != ?) LIMIT ?  [["name", "Deon Waelchi"], ["id", 1], ["LIMIT", 1]]
  SQL (1.0ms)  UPDATE "people" SET "votes_count" = ?, "updated_at" = ? WHERE "people"."id" = ?  [["votes_count", 1], ["updated_at", "2020-01-21 09:20:49.941928"], ["id", 1]]

Redirected to http://localhost:3000/
Completed 302 Found in 24ms (ActiveRecord: 7.5ms)


Started GET "/" for 127.0.0.1 at 2020-01-21 14:50:49 +0530
Processing by ApplicationController#home as HTML
  Rendering application/home.html.erb within layouts/application

  Rendered people/_person.html.erb (2.4ms)
   (0.3ms)  SELECT "profiles"."address" FROM "profiles" WHERE "profiles"."person_id" = ?  [["person_id", 30]]
  Rendered people/_person.html.erb (2.2ms)
  ...

  Rendered application/home.html.erb within layouts/application (159.8ms)
Completed 200 OK in 190ms (Views: 179.0ms | ActiveRecord: 6.8ms)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That took the same amount of time as reloading the page, plus a little extra for the actual voting part.&lt;/p&gt;

&lt;p&gt;Let's make it an AJAX request. Now, our "people/_person.html.erb" looks like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ruby"&gt;&lt;code&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="sx"&gt;%= button_to "Vote #{person.votes_count}", vote_person_path(person), remote: true %&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Our controller action returns a JS response, which looks like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ruby"&gt;&lt;code&gt;&lt;span class="err"&gt;$&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"#&amp;lt;%= @person.id %&amp;gt;"&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;html&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"&amp;lt;%= j render(partial: 'person', locals: {person: @person}) %&amp;gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can see, we're replacing only the content we need. We provide an HTML ID to hook onto a div and replace it. Of course, we can further optimize this by replacing only the button content, but for the purposes of this post, let's replace the entire partial.&lt;/p&gt;

&lt;p&gt;Results?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Started POST "/people/1/vote" for 127.0.0.1 at 2020-01-21 14:52:56 +0530
Processing by PeopleController#vote as JS

  Person Load (0.2ms)  SELECT  "people".* FROM "people" WHERE "people"."id" = ? LIMIT ?  [["id", 1], ["LIMIT", 1]]
   (0.1ms)  begin transaction
  Person Exists (0.3ms)  SELECT  1 AS one FROM "people" WHERE "people"."name" = ? AND ("people"."id" != ?) LIMIT ?  [["name", "Deon Waelchi"], ["id", 1], ["LIMIT", 1]]
  SQL (0.4ms)  UPDATE "people" SET "votes_count" = ?, "updated_at" = ? WHERE "people"."id" = ?  [["votes_count", 2], ["updated_at", "2020-01-21 09:22:56.532281"], ["id", 1]]
   (1.6ms)  commit transaction
  Rendering people/vote.js.erb
   (0.2ms)  SELECT "profiles"."address" FROM "profiles" WHERE "profiles"."person_id" = ?  [["person_id", 1]]

  Rendered people/_person.html.erb (3.2ms)
  Rendered people/vote.js.erb (6.3ms)
Completed 200 OK in 31ms (Views: 14.6ms | ActiveRecord: 2.9ms)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;30ms! That's it! How great is that?&lt;/p&gt;

&lt;p&gt;&lt;em&gt;ProTip: If you don't want to mess around with a bunch of HTML IDs and classes to figure out when/what to replace, consider using the &lt;a href="https://github.com/renderedtext/render_async"&gt;render_async gem&lt;/a&gt;. It does a lot of the heavy lifting out of the box.&lt;/em&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  3.  Use Websockets
&lt;/h3&gt;

&lt;p&gt;One of the great things about an HTML reload is that it gets you fresh content from the server every time. With an AJAX request, you only see the latest content for the little snippet.&lt;/p&gt;

&lt;p&gt;WebSockets are a great piece of technology that let your server push updates to the client, instead of the client requesting for new information.&lt;/p&gt;

&lt;p&gt;This can be useful when you need to build dynamic webpages. Imagine you need to display the score of a game on your website. To fetch new content you can,&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Tell your users to reload the entire page&lt;/li&gt;
&lt;li&gt;Provide a reload button that refreshes just the score&lt;/li&gt;
&lt;li&gt;Use JavaScript to keep polling the backend every second

&lt;ul&gt;
&lt;li&gt;This will keep pinging the server even when there is no change in data&lt;/li&gt;
&lt;li&gt;Each client will make calls every second - easily overwheling the server&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;Use WebSockets!&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;With WebSockets, the server has control of when to push data to all clients (or even a subset). Since the server knows when data changes, it can push data only when there is a change!&lt;/p&gt;

&lt;p&gt;Rails 5 released &lt;a href="https://guides.rubyonrails.org/action_cable_overview.html"&gt;ActionCable&lt;/a&gt;, which lets you manage all things WebSockets. It provides a JS framework for the client to subscribe to the server and a backend framework for the server to publish changes. With action cable, you have the ability to choose any WebSocket service of your choice. It could be &lt;a href="https://www.npmjs.com/package/faye-websocket"&gt;Faye&lt;/a&gt;, a self-managed web socket service, or &lt;a href="https://pusher.com"&gt;Pusher&lt;/a&gt; a subscription service.&lt;/p&gt;

&lt;p&gt;Personally, I'd choose a subscription for this, as it reduces the number of things you need to manage.&lt;/p&gt;

&lt;p&gt;Okay, back to WebSockets. Once you're done setting up ActionCable, your view will not be able to listen to JSON input from the server. Once it receives it, the hook actions you've written will replace the respective HTML content.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://guides.rubyonrails.org/action_cable_overview.html"&gt;Rails docs&lt;/a&gt; and &lt;a href="https://pusher.com/tutorials/chat-app-ruby-rails"&gt;Pusher&lt;/a&gt; have great tutorials on how to build with WebSockets. They're must-reads!&lt;/p&gt;

&lt;h2&gt;
  
  
  Caching
&lt;/h2&gt;

&lt;p&gt;The majority of load time gets used up in rendering views. This includes loading all CSS, JS and images, rendering out HTML from ERB files and more.&lt;/p&gt;

&lt;p&gt;One way to reduce a chunk of the load time is to identify parts of your application that you know will stay static for some amount of time or until an event occurs.&lt;/p&gt;

&lt;p&gt;In our example, it's obvious that until someone votes, the home page will essentially look the same for everyone (currently there is no option for users to edit their addresses). Let's try to cache the entire "home.html.erb" page until an event (vote) occurs.&lt;/p&gt;

&lt;p&gt;Let's use the &lt;a href="https://github.com/petergoldstein/dalli"&gt;Dalli gem&lt;/a&gt;. This uses &lt;a href="https://memcached.org"&gt;Memcached&lt;/a&gt; to quickly store and retrieve fragments of information. Memcached does not have a datatype for storage, leaving you to store essentially whatever you like.&lt;/p&gt;

&lt;h3&gt;
  
  
  1.  Caching Views
&lt;/h3&gt;

&lt;p&gt;The load time for 2000 records without caching, is 3500ms!&lt;/p&gt;

&lt;p&gt;Let's cache everything in "home.html.erb". It's simple,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ruby"&gt;&lt;code&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="sx"&gt;% cache &lt;/span&gt;&lt;span class="k"&gt;do&lt;/span&gt; &lt;span class="sx"&gt;%&amp;gt;
  &amp;lt;ul&amp;gt;&lt;/span&gt;
    &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="sx"&gt;% @people.each &lt;/span&gt;&lt;span class="k"&gt;do&lt;/span&gt; &lt;span class="o"&gt;|&lt;/span&gt;&lt;span class="n"&gt;person&lt;/span&gt;&lt;span class="o"&gt;|&lt;/span&gt; &lt;span class="sx"&gt;%&amp;gt;
      &amp;lt;li id="&amp;lt;%= person.id %&amp;gt;&lt;/span&gt;&lt;span class="s2"&gt;"&amp;gt;&amp;lt;%= render person %&amp;gt;&amp;lt;/li&amp;gt;
    &amp;lt;% end %&amp;gt;
  &amp;lt;/ul&amp;gt;
&amp;lt;% end %&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, install the Dalli gem and change the cache store in "development.rb" to:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ruby"&gt;&lt;code&gt;&lt;span class="n"&gt;config&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;cache_store&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="ss"&gt;:dalli_store&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then, if you're on Mac or Linux, simply start the Memcached service like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;memcached &lt;span class="nt"&gt;-vv&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now let's reload!!&lt;/p&gt;

&lt;p&gt;That took about 537ms! That's a 7x improvement in speed!&lt;/p&gt;

&lt;p&gt;You'll also see that there are far less MySQL queries because the entire HTML was stored in Memcached and read from there again, without ever pinging your database.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--OUClUd72--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/v1/images/blog/2020-01/image8.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--OUClUd72--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/v1/images/blog/2020-01/image8.png" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you pop on over to your application logs, you'll also see that this entire page was read from the cache.&lt;/p&gt;

&lt;p&gt;This example of course is just scratching the surface of view caching. You can cache the partial rendering and scope it to each person object (this is called &lt;a href="https://blog.appsignal.com/2018/03/20/fragment-caching-in-rails.html"&gt;fragment caching&lt;/a&gt;) or you can cache the entire collection itself (this is called &lt;a href="https://blog.appsignal.com/2018/04/03/russian-doll-caching-in-rails.html"&gt;collection caching&lt;/a&gt;). Further for more nested view rendering, you can perform &lt;a href="https://blog.appsignal.com/2018/08/14/rails-collection-caching.html"&gt;Russian Doll caching&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  2.  Caching Database Queries
&lt;/h3&gt;

&lt;p&gt;Another optimization you can do to improve view speed is to cache complex database queries. If your application shows stats and analytics, chances are that you are performing a complex database query to calculate each metric. You can store the output of that into Memcached and then assign a timeout to it. This means that after the timeout, the calculation will be performed again and then stored to the cache.&lt;/p&gt;

&lt;p&gt;For example, let's assume that the application needs to display the size of a users team. This could be a complex calculation involving counts of direct reportees, outsourced consultants and more.&lt;/p&gt;

&lt;p&gt;Instead of repeating the calculation over and over again, you can cache it!&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def team_size
  Rails.cache.fetch(:team_size, expires_in: 8.hour) do
    analytics_client = AnalyticsClient.query!(self)
    analytics_client.team_size
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This cache will auto-expire after 8 hours. Once that happens, the calculation will be performed again and the latest value will be cached for the next 8 hours.&lt;/p&gt;

&lt;h3&gt;
  
  
  3.  Database Indexes
&lt;/h3&gt;

&lt;p&gt;You can also speed up queries by using indexes. A simple query to fetch all addresses of a person,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;person.addresses
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This query asks the Address table to return all addresses where &lt;code&gt;person_id&lt;/code&gt; column is &lt;code&gt;person.id&lt;/code&gt;. Without indexes, the database has to inspect each row individually to check if it matches &lt;code&gt;person.id&lt;/code&gt;. However, with indexes, the database has a list of addresses that match a certain &lt;code&gt;person.id&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Here's a great resource to learn more about &lt;a href="https://semaphoreci.com/blog/2017/05/09/faster-rails-is-your-database-properly-indexed.html"&gt;database indexes&lt;/a&gt;!&lt;/p&gt;

&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;p&gt;In this post, we explored how to improve your Rails app's view performance by making improvements to database utilization, using third-party tools and services and restricting what users see.&lt;/p&gt;

&lt;p&gt;If you are looking to improve your app's performance, start out simple and keep measuring as you go along! Clean up your database queries, then create AJAX requests wherever you can, and finally cache as many views as possible. You can move on to WebSockets and database caching after that.&lt;/p&gt;

&lt;p&gt;However, be cautious—optimization is a slippery slope. You might find yourself as addicted as me!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;P.S. For monitoring the performance of your Rails app in production, &lt;a href="https://appsignal.com/"&gt;check out AppSignal's APM - built by Ruby devs for Ruby devs&lt;/a&gt;. 🚀&lt;/strong&gt; &lt;/p&gt;

&lt;p&gt;&lt;em&gt;Guest author Swaathi Kakarla is the co-founder and CTO at &lt;a href="https://www.skcript.com/"&gt;Skcript&lt;/a&gt;. She enjoys talking and writing about code efficiency, performance, and startups. She’s also the chapter lead for &lt;a href="https://developers.google.com/community/gdg"&gt;Google Developers Group, Chennai&lt;/a&gt;!&lt;/em&gt;&lt;/p&gt;

</description>
      <category>ruby</category>
      <category>rails</category>
      <category>beginners</category>
      <category>webdev</category>
    </item>
  </channel>
</rss>
