<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Chronus Engineering on Medium]]></title>
        <description><![CDATA[Stories by Chronus Engineering on Medium]]></description>
        <link>https://medium.com/@ChronusEngineering?source=rss-e33b22388069------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*mfKa-3DjQz7pn93SOdP2hQ.png</url>
            <title>Stories by Chronus Engineering on Medium</title>
            <link>https://medium.com/@ChronusEngineering?source=rss-e33b22388069------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 05:22:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ChronusEngineering/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Modern web testing with Playwright]]></title>
            <link>https://engineering.chronus.com/modern-web-testing-with-playwright-3b4d92c189fb?source=rss-e33b22388069------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b4d92c189fb</guid>
            <category><![CDATA[selenium-alternative]]></category>
            <category><![CDATA[playwright-automation]]></category>
            <category><![CDATA[playwrights]]></category>
            <category><![CDATA[selenium]]></category>
            <category><![CDATA[test-automation]]></category>
            <dc:creator><![CDATA[Chronus Engineering]]></dc:creator>
            <pubDate>Fri, 17 Nov 2023 08:51:05 GMT</pubDate>
            <atom:updated>2023-11-17T08:51:05.562Z</atom:updated>
            <content:encoded><![CDATA[<p>By <a href="https://www.linkedin.com/in/devanand-nagarajan-69b359ba/">Devanand Nagarajan</a> and <a href="https://www.linkedin.com/in/swetha-srinivasan-869129168/">Swetha Srinivasan</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/0*XruuaYZ1G48eypwd.png" /></figure><h3>Background</h3><p>At Chronus, we are in the continuous process of improving the existing automation infrastructure. We use Selenium as the primary automation framework for our E2E testing. The test script’s maintainability over time has added complexity. Hence, we needed to investigate other modern frameworks available in the market that we could use as our secondary test automation framework. Out of the tools/ framework explored, ‘Playwright’ seemed the propitious tool to look out for. In this article, we highlight some attractive features that make Playwright stand out.</p><h3>Reality pain points in automation</h3><p>Until recently, most web applications consisted of a standard web technology stack with a client-server model, HTML, CSS, and simple JS, where opening browsers, filling out a form, and doing simple clicks were sufficient. Automating these applications using Selenium was relatively easy.</p><p>Most of us have learned Selenium, and any test automation tools from any online platforms &amp; courses, and practiced the concepts over less complex websites. Automation would have seemed smooth sailing and effortless, right? Well, that’s not the case in reality! Modern web Applications have evolved with complex JS, Ajax, Microservices and Scalable web pages, where we need to tackle tricky and uncertain situations.</p><p>Selenium, the tool that has been ruling web automation testing for more than a decade, seems difficult to cope with evolving needs. Although Selenium is under active development and continues to dominate automation testing, the emergence of new tools like Playwright, Puppeteer, etc., have enraptured the automation market.</p><blockquote><strong>Key Features that Make Playwright a Powerful Automation Testing Tool</strong></blockquote><h3><strong><em>Timeout-free Automation</em></strong></h3><p>Modern web applications are designed in such a way that they respond to the user interaction dynamically depending upon the request. This asynchronous behavior makes things challenging to automate.</p><p><strong><em>The Flakiness conundrum: </em></strong>Most of us during automation have faced exceptions such as <em>StaleElementReferenceException</em>, <em>NoSuchElementException</em>, <em>and ElementNotVisibleException </em>and might have wondered w<em>hy my script passes sometimes and throws encounters other times.</em> One of the common reasons for a flaky failure is that elements we are trying to interact with may be available for interaction at unpredictable time intervals.</p><p>Playwright Actionability handles this automatically behind the scenes using its intelligent auto-wait mechanism for every action and makes tests more stable and reliable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*USmaGORlRqdFp8lb" /><figcaption>source: <a href="https://playwright.dev/docs/actionability">https://playwright.dev/docs/actionability</a></figcaption></figure><h3>Ubiquitous — Any Browser and Any Platform</h3><p>Cross-browser testing sounds like a straightforward process of running the automation scripts across different browsers by changing the driver invocation lines. But it is much more complex than that!</p><p>Browsers work differently because of their different base engines. The element we want to interact with might appear at different time intervals in different browsers depending on its implementation or work differently altogether. Despite having proper waiting mechanisms, the above scenario can lead to flaky failures across different browsers.</p><p>Playwright communicates with all the browsers using a single API. Hence, it’s guaranteed that a single script written in Playwright will consistently pass across its supported browser.</p><h3>Browser Context</h3><p>One of the standout features that Playwright offers is browser context, which provides a way to operate multiple independent browser sessions.</p><p>Before diving deep into the feature, let’s look at driver invocation lines in Selenium and Playwright.</p><pre>IN SELENIUM:<br>driver = new FirefoxDriver() // create browser instance<br>driver.get(&quot;https://www.google.com&quot;) // launch a tab in browser</pre><pre>IN PLAYWRIGHT:<br>browser = await chromium.launch() // create browser instance<br>context = await browser.newContext() // create browser context<br>page = await context.newPage() // launch a tab in browser context<br>page.goto(“https://www.google.com”)</pre><p><strong>So, What exactly is a ‘Context’ in Playwright?</strong></p><p>The browser contexts are like incognito tabs, which are independent and isolated within a browser instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*CQK1Wr4XRFuDzRZX" /></figure><p><strong>What’s the deal?</strong></p><p>There may be test scenarios that require testing user behavior with different roles. For example, consider an e-learning platform where a teacher sends a message to the student.</p><p>Selenium can perfectly handle the automation for this scenario but in a more complex way. In Selenium, we can achieve this scenario by logging in and logging out as different users consecutively or by initializing two browser instances for the two users.</p><p>However, Playwright can handle this situation more efficiently. In the same browser instance, we can create multiple browser contexts for respective users.</p><h3>Session Reuse</h3><p>Another excellent feature that Playwright offers is the ability to reuse the authentication state across tests.</p><p>Let’s assume there is a test file with ten different test scenarios. In each scenario, the same user logs in and performs some actions according to the test scenario.</p><p><strong>The traditional way</strong></p><pre>test.beforeEach(async({page}) =&gt; {<br>    await page.goto(‘https://www.testsite.com/&#39;)<br>    await page.click(‘#login’)<br>    await page.fill(‘input#username’, ‘user123’)<br>    await page.fill(‘input#password’, ‘user123’)<br>    const loginBtn = await page.locator(‘button.btn.btn-primary’,   {hasText:’Log in’})<br>    await loginBtn.click()<br>})<br><br>test1() {}<br>test2() {}<br>.<br>.<br>.<br>test10() {}</pre><p><em>The setback:</em> Given that it is the same user in the picture across all tests, redoing the login for every test will slow test execution.</p><p><strong>Time for Some Magic!</strong></p><pre>test.beforeAll(async ({ browser }) =&gt; {<br>  const context = await browser.newContext()<br>  const page = await context.newPage()<br>  await page.goto(&#39;https://www.testsite.com/&#39;)<br>  await page.click(&#39;#login&#39;)<br>  await page.fill(&#39;input#username&#39;, &#39;user123&#39;)<br>  await page.fill(&#39;input#password&#39;, &#39;user123&#39;)<br>  const loginBtn = await page.locator(&#39;button.btn.btn-primary&#39;,   {hasText:&#39;Log in&#39;})<br>  await loginBtn.click()<br>  await context.storageState({ path: &#39;state.json&#39; })<br>  webContext = await browser.newContext({ storageState: &#39;state.json&#39; })<br>  await page.close();<br>});</pre><p>After the first successful login, the signed-in state is captured and stored. Then, a new web context is created by injecting the stored state, which enables us to skip the login step for the rest of the tests. Voila!</p><p>We can achieve the above configuration at the test script level and the global level as well. Just imagine the time saved by skipping logins for the ’n’ number of tests.</p><h3>Visual Testing</h3><p>In addition to classical automation, visual testing is an important weapon to have in the arsenal. Most modern test automation tools have this ability, which is present in Playwright as well.</p><p>Playwright does visual testing by comparing screenshots of the page. In the initial run, we take the ‘<em>reference</em>’ screenshots, and the subsequent runs will be compared against the reference screenshots.</p><p><strong>Alright, ready for a challenge?</strong></p><p>Try finding out if there is any difference between the below ‘<em>Reference Screenshot</em>’ and ‘<em>Actual Screenshot</em>’</p><p><strong>Reference Screenshot:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/0*_eVRudWkj_yeHKzz" /></figure><p><strong>Actual Screenshot:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/0*ViA47FlCarSRI1ky" /></figure><p><strong>No success yet?</strong></p><p><strong>The difference:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/0*ZHN0Jqq28Pxb406O" /></figure><p>There is a minor variation in reference and actual screenshot, which is the timestamp that is displayed at the top right corner of the page. We could clearly notice that the tool highlights the “<em>difference area</em>”, which is difficult to spot with the naked eye.</p><h3>Debugging Made Super Easy!</h3><p>Prominent difference could be straight away felt when debugging scripts in Playwright when compared with Selenium / other automation tools.</p><p><strong>Playwright Inspector</strong></p><p>Playwright Inspector is a GUI tool that helps to debug the scripts. A Few of the useful features are,</p><ul><li>Pick locators</li><li>Record and Replay</li><li>Robust logging</li><li>Breakpoints</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*W3nqqID91DpMBkxi" /><figcaption>Inspector tool in Action</figcaption></figure><p><strong>Playwright Tracer</strong></p><p>Playwright Trace Viewer is a GUI tool that enables one to explore recorded Playwright traces after the script has run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*igsV8CoK8G_E0vuN" /></figure><h3>Closing Thoughts</h3><p>So, how does one choose the right tool? One of the critical aspects that determine the tool selection is subjective to the scenario in which they are used.</p><p>However, when we focus the testing on how users will interact with a given website, Playwright is much more powerful than the conventional web driver, given the features discussed above.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b4d92c189fb" width="1" height="1" alt=""><hr><p><a href="https://engineering.chronus.com/modern-web-testing-with-playwright-3b4d92c189fb">Modern web testing with Playwright</a> was originally published in <a href="https://engineering.chronus.com/">Chronus Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migrating to Multi-DNS using DNSControl]]></title>
            <link>https://engineering.chronus.com/migrating-to-multi-dns-using-dnscontrol-eb1d02fac57c?source=rss-e33b22388069------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb1d02fac57c</guid>
            <category><![CDATA[dns-control]]></category>
            <category><![CDATA[dns]]></category>
            <category><![CDATA[dnsimple]]></category>
            <category><![CDATA[multi-dns]]></category>
            <category><![CDATA[route-53]]></category>
            <dc:creator><![CDATA[Chronus Engineering]]></dc:creator>
            <pubDate>Mon, 05 Jun 2023 11:01:15 GMT</pubDate>
            <atom:updated>2023-06-05T11:01:15.373Z</atom:updated>
            <content:encoded><![CDATA[<p>By <a href="http://www.linkedin.com/in/subramanianers">Subramanian E R S</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/0*xj8IJRsnsHcsROqk.png" /></figure><h3>Introduction</h3><p>The most important component in any application infrastructure is arguably the Domain Name System(DNS) component. If something is wrong with your DNS, users will not be able to access your application. There are multiple cloud DNS solutions out there like AWS Route53, Cloudflare, DNSimple, Azure DNS, etc. And having occasional downtimes/issues with these cloud DNS solutions is not so uncommon. This calls for a multi-DNS approach for improved availability and resiliency in your application infrastructure. Multiple DNS providers means more management overhead. But at Chronus, we migrated from a single-DNS (AWS Route53) to multi-DNS (AWS Route53 and DNSimple) with minimum management overhead using DNSControl.</p><h3>Why not use DNS Zone Transfers?</h3><p>Since we are considering the management of DNS records across multiple providers, the most common solution to pop up is DNS Zone Transfers. DNS Zone transfers use the AXFR protocol to replicate DNS records across multiple DNS servers. Upon its configuration, any changes made to the primary DNS server are automatically replicated to the secondary DNS servers. But not all DNS providers support this feature. Route53 and Google DNS are two examples of primary DNS providers that do not support zone transfers. In addition, there are a few security and efficiency risks involved, and one would also lose out on the perks offered by the DNSControl solution as discussed in the following sections.</p><h3>DNSControl Migration</h3><p><a href="https://stackexchange.github.io/dnscontrol/">DNSControl</a> is an opensource CLI tool that can be used to manage DNS records across multiple DNS providers. DNSControl also facilitates easy migration of DNS records from an existing DNS provider zone to a newly created one.</p><h4>Setup</h4><ul><li>Create a folder in local to store DNSControl configuration and DNS records. Preferably, also create a private Github repository to allow for collaboration with other teams/members.</li></ul><pre>mkdir ChronusDNSControl<br>cd ChronusDNSControl<br>mkdir zones</pre><ul><li>Download and install the latest and stable prebuilt binary assets from the <a href="https://github.com/StackExchange/dnscontrol/releases">Releases</a> page.</li><li>Create a file creds.json in the below format:</li></ul><pre>{<br>    &quot;global_r53&quot;: {<br>      &quot;KeyId&quot;: &quot;&lt;AWS_ACCESS_KEY&gt;&quot;,<br>      &quot;SecretKey&quot;: &quot;&lt;AWS_SECRET_KEY&gt;&quot;<br>    },<br>    &quot;global_dnsimple&quot;: {<br>      &quot;token&quot;: &quot;&lt;DNSIMPLE_ACCOUNT_TOKEN&gt;&quot;<br>    }<br>}</pre><p>The key names — <strong>global_r53</strong> and <strong>global_dnsimple</strong> are only placeholders, unless you have multiple credentials with the same DNS provider.</p><h4>Fetch existing records for migration</h4><p>The intent here is to fetch all the existing DNS records from Route53 in a single file in an easily readable and processable format (JSON).</p><ul><li>The DNS records need to be pulled in from the existing Route53 record zone</li></ul><pre>dnscontrol get-zones --format tsv --out=chronus.com.tsv global_r53 ROUTE53 chronus.com</pre><p>The above command pulls in the existing records from the domain name <strong>chronus.com </strong>and stores in the tab-separated values file — <strong>chronus.com.tsv</strong>.</p><ul><li>Though, we have the DNS records in a tsv file, it is easier to work with json format.</li></ul><pre>cat chronus.com.tsv | jq --raw-input --slurp &#39;split(&quot;\n&quot;) | map(split(&quot;\t&quot;)) | .[0:-1] | map( { &quot;record_name&quot;: .[0], &quot;value&quot;: .[5], &quot;type&quot;: .[4], &quot;ttl&quot;: .[2] } )&#39; &gt; zones/chronus.com.json</pre><p>The above command converts the tsv records to json format and stores them in the file <strong>chronus.com.json</strong>.</p><ul><li>The tsv file (chronus.com.tsv) is no longer required and can now be removed.</li></ul><pre>rm chronus.com.tsv</pre><h4>Custom code for handling multiple DNS providers</h4><p>Different DNS providers demand different formats for creating the DNS records. Hence, while managing DNS records across different providers, custom code is required to reformat the DNS records to suit the different DNS providers.</p><pre>function getRecords(zoneName) {<br><br>// Read and return JSON records from the JSON file(chronus.com.json)<br>  var domains = ...<br><br>// Declare separate arrays to insert records requiring different formats<br>  var nonAliasRecords = [], route53AliasRecords = [],  dnsimpleAliasRecords = [], route53SRVRecords = [], dnsimpleSRVRecords = []<br>  <br>  for (var i = 0; i &lt; domains.length; i++) {<br>    // Custom code for pushing records into respective arrays<br>  }<br><br>  return [nonAliasRecords, route53AliasRecords, dnsimpleAliasRecords, route53SRVRecords, dnsimpleSRVRecords]<br>}</pre><p>Let us try to understand the above code snippet in parts:</p><ul><li>The function <strong>getRecordsFromZoneFile</strong> retrieves the JSON array present in the chronus.com.json file(zoneName = chronus)</li><li>The function <strong>getRecords</strong> loops through the retrieved JSON records and adds them to the different record sets</li><li>In Chronus’ use case, the DNS record formats for SRV and ALIAS records were found to be different in Route53 and DNSimple. Hence, we created different arrays so that they can be processed separately (route53AliasRecords, dnsimpleAliasRecords, route53SRVRecords, dnsimpleSRVRecords). If you find more record formats being different for the DNS providers you choose, you have to create different arrays to process them separately as well</li></ul><h4>DNSControl Functionality Code</h4><p>The above custom code should return all the DNS records suited for different DNS providers. Now the main DNSControl functionality code can be written to import these DNS records</p><pre>// Define the domain registrars of the differnt DNS providers<br>var R53 = NewDnsProvider(ROUTE53_ACCOUNT, DNS_PROVIDERS.ROUTE53);<br>var DNSIMPLE = NewDnsProvider(GLOBAL_DNSIMPLE, DNS_PROVIDERS.DNSIMPLE);<br>var REG_CHANGEME = NewRegistrar(THIRD_PARTY, DNS_PROVIDERS.NONE);<br>var allRecords = getAllRecords(zoneName)<br>var nonAliasRecords = allRecords[0]<br>var aliasRecordsR53 = allRecords[1]<br>var aliasRecordsDNSimple = allRecords[2]<br>var srvRecordsR53 = allRecords[3]<br>var srvRecordsDNSimple = allRecords[4]<br># Import records into Route53<br>D(zoneName + &quot;!route53&quot;, REG_CHANGEME, DnsProvider(R53),&lt;INSERT_TTL_IN_SECONDS_HERE&gt;,aliasRecordsR53,nonAliasRecords,srvRecordsR53)# Import records into DNSimple<br>D(zoneName + &quot;!dnsimple&quot;, REG_CHANGEME, DnsProvider(DNSIMPLE),&lt;INSERT_TTL_IN_SECONDS_HERE&gt;,aliasRecordsDNSimple,nonAliasRecords,srvRecordsDNSimple)</pre><p>Place the above code snippet into a file named <strong>dnsconfig.js</strong>. You can see here that we used the function <strong>getAllRecords</strong> containing the custom logic to fetch all DNS records in the right formats for the DNS providers used. The next step was simply to pass these list of records in a DNSControl friendly syntax(D records) to create the records.</p><p>We have taken advantage of the <strong>Split Horizon DNS </strong>feature supported by DNSControl — (<strong>zoneName + “!route53” </strong>and<strong> zoneName + “!dnsimple”</strong>). This allows us to import the DNS records belonging to the same domain name(chronus.com) across different DNS providers. This would not be possible without Split Horizon DNS.</p><h4>Importing DNS Records using DNSControl</h4><p>Having completed developing the custom solution using DNSControl, it is now time to import the DNS records into the different DNS providers.</p><pre>dnscontrol preview --v zoneName=chronus.com</pre><p>The preview command should output the changes being made to the DNS records.</p><pre>dnscontrol push --v zoneName=chronus.com</pre><p>The push command makes the changes displayed in the preview command’s output.</p><p>Thus, the DNS records in an existing DNS provider can be migrated to a new DNS provider.</p><h4>Managing DNS Records using DNSControl</h4><p>Having imported the records to the different DNS providers, you can now continue using DNSControl to add, modify or delete DNS records in multiple DNS providers at the same time by simply making changes in the JSON file. The schema for adding new DNS records for different record types in the JSON file (zones/chronus.com.json) can be found below:</p><ul><li>A, AAAA, CNAME, TXT</li></ul><pre>{<br>    &quot;record_name&quot;: &quot;&lt;record_name&gt;&quot;,<br>    &quot;value&quot;: &quot;&lt;record_value/target&gt;&quot;,<br>    &quot;type&quot;: &quot;&lt;record_type - A, AAAA, CNAME or TXT&gt;&quot;,<br>    &quot;ttl&quot;: &quot;&lt;TTL&gt;&quot;<br>}</pre><ul><li>CAA</li></ul><pre>{<br>    &quot;record_name&quot;: &quot;&lt;record_name&gt;&quot;,<br>    &quot;value&quot;: &quot;&lt;flag&gt; &lt;tag&gt; &lt;record_value/target&gt;&quot;,<br>    &quot;type&quot;: &quot;CAA&quot;,<br>    &quot;ttl&quot;: &quot;&lt;TTL&gt;&quot;<br>}</pre><ul><li>MX</li></ul><pre>{<br>    &quot;record_name&quot;: &quot;&lt;record_name&gt;&quot;,<br>    &quot;value&quot;: &quot;&lt;record_value/target&gt; &lt;priority&gt; &lt;weight&gt; &lt;port&gt;&quot;,<br>    &quot;type&quot;: &quot;MX&quot;,<br>    &quot;ttl&quot;: &quot;&lt;TTL&gt;&quot;<br>}</pre><ul><li>SRV</li></ul><pre>{<br>    &quot;record_name&quot;: &quot;&lt;record_name&gt;&quot;,<br>    &quot;value&quot;: &quot;&lt;priority&gt; &lt;weight&gt; &lt;port&gt; &lt;record_value/target&gt;&quot;,<br>    &quot;type&quot;: &quot;SRV&quot;,<br>    &quot;ttl&quot;: &quot;&lt;TTL&gt;&quot;<br>}</pre><ul><li>ALIAS</li></ul><pre>{<br>    &quot;record_name&quot;: &quot;&lt;record_name&gt;&quot;,<br>    &quot;value&quot;: &quot;&lt;record_value/target&gt; atype=&lt;alias_type&gt; zone_id=&lt;hostedZoneId&gt;&quot;,<br>    &quot;type&quot;: &quot;R53_ALIAS&quot;,<br>    &quot;ttl&quot;: &quot;&lt;TTL&gt;&quot;<br>}</pre><h3>Conclusion</h3><p>And that is how we used DNSControl@Chronus to migrate and manage DNS records across different DNS providers like Route53 and DNSimple from a single place with minimum overhead. It also has certain additional advantages:</p><ul><li>Combining with Git for version control to track changes</li><li>Adopting Code reviews/Pull requests to prevent accidental updates</li><li>Buidling a CI/CD pipeline to streamline changes and more</li></ul><p>DNSControl is also extendable, meaning you can integrate other DNS providers to be used along with the existing ones. To learn more about DNSControl, check out the links in the references section below.</p><h3>References</h3><ul><li><a href="https://stackexchange.github.io/dnscontrol/">https://stackexchange.github.io/dnscontrol/</a></li><li><a href="https://github.com/StackExchange/dnscontrol">https://github.com/StackExchange/dnscontrol</a></li><li><a href="https://stackexchange.github.io/dnscontrol/getting-started">https://stackexchange.github.io/dnscontrol/getting-started</a></li><li><a href="https://www.digitalocean.com/community/tutorials/how-to-deploy-and-manage-your-dns-using-dnscontrol-on-debian-10">https://www.digitalocean.com/community/tutorials/how-to-deploy-and-manage-your-dns-using-dnscontrol-on-debian-10</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb1d02fac57c" width="1" height="1" alt=""><hr><p><a href="https://engineering.chronus.com/migrating-to-multi-dns-using-dnscontrol-eb1d02fac57c">Migrating to Multi-DNS using DNSControl</a> was originally published in <a href="https://engineering.chronus.com/">Chronus Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[EC2 Autoscaling using custom policies]]></title>
            <link>https://engineering.chronus.com/autoscaling-aws-ec2-web-servers-chronus-3d1a67789509?source=rss-e33b22388069------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d1a67789509</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[scaling-policies]]></category>
            <category><![CDATA[autoscaling]]></category>
            <category><![CDATA[ec2]]></category>
            <category><![CDATA[web-server]]></category>
            <dc:creator><![CDATA[Chronus Engineering]]></dc:creator>
            <pubDate>Fri, 01 Apr 2022 07:20:12 GMT</pubDate>
            <atom:updated>2022-06-29T18:50:51.793Z</atom:updated>
            <content:encoded><![CDATA[<p>By <a href="http://www.linkedin.com/in/subramanianers">Subramanian E R S</a> and <a href="https://www.linkedin.com/in/kiran-gowtham">Kiran Gowtham</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/0*LC6tTVKxrV04OJo3.png" /></figure><h4>Introduction</h4><p>In today’s world of unprecedented and flash workloads, manually launching new web servers to handle increasing traffic is no longer the way to go. An automated setup is of the highest need in any application infrastructure to ensure maximum <strong>availability, durability and scalability</strong>. Let us take a look at how AWS EC2 Autoscaling fits in and dive deep into its configuration for Web servers@Chronus.</p><h4>What is EC2 Autoscaling?</h4><p>AWS offers EC2 Autoscaling to automatically add or remove servers from your application infrastructure based on a set of predetermined policies and requirements. The constituents of an EC2 Autoscaling setup can be found below.</p><h4>Players on the Field</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wiRryIyzMbiFILUZ.png" /><figcaption>Web Scaling Architecture@Chronus</figcaption></figure><h4>Cloudwatch Metrics</h4><p>Cloudwatch metrics contain information about the state and performance of your resources on the AWS cloud. Some of these examples include but are not limited to CPU Utilization, total free memory available, disk usage. In addition to the plethora of Cloudwatch metrics that are readily available in AWS, custom metrics can also be pushed to Cloudwatch from your EC2 servers.</p><h4>Cloudwatch Alarms</h4><p>Cloudwatch alarms in AWS help dictate the next course of action based on the current state of a specific Cloudwatch metric. Minimum and maximum thresholds and the action to be taken can be configured in Cloudwatch alarms. One such example could be to create a Cloudwatch alarm to monitor the CPU Utilization Cloudwatch metric of an EC2 server and trigger an email action when the CPU Utilization exceeds the set alarm threshold.</p><h4>Autoscaling Groups</h4><p>An Autoscaling Group is the crux of the EC2 Autoscaling setup in AWS. An Autoscaling group is responsible for managing a set of EC2 instances according to some predetermined scaling policy.</p><h4>AMI (Amazon Machine Image)</h4><p>AMI defines what is present inside an EC2 instance. It can dictate the Operating System, the type of services installed and even some predefined data that you would want in your EC2 instance at the point of server creation. An AMI can be both obtained from the AWS Marketplace or custom-built by the users.</p><p><strong>Note: </strong>An important part of using an AMI is making sure that you update it when deployment is complete so that the newly autoscaled servers will have the latest version of the application. At Chronus, this is done with the help of a Lambda function that gets invoked at the end of every deployment.</p><h4>Launch Template</h4><p>If an ASG defines how and when to scale, the Launch template defines what exactly to scale. The Launch template would contain instance configuration information like what AMI to use, the EC2 instance type, SSH key-pair, custom launch scripts, etc.</p><p>Having understood the constituents of an EC2 Autoscaling setup, let us dive deep into the Scaling policies used @ Chronus.</p><h4>Scaling Policies @ Chronus</h4><p>Chronus EC2 web servers primarily processes two types of requests, namely, web requests and chat requests and a total of 4 dynamic scaling policies. Each scaling policy has its own threshold and serves a purpose of its own. All the metrics are provided through CloudWatch. A generic assumption behind all the metrics threshold mentioned below is that the value of the threshold should be less than the critical level. This is necessary because even with custom-built AMIs, it takes at least a few minutes to have the newly autoscaled servers ready to service requests.</p><h4>CPU Based Scaling</h4><p>The most primitive and readily available metric for any EC2 autoscaling setup is CPU Utilization percentage. Data for this metric is provided by AWS and available through AWS Cloudwatch for each EC2 instance. This is the only scaling policy that is <strong>common for both web and chat requests</strong>.</p><blockquote><strong>Threshold:</strong> AWS will consider CPU Util across available EC2 servers in the ASG and strives to maintain an average Util% value of <strong>80</strong>.</blockquote><blockquote><strong>Usage: </strong>CPU Util% metric will help to scale in the event of high CPU Utilization in the web servers</blockquote><h4>Requests in Queue</h4><p>This is a custom-built scaling policy catering to scaling the servers solely based on the number of web requests. All web servers maintain a request queue for processing the requests. RIQ (Requests in Queue) is a custom metric that is pushed to CloudWatch by Chronus web servers.</p><blockquote><strong>Threshold:</strong> Based on historical data for RPM, average response time and the number of web processes present, Chronus arrived at a value of more than <strong>10</strong> requests per minute</blockquote><blockquote><strong>Usage: </strong>RIQ scaling would take place when there is a spike in RPM due to increased traffic or slow request processing</blockquote><h4>Percentage Capacity Used</h4><p>The scaling policies discussed are reactive scaling policies. But, PCU or Percentage Capacity Used scaling policy is a preemptive scaling policy that makes use of a custom Cloudwatch metric designed and developed by Chronus. Like RIQ, PCU scaling policy caters to web request scaling only. <strong><em>So what is PCU?</em></strong></p><p>PCU is a custom metric used to determine whether the web servers are processing the requests to their maximum capacity. It is calculated as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/0*ZYHmnfqXseUgbOeK.png" /><figcaption>The formula for calculating PCU Metric Value (This formula applies only to single-threaded applications)</figcaption></figure><blockquote><strong>Threshold:</strong> When the web-server processes are working at more than <strong>80%</strong> of its processing power, the scaling alarm will be triggered.</blockquote><blockquote><strong>Usage:</strong> It helps to preemptively scale our web-servers with the assumption that there is an increase in requests and our servers are already servicing these requests to their maximum potential</blockquote><p>Let us take a look at a couple of scenarios to understand the above scaling formulae:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/0*rtfDARVnxmJ3Cua7.png" /><figcaption>Available capacity of 120 seconds (2 minutes) for processing</figcaption></figure><h4>Scenario 1:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/0*S4sdR5OSP02gPwJF.png" /><figcaption>Scenario 1: PCU value of 23.33%</figcaption></figure><p>In Scenario 1, no scaling action is performed as the calculated PCU value of <strong>23.33%</strong> is lower than the threshold value of 80%.</p><h4>Scenario 2:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/0*6uA6xVIsJVu-6tgm.png" /><figcaption>Scenario 2: PCU value of 84.58%</figcaption></figure><p>In Scenario 2, a scale-out action is performed as the calculated PCU value of <strong>84.58%</strong> is greater than the threshold value of 80%.</p><h4>Web-socket Connections Count</h4><p>The final scaling policy is an <strong>exclusive chat request based scaling policy</strong>. Chronus uses socket connections to send and receive chat messages. Hence the number of socket connections established provides us with the load on the chat application. Like PCU, the Web-socket Connections (WCC) policy is also a preemptive scaling policy. WCC is also a custom metric pushed by the web servers to Cloudwatch.</p><blockquote><strong>Threshold:</strong> An appropriate threshold value of socket connections was adopted to configure scaling actions</blockquote><blockquote><strong>Usage:</strong> During the excessive use of the chat application, WCC scaling policy scales out to handle the traffic surge</blockquote><h4><strong>Future Scope</strong></h4><h4>Autoscaling Warm Pool</h4><p>Currently, Web server autoscaling@Chronus is triggered based on a predefined set of multiple metrics and scaling policies. At present, the scaling policies are either preemptive or real-time. Irrespective of the type of metric or scaling policy, it would take at least 5 minutes for the new server to start servicing requests from the start of the scaling out action.</p><p>This delay is mainly attributed to the time taken to create a new EC2 web server and run server configuration steps like code deployment, setting up logrotate, etc. This delay of 5 minutes might prove to be costly at times of flash loads.</p><p>To avoid such delays, Chronus will explore <strong>AWS Auto-Scaling Warm Pool</strong>. This would allow for booting up a pool of additional servers and having them in standby mode. Hence, whenever a scaling out event is triggered, instead of creating a new server, AWS will add the instance from this warm pool to the Autoscaling Group. This will help in reducing the time taken to set up the web servers considerably.</p><h4>ML-based Scaling</h4><p>All the discussed scaling policies thresholds’ are preemptively decided by Chronus based on historical data. Chronus looks forward to using ML models to predict scaling scenarios and the corresponding scaling factors.</p><h4>Conclusion</h4><p>Though we have described all the core components and the scaling policies@Chronus, there is a key point to keep in mind — <strong><em>any Autoscaling architecture should be a continuously evolving one</em></strong>. More components/practices can always be integrated for faster/smoother scaling. Changes in existing scaling policies or the addition of new ones should be accommodated as the customer traffic load evolves over time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d1a67789509" width="1" height="1" alt=""><hr><p><a href="https://engineering.chronus.com/autoscaling-aws-ec2-web-servers-chronus-3d1a67789509">EC2 Autoscaling using custom policies</a> was originally published in <a href="https://engineering.chronus.com/">Chronus Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling Race Conditions in Rails Application]]></title>
            <link>https://engineering.chronus.com/handling-race-conditions-in-ruby-on-rails-application-7c393dc631dd?source=rss-e33b22388069------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c393dc631dd</guid>
            <category><![CDATA[pessimistic-locking]]></category>
            <category><![CDATA[optimistic-locking]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[race-condition]]></category>
            <category><![CDATA[advisory-lock]]></category>
            <dc:creator><![CDATA[Chronus Engineering]]></dc:creator>
            <pubDate>Fri, 01 Apr 2022 07:17:44 GMT</pubDate>
            <atom:updated>2022-04-01T07:17:44.045Z</atom:updated>
            <content:encoded><![CDATA[<p>By <a href="https://www.linkedin.com/in/veera213">Veera Narayana</a> &amp; <a href="https://www.linkedin.com/in/m-santosh-dora">M. Santosh Dora</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*slX1rZQaXaFH_GQ7.png" /></figure><h3>What are Race conditions?</h3><ul><li>Race conditions are undesirable situations caused when the concurrent execution of the code causes unexpected results, compared to the scenario of having them executed sequentially.</li><li>Race conditions occur when two or more concurrent processes access shared resources simultaneously.</li></ul><h4>Example</h4><p><strong>Refreshing User profile</strong></p><ul><li>Let’s assume a scenario where the user updated her profile twice, and the system is processing both profile update requests using two different background jobs. If two jobs run at the same time, we will quite likely have the following scenario:</li></ul><pre>def refresh_user_in_background(user, details_to_update)<br>  create_background_job do<br>    refresh_user(user, details_to_update)<br>  end<br>end</pre><pre>def refresh_user(user, details_to_update)<br>  user_profile = UserProfile.find_or_create_by(user)<br>  # Refresh User Profile<br>end</pre><blockquote><strong>Request_1:</strong> Checks if user profile record exists and proceeds as no user profile record is found.</blockquote><blockquote><strong>Request_2</strong>: Checks if user profile record exists and proceeds as no user profile record is found.</blockquote><blockquote><strong>Request_1</strong>: Creates a new user profile record for the user.</blockquote><blockquote><strong>Request_2:</strong> Creates a new user profile record for the user.</blockquote><ul><li>We will end up creating two user profile records for the same user.</li></ul><h3>Techniques to prevent race conditions</h3><p><strong>Things to consider:</strong></p><ul><li>Considered MySQL as the underlying database.</li><li>MySQL runs transactions at the “Repeatable Read” isolation level by default.</li><li>There is an option to set the isolation level to Serializable (highest level) to prevent race conditions overall.</li><li>But the problem is there will be performance implications since MySQL internally uses locks for every transaction.</li><li>Instead of changing the isolation level, we can use the following techniques to prevent the following types of race conditions.</li></ul><h3>1. Unique index on columns</h3><p><strong><em>i) find_or_create_by:</em></strong></p><pre>class AddUniqueIndexToUserId &lt; ActiveRecord::Migration<br>  def change<br>    add_unique_index :user_id<br>  end<br>end</pre><ul><li>If we have a unique index on the user_id column for the user profile table, the database will prevent the creation of duplicate user profile records.</li><li>Database halts the execution of code with uniqueness exception.</li><li>This way, we can prevent the creation of two user profile records.</li><li>The problem with find_or_create_by is that Request_2 from the above example will not refresh the user profile record since the program stops with a uniqueness error.</li></ul><p><strong><em>ii) create_or_find_by:</em></strong></p><pre>def refresh_user_in_background(user, details_to_update)<br>  create_background_job do<br>    refresh_user(user, details_to_update)<br>  end<br>end</pre><pre>def refresh_user(user, details_to_update)<br>  user_profile = UserProfile.create_or_find_by(user)<br>  # Refresh User Profile<br>end</pre><ul><li>Rails 6 added <a href="https://github.com/rails/rails/pull/31989">create_or_find_by</a> and <a href="https://github.com/rails/rails/pull/31989">create_or_find_by!</a>. These methods rely on unique constraints on the database level. If the creation fails, it is because of the unique constraints on given columns, and it will try to find the record using find_by!.</li><li>When we use create_or_find_by, we will have the following scenario:</li></ul><blockquote><strong>Request_1:</strong> Creates user profile record</blockquote><blockquote><strong>Request_2</strong>: Tries to create but fails with an uniqueness exception.</blockquote><blockquote><strong>Request_1</strong>: Finds user profile record for the user.</blockquote><blockquote><strong>Request_2:</strong> Finds user profile record for the user.</blockquote><ul><li>This way, we prevent race conditions to happen.</li></ul><h4>When to Use:</h4><ul><li>Use create_or_find_by in scenarios where creating a new record is more likely than updating the record and find_or_create_by in the opposite scenario.</li></ul><h3>2. Optimistic Locking</h3><p>Optimistic locking is a strategy where you read a record, take note of a version number and check that the version hasn’t changed before you write the record back.</p><ul><li>Let’s assume a user tries to get a refund twice for a single item, roughly at the same time, and the system processes two requests simultaneously. We will quite likely have the following scenario:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca0c58feb5cb0132ce3019eda82359a7/href">https://medium.com/media/ca0c58feb5cb0132ce3019eda82359a7/href</a></iframe><blockquote><strong>Request_1:</strong> Checks if refund is made and proceeds as refund is not done.</blockquote><blockquote><strong>Request_2:</strong> Checks if refund is made and proceeds as refund is not done.</blockquote><blockquote><strong>Request_1:</strong> Arrive at the code that creates a refund request for the user.</blockquote><blockquote><strong>Request_2:</strong> Arrive at the code that creates a refund request for the same user.</blockquote><ul><li>We will end up refunding twice for a single amount.</li><li>Rails provide a way to handle this by using lock_version in models. ActiveRecord will prevent an update of the record if the lock_version for that particular record has changed, by raising ActiveRecord::StaleObjectError.</li><li>This way, we can prevent race conditions using this technique.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ee1200b4b1f61d632676b489e41d8ad/href">https://medium.com/media/8ee1200b4b1f61d632676b489e41d8ad/href</a></iframe><ul><li>So, after adding the lock version, the behavior is the following:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/94f069114ee0e537fe437ecd6ddca6f5/href">https://medium.com/media/94f069114ee0e537fe437ecd6ddca6f5/href</a></iframe><ul><li><strong>Drawback: </strong>Rollback transactions will be executed after ActiveRecord::StaleObjectError is raised.</li></ul><h4>When to use:</h4><ul><li>This locking is suitable when the cost of rolling back a transaction is significantly less.</li><li>Use optimistic locking in the case when users want to be notified about race conditions<strong> </strong>when updating the object.</li></ul><h3><strong>3. Pessimistic Locking (Row-level locking)</strong></h3><ul><li>Pessimistic locking is when you lock the record for your exclusive use until you have finished with it.</li><li>We will lock the record after reading it, such that other transactions won’t be able to update/delete the same record.</li><li>We can solve the previously mentioned refund problem by adding an exclusive lock as shown below:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/007b152baa0662887b0a023c53bf03f1/href">https://medium.com/media/007b152baa0662887b0a023c53bf03f1/href</a></iframe><ul><li>When we lock user records using the lock method, other transactions won’t be able to update/delete the same. This way, we can prevent race conditions using this technique.</li><li>Under the hood, ActiveRecord will perform a <strong>SELECT FOR UPDATE</strong> query, which will prevent any modification of that record within any other transaction. Also, it internally reloads the record (with reload method). That way, we can be sure we operate on the most recent data.</li><li>With this approach, it is possible to have a deadlock: transaction A has lock 1, transaction B has lock 2, and transaction A is trying to acquire lock 2 while transaction B is trying to acquire lock 1.</li><li>A simple way to avoid deadlocks is to establish a rule that you always have to acquire all the locks in ascending order. If you <em>know</em> you need lock numbers 1 and 2, you <em>must</em> acquire them in that order.</li></ul><h4>When to use:</h4><ul><li>Pessimistic locking is suitable when the cost of rolling back a transaction is very high or when the rollback option is not possible (like when it involves calling 3rd party APIs).</li></ul><h3>4. Advisory Lock</h3><ul><li>An advisory lock is a cooperative lock.</li><li>An advisory lock is based on the concept that all processes will use an agreed-upon convention to cooperate to use a shared resource. That means the process that holds the lock can only use the shared resource.</li><li>Advisory locks can easily prevent the concurrent execution of the code.</li><li>Imagine a situation where you need to fetch the current amount in the account, modify the amount, and reinstate the correct value in the account after the modification. To be more precise, we have some background job workers to handle this logic, and the code looks like this:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ee4f68ed4a46745f53b18d8c1edd327/href">https://medium.com/media/7ee4f68ed4a46745f53b18d8c1edd327/href</a></iframe><ul><li>If <em>handle_update_transaction</em> is executed concurrently by n workers, depending on when the amount is fetched, and modification and updates happen, we can get different results. This inconsistency would not have occurred if the workers had executed the job sequentially.</li><li>This can be handled by using an advisory lock, which prevents the concurrent execution of the code.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff80830c8a38dd0db9eaa707c5a38914/href">https://medium.com/media/ff80830c8a38dd0db9eaa707c5a38914/href</a></iframe><ul><li>Now with the lock “update_account_#{user_id}_lock’, what happens is all the process that needs to acquire the same lock will have to wait for the existing lock to be released.</li><li>With this, we can guarantee that only a single background job can access the code simultaneously, solving our inconsistency problem.</li></ul><h4>When to use:</h4><ul><li>Use Advisory locks to handle concurrency control mechanisms at the application level.</li><li>Also, if we need to restrict multiple workers to access the same piece of code at a time, you should use advisory locks.</li></ul><h3><strong>Conclusion</strong></h3><ul><li>If not appropriately handled, <strong>Race conditions</strong> can have terrible consequences. Fortunately, we can easily avoid these issues by understanding the possible scenarios and strategies to mitigate them.</li><li>Before choosing any approach, understand the scenario for which it is to be used and the tradeoffs it carries.</li></ul><h3><strong>Reference</strong></h3><ol><li><a href="https://karolgalanciak.com/blog/2020/06/07/race-conditions-on-rails/">https://karolgalanciak.com/blog/2020/06/07/race-conditions-on-rails/</a></li><li><a href="https://api.rubyonrails.org/classes/ActiveRecord/Locking/Pessimistic.html">https://api.rubyonrails.org/classes/ActiveRecord/Locking/Pessimistic.html</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c393dc631dd" width="1" height="1" alt=""><hr><p><a href="https://engineering.chronus.com/handling-race-conditions-in-ruby-on-rails-application-7c393dc631dd">Handling Race Conditions in Rails Application</a> was originally published in <a href="https://engineering.chronus.com/">Chronus Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Improve Page Load Time Using Brotli Compression]]></title>
            <link>https://engineering.chronus.com/improve-page-load-time-using-brotli-compression-63fdc0344491?source=rss-e33b22388069------2</link>
            <guid isPermaLink="false">https://medium.com/p/63fdc0344491</guid>
            <category><![CDATA[cloudfront]]></category>
            <category><![CDATA[benchmark]]></category>
            <category><![CDATA[compression]]></category>
            <category><![CDATA[page-speed]]></category>
            <category><![CDATA[brotli]]></category>
            <dc:creator><![CDATA[Chronus Engineering]]></dc:creator>
            <pubDate>Mon, 13 Sep 2021 11:28:17 GMT</pubDate>
            <atom:updated>2021-09-13T11:28:17.796Z</atom:updated>
            <content:encoded><![CDATA[<p>By <a href="https://www.linkedin.com/in/sudharsan-pattan-977a1619b/">Sudharsan Pattan</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EbJaIgkoFuOGN0oa.png" /></figure><p>Compression is an effective way to improve page load time and save bandwidth. The static assets and the dynamic server responses are usually compressed and sent to the client, where they are decompressed to get the content back. This improves the page load time, as the transfer is faster with smaller data. So far, Gzip has been the most popular compression technique, offering a balance between speed and quality. But is it time to replace Gzip with Brotli?</p><p><strong>What is Brotli?</strong></p><p>Brotli is a compression algorithm that was developed by Google to be used in woff2 and was later generalized for broader use. Its compression ratio is comparable to the best currently available general-purpose compression methods.</p><p>Brotli has 11 compression quality levels (1 – 11). The higher the quality level, the higher the compression ratio. However, using higher compression levels will impact the compression speed.</p><p>All modern web browsers <a href="https://caniuse.com/brotli">support Brotli</a>, and about 94% of users use Brotli supported browsers. To determine if a browser supports Brotli, use the Accept-Encoding request header.</p><p><strong>How does Brotli achieve such a high compression ratio?</strong></p><p>Brotli uses a static dictionary derived from a large corpus of HTML and text documents, in addition to the <a href="https://en.wikipedia.org/wiki/LZ77_and_LZ78#LZ77">dynamically populated sliding window</a> used in most general-purpose algorithms. It contains commonly used words or syllables from English and other languages, as well as common phrases used in languages like HTML and JavaScript. It is further extended by transforms, which slightly changes the words in the static dictionary, thereby matching more sequences.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4afb53d2ee39fdfb73a3778f23d2a57/href">https://medium.com/media/d4afb53d2ee39fdfb73a3778f23d2a57/href</a></iframe><p>At least 40% of the words in the static English content served up by Chronus matched the words in the static dictionary without transformation. But what if the content is in a language that is not part of the static dictionary?</p><p>Interestingly, Brotli outperformed Gzip by more than 20% in compression ratio while compressing a 112K <a href="https://en.wikipedia.org/wiki/Tamil_language">Tamil language</a> text file. So it’s not just about the static dictionary. <strong>Brotli can give a higher compression ratio for most text files</strong>.</p><p><strong>Benchmarking Brotli Compression Ratio and Speeds</strong></p><p>Compared to Gzip, the Brotli-compressed static JS and CSS assets used at Chronus are at least <strong>15% smaller</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*8tgRBatVHDAz8K9b.png" /><figcaption>Brotli’s compression compared to Gzip.</figcaption></figure><p>While Brotli’s decompression speed is comparable to that of Gzip, its compression speed is considerably slower than that of Gzip.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/052e2cec988bd342b8f5bea5be5825c6/href">https://medium.com/media/052e2cec988bd342b8f5bea5be5825c6/href</a></iframe><p>The static assets have to be compressed only when their contents change. But they have to be decompressed every time the client requests them. The compression speed is insignificant here. With a higher compression ratio and comparable decompression speed, <strong>Brotli is the best fit for static assets</strong>.</p><p>For on-the-fly compression of dynamic server responses, the compression speed is also important. Using the <a href="https://github.com/google/ngx_brotli">ngx_brotli</a> filter module to compress on the fly, the Brotli compressed responses were smaller as expected. But the overall time was slightly greater compared to Gzip compressed responses. The <a href="https://github.com/google/ngx_brotli#brotli_comp_level">brotli_comp_level</a> config option can be used to tune the compression quality level. Setting it to ‘4’ is <a href="https://web.dev/codelab-text-compression-brotli/">considered good enough</a> for dynamic content, producing smaller responses faster. However, the results weren’t consistent enough for us to replace Gzip for dynamic content.</p><p><strong>Serving Static Assets with CloudFront Edge Compression</strong></p><p>At Chronus, CloudFront is used to serve static assets. It supports <a href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/ServingCompressedFiles.html">automatic compression</a> and eliminates the need to place compressed files at the origin.</p><ul><li>Automatic edge compression can be enabled using a cache policy.</li><li>Based on the Accept-Encoding request header, the file will be served in one of the compressed formats supported by the client.</li><li>If the client supports Gzip and Brotli, and one of these compressed objects is present in the cache, it is returned. If both the compressed objects are present in the cache, the Brotli-compressed object is returned. If neither is present in the cache, the file is Brotli-compressed and returned (also cached). Because of this, the same file might be served with different compressed formats from different edge locations if the client supports both.</li><li>Compression is performed only if the response from the origin includes the Content-Length header. In our case, the origin S3 will always include the header in the response.</li><li>After enabling compression for existing objects, the CloudFront cache must be <a href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Invalidation.html">invalidated, or you must use versioned file names</a>.</li></ul><p><strong>Conclusion</strong></p><p>Is it time to replace Gzip with Brotli? The answer is —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HyM-mdzmECfxShVS.png" /></figure><p>woff2 uses Brotli, and it is a W3C recommendation. Brotli’s performance is not limited to the static dictionary, and it does well in compressing most static text files irrespective of the language. The data transfer cost of CDNs is based on the volume of data served, and smaller files are cost-effective. For dynamic content, the Brotli compression level can be adjusted to find the right level (4?!), offering a better ratio and speed than Gzip. As always, the best way to find out is to benchmark ;)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63fdc0344491" width="1" height="1" alt=""><hr><p><a href="https://engineering.chronus.com/improve-page-load-time-using-brotli-compression-63fdc0344491">Improve Page Load Time Using Brotli Compression</a> was originally published in <a href="https://engineering.chronus.com/">Chronus Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How we improved the Rails Test startup time by 70%]]></title>
            <link>https://engineering.chronus.com/how-we-improved-the-rails-test-startup-time-by-70-percent-e99590bc0e46?source=rss-e33b22388069------2</link>
            <guid isPermaLink="false">https://medium.com/p/e99590bc0e46</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[minitest]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Chronus Engineering]]></dc:creator>
            <pubDate>Fri, 09 Jul 2021 21:17:26 GMT</pubDate>
            <atom:updated>2021-07-09T21:17:26.765Z</atom:updated>
            <content:encoded><![CDATA[<p>By <a href="https://www.linkedin.com/in/prathap-the-webdev/">Prathap</a> and <a href="https://www.linkedin.com/in/mohan-raj-10">Mohan Raj</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*hWyoB_nfMz-GitAuIMY7Pg.png" /></figure><p>As part of our development process, we write extensive test cases for each functionality. We tend to run the tests multiple times while writing or validating the test cases. As the test startup time was high, we had to wait longer to validate the test cases. This slowed down the process. So we worked on speeding up the test startup process and we achieved a <strong>75 percent decrease</strong> in the startup time. This article will describe how we approached and hunted down the time-consuming steps and fixed them.</p><p><strong>Note:</strong> The changes mentioned in this article help in improving test startup time while writing/validating individual tests and may not be applicable while running complete test suites. So, we recommend applying the changes based on a flag or ENV variable.</p><p>We use <strong>Ruby on Rails</strong> for our back-end and <strong>Minitest</strong> framework for testing. But the changes will work for other test frameworks (like ‘<strong>rspec’</strong>) as well.</p><p>As a first step, we defined the test startup time to be the time between rails test command invocation and the setup method invocation. We measured the current setup time as below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/299281cac060a95f02a4fe0fbf1078d6/href">https://medium.com/media/299281cac060a95f02a4fe0fbf1078d6/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FDiEyjlvSHm6ZVuUhiETvQ.png" /><figcaption>Result of running foo_test.rb</figcaption></figure><p>We had been waiting <strong>27</strong> <strong>seconds</strong> for each run to kick start (Whaat?!)</p><h3>Understanding the startup time</h3><p>To break down the <strong>27 seconds</strong>, we need to understand the rails initialization process. RailsGuides explains the rails server startup process in-depth <a href="https://guides.rubyonrails.org/initialization.html">here</a>. But the rails test startup process varies slightly.</p><p>At a high level, we can break the test startup process into three phases:</p><p><strong>1. Rails initialization</strong></p><p>This is the launch phase and is invoked on running rails test command which through a series of Rails-internal steps invokes FooTest.</p><p><strong>2. Application initialization</strong></p><p>In this phase, all the gems we use in our code and the modules in our application code are initialized. This is accomplished by FooTest, which requires ‘<strong>config/environment.rb</strong>’ and in turn ‘<strong>application.rb</strong>’ which initializes our application.</p><p><strong>3. Test initialization</strong></p><p>This phase initializes the minitest framework and runs the test code. Minitest is automatically invoked when require &#39;minitest/autorun&#39; is executed. The minitest framework invokes and executes our test code.</p><p>To measure the time for each phase we printed Time.now in the following places:</p><p>​ ​ ​​​ ​ ​​​ ​1. Beginning of <strong>boot.rb</strong><br>​ ​ ​​​ ​ ​​​ ​2. Beginning of <strong>application.rb</strong><br>​ ​ ​​​ ​ ​​​ ​3. Just before require &#39;minitest/autorun&#39; <br>​ ​ ​​​ ​ ​​​ ​4. ‘setup’ method in FooTest</p><p>And the results are listed in the following table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*-jy1FqJx6ZuIySXyvFT2EA.png" /><figcaption>Startup time in the beginning</figcaption></figure><p>As we can see, the Rails initialization step takes negligible time. So, we focused on the other two phases.</p><h3>Application initialization:</h3><p>This phase eats up more than<strong> 60 percent </strong>of our load time. We found that preloaders like <a href="https://github.com/rails/spring"><strong>Spring</strong></a> will help us reduce time here.</p><p><strong>What is Spring?</strong></p><blockquote><em>Spring is a Rails application preloader. It speeds up development by keeping your application running in the background so you don’t need to boot it every time you run a test, rake task or migration.</em></blockquote><p>We configured our application to use the Spring preloader. And, aha! On consecutive test builds the Spring preloader took only <strong>2 seconds </strong>(was previously 18 seconds) in this phase. We succeeded in bringing down the time in this phase but, the test initialization phase still took 8 seconds.</p><p>However, on our day-to-day tests, we started seeing random segmentation faults, and assets did not refresh on update. We decided that Spring caused more harm than good, and we disabled Spring every time we ran the server or performed tests. Also, we found that we are not alone here (refer to the <a href="https://discuss.rubyonrails.org/t/spring-fails-to-notice-changes-and-reload-frequently-enough-that-it-is-a-constant-hindrance/74496/5">discussion</a> and also the tweet below) and hence we got rid of Spring.</p><h3>Will Jessop 🇪🇺 on Twitter: &quot;Rails developers: Should Spring be removed as a default when creating a new Rails app? / Twitter&quot;</h3><p>Rails developers: Should Spring be removed as a default when creating a new Rails app?</p><h3>No Spring. What next?</h3><p>On closer look, the Application Initialization phase involves:<br>​ ​ ​​ ​ ​ ​​​ ​ ​​​ ​1. Loading Gems (5 seconds)<br>​ ​ ​​​ ​ ​ ​​​ ​ ​​​ ​2.​ Loading the rest of the application (13 seconds)</p><p>Gems are loaded by the command Bundler.require(*Rails.groups) present in config/application.rb)</p><h4>Cutting down Gem load time (using Bumbler gem)</h4><p>We wanted to find out which gems took more time. For this, we used the <a href="https://github.com/nevir/Bumbler">Bumbler</a> gem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*SWPd4vq3fJlaYO0_hCAk3Q.png" /><figcaption>Bumbler gem results</figcaption></figure><p>We found few time-consuming gems which were needed only in specific tests and were not required during test startup. For those gems, we added require: false in Gemfile. For eg:</p><pre>gem &#39;premailer&#39;, require: false</pre><p>And added require &#39;premailer&#39; in the necessary places. This helped us to reduce the gem loading time to ~3 seconds by skipping 7 gems from loading during test startup.</p><h4>Cutting down application load time:</h4><p>Here, we first started with checking out which files were being loaded. For this we used <a href="https://ruby-doc.org/core-2.5.0/TracePoint.html"><strong>TracePoint</strong></a>. We appended the following code snippet to /config/boot.rb</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32ba73f6e68107a05ffcbcac83730395/href">https://medium.com/media/32ba73f6e68107a05ffcbcac83730395/href</a></iframe><p>The following is an excerpt of the output of running the test:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*3C6L8r9a2xFSnTAZQUFUWA.png" /></figure><p>These files are loaded as a result of eager loading files defined as part of config.eager_load_paths in config/application.rb. We felt that loading all the models, controllers, etc. for testing just one model was overkill. But we found that eager loading is needed for speeding up the Test Suite, which affected the individual test run time. So we made the following change in the config/environments/test.rb.</p><pre>config.eager_load = ENV.fetch(&#39;EAGER_LOAD&#39;, true)</pre><p>Now on measuring the time taken with ENV[&#39;EAGER_LOAD&#39;] set to false, this phase took only <strong>10</strong> <strong>seconds</strong>. We reduced the time by nearly <strong>50 percent </strong>in this phase. Yay!</p><p><strong>BootSnap</strong></p><p>We were still not satisfied and continued the hunt. We came across another interesting gem — ‘<a href="https://github.com/Shopify/bootsnap"><strong>Bootsnap</strong></a>’ — which helps in reducing the file load time by caching the Kernel#require calls.</p><p>Upon configuring the bootsnap, we were able to reduce the time by <strong>3 more seconds.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*VmIFj626VIS0ANr29vsdeQ.png" /><figcaption>Test startup time after speeding up application initialization</figcaption></figure><p>The time taken for application initialization (7 seconds) includes the Gem load time of 3 seconds. Drilling down further on the <a href="https://guides.rubyonrails.org/initialization.html#back-to-config-environment-rb">Rails initialization</a> process, we understood that every major component in Rails (ActiveSupport, ActionController, etc.) implements a <a href="https://api.rubyonrails.org/v5.1.7/classes/Rails/Railtie.html#:~:text=Rails%3A%3ARailtie%20is%20the,responsible%20for%20their%20own%20initialization.">railtie</a> to add hooks to the app initialization process. We also found that all ActiveRecord Observers are being initialized as part of the after_initialize hook in <a href="https://github.com/rails/rails-observers/blob/master/lib/rails/observers/railtie.rb#L28">ActiveRecord::Railtie</a> and took around 2.7 seconds to load, as our application had many observers. Plus, <a href="https://guides.rubyonrails.org/configuring.html#using-initializer-files">load_config_initializer</a> loads the initializers present in the config/initializers/ folder which took around 600 ms to load. These steps are necessary and cannot be skipped. As we were not able to further reduce the time in this phase, we decided to work on the next phase.</p><h3>Test Initialization</h3><p>In the <strong>TracePoint </strong>result, we also saw that many (.yml) files were loaded after the Minitest process initialization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*oQJ_WnT5Sx2_6QGE2n0UGw.png" /></figure><p>All the fixture files present in the test/fixtures/ folder were loaded on initializing the tests. This took <strong>8 seconds</strong>.</p><p>We didn’t think we could improve here as these were required for accessing the ActiveRecord object directly (WITHOUT triggering the DB query) using the notation:</p><pre>foo(:bar)</pre><p>where ‘foo’ is the table name and ‘:bar’ is the fixture name.</p><p>After the fixtures were loaded, there was a little time gap before the setup method invocation. We doubted any DB queries were being fired. So we turned on the logger for the test environment. We added the following in test.rb to print the fired DB queries to the terminal.</p><pre>config.logger = Logger.new(STDOUT)</pre><p>Now on running the tests after turning the logger on, we were able to see multiple delete and insert queries.</p><p>From the Rails <a href="https://api.rubyonrails.org/v3.1/classes/ActiveRecord/Fixtures.html">documentation</a> we understood that:</p><blockquote><em>The testing environment will automatically load all fixtures into the database during the test initialization process. To ensure consistent data, the environment deletes the fixtures before running the load.</em></blockquote><p><strong>Myth Busted!</strong></p><p><em>To our surprise, we found that calling foo(:bar) also triggered a DB query to fetch the ‘bar’ object.</em></p><p>Upon further investigation, we found that fixtures help mainly in naming the objects foo(:bar)in transactional fixtures and we were using transaction fixtures in the config (self.use_transactional_fixtures = true) and the following config was responsible for loading all the fixtures.</p><pre>fixtures: all</pre><p>So we removed the above line and defined only the required fixtures in each test file as below</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf6a449d29d55cd1b646b2dda7cc5122/href">https://medium.com/media/cf6a449d29d55cd1b646b2dda7cc5122/href</a></iframe><h3>So, is the mission accomplished?</h3><p><strong>NO :(</strong></p><p>This approach will work for brand new projects; but for larger projects such as ours (with 1,500+ test files), one cannot manually identify the required fixtures for each existing test file and define them. So we went ahead on a dynamic approach that will load the required fixtures on demand. To achieve this we handled ‘method_missing’ in tests to replicate the fixture loading behavior as below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa90f95dd4368b3bb23597f31f45026c/href">https://medium.com/media/fa90f95dd4368b3bb23597f31f45026c/href</a></iframe><p>setup_fixtures method in the above snippet loads the fixtures in the (.yml) files to the database and its source code can be referred to <a href="https://apidock.com/rails/v6.1.3.1/ActiveRecord/TestFixtures/setup_fixtures">here</a>.</p><p>Using this approach, we got rid of the test fixture generation step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*uvUDkdssMa7uaAvYybQo1w.png" /><figcaption>Test startup time in the end</figcaption></figure><p>We have finally reduced the test startup time from 27 seconds to 7 seconds, an almost <strong>75 percent </strong>decrease without even using Spring. After these changes, when we tried enabling the spring, the test started blazingly fast in less than <strong>2 seconds</strong>. We will keep an eye on the improvements in the Spring framework which will avoid random errors.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e99590bc0e46" width="1" height="1" alt=""><hr><p><a href="https://engineering.chronus.com/how-we-improved-the-rails-test-startup-time-by-70-percent-e99590bc0e46">How we improved the Rails Test startup time by 70%</a> was originally published in <a href="https://engineering.chronus.com/">Chronus Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>