<?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 JettyCloud on Medium]]></title>
        <description><![CDATA[Stories by JettyCloud on Medium]]></description>
        <link>https://medium.com/@jettycloud?source=rss-9ab6c9a6474f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*O8P4eQL2f5_XC9Ek3ZH8GA.jpeg</url>
            <title>Stories by JettyCloud on Medium</title>
            <link>https://medium.com/@jettycloud?source=rss-9ab6c9a6474f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 09:58:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jettycloud/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[Negative testing: Conflict creator or reliable software release assistant?]]></title>
            <link>https://medium.com/@jettycloud/negative-testing-conflict-creator-or-reliable-software-release-assistant-447a7e94b48e?source=rss-9ab6c9a6474f------2</link>
            <guid isPermaLink="false">https://medium.com/p/447a7e94b48e</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[qa]]></category>
            <category><![CDATA[negative-testing]]></category>
            <category><![CDATA[quality-assurance]]></category>
            <dc:creator><![CDATA[JettyCloud]]></dc:creator>
            <pubDate>Mon, 05 Feb 2024 07:42:17 GMT</pubDate>
            <atom:updated>2024-02-05T13:57:20.014Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*we9z2E9isPu_I6pq6XYNfQ.png" /></figure><p>My name is <a href="https://medium.com/@tanya.grigorkevich">Tanya</a>, I’ve been working as a QA engineer for five years. I worked in a startup, two major projects, and a couple of smaller ones. Throughout my testing career, I’ve come to realize that negative testing, which involves checking software through non-obvious negative scenarios, is an excellent way to ensure product quality. However, I’ve often heard questions like these regarding this approach</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZpeQcx76bXpTyPcCFAN9JQ.png" /></figure><p>Such misunderstanding among colleagues can lead to conflicts and disputes at work. However, all of this can be avoided. So let’s figure out why a tester may execute seemingly strange and illogical cases. What is the value and benefit of such an approach? And how can we explain this to our colleagues?</p><h3>Test types</h3><p>There are two main types of tests used to check software: positive and negative. The most common one is positive testing. These tests ensure that the software works correctly by inputting valid values or going through valid scenarios. However, positive testing does not guarantee stability and reliability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3YF2kttFUxhd34FmbZmHJg.png" /></figure><p>Negative testing involves tests that intentionally introduce errors or failures into the system to check its response. Negative testing is aimed at finding errors or weaknesses in the system so that they can be fixed before it is deployed into production.</p><p>Intentionally introducing errors into a system may seem illogical to some and raise a lot of questions. Therefore, this approach is often forgotten or simply avoided. However, in practice, it is a very important tool — let’s further explore why.</p><h3>Advantages of negative testing</h3><p><strong>The main advantage of negative testing is that it accounts for the possibility of entering incorrect or unsupported data.</strong> Simple examples could include selecting a date in the past or entering a credit card from a provider not supported by the system.</p><p>Here’s another case: In 1999, the Mars Climate Orbiter reached Mars, but a navigation error caused it to burn up in the atmosphere. The error was caused by one team using the metric system of measurements while another used the imperial system. Negative testing would have helped avoid this confusion: if metric system data were entered into a system expecting imperial system data, a bug would have been detected at an early stage, preventing it from going into production, and the satellite would not have burned up.</p><p><strong>The next advantage, and in my opinion the most important one, is security. </strong>Negative testing helps identify potential vulnerabilities in the system or errors that could harm users and bystanders.</p><p>A historical example is the Boeing 737 Max issues (2018–2019): due to a malfunction in one angle-of-attack sensor, the program incorrectly directed the aircraft downward towards the ground, mistakenly believing it was dangerously pitching up. This led to two fatal crashes. The bug in this case was related to incorrect handling of input data from the sensor and the behavior of the software when the sensor data was incorrect or invalid.</p><p><strong>Negative testing takes into account the possibility of using a software application in complex conditions, especially when there are dependencies between different parts of functionality within the system. </strong>There is a likelihood that you may encounter errors when one of the stages is disrupted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WsotHqgjk2yzz8qzMutFUw.png" /></figure><p>Therefore, it is important to ensure that your portion of functionality or the entire software does not break down.</p><p>Let’s consider a bug related to user account activation. The essence of it is that there is some dependency between different parts of functionality, and when activating the account, a system failure occurs, causing the system to break down.</p><p>Let’s imagine there is a dependency between different parts of functionality and the type of user account (standard and premium). And we know that for a premium account, during the activation stage, we can enable parameter A in the flow to immediately provide access to a specific option. However, this parameter entails loading a large amount of data. For a standard account, this parameter is only available after activation and purchasing an additional license for this option. Therefore, enabling parameter A should only be available after these two conditions are met. The goal of negative testing is to deliberately enable parameter A for a standard account by sending a request to the database during activation and see what happens in this case. Here’s what happens: the system breaks down because the account is not yet ready to handle large volumes of data. As a result, the user cannot complete the flow and consequently cannot use the software further.</p><p>Therefore, by forcibly inducing system failures, we can understand how the system reacts and devise ways to prevent such situations or keep the system operational.</p><p><strong>Negative testing helps the tester improve requirements and enhance user usability. </strong>A very common scenario is with web applications where the UI lacks accompanying messages, pop-ups, or hints for the user, for example, indicating that they have entered incorrect data or are attempting an action that is unavailable to them. User misunderstanding can lead to a negative reaction and reluctance to use the product. Conducting only positive cases may overlook this aspect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EDv3h8_aNEjMC9qA77lrRA.png" /></figure><p><strong>Of course, these are not all the advantages of this method, but by discovering and fixing errors before system launch, you can avoid costly corrections at later stages and potential customer dissatisfaction.</strong></p><h3>Use of negative testing</h3><h4>Check yourself</h4><p>Before starting to apply negative testing, the engineer should ask themselves several questions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rmI7qfQdbgJC2ffWp1yPbQ.png" /></figure><h4>Don’t limit yourself to standard techniques</h4><p>In professional literature and on the internet, the application of only two techniques of negative testing is most often described — Equivalence Partitioning and Boundary Value Analysis. You will find confirmation of this in books such as “Software Testing: A Craftsman’s Approach” (Paul Jorgensen) and “The Art of Software Testing” (Glenford Myers), in materials of popular certification courses in testing, such as ISTQB, and in many discussions on forums and communities of testers, for example, on Stack Overflow or Software Testing Professionals.</p><p>But I believe that engineers should not limit themselves to just these techniques. Based on my experience, I can note that there are many other test design techniques that are no less effective and important when creating negative test cases. For example, let’s consider the following:</p><p><strong>Cause-Effect Graphing: </strong>This method uses graphical representation to establish the relationship between problems and their causes. Among the possible emerging causes, testers look for those that may lead to negative results.</p><p><strong>State Transition Testing:</strong> This method involves checking whether the system correctly handles transitions from one state to another. In negative testing, the system’s handling of incorrect or unforeseen transitions is verified.</p><p><strong>Attack Testing:</strong> This method is used to “break” the system and observe how it handles incorrect usage or input.</p><p>All of these test design techniques allow for more thorough and systematic negative testing, as well as simplifying the process of identifying sources of errors in the system and detecting critical bugs. More information about different types of test design techniques can be found in the table in the book “A Practitioner’s Guide to Software Test Design.”</p><h4>Act systematically</h4><p>There’s no need to rush into creating negative test cases right away. It’s important to follow this rule:</p><ul><li>Start development and testing with simple positive test cases.</li><li>Only then move on to simple negative tests.</li><li>After that, proceed to complex positive tests.</li><li>And finally, tackle complex negative tests.</li></ul><p>That’s it, there’s no need to overcomplicate things; this approach works great in practice.</p><h3>How to minimize conflicts</h3><h4>From the tester’s perspective</h4><p>When disagreements arise with the team, don’t be afraid to stand up for your point of view while maintaining respect for your colleagues’ work. Remember that we’re all in the same boat and working towards common goals. Try to calmly explain the essence of negative testing, provide a couple of arguments for why it’s necessary, and explain the goals of your negative test cases. Examples from this article may help with this. If you’ve found a bug using this method and need to inform a developer, remember their vulnerability and their strong defense of their code. Immediately inform them that you conducted negative testing and that it’s part of your job.</p><h4>From the team’s perspective</h4><p>When the tester is writing negative checks, they may have a number of questions that may seem strange at first glance. But you should understand that nothing is done in vain. Most likely, the tester needs to know some technical details to make decisions in choosing testing techniques or compiling necessary checklists, tests, etc. So don’t avoid questions, calmly clarify their purpose. Don’t tell the tester not to spend time on negative checks and criticize them for it — it’s part of their job.</p><p>What do you think of negative testing? Do you use this approach at work or prefer positive tests? Let me know in the comments!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=447a7e94b48e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pandora box of the requirements testing & Data QA: videos from our QA Party]]></title>
            <link>https://medium.com/@jettycloud/pandora-box-of-the-requirements-testing-data-qa-videos-from-our-qa-party-d7417ff647f9?source=rss-9ab6c9a6474f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7417ff647f9</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[data-quality]]></category>
            <category><![CDATA[qa]]></category>
            <dc:creator><![CDATA[JettyCloud]]></dc:creator>
            <pubDate>Mon, 13 Nov 2023 14:48:59 GMT</pubDate>
            <atom:updated>2023-11-13T14:48:59.226Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D0oZLlGXMlkfpxyD9mOJ0w.png" /></figure><p>In September we held our first QA Party — a fun professional event for QA Engineers. We arranged our meeting at the lively Tbilisi city center, invited experienced speakers, who revealed their testing secrets, and partnered up with local brands to bring the participants gifts.</p><p>Our next QA Party will take place in Batumi on November, 15th. Get ready for even more testing tips and tricks, exciting giveaways and friendly networking. <a href="https://tkt.ge/event/378901/qa-party-in-batumi">Get your ticket on tkt.ge</a>.</p><p>Meanwhile we are ready to share recordings of the repost from the first event! Language — Russian.</p><p><strong>Ivan Lobashev, Data Art: Pandora box of the requirements testing</strong></p><p>QA Engineers are not sure that they have checked everything? The project timeline is disrupted due to a high number of improvements or inaccurate estimations? The QA team lacks a full understanding of the product’s business logic?</p><p>It’s difficult to identify what can be affected by new functionality, and management rejects all suggestions to improve processes. All of these issues can be addressed through requirements testing! Ivan will open this Pandora’s box and discuss the importance of requirements testing, requirements-related bugs, various approaches to requirements testing, the benefits of this event, and related topics. Whether you are currently facing these challenges in your project, tend to optimize tasks to be more efficient, or are interested in building, reviewing, or enhancing QA processes, this is a relevant topic for you.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FHKU3XBTxbnE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DHKU3XBTxbnE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FHKU3XBTxbnE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/83ac54a1afaf25ffb8a22e8c7e7d91e4/href">https://medium.com/media/83ac54a1afaf25ffb8a22e8c7e7d91e4/href</a></iframe><p><strong>Natalia Yakhina, Quantori: Data QA: what, who &amp; why?</strong></p><p>Natalya’s presentation aims to briefly describe the specifics of data quality: why data quality matters, what quality dimensions exist, how to assess the data quality and finely who are the engineers ensuring the high level of data quality.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FPbDprwm77nY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DPbDprwm77nY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FPbDprwm77nY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/102c79ef7444bc9dbac2e4d3d1fae80d/href">https://medium.com/media/102c79ef7444bc9dbac2e4d3d1fae80d/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7417ff647f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introducing RingCentral Metrics Facade — the missing library for working with metrics]]></title>
            <link>https://medium.com/@jettycloud/introducing-ringcentral-metrics-facade-the-missing-library-for-working-with-metrics-e12b5900ee03?source=rss-9ab6c9a6474f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e12b5900ee03</guid>
            <category><![CDATA[metrics]]></category>
            <category><![CDATA[prometheus]]></category>
            <category><![CDATA[monitoring]]></category>
            <dc:creator><![CDATA[JettyCloud]]></dc:creator>
            <pubDate>Wed, 25 Oct 2023 11:58:42 GMT</pubDate>
            <atom:updated>2023-10-25T13:48:50.026Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Introducing RingCentral Metrics Facade — the missing library for working with metrics</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Exh49ZITccrNj7gg4_2CtA.png" /></figure><p>I am <a href="https://github.com/devromik">Roman Shulnyaev</a>, and my co-author is <a href="https://github.com/rc-mairovichaa">Andrei Mairovich</a>. We are developers at JettyCloud, an innovative software development company crafting solutions for <a href="https://www.ringcentral.com/">RingCentral</a>. Our team works on integration projects, such as <a href="https://www.redhat.com/en/topics/api/what-does-an-api-gateway-do">API Gateway</a>. API Gateway is the entry point for <a href="https://developers.ringcentral.com/api-reference">RingCentral Platform API</a>, acting as a reverse HTTP proxy to various services and supporting essential cross-cutting concerns like authorization and server-side service discovery.</p><p>API Gateway provides a wealth of metrics (thousands!): from request processing durations to error rates. These metrics give us a deep understanding of how API Gateway is performing. Some of them are dynamic and lose relevance over time. For instance, the metric for the number of proxy errors on a specific server (host:port) may no longer be relevant if the set of servers changes.</p><p>During our project work, we discovered that mainstream solutions for working with metrics were missing a few important features, including:</p><ol><li>The ability to set parameter defaults and override parameters for a subset of metrics selected with a predicate. Imagine your project has 100 histograms. A histogram is a metric that allows you to calculate and export a number of statistical values: min, max, mean, 50th percentile, 99th percentile, etc. If you choose to calculate and export only max, mean, and 99th percentile, a library should enable you to do so “in one line”, without changing the definition code of all 100 histograms, like this:</li></ol><pre>registry.preConfigure(allMetrics(), modifying().histogram(withHistogram().measurables(MAX, MEAN, PERCENTILE_99)));</pre><p>This feature:</p><ul><li>Simplifies managing a large number of metrics.</li><li>Enables a metric’s implementation not to perform costly operations of calculating values not included in the set of values defined for this metric.</li><li>Allows for overriding metrics defined in third-party libraries, even when you don’t have access to the source code.</li></ul><p>2. Eviction and expiration for <a href="https://prometheus.io/docs/concepts/data_model/#metric-names-and-labels">labeled metrics</a>. A library should allow you to specify the maximum number of combinations of label values for each labeled metric. When this threshold is exceeded, the combination that has not been updated for the longest time should be automatically removed to avoid consuming too much system resources. Additionally, a library should allow specifying the expiration time for a combination of label values. If a combination has not been updated during this time, it should be automatically removed. This feature resolves the challenge of dealing with dynamic metrics.</p><p>As a result, we developed a new solution, <a href="https://github.com/ringcentral/metrics-facade">RingCentral Metrics Facade</a>, which we will introduce in this article. We have also developed and adopted a number of high-performance metric implementations, like <a href="https://github.com/ringcentral/metrics-facade/tree/release_3-1/metrics-facade-default-impl/src/main/java/com/ringcentral/platform/metrics/defaultImpl/histogram/hdr">HDR histogram</a> from the great <a href="https://github.com/vladimir-bukhtoyarov/rolling-metrics">rolling-metrics</a> library and our brand-new <a href="https://github.com/ringcentral/metrics-facade/tree/release_3-1/metrics-facade-default-impl/src/main/java/com/ringcentral/platform/metrics/defaultImpl/histogram/scale">Scale histogram</a>. By using our library, you will not only gain access to all the aforementioned features but also significantly enhance metrics calculation performance. And, of course, we will provide you with <a href="https://github.com/ringcentral/metrics-facade/tree/release_3-1/metrics-facade-benchmark">benchmarks</a>. 😉</p><p>We welcome your feedback, bug reports, and pull requests to help us improve the library. Whether you have suggestions for new features or have found a bug that needs fixing, we appreciate your contributions to make the library even better.</p><p>And now, let’s get started!</p><h3>A first metric creation and export</h3><p>To use the library, you need to add the following dependencies to your project:</p><ol><li><strong>metrics-facade-base</strong>. This dependency provides the core interfaces and base capabilities of the library: Metric, Label, Var, Counter, Rate, Histogram, Timer, MetricRegistry etc.</li><li><strong>metrics-facade-default-impl</strong>. This dependency provides the default implementation of the library’s core interfaces and base capabilities, including the implementations for all metric types: Var, Counter, Rate, Histogram, Timer etc. These implementations are designed to be efficient and high-performance, while also providing a high degree of flexibility and customization options. The library also offers a module for Dropwizard implementations, which you can enable by adding the metrics-facade-dropwizard dependency instead of metrics-facade-default-impl.</li><li><strong>metrics-facade-prometheus</strong>. This dependency provides the necessary classes and interfaces to integrate with the Prometheus monitoring system.</li></ol><p>Maven (<a href="https://github.com/ringcentral/metrics-facade/blob/articles/metrics-facade-articles/pom.xml">example of pom.xml</a>):</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;com.ringcentral.platform.metrics&lt;/groupId&gt;<br>    &lt;artifactId&gt;metrics-facade-base&lt;/artifactId&gt;<br>    &lt;version&gt;3.1.0-RELEASE&lt;/version&gt;<br>&lt;/dependency&gt;<br><br>&lt;dependency&gt;<br>    &lt;groupId&gt;com.ringcentral.platform.metrics&lt;/groupId&gt;<br>    &lt;artifactId&gt;metrics-facade-default-impl&lt;/artifactId&gt;<br>    &lt;version&gt;3.1.0-RELEASE&lt;/version&gt;<br>&lt;/dependency&gt;<br><br>&lt;dependency&gt;<br>    &lt;groupId&gt;com.ringcentral.platform.metrics&lt;/groupId&gt;<br>    &lt;artifactId&gt;metrics-facade-prometheus&lt;/artifactId&gt;<br>    &lt;version&gt;3.1.0-RELEASE&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>Gradle:</p><pre>implementation(&quot;com.ringcentral.platform.metrics:metrics-facade-base:3.1.0-RELEASE&quot;)<br><br>implementation(&quot;com.ringcentral.platform.metrics:metrics-facade-default-impl:3.1.0-RELEASE&quot;)<br><br>implementation(&quot;com.ringcentral.platform.metrics:metrics-facade-prometheus:3.1.0-RELEASE&quot;)</pre><p>Please replace 3.1.0 with the actual version of the library.</p><h3>Example</h3><p>The basic example of creating and exporting a metric can be found in <a href="https://github.com/ringcentral/metrics-facade/blob/articles/metrics-facade-articles/src/main/java/com/ringcentral/platform/metrics/articles/intro/Listing01.java">Listing01</a>:</p><pre>// 1) Create registry<br>var registry = new DefaultMetricRegistry();<br><br>// 2) Register metric<br>Counter counter = registry.counter(withName(&quot;requests&quot;, &quot;total&quot;));<br><br>// 3) Update metric<br>counter.inc();<br><br>// 4) Create exporter<br>PrometheusMetricsExporter exporter = new PrometheusMetricsExporter(registry);<br><br>// 5) Export metrics<br>System.out.println(exporter.exportMetrics());</pre><p>Output:</p><pre># HELP requests_total Generated from metric instances with name requests.total<br># TYPE requests_total gauge<br>requests_total 1.0</pre><p>As you can see, creating, updating and exporting a metric is pretty simple. In the next section, we will explore the various metric types available in the library.</p><h3>Metrics and Measurables</h3><p><a href="https://github.com/ringcentral/metrics-facade/blob/release_3-1/metrics-facade-base/src/main/java/com/ringcentral/platform/metrics/Metric.java">Metric</a> is a typed entity that measures a specified set of values, called <a href="https://github.com/ringcentral/metrics-facade/blob/release_3-1/metrics-facade-base/src/main/java/com/ringcentral/platform/metrics/measurables/Measurable.java">Measurables</a>, and provides the results of the measurements.</p><p>Metric type, such as <a href="https://github.com/ringcentral/metrics-facade/blob/release_3-1/metrics-facade-base/src/main/java/com/ringcentral/platform/metrics/counter/Counter.java">Counter</a> or <a href="https://github.com/ringcentral/metrics-facade/blob/release_3-1/metrics-facade-base/src/main/java/com/ringcentral/platform/metrics/histogram/Histogram.java">Histogram</a>, supports measuring a specific set of Measurables and provides a set of operations, like Counter.inc() or Histogram.update(), that impact the results of the measurements.</p><p>The library provides various metric types, including Counter, Rate, Histogram, Timer, and several types of Var (Gauge), as shown in the diagram below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*Y7MbhazX9nzua-uYAKpKzw.jpeg" /></figure><h3>Examples</h3><h4>Counter</h4><p>com.ringcentral.platform.metrics.counter.Counter is a java.lang.Long based counter that supports the single measurable Counter.COUNT — the current value of the counter. The counter is explicitly incremented or decremented to perform the measurement. Check out <a href="https://github.com/ringcentral/metrics-facade/blob/articles/metrics-facade-articles/src/main/java/com/ringcentral/platform/metrics/articles/intro/Listing02.java">Listing02</a>:</p><pre>// 1) Create registry<br>var registry = new DefaultMetricRegistry();<br><br>// 2) Register metric<br>Counter counter = registry.counter(<br>    withName(&quot;requests&quot;, &quot;total&quot;),<br>    () -&gt; withCounter().description(&quot;Client request count&quot;));<br><br>// 3) Increase counter<br>counter.inc();<br><br>// 4) Create exporter<br>var exporter = new PrometheusMetricsExporter(registry);<br><br>// 5) Export metrics<br>System.out.println(exporter.exportMetrics());</pre><p>Output:</p><pre># HELP requests_total Client request count<br># TYPE requests_total gauge<br>requests_total 1.0</pre><h4>Timer</h4><p>com.ringcentral.platform.metrics.timer.Timer allows for measuring the frequency, rate, and statistical distribution of durations of a specific action. Measurables include:</p><ul><li>Counter.COUNT: the number of times the action occurs</li><li>Rate.MEAN_RATE: the mean rate of the action</li><li>Rate.ONE_MINUTE_RATE: the rate of the action over the last minute</li><li>Rate.FIVE_MINUTES_RATE: the rate of the action over the last five minutes</li><li>Rate.FIFTEEN_MINUTES_RATE: the rate of the action over the last fifteen minutes</li><li>Rate.RATE_UNIT: the unit of measurement for rate (e.g. events per second)</li><li>Histogram.TOTAL_SUM: the total duration of the action</li><li>Histogram.MIN: the shortest duration of the action</li><li>Histogram.MAX: the longest duration of the action</li><li>Histogram.MEAN: the mean duration of the action</li><li>Histogram.STANDARD_DEVIATION: the standard deviation of the duration</li><li>Histogram.Percentile: the distribution of durations (e.g. PERCENTILE_5, PERCENTILE_10, etc.)</li><li>Histogram.Bucket: the duration <a href="https://prometheus.io/docs/concepts/metric_types/#histogram">buckets</a> (e.g. Histogram.MS_10_BUCKET, Histogram.SEC_1_BUCKET, etc.)</li><li>Timer.DURATION_UNIT: the unit of measurement for duration (e.g. milliseconds)</li></ul><p>Here is a simple example <a href="https://github.com/ringcentral/metrics-facade/blob/articles/metrics-facade-articles/src/main/java/com/ringcentral/platform/metrics/articles/intro/Listing03.java">Listing03</a> of how to use Timer:</p><pre>// 1) Create registry<br>var registry = new DefaultMetricRegistry();<br><br>// 2) Register metric<br>Timer timer = registry.timer(withName(&quot;request&quot;, &quot;duration&quot;, &quot;seconds&quot;));<br><br>// 3) Update metric. Let&#39;s assume that there were 3 requests: 5, 10 and 15 seconds long<br>timer.update(5, SECONDS);<br>timer.update(10, SECONDS);<br>timer.update(15, SECONDS);<br><br>// 4) Create exporter<br>var exporter = new PrometheusMetricsExporter(registry);<br><br>// 5) Export metrics<br>System.out.println(exporter.exportMetrics());</pre><p>Output:</p><pre># HELP request_duration_seconds Generated from metric instances with name request.duration.seconds<br># TYPE request_duration_seconds summary<br>request_duration_seconds{quantile=&quot;0.5&quot;,} 10.0<br>request_duration_seconds{quantile=&quot;0.9&quot;,} 15.0<br>request_duration_seconds{quantile=&quot;0.99&quot;,} 15.0<br>request_duration_seconds_count 3.0<br># HELP request_duration_seconds_min Generated from metric instances with name request.duration.seconds<br># TYPE request_duration_seconds_min gauge<br>request_duration_seconds_min 5.0<br># HELP request_duration_seconds_mean Generated from metric instances with name request.duration.seconds<br># TYPE request_duration_seconds_mean gauge<br>request_duration_seconds_mean 10.0<br># HELP request_duration_seconds_max Generated from metric instances with name request.duration.seconds<br># TYPE request_duration_seconds_max gauge<br>request_duration_seconds_max 15.0</pre><h3>Configuration of Measurables</h3><p>As previously mentioned, Timer supports Histogram.Bucket and Histogram.STANDARD_DEVIATION Measurables, but these were not included in the output. The reason for this is that each Metric subtype has a default set of Measurables, such as <a href="https://github.com/ringcentral/metrics-facade/blob/release_3-1/metrics-facade-base/src/main/java/com/ringcentral/platform/metrics/timer/AbstractTimer.java#L23">DEFAULT_TIMER_MEASURABLES</a> for Timer, and this default set for Timer does not include Histogram.Bucket or Histogram.STANDARD_DEVIATION Measurables. However, when registering a metric, you can override the set of Measurables for this specific metric. The override will only be applied to that metric and not to other metrics. See <a href="https://github.com/ringcentral/metrics-facade/blob/articles/metrics-facade-articles/src/main/java/com/ringcentral/platform/metrics/articles/intro/Listing04.java">Listing04</a> for an example:</p><pre>// 1) Create registry<br>var registry = new DefaultMetricRegistry();<br><br>// 2) Register metric.<br>Timer timer = registry.timer(withName(&quot;request&quot;, &quot;duration&quot;, &quot;seconds&quot;), () -&gt; withTimer()<br>    // 3) Specify custom set of measurables<br>    .measurables(<br>        COUNT,<br>        TOTAL_SUM,<br>        Bucket.of(5, SECONDS),<br>        Bucket.of(10, SECONDS),<br>        Bucket.of(15, SECONDS)));<br><br>// 4) Let&#39;s assume that there were 3 requests: 5, 10 and 15 seconds long<br>timer.update(5, SECONDS);<br>timer.update(10, SECONDS);<br>timer.update(15, SECONDS);<br><br>// 5) Create exporter<br>var exporter = new PrometheusMetricsExporter(registry);<br><br>// 6) Export metrics<br>System.out.println(exporter.exportMetrics());</pre><p>Output:</p><pre># HELP request_duration_seconds Generated from metric instances with name request.duration.seconds<br># TYPE request_duration_seconds histogram<br>request_duration_seconds_bucket{le=&quot;5&quot;,} 1.0<br>request_duration_seconds_bucket{le=&quot;10&quot;,} 2.0<br>request_duration_seconds_bucket{le=&quot;15&quot;,} 3.0<br>request_duration_seconds_bucket{le=&quot;+Inf&quot;,} 3.0<br>request_duration_seconds_count 3.0<br>request_duration_seconds_sum 30.0</pre><p>As expected, the set of exported values changed:</p><ul><li>request_duration_seconds_mean, request_duration_seconds_min, etc. are not present anymore,</li><li>request_duration_seconds_bucket and request_duration_seconds_sum are added,</li><li>request_duration_seconds_count is left as it is.</li></ul><p>In the next section, we will learn about labeled metrics.</p><h3>Labeled Metrics</h3><p><strong>Labeled metric</strong> is a metric associated with a set of attributes called <strong>labels</strong>. When updating a labeled metric, you must specify values for all the labels configured for that metric, considering their order. For each combination of label values with at least one update, a separate Metric instance is generated. This instance is represented by the MetricInstance interface, which provides measurement results for that combination:</p><pre>interface Metric extends Iterable&lt;MetricInstance&gt; {<br>    ...<br>}<br><br>interface MetricInstance {<br>    ...<br>    Set&lt;Measurable&gt; measurables();<br>    &lt;V&gt; V valueOf(Measurable measurable) throws NotMeasuredException;<br>}</pre><p>To better understand this definition, let’s consider the following example.</p><p>Suppose we are developing an HTTP service that calls several other HTTP services to perform its tasks. Each external service is represented by multiple instances running on specific servers. The service you’re developing can call any of these instances, e.g., using round-robin balancing.</p><p>Assume that we want to have a separate request execution Timer for each instance of an external service, meaning for each combination of service and server for which at least one request has been made. To achieve this, in <a href="https://github.com/ringcentral/metrics-facade/blob/articles/metrics-facade-articles/src/main/java/com/ringcentral/platform/metrics/articles/intro/Listing05.java">Listing05</a> we define a <strong>labeled</strong> Timer with the labels service and server:</p><pre>// 1) Create registry<br>var registry = new DefaultMetricRegistry();<br><br>// 2) Define labels. Typically, we define labels as constants, but in this example, we deviate from that convention for the sake of brevity<br>var service = new Label(&quot;service&quot;);<br>var server = new Label(&quot;server&quot;);<br><br>// 3) Register metric<br>Timer httpClientRequestTimer = registry.timer(<br>    withName(&quot;http&quot;, &quot;client&quot;, &quot;request&quot;, &quot;duration&quot;, &quot;seconds&quot;),<br>    () -&gt; withTimer()<br>        .labels(service, server)<br>        // We leave only one measurable for the sake of brevity<br>        .measurables(COUNT));<br><br>// 4) Auth service is called once<br>httpClientRequestTimer.update(<br>    1, SECONDS,<br>    forLabelValues(service.value(&quot;auth&quot;), server.value(&quot;127.0.0.1&quot;)));<br><br>// 5) Contacts service is called 3 times on the server 127.0.0.1<br>for (int i = 1; i &lt;= 3; ++i) {<br>    httpClientRequestTimer.update(<br>        i, SECONDS,<br>        forLabelValues(service.value(&quot;contacts&quot;), server.value(&quot;127.0.0.1&quot;)));<br>}<br><br>// 6) Contacts service is called 6 times on the server 127.0.0.2<br>for (int i = 1; i &lt;= 6; ++i) {<br>    httpClientRequestTimer.update(<br>        i, SECONDS,<br>        forLabelValues(service.value(&quot;contacts&quot;), server.value(&quot;127.0.0.2&quot;)));<br>}<br><br>// Labeled metric instances are added asynchronously<br>sleep(100);<br><br>// 7) Create exporter<br>var exporter = new PrometheusMetricsExporter(registry);<br><br>// 8) Export metrics<br>System.out.println(exporter.exportMetrics());</pre><p>Output:</p><pre># HELP http_client_request_duration_seconds Generated from metric instances with name http.client.request.duration.seconds<br># TYPE http_client_request_duration_seconds summary<br>http_client_request_duration_seconds_count{service=&quot;auth&quot;,server=&quot;127.0.0.1&quot;,} 1.0<br>http_client_request_duration_seconds_count{service=&quot;contacts&quot;,server=&quot;127.0.0.1&quot;,} 3.0<br>http_client_request_duration_seconds_count{service=&quot;contacts&quot;,server=&quot;127.0.0.2&quot;,} 6.0</pre><p>The output shows the generated metrics for the labeled Timer defined in the code. The Timer is named http.client.request.duration.seconds and has two labels: service and server. There are two instances of the metric for the contacts service, with different values for the server label (“127.0.0.1” and “127.0.0.2”), and one instance for the auth service with “127.0.0.1” as the value for the server label. The COUNT for the auth service is 1.0, indicating that it was called once. For the contacts service, the COUNTs are 3.0 and 6.0 for servers “127.0.0.1” and “127.0.0.2”, respectively, indicating the number of times the contacts service was called on each server.</p><p>The lifetime of some metric instances coincides with the lifetime of the metric itself, while others can be added or removed based on specific conditions. Metric implements Iterable&lt;MetricInstance&gt;, thereby providing the current set of the metric’s instances. It is also possible to subscribe to the events metricInstanceAdded and metricInstanceRemoved. These features are widely utilized by a majority of exporters.</p><p>An update of a metric is taken into account by the corresponding subset of instances. By default, only the <strong>total instance</strong> is created along with the metric (it can be disabled through metric configuration). The total instance takes all updates into account and has the same lifetime as the metric itself. This is the only instance created for non-labeled metrics. If the metric is labeled, an instance is created for each combination of label values. These instances take into account only those updates that are made for the corresponding combination, as shown in <a href="https://github.com/ringcentral/metrics-facade/blob/articles/metrics-facade-articles/src/main/java/com/ringcentral/platform/metrics/articles/intro/Listing06.java">Listing06</a>:</p><pre>// 1) Create registry<br>var registry = new DefaultMetricRegistry();<br><br>// 2) Define labels. Typically, we define labels as constants, but in this example, we deviate from that convention for the sake of brevity<br>var service = new Label(&quot;service&quot;);<br>var server = new Label(&quot;server&quot;);<br><br>Histogram httpClientFailoverCountHistogram = registry.histogram(<br>    withName(&quot;http&quot;, &quot;client&quot;, &quot;failover&quot;, &quot;count&quot;, &quot;histogram&quot;),<br>    () -&gt; withHistogram()<br>        .labels(service, server)<br>        .allSlice().noLevels());<br><br>// 3) Update the total instance and the instance (auth, 127.0.0.1)<br>httpClientFailoverCountHistogram.update(10, forLabelValues(service.value(&quot;auth&quot;), server.value(&quot;127.0.0.1&quot;)));<br><br>// 4) Update the total instance and the instance (auth, 127.0.0.2)<br>httpClientFailoverCountHistogram.update(20, forLabelValues(service.value(&quot;auth&quot;), server.value(&quot;127.0.0.2&quot;)));<br><br>// 5) Update the total instance and the instance (contacts, 127.0.0.3)<br>httpClientFailoverCountHistogram.update(30, forLabelValues(service.value(&quot;contacts&quot;), server.value(&quot;127.0.0.3&quot;)));<br><br>// 6) Update the total instance and the instance (contacts, 127.0.0.4)<br>httpClientFailoverCountHistogram.update(40, forLabelValues(service.value(&quot;contacts&quot;), server.value(&quot;127.0.0.4&quot;)));<br><br>// Labeled metric instances are added asynchronously.<br>sleep(100);<br><br>httpClientFailoverCountHistogram.forEach(instance -&gt; {<br>    List&lt;String&gt; labelValuesString = instance.labelValues().stream()<br>        .map(lv -&gt; lv.label().name() + &quot;=&quot; + lv.value())<br>        .collect(toList());<br><br>    // Snapshot-based approach for getting values<br>    MeasurableValues values = instance.measurableValues();<br><br>    String valuesString = &quot;{&quot; + instance.measurables().stream()<br>        .sorted(comparing(m -&gt; m.getClass().getName()))<br>        .map(m -&gt; {<br>            String name =<br>                m instanceof Histogram.Percentile ?<br>                &quot;Percentile_&quot; + ((Histogram.Percentile)m).quantileAsString() :<br>                m.getClass().getSimpleName();<br><br>            // or instance.valueOf(m) but this approach is not snapshot-based, e.i., is not consistent, and should not be used unnecessarily<br>            return name + &quot;=&quot; + values.valueOf(m);<br>        })<br>        .collect(joining(&quot;, &quot;)) + &quot;}&quot;;<br><br>    System.out.println(<br>        &quot;Metric instance:\n&quot;<br>        + &quot;  label values = &quot; + labelValuesString + &quot;,\n&quot;<br>        + &quot;  total instance = &quot; + instance.isTotalInstance() + &quot;,\n&quot;<br>        + &quot;  measurable values = &quot; + valuesString);<br>});</pre><p>Output:</p><pre>Metric instance:<br>  label values = [],<br>  total instance = true,<br>  measurable values = {Count=4, Max=40, Mean=25.0, Min=10, Percentile_0.5=20.0, Percentile_0.99=40.0, Percentile_0.9=40.0}<br>  <br>Metric instance:<br>  label values = [service=auth, server=127.0.0.1],<br>  total instance = false,<br>  measurable values = {Count=1, Max=10, Mean=10.0, Min=10, Percentile_0.5=10.0, Percentile_0.99=10.0, Percentile_0.9=10.0}  <br>  <br>Metric instance:<br>  label values = [service=auth, server=127.0.0.2],<br>  total instance = false,<br>  measurable values = {Count=1, Max=20, Mean=20.0, Min=20, Percentile_0.5=20.0, Percentile_0.99=20.0, Percentile_0.9=20.0}<br><br>Metric instance:<br>  label values = [service=contacts, server=127.0.0.3],<br>  total instance = false,<br>  measurable values = {Count=1, Max=30, Mean=30.0, Min=30, Percentile_0.5=30.0, Percentile_0.99=30.0, Percentile_0.9=30.0}  <br>  <br>Metric instance:<br>  label values = [service=contacts, server=127.0.0.4],<br>  total instance = false,<br>  measurable values = {Count=1, Max=40, Mean=40.0, Min=40, Percentile_0.5=40.0, Percentile_0.99=40.0, Percentile_0.9=40.0}</pre><p>The lifecycle of such an instance may end earlier than the lifecycle of the metric, in cases such as eviction or expiration, that we’ll discuss in the next section.</p><h3>Labeled Metrics Eviction and Expiration</h3><p>Let’s assume that servers for external services are not statically configured, and are periodically requested from an external “discovery” service. Since services are discovered dynamically, the set of their servers changes over time. The set of MetricInstances of the timer will, accordingly, grow indefinitely. Some of the MetricInstances will represent non-existent servers, and because they have already been exported to external monitoring systems, they are no longer needed, but at the same time they continue to consume system resources.</p><p>To solve this problem, Metrics Facade allows you to set for each labeled metric:</p><ul><li>The maximum number of combinations of label values. When this threshold is exceeded, the combination that has not been updated for the longest time, will be automatically removed. This feature is called <strong>eviction</strong>.</li><li>The expiration time for a combination of label values. If a combination has not been updated during this time, it will be automatically removed. This feature is called <strong>expiration</strong>.</li></ul><p><a href="https://github.com/ringcentral/metrics-facade/blob/articles/metrics-facade-articles/src/main/java/com/ringcentral/platform/metrics/articles/intro/Listing07.java">Example of eviction</a>:</p><pre>// 1) Create registry<br>var registry = new DefaultMetricRegistry();<br><br>// 2) Define labels<br>var service = new Label(&quot;service&quot;);<br><br>// 3) Register metric<br>Counter counter = registry.counter(withName(&quot;requests&quot;, &quot;total&quot;), () -&gt; withCounter()<br>    .labels(service)<br>    .maxLabeledInstancesPerSlice(3)<br>    .allSlice().noLevels());<br><br>// 4) Process requests for 6 different services<br>for (int i = 1; i &lt;= 6; ++i) {<br>    counter.inc(forLabelValues(service.value(&quot;service-&quot; + i)));<br>    sleep(2);<br>}<br><br>// Labeled metric instances are added asynchronously<br>sleep(100);<br><br>// 5) Create exporter<br>var exporter = new PrometheusMetricsExporter(registry);<br><br>// 6) Export metrics<br>System.out.println(exporter.exportMetrics());</pre><p>Output:</p><pre># HELP requests_total Generated from metric instances with name requests.total<br># TYPE requests_total gauge<br>requests_total{service=&quot;service-4&quot;,} 1.0<br>requests_total{service=&quot;service-5&quot;,} 1.0<br>requests_total{service=&quot;service-6&quot;,} 1.0</pre><p>As expected, there are only 3 instances of the metric requests_total left.</p><p><a href="https://github.com/ringcentral/metrics-facade/blob/articles/metrics-facade-articles/src/main/java/com/ringcentral/platform/metrics/articles/intro/Listing08.java">Example of expiration</a>:</p><pre>// 1) Create registry<br>var registry = new DefaultMetricRegistry();<br><br>// 2) Define labels<br>var service = new Label(&quot;service&quot;);<br><br>// 3) Register metric<br>Counter counter = registry.counter(withName(&quot;requests&quot;, &quot;total&quot;), () -&gt; withCounter()<br>    .labels(service)<br>    .expireLabeledInstanceAfter(1, SECONDS)<br>    .allSlice().noLevels());<br><br>// 4) Process requests for 3 different services<br>for (int i = 1; i &lt;= 3; ++i) {<br>    counter.inc(forLabelValues(service.value(&quot;service-&quot; + i)));<br>}<br><br>// Labeled metric instances are added asynchronously<br>sleep(100);<br><br>// 5) Create exporter<br>var exporter = new PrometheusMetricsExporter(registry);<br><br>// 6) Export metrics before expiration time has passed<br>System.out.println(&quot;Before expiration time:\n&quot; + exporter.exportMetrics());<br><br>// 7) Export metrics after expiration time has passed.<br>// We have to add 10 seconds because (expireLabeledInstanceAfter + 10) seconds is a period of checking MetricInstances for expiration<br>sleep(TimeUnit.SECONDS.toMillis(1) + TimeUnit.SECONDS.toMillis(10));<br><br>System.out.println(&quot;After expiration time:\n&quot; + exporter.exportMetrics());</pre><p>Output:</p><pre>Before expiration time:<br><br># HELP requests_total Generated from metric instances with name requests.total<br># TYPE requests_total gauge<br>requests_total{service=&quot;service-1&quot;,} 1.0<br>requests_total{service=&quot;service-2&quot;,} 1.0<br>requests_total{service=&quot;service-3&quot;,} 1.0<br><br>After expiration time:</pre><p>As expected, there are no requests_total metrics after expiration time has passed.</p><h3>Slices and Levels</h3><p>We often find it useful to aggregate measurements based on specific conditions or labels. Metrics Facade provides this flexibility through the concepts of slices and levels.</p><p><strong>Slice</strong> is a child metric that considers only those updates of the parent metric that satisfy a given condition or predicate. A slice can have its own configuration: name suffix, labels (which must be a sublist of the parent metric’s labels), measurable values, etc. By default, a metric has only one slice — AllSlice, which takes all updates into account.</p><p><strong>Slice Level</strong> is a set of MetricInstances of the slice for the first k labels, where k ranges from 1 to &lt;label_count&gt; — 1.</p><p>Consider the example of a timer with two labels — service and server:</p><pre>Timer httpClientRequestTimer = registry.timer(withName(&quot;http&quot;, &quot;client&quot;, &quot;request&quot;, &quot;duration&quot;, &quot;seconds&quot;), () -&gt; withTimer()<br>    .labels(service, server)<br>    // We leave only one measurable for the sake of brevity<br>    .measurables(COUNT));</pre><p>Here, we may find it useful to have:</p><ol><li>MetricInstance for each service, summarizing all updates for this service.</li><li>MetricInstance for each server, where it suffices to measure only MAX, MEAN, and PERCENTILE_99, considering only updates for services whose name either starts with “auth” or contains the “contacts” substring.</li></ol><p>We can use the functionality of slices and levels to implement these requirements, as shown in <a href="https://github.com/ringcentral/metrics-facade/blob/articles/metrics-facade-articles/src/main/java/com/ringcentral/platform/metrics/articles/intro/Listing09.java">Listing09</a>:</p><pre>// 1) Create registry<br>var registry = new DefaultMetricRegistry();<br><br>// 2) Define labels<br>var service = new Label(&quot;service&quot;);<br>var server = new Label(&quot;server&quot;);<br><br>// 3) Register metric<br>Timer httpClientRequestTimer = registry.timer(withName(&quot;http&quot;, &quot;client&quot;, &quot;request&quot;), () -&gt; withTimer()<br>    .labels(service, server)<br>    .measurables(COUNT, TOTAL_SUM)<br>    .allSlice().enableLevels() // implements requirement 1. Enabled by default for AllSlice<br>    .slice(&quot;by&quot;, &quot;server&quot;) // implements requirement 2<br>        .predicate(labelValuesMatchingAll(service.mask(&quot;auth*|*contacts*&quot;)))<br>        .labels(server)<br>        .measurables(MAX, MEAN, PERCENTILE_99)<br>        .noTotal()); // disable total instance for this slice<br><br>// 4) Update metric<br><br>// 4.1) (auth, 127.0.0.1). Let&#39;s assume that there were 2 requests: 100 and 300 milliseconds long<br>httpClientRequestTimer.update(<br>    100, MILLISECONDS,<br>    forLabelValues(service.value(&quot;auth&quot;), server.value(&quot;127.0.0.1&quot;)));<br><br>httpClientRequestTimer.update(<br>    300, MILLISECONDS,<br>    forLabelValues(service.value(&quot;auth&quot;), server.value(&quot;127.0.0.1&quot;)));<br><br>// 4.2) (auth, 127.0.0.2). Let&#39;s assume that there were 2 requests: 200 and 400 milliseconds long<br>httpClientRequestTimer.update(<br>    200, MILLISECONDS,<br>    forLabelValues(service.value(&quot;auth&quot;), server.value(&quot;127.0.0.2&quot;)));<br><br>httpClientRequestTimer.update(<br>    400, MILLISECONDS,<br>    forLabelValues(service.value(&quot;auth&quot;), server.value(&quot;127.0.0.2&quot;)));<br><br>// 4.3) (user-contacts, 127.0.0.3): start a stopwatch before executing the request<br>Stopwatch stopwatch = httpClientRequestTimer.stopwatch(forLabelValues(<br>    service.value(&quot;user-contacts&quot;),<br>    server.value(&quot;127.0.0.3&quot;)));<br><br>// The (user-contacts, 127.0.0.3) request execution took 600 milliseconds<br>sleep(600);<br><br>// Stop the stopwatch after executing the request to (user-contacts, 127.0.0.3)<br>stopwatch.stop();<br><br>// Labeled metric instances are added asynchronously<br>sleep(100);<br><br>// 5) Create exporter<br>var exporter = new TelegrafMetricsJsonExporter(false, registry);<br><br>// 6) Export metrics<br>System.out.println(new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(exporter.exportMetrics()));</pre><p>Output:</p><pre>{<br>  // Total instance:<br>  &quot;http.client.request.count&quot;: 5,<br>  &quot;http.client.request.duration.totalSum&quot;: 1602.8731619999999,<br>  <br>  // Level instances with label &quot;service&quot;:<br>  &quot;http.client.request.auth.count&quot;: 4,<br>  &quot;http.client.request.auth.duration.totalSum&quot;: 1000.0,<br>  <br>  &quot;http.client.request.user-contacts.count&quot;: 1,<br>  &quot;http.client.request.user-contacts.duration.totalSum&quot;: 602.873162,<br>  <br>  // Regular labeled instances with labels &quot;service&quot; and &quot;server&quot;:<br>  &quot;http.client.request.auth.127.0.0.1.count&quot;: 2,<br>  &quot;http.client.request.auth.127.0.0.1.duration.totalSum&quot;: 400.0,<br>  <br>  &quot;http.client.request.auth.127.0.0.2.count&quot;: 2,<br>  &quot;http.client.request.auth.127.0.0.2.duration.totalSum&quot;: 600.0,<br>  <br>  &quot;http.client.request.user-contacts.127.0.0.3.count&quot;: 1,<br>  &quot;http.client.request.user-contacts.127.0.0.3.duration.totalSum&quot;: 602.873162,<br>  <br>  // Instances of the &quot;by.server&quot; slice:<br>  &quot;http.client.request.by.server.127.0.0.1.duration.max&quot;: 301.989887,<br>  &quot;http.client.request.by.server.127.0.0.1.duration.mean&quot;: 200.409088,<br>  &quot;http.client.request.by.server.127.0.0.1.duration.99_percentile&quot;: 301.989887,<br>  <br>  &quot;http.client.request.by.server.127.0.0.2.duration.max&quot;: 400.55603099999996,<br>  &quot;http.client.request.by.server.127.0.0.2.duration.mean&quot;: 299.630592,<br>  &quot;http.client.request.by.server.127.0.0.2.duration.99_percentile&quot;: 400.55603099999996,<br>  <br>  &quot;http.client.request.by.server.127.0.0.3.duration.max&quot;: 603.979775,<br>  &quot;http.client.request.by.server.127.0.0.3.duration.mean&quot;: 601.882624,<br>  &quot;http.client.request.by.server.127.0.0.3.duration.99_percentile&quot;: 603.979775<br>}</pre><p>In this example, we’ve opted to use TelegrafMetricsJsonExporter instead of PrometheusMetricsExporter. This decision is based on the consideration that the concept of levels doesn’t integrate well with Prometheus. Prometheus has its own built-in capability to aggregate metrics, making the use of levels redundant or potentially conflicting.</p><p>As you can see from the output, the following MetricInstances were created:</p><ol><li><strong>Total instance</strong>. This is a total instance that has received all the five updates as represented by “http.client.request.count”: 5.</li><li><strong>Level instances with label service</strong>. These are automatically created level instances associated with each service. For example, there were four requests to the service “auth” (“http.client.request.auth.count”: 4), and their total duration sums up to 1000 (“http.client.request.auth.duration.totalSum”: 1000.0).</li><li><strong>Regular labeled instances with labels service and server</strong>. These are regular instances labeled with both service and server. For example, there was two request to the service “auth” and the server “127.0.0.1” (“http.client.request.auth.127.0.0.1.count”: 2), and their total duration sums up to 400 (“http.client.request.auth.127.0.0.1.duration.totalSum”: 400.0).</li><li><strong>Instances of the “by.server” slice</strong>. These are instances specific to the “by server” slice. For each server, measurables such as maximum duration (…duration.max), mean duration (…duration.mean), and 99th percentile duration (…duration.99_percentile) are recorded. For example, for the server “127.0.0.1”, the maximum duration was approximately 300 (“http.client.request.by.server.127.0.0.1.duration.max”: 301.989887), the mean duration was approximately 200 (“http.client.request.by.server.127.0.0.1.duration.mean”: 200.409088), and the 99th percentile duration was approximately 300 (“http.client.request.by.server.127.0.0.1.duration.99_percentile”: 301.989887).</li></ol><p>In the next section, we’ll describe the configuration capabilities of the library.</p><h3>Flexible Configuration</h3><p>The library allows you to set parameter defaults and override parameters for a subset of metrics selected with a predicate.</p><p>Suppose you have multiple timers in your project. For most of them, you want to measure Counter.COUNT, Histogram.MAX, Histogram.MEAN, Histogram.PERCENTILE_90. However, for the timer for processing incoming HTTP requests, you also want to measure Histogram.MIN, Histogram.PERCENTILE_75, and Histogram.PERCENTILE_99.</p><p>To achieve this:</p><ol><li>Set <strong>default</strong> measurables for timers:</li></ol><pre>registry.preConfigure(allMetrics(), modifying().timer(withTimer().measurables(<br>   COUNT,<br>   MAX, <br>   MEAN, <br>   PERCENTILE_90)));​​</pre><p>2. Set specific measurables when defining the timer for processing incoming HTTP requests (the defaults will be overridden):</p><pre>Timer httpRequestTimer = registry.timer(<br>   withName(&quot;http&quot;, &quot;request&quot;, &quot;duration&quot;),<br>   () -&gt; withTimer().measurables(<br>       COUNT,<br>       MIN,<br>       MAX,<br>       MEAN,<br>       PERCENTILE_75,<br>       PERCENTILE_90,<br>       PERCENTILE_99)</pre><p>For more detailed examples, refer to DefaultsSample.java and OverridesSample.java in the <a href="https://github.com/ringcentral/metrics-facade/tree/release_3-1/metrics-facade-samples">samples</a> module.</p><p>This configuration scheme allows:</p><ul><li>Set the configuration in one place without having to change the code of defining each metric involved.</li><li>Add (in future versions) support for new measurable values without breaking backward compatibility. Unlike most other libraries for working with metrics, the Metrics Facade interfaces do not provide methods for getting values of specific measured values, like double Histogram.mean(). Instead, methods are used that take Measurable as a parameter: MetricInstance.valueOf(Measurable) or MetricInstance.measurableValues().valueOf(Measurable). This design allows the library to remain extremely flexible in terms of supporting new features.</li></ul><h3>Configuration Stages</h3><p>Metric configurations are applied in the following order — the last applied wins:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/206/1*ofQFB2_m8017FHWvB16dXA.jpeg" /></figure><h4>Stage 0: Metric Defaults</h4><p>Each metric type has its own set of default Measurables. The default Measurables for Rate and Histogram are shown in the table below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DJuDsYmNQQmybgVu9Leilw.png" /></figure><p>These default Measurables are used if they are not overridden in subsequent stages.</p><h4>Stage 1: MetricRegistry.preConfigure</h4><p>MetricRegistry.preConfigure sets default parameters for a given set of metrics. Let’s say we want to disable the MIN, MAX and MEAN measurables for all histograms. MetricRegistry.preConfigure allows us to get rid of these undesired Measurables. <a href="https://github.com/ringcentral/metrics-facade/blob/articles/metrics-facade-articles/src/main/java/com/ringcentral/platform/metrics/articles/intro/Listing10.java">Listing10</a>:</p><pre>// 1) Create registry<br>var registry = new DefaultMetricRegistry();<br><br>// 2) Set up the default set of Measurables for histograms<br>registry.preConfigure(<br>    allMetrics(),<br>    modifying().histogram(withHistogram().measurables(COUNT, TOTAL_SUM, PERCENTILE_50, PERCENTILE_90, PERCENTILE_99)));<br><br>// 3) Register histogram<br>Histogram histogram = registry.histogram(withName(&quot;histogram&quot;, &quot;override&quot;, &quot;metricTypeDefault&quot;, &quot;measurables&quot;));<br><br>// 4) Update histogram<br>for (int i = 0; i &lt; 10; ++i) {<br>    histogram.update(i);<br>}<br><br>// 5) Create exporter<br>var exporter = new PrometheusMetricsExporter(registry);<br><br>// 7) Export metrics<br>System.out.println(exporter.exportMetrics());</pre><p>Output:</p><pre># HELP histogram_override_metricTypeDefault_measurables Generated from metric instances with name histogram.override.metricTypeDefault.measurables<br># TYPE histogram_override_metricTypeDefault_measurables summary<br>histogram_override_metricTypeDefault_measurables{quantile=&quot;0.5&quot;,} 4.0<br>histogram_override_metricTypeDefault_measurables{quantile=&quot;0.9&quot;,} 8.0<br>histogram_override_metricTypeDefault_measurables{quantile=&quot;0.99&quot;,} 9.0<br>histogram_override_metricTypeDefault_measurables_count 10.0<br>histogram_override_metricTypeDefault_measurables_sum 45.0</pre><p>As expected, histogram_override_metricTypeDefault_measurables has only COUNT, SUM and PERCENTILE Measurables.</p><h4>Stage 2: Metric Definition</h4><p>Now, let’s suppose we need more detailed statistics for a particular Metric. In such cases, we can customize the Measurables by specifying them during the registration of the Metric. <a href="https://github.com/ringcentral/metrics-facade/blob/articles/metrics-facade-articles/src/main/java/com/ringcentral/platform/metrics/articles/intro/Listing11.java">Listing11</a>:</p><pre>// 1) Create registry<br>var registry = new DefaultMetricRegistry();<br><br>// 2) Set up the default set of Measurables for histograms<br>registry.preConfigure(<br>    allMetrics(),<br>    modifying().histogram(withHistogram().measurables(COUNT, TOTAL_SUM, PERCENTILE_50, PERCENTILE_90, PERCENTILE_99)));<br><br>// 3) Create Histogram with custom Measurables<br>Histogram histogram = registry.histogram(<br>    withName(&quot;histogram&quot;, &quot;override&quot;, &quot;metricTypeDefaultAndPreConfigured&quot;, &quot;measurables&quot;),<br>    () -&gt; withHistogram().measurables(<br>        COUNT,<br>        TOTAL_SUM,<br>        PERCENTILE_10, PERCENTILE_25, PERCENTILE_50, PERCENTILE_90, PERCENTILE_99, PERCENTILE_999));<br><br>// 4) Update histogram<br>for (int i = 0; i &lt; 10; i++) {<br>    histogram.update(i);<br>}<br><br>// 5) Create exporter<br>var exporter = new PrometheusMetricsExporter(registry);<br><br>// 6) Export metrics<br>System.out.println(exporter.exportMetrics());</pre><p>Output:</p><pre># HELP histogram_override_metricTypeDefaultAndPreConfigured_measurables Generated from metric instances with name histogram.override.metricTypeDefaultAndPreConfigured.measurables<br># TYPE histogram_override_metricTypeDefaultAndPreConfigured_measurables summary<br>histogram_override_metricTypeDefaultAndPreConfigured_measurables{quantile=&quot;0.1&quot;,} 0.0<br>histogram_override_metricTypeDefaultAndPreConfigured_measurables{quantile=&quot;0.25&quot;,} 2.0<br>histogram_override_metricTypeDefaultAndPreConfigured_measurables{quantile=&quot;0.5&quot;,} 4.0<br>histogram_override_metricTypeDefaultAndPreConfigured_measurables{quantile=&quot;0.9&quot;,} 8.0<br>histogram_override_metricTypeDefaultAndPreConfigured_measurables{quantile=&quot;0.99&quot;,} 9.0<br>histogram_override_metricTypeDefaultAndPreConfigured_measurables{quantile=&quot;0.999&quot;,} 9.0<br>histogram_override_metricTypeDefaultAndPreConfigured_measurables_count 10.0<br>histogram_override_metricTypeDefaultAndPreConfigured_measurables_sum 45.0</pre><p>As expected, histogram_override_metricTypeDefaultAndPreConfigured_measurables measures a greater number of PERCENTILEs.</p><h4>Stage 3: MetricRegistry.postConfigure</h4><p>Let’s imagine there is an environment where we are not very interested in PERCENTILE_99. MetricRegistry.postConfigure enables us to exclude the unwanted Measurable. <a href="https://github.com/ringcentral/metrics-facade/blob/articles/metrics-facade-articles/src/main/java/com/ringcentral/platform/metrics/articles/intro/Listing12.java">Listing12</a>:</p><pre>// 1) Create registry<br>var registry = new DefaultMetricRegistry();<br><br>// 2) Set up the default set of Measurables for histograms<br>registry.preConfigure(<br>    allMetrics(),<br>    modifying().histogram(withHistogram().measurables(COUNT, TOTAL_SUM, PERCENTILE_50, PERCENTILE_90, PERCENTILE_99)));<br><br>var inTargetEnvironment = true;<br><br>if (inTargetEnvironment) {<br>    // 3) Override any other definitions of set of Measurables for histograms<br>    registry.postConfigure(<br>        allMetrics(),<br>        modifying().histogram(withHistogram().measurables(COUNT, TOTAL_SUM, PERCENTILE_50, PERCENTILE_90)));<br>}<br><br>// 4) Create Histogram with custom Measurables<br>Histogram histogram = registry.histogram(<br>    withName(&quot;histogram&quot;, &quot;override&quot;, &quot;metricTypeDefaultAndPreConfiguredAndMetricDefinition&quot;, &quot;measurables&quot;),<br>    () -&gt; withHistogram().measurables(<br>        COUNT,<br>        TOTAL_SUM,<br>        PERCENTILE_10, PERCENTILE_25, PERCENTILE_50, PERCENTILE_90, PERCENTILE_99, PERCENTILE_999));<br><br>// 5) Update histogram<br>for (int i = 0; i &lt; 10; i++) {<br>    histogram.update(i);<br>}<br><br>// 6) Create exporter<br>var exporter = new PrometheusMetricsExporter(registry);<br><br>// 7) Export metrics<br>System.out.println(exporter.exportMetrics());</pre><p>Output:</p><pre># HELP histogram_override_metricTypeDefaultAndPreConfiguredAndMetricDefinition_measurables Generated from metric instances with name histogram.override.metricTypeDefaultAndPreConfiguredAndMetricDefinition.measurables<br># TYPE histogram_override_metricTypeDefaultAndPreConfiguredAndMetricDefinition_measurables summary<br>histogram_override_metricTypeDefaultAndPreConfiguredAndMetricDefinition_measurables{quantile=&quot;0.5&quot;,} 4.0<br>histogram_override_metricTypeDefaultAndPreConfiguredAndMetricDefinition_measurables{quantile=&quot;0.9&quot;,} 8.0<br>histogram_override_metricTypeDefaultAndPreConfiguredAndMetricDefinition_measurables_count 10.0<br>histogram_override_metricTypeDefaultAndPreConfiguredAndMetricDefinition_measurables_sum 45.0</pre><p>As expected, histogram_override_metricTypeDefaultAndPreConfiguredAndMetricDefinition_measurables has only COUNT, SUM, PERCENTILE_50, and PERCENTILE_90 Measurables.</p><h4>Predicates</h4><p>In the described scenarios, we configured the whole set of metrics using the allMetrics predicate, for example, registry.preConfigure(allMetrics(), …). However, the library offers many more specific predicates. Let’s say a third-party library registers its own Metrics that we are not particularly interested in. To reduce the set of Measurables for these metrics, we can do <a href="https://github.com/ringcentral/metrics-facade/blob/articles/metrics-facade-articles/src/main/java/com/ringcentral/platform/metrics/articles/intro/Listing13.java">the following</a>:</p><pre>// 1) Create registry<br>var registry = new DefaultMetricRegistry();<br><br>// 2) Reduce the set of Measurables for the third party metrics<br>registry.postConfigure(<br>    metricsWithNamePrefix(&quot;third.party&quot;),<br>    modifying().histogram(withHistogram().measurables(COUNT, TOTAL_SUM, PERCENTILE_99)));<br><br>// 3) Register third party metric<br>Histogram thirdPartyHistogram = registry.histogram(<br>    withName(&quot;third&quot;, &quot;party&quot;, &quot;histogram&quot;),<br>    () -&gt; withHistogram()<br>        .description(&quot;Third party histogram&quot;)<br>        .measurables(COUNT, TOTAL_SUM, PERCENTILE_50, PERCENTILE_90, PERCENTILE_99, PERCENTILE_999));<br><br>// 4) Register app metric<br>Histogram appHistogram = registry.histogram(<br>    withName(&quot;app&quot;, &quot;histogram&quot;),<br>    () -&gt; withHistogram()<br>        .description(&quot;App histogram&quot;)<br>        .measurables(COUNT, TOTAL_SUM, PERCENTILE_50, PERCENTILE_90, PERCENTILE_99));<br><br>// 5) Update histograms<br>for (int i = 0; i &lt; 10; ++i) {<br>    appHistogram.update(i);<br>    thirdPartyHistogram.update(i);<br>}<br><br>// 6) Create exporter<br>var exporter = new PrometheusMetricsExporter(registry);<br><br>// 7) Export metrics<br>System.out.println(exporter.exportMetrics());</pre><p>Output:</p><pre># HELP third_party_histogram Third party histogram<br># TYPE third_party_histogram summary<br>third_party_histogram{quantile=&quot;0.99&quot;,} 9.0<br>third_party_histogram_count 10.0<br>third_party_histogram_sum 45.0<br><br># HELP app_histogram App histogram<br># TYPE app_histogram summary<br>app_histogram{quantile=&quot;0.5&quot;,} 4.0<br>app_histogram{quantile=&quot;0.9&quot;,} 8.0<br>app_histogram{quantile=&quot;0.99&quot;,} 9.0<br>app_histogram_count 10.0<br>app_histogram_sum 45.0</pre><p>As expected, the third party metric has the reduced set of Measurables.</p><p>The library provides plenty of predicates out-of-the-box, that allows us to select any subset of metrics to be modified:</p><pre>registry.postConfigure(metricWithName(&quot;a.b.c&quot;), modifying().metric(withMetric().disable()));<br>registry.postConfigure(metricsWithNamePrefix(&quot;a.b&quot;), modifying().histogram(withHistogram().enable()));<br>registry.postConfigure(metricsMatchingNameMask(&quot;a.**.b&quot;), modifying().histogram(withHistogram().enable()));<br><br>registry.postConfigure(<br>    metrics()<br>        .including(metricsMatchingNameMask(&quot;a.b.**.d.**&quot;)).excluding(metricWithName(&quot;a.b.c.d&quot;))<br>        .including(metricsWithNamePrefix(&quot;d.e.f&quot;)).excluding(metricsWithNamePrefix(&quot;d.e.f.g&quot;)),<br>    modifying().meter(withMeter().disable()));<br><br>assert registry.timer(withName(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;)).isEnabled();<br>assert !registry.timer(withName(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;, &quot;e&quot;)).isEnabled(); // disabled<br>assert !registry.timer(withName(&quot;a&quot;, &quot;b&quot;, &quot;x&quot;, &quot;d&quot;)).isEnabled(); // disabled<br>assert !registry.timer(withName(&quot;d&quot;, &quot;e&quot;, &quot;f&quot;)).isEnabled(); // disabled<br>assert registry.timer(withName(&quot;d&quot;, &quot;e&quot;, &quot;f&quot;, &quot;g&quot;)).isEnabled();<br>assert registry.timer(withName(&quot;d&quot;, &quot;e&quot;, &quot;f&quot;, &quot;g&quot;, &quot;h&quot;)).isEnabled();</pre><p>In the next section, we will learn about exporting metrics, making them available for visualizing and analyzing.</p><h3>Metric Reporters</h3><p>Typically, metrics are used to provide runtime information about an application instance. In order to do this, it is necessary not only to collect metrics but also to export them to external monitoring systems that provide various means of visualizing and analyzing the collected metrics. For example, <a href="https://prometheus.io/">Prometheus</a>.</p><p><strong>Metrics reporter</strong> allows you to present metrics in the format of a specific monitoring system; some reporters additionally send metrics to an external monitoring system in the appropriate format.</p><p>Let’s explore one of the most widely used PrometheusMetricsExporter.</p><h3>PrometheusMetricsExporter</h3><p>PrometheusMetricsExporter exports metrics in the <a href="https://prometheus.io/">Prometheus</a> format.</p><p>To use this exporter, you need to add the following dependency:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;com.ringcentral.platform.metrics&lt;/groupId&gt;<br>    &lt;artifactId&gt;metrics-facade-prometheus&lt;/artifactId&gt;<br>    &lt;version&gt;3.1.0-SNAPSHOT&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p><a href="https://github.com/ringcentral/metrics-facade/blob/articles/metrics-facade-articles/src/main/java/com/ringcentral/platform/metrics/articles/intro/Listing14.java">Example</a>:</p><pre>// 1) Create registry<br>var registry = new DefaultMetricRegistry();<br><br>// 2) Define labels<br>var service = new Label(&quot;service&quot;);<br><br>// 3) Register metric<br>Histogram histogram = registry.histogram(withName(&quot;failover&quot;, &quot;count&quot;, &quot;histogram&quot;), () -&gt; withHistogram()<br>    .description(&quot;Failover count histogram&quot;)<br>    .labels(service)<br>    .measurables(<br>        COUNT, TOTAL_SUM,<br>        Buckets.of(linearScale().from(0).steps(1, 2).withInf()),<br>        PERCENTILE_50)<br>    // We&#39;ve changed the Histogram implementation to Scale, which we&#39;ll describe in detail in the upcoming article<br>    .impl(scale().with(linearScale().from(0).steps(1, 2).withInf())));<br><br>// 4) Update metric<br>histogram.update(0, forLabelValues(service.value(&quot;auth&quot;)));<br>histogram.update(1, forLabelValues(service.value(&quot;auth&quot;)));<br><br>histogram.update(1, forLabelValues(service.value(&quot;contacts&quot;)));<br>histogram.update(2, forLabelValues(service.value(&quot;contacts&quot;)));<br><br>// Metric instances are added asynchronously<br>sleep(100);<br><br>// 5) Create exporter<br>PrometheusMetricsExporter exporter = new PrometheusMetricsExporter(registry);<br><br>// 5) Export metrics<br>System.out.println(exporter.exportMetrics());</pre><p>Output:</p><pre># HELP failover_count_histogram Failover count histogram<br># TYPE failover_count_histogram histogram<br>failover_count_histogram_bucket{service=&quot;auth&quot;,le=&quot;0&quot;,} 1.0<br>failover_count_histogram_bucket{service=&quot;auth&quot;,le=&quot;1&quot;,} 2.0<br>failover_count_histogram_bucket{service=&quot;auth&quot;,le=&quot;2&quot;,} 2.0<br>failover_count_histogram_bucket{service=&quot;auth&quot;,le=&quot;+Inf&quot;,} 2.0<br>failover_count_histogram_count{service=&quot;auth&quot;,} 2.0<br>failover_count_histogram_sum{service=&quot;auth&quot;,} 1.0<br><br>failover_count_histogram_bucket{service=&quot;contacts&quot;,le=&quot;0&quot;,} 0.0<br>failover_count_histogram_bucket{service=&quot;contacts&quot;,le=&quot;1&quot;,} 1.0<br>failover_count_histogram_bucket{service=&quot;contacts&quot;,le=&quot;2&quot;,} 2.0<br>failover_count_histogram_bucket{service=&quot;contacts&quot;,le=&quot;+Inf&quot;,} 2.0<br>failover_count_histogram_count{service=&quot;contacts&quot;,} 2.0<br>failover_count_histogram_sum{service=&quot;contacts&quot;,} 3.0<br><br># HELP failover_count_histogram_summary Failover count histogram<br># TYPE failover_count_histogram_summary summary<br>failover_count_histogram_summary{service=&quot;auth&quot;,quantile=&quot;0.5&quot;,} 0.0<br>failover_count_histogram_summary_count{service=&quot;auth&quot;,} 2.0<br>failover_count_histogram_summary_sum{service=&quot;auth&quot;,} 1.0<br><br>failover_count_histogram_summary{service=&quot;contacts&quot;,quantile=&quot;0.5&quot;,} 1.0<br>failover_count_histogram_summary_count{service=&quot;contacts&quot;,} 2.0<br>failover_count_histogram_summary_sum{service=&quot;contacts&quot;,} 3.0</pre><p>You have the flexibility to extensively modify the export: adjust names, disable certain metrics or measurables, etc. For this particular export, suppose you want to:</p><ol><li>Disable metric instances for contacts service.</li><li>Disable the Histogram.MEAN measurable.</li></ol><p>You can accomplish this <a href="https://github.com/ringcentral/metrics-facade/blob/articles/metrics-facade-articles/src/main/java/com/ringcentral/platform/metrics/articles/intro/Listing15.java">as follows</a>:</p><pre>// 1) Create registry<br>var registry = new DefaultMetricRegistry();<br><br>// 2) Define labels<br>var service = new Label(&quot;service&quot;);<br><br>// 3) Register metric<br>Histogram histogram = registry.histogram(withName(&quot;failover&quot;, &quot;count&quot;, &quot;histogram&quot;), () -&gt; withHistogram()<br>    .description(&quot;Failover count histogram&quot;)<br>    .labels(service)<br>    .measurables(<br>        COUNT, TOTAL_SUM,<br>        Buckets.of(linearScale().from(0).steps(1, 2).withInf()),<br>        PERCENTILE_50)<br>    // We&#39;ve changed the Histogram implementation to Scale, which we&#39;ll describe in detail in the upcoming article<br>    .impl(scale().with(linearScale().from(0).steps(1, 2).withInf())));<br><br>// 4) Update metric<br>histogram.update(0, forLabelValues(service.value(&quot;auth&quot;)));<br>histogram.update(1, forLabelValues(service.value(&quot;auth&quot;)));<br><br>histogram.update(1, forLabelValues(service.value(&quot;contacts&quot;)));<br>histogram.update(2, forLabelValues(service.value(&quot;contacts&quot;)));<br><br>// Metric instances are added asynchronously<br>sleep(100);<br><br>// 4) Define exporter<br><br>// 4.1) Modify MetricInstances export. To do this, we need to modify instance sample specs:<br>PrometheusInstanceSampleSpecModsProvider instanceSampleSpecModsProvider = new PrometheusInstanceSampleSpecModsProvider();<br><br>instanceSampleSpecModsProvider.addMod(<br>    forMetricInstancesMatching(namePrefix(&quot;failover&quot;), instance -&gt; &quot;contacts&quot;.equals(instance.valueOf(service))),<br>    (metric, instance, currSpec) -&gt; instanceSampleSpec().disable());<br><br>// 4.2) Modify measurables export. To do this, we need to modify sample specs:<br>PrometheusSampleSpecModsProvider sampleSpecModsProvider = new PrometheusSampleSpecModsProvider();<br><br>sampleSpecModsProvider.addMod(<br>    forMetricInstancesMatching(namePrefix(&quot;failover&quot;), instance -&gt; instance instanceof HistogramInstance),<br>    (instanceSampleSpec, instance, measurableValues, measurable, currSpec) -&gt;<br>         sampleSpec().enabled(!(measurable instanceof Histogram.Percentile)));<br><br>// 4.3) Create exporter<br>PrometheusMetricsExporter exporter = new PrometheusMetricsExporter(prometheusInstanceSamplesProvider(registry)<br>    .instanceSampleSpecModsProvider(instanceSampleSpecModsProvider)<br>    .sampleSpecModsProvider(sampleSpecModsProvider)<br>    .build());<br><br>// 5) Export metrics<br>System.out.println(exporter.exportMetrics());</pre><p>Output:</p><pre># HELP failover_count_histogram_summary Failover count histogram<br># TYPE failover_count_histogram_summary summary<br>failover_count_histogram_summary_count{service=&quot;auth&quot;,} 2.0<br>failover_count_histogram_summary_sum{service=&quot;auth&quot;,} 1.0<br><br># HELP failover_count_histogram Failover count histogram<br># TYPE failover_count_histogram histogram<br>failover_count_histogram_bucket{service=&quot;auth&quot;,le=&quot;0&quot;,} 1.0<br>failover_count_histogram_bucket{service=&quot;auth&quot;,le=&quot;1&quot;,} 2.0<br>failover_count_histogram_bucket{service=&quot;auth&quot;,le=&quot;2&quot;,} 2.0<br>failover_count_histogram_bucket{service=&quot;auth&quot;,le=&quot;+Inf&quot;,} 2.0<br>failover_count_histogram_count{service=&quot;auth&quot;,} 2.0<br>failover_count_histogram_sum{service=&quot;auth&quot;,} 1.0</pre><p>The library also provides the following built-in reporters:</p><ul><li><a href="https://github.com/ringcentral/metrics-facade#zabbixmetricsjsonexporter-and-zabbixlldmetricsreporter">ZabbixMetricsJsonExporter and ZabbixLldMetricsReporter</a></li><li><a href="https://github.com/ringcentral/metrics-facade#telegrafmetricsjsonexporter">TelegrafMetricsJsonExporter</a></li><li><a href="https://github.com/ringcentral/metrics-facade#jmxmetricsreporter">JmxMetricsReporter</a></li></ul><p>In the next section, we’ll show how to enrich your applications with commonly used sets of metrics in a quick and convenient way.</p><h3>Metric Producers</h3><p>When working on multiple projects, developers often redefine the same metrics over and over, particularly those related to system performance. This practice is not only labor-intensive but also prone to inconsistencies and errors.</p><p>MetricProducer offers a solution to this challenge by adding a predefined set of commonly used metrics into a registry. Consider the following <a href="https://github.com/ringcentral/metrics-facade/blob/articles/metrics-facade-articles/src/main/java/com/ringcentral/platform/metrics/articles/intro/Listing16.java">example</a>, where SystemMetricsProducer registers a comprehensive suite of system metrics:</p><pre>// 1) Create registry<br>var registry = new DefaultMetricRegistry();<br><br>// 2) Produce system metrics:<br>new SystemMetricsProducer().produceMetrics(registry);<br><br>// 3) Create exporter<br>PrometheusMetricsExporter exporter = new PrometheusMetricsExporter(registry);<br><br>// 4) Export metrics<br>System.out.println(exporter.exportMetrics());</pre><p>Output (simplified):</p><pre># HELP Memory_heap_usage Used divided by max<br># TYPE Memory_heap_usage gauge<br>Memory_heap_usage 0.0024309158325195312<br># HELP OperatingSystem_processCpuLoad The &#39;recent cpu usage&#39; for the process of corresponding type<br># TYPE OperatingSystem_processCpuLoad gauge<br>OperatingSystem_processCpuLoad 0.0<br># HELP Threads_count The current number of live threads including both daemon and non-daemon threads<br># TYPE Threads_count gauge<br>Threads_count 7.0<br># HELP Classes_loaded The number of classes that are currently loaded in the Java virtual machine<br># TYPE Classes_loaded gauge<br>Classes_loaded 1791.0<br># HELP Runtime_startTime The start time of the Java virtual machine in milliseconds<br># TYPE Runtime_startTime gauge<br>Runtime_startTime 1.684080364168E12<br># HELP Memory_heap_max The maximum amount of memory in bytes that can be used for memory management<br># TYPE Memory_heap_max gauge<br>Memory_heap_max 4.294967296E9<br># HELP OperatingSystem_committedVirtualMemorySize The amount of virtual memory that is guaranteed to be available to the running process in bytes<br># TYPE OperatingSystem_committedVirtualMemorySize gauge<br>OperatingSystem_committedVirtualMemorySize 4.1064493056E10<br># HELP Memory_non_heap_committed The amount of memory in bytes that is committed for the Java virtual machine to use<br># TYPE Memory_non_heap_committed gauge<br>Memory_non_heap_committed 1.31072E7<br>...</pre><p>The library provides the following MetricProducers:</p><ul><li>SystemMetricsProducer: a comprehensive suite of metrics related to system performance, combining all the producers listed below.</li><li>RuntimeMetricsProducer: metrics associated with the Java Virtual Machine (JVM).</li><li>OperatingSystemMetricsProducer: metrics specific to the operating system.</li><li>GarbageCollectorsMetricsProducer: metrics related to garbage collection activities.</li><li>MemoryMetricsProducer: metrics detailing memory usage.</li><li>ThreadsMetricsProducer: metrics related to thread activities.</li><li>BufferPoolsMetricsProducer: metrics related to buffer pools.</li></ul><p>ClassesMetricsProducer: metrics related to the JVM’s class loading system.</p><h3>Integration with Spring Boot</h3><p>Metrics Facade provides full integration with Spring Boot, making it easy to incorporate its powerful features into your Spring Boot applications. To get started with this integration, check out the comprehensive example available in the <a href="https://github.com/ringcentral/metrics-facade/tree/release_3-1/metrics-facade-spring/metrics-facade-spring-boot-sample-app">metrics-facade-spring-boot-sample-app</a> module. In an upcoming article, we will delve into the details of integrating Metrics Facade with Spring Boot. We will provide you with step-by-step guidance and best practices for a seamless experience.</p><h3>To Sum Up</h3><p>In this introductory article, we’ve provided an overview of the key concepts and features of the RingCentral Metrics Facade library, which offers a unified and flexible API for collecting and exporting various types of metrics. You can find practical examples demonstrating all the features of the library in the <a href="https://github.com/ringcentral/metrics-facade/tree/release_3-1/metrics-facade-samples">samples</a> module. These examples will help you gain a deeper understanding of how to effectively use the library in your projects.</p><p>In the upcoming article, we will explore the metric implementations available in the library and provide you with respective benchmarks to help you better understand their performance characteristics. For more information and a comprehensive overview of the library, be sure to visit the <a href="https://github.com/ringcentral/metrics-facade">README</a> on the project’s GitHub page.</p><p>Stay tuned for the next article in the series, and happy metric collecting!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e12b5900ee03" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I became a mentor at QA BootCamp and realized flaws in my work process]]></title>
            <link>https://medium.com/@jettycloud/how-i-became-a-mentor-at-qa-bootcamp-and-realized-flaws-in-my-work-process-d174d9b3469d?source=rss-9ab6c9a6474f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d174d9b3469d</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[qa-testing]]></category>
            <category><![CDATA[qa]]></category>
            <category><![CDATA[process-improvement]]></category>
            <dc:creator><![CDATA[JettyCloud]]></dc:creator>
            <pubDate>Mon, 16 Oct 2023 07:18:18 GMT</pubDate>
            <atom:updated>2023-10-16T07:18:41.091Z</atom:updated>
            <content:encoded><![CDATA[<h3>How I became a mentor and realized flaws in my work process</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SvWsEWSyF3ek_Lz1v0RqcA.png" /></figure><p>Hi everyone! My name is Olga Melnikova, and I work at Jetty Cloud. Last year our company held the QA BootCamp — a project for relatives of the employees, that allowed them to learn what a QA engineer does. Lecturers and mentors shared the knowledge needed to work in the IT industry.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7yDlDGUoE3rvW_hJ_Krxxw.jpeg" /><figcaption>Olga Melnikova</figcaption></figure><p>The employees of our company became speakers and mentors. I thought it could be an interesting experience for me too: I had never trained anyone or given public lectures before. I thought it would be easy — after all, I have more than 15 years of experience in testing, what could go wrong? I was offered to choose the topics I was ready to talk about. I chose ones that seemed simple to me: Test Documentation and Test case.</p><p>In reality everything turned out to be not so simple. To prepare lectures on the theory of testing, I had to process a huge amount of information. Books, Google articles, descriptions of standards. I spent hours going through them. But finally I managed to write the lectures and record videos on them. And in the process of preparing these lectures and answering participants’ questions, I realized that I don’t use much of what I talk about in my work. To be more precise, it was as if we had completely forgotten that the test processes depend on the context and should be different for each project.</p><h3>Organization of our QA process</h3><p>In this section I would like to briefly talk about our working processes. We test a Media Server that interacts directly with clients. Due to this, our testing process has some peculiarities.</p><ol><li>There is almost no business logic in the server (= no use cases).</li><li>We have a large number of client-specific tests because the service interacts directly with clients.</li><li>Passing an end-to-end test is not always an indicator that everything has worked correctly. Therefore, we have to analyze logs and traces.</li><li>There are many complex technical details.</li></ol><p>We really tried hard to write good quality, detailed test cases so that all the necessary information for testing execution would be included in the test. It would allow people from other teams or new colleagues to easily run pass the test case following our steps, or use the tests to study the system’s operation, and so on. And at some point, it became clear that we couldn’t keep up.</p><p>Writing tests became very difficult: analyzing logs, analyzing traffic, working with the network — blocking traffic, adding problems to the network, and so on. Features appeared, disappeared, changed. Tests became outdated. Some implementation details changed. All of this led to the need of updating a large number of test cases, and provoked stress and dissatisfaction with the work outcomes.</p><p>As a result, we encountered the following problems:</p><ul><li>Test cases were way too complex and unreadable. It was challenging to extract the essential information from cumbersome and very detailed steps.</li><li>The functionality of the server changed periodically, rendering the tests invalid.</li><li>Supporting and writing test cases consumed a lot of time. The more details there were in a test, the harder it was to create and keep it up to date.</li><li>Many functionally similar tests existed for different types of clients.</li></ul><p>It turned out that the team spent a lot of time writing and maintaining detailed test cases. The team struggled to complete testing on time and ensure the proper quality of the product.</p><h3>Reflections after QA BootCamp</h3><p>While I was giving lectures, I realized that I don’t always apply in my work what I’m telling the participants of the QA BootCamp. Specifically, that testing heavily depends on the context. Depending on the project’s characteristics, the choice of testing documentation can vary. There are no universally applicable solutions. Sometimes it’s better to write detailed test cases, and other times it’s better to stick to a checklist. I started thinking that I’m not actually following my own advice in my job. We consulted with the team and decided to adapt our process to the existing conditions.</p><p>We made the following decisions:</p><ul><li>We no longer wait for test cases to be perfect.</li><li>We no longer expect test cases to contain all the necessary information for test execution.</li><li>We no longer expect any engineer to be able to pass our tests without preparation.</li><li>We are okay with the fact that our tests require some learning and knowledge of our project to be executed and understood.</li></ul><h3>Changes we applied to the Work Process</h3><ol><li><strong>We have moved all our end-to-end tests out of the test management tool into a Google Sheets spreadsheet and named it “Acceptance”.</strong> It’s essentially a list of features that need to be tested across all types of clients.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GVFI4_t3GQrgNKgoodAZXQ.png" /></figure><p>For each release, we copy the spreadsheet, record the release version and client versions. We then update the results of our tests in the spreadsheet and add the testing results to our test report.</p><p><strong>2. We have stopped writing detailed tests.</strong> We then update the results of our tests in the spreadsheet and add the testing results to our test report. We have stopped writing detailed tests. In the tests, we now only write steps, while all technical details are documented in our internal Wikipedia. Writing a test used to take over an hour, as we had to insert log excerpts, Wireshark screenshots, and describe how to properly set up a filter for Wireshark. Then, if something changed, like in the logs, the tests became invalid, and we had to edit many tests at once.</p><p>Now, in the tests, we only insert a link to the relevant Wikipedia page with a description of the feature, examples of logs, and traces. This way, if something changes, we only need to edit one Wikipedia page, and not 10 test cases.</p><h3>Impact on Our Processes</h3><ol><li>It has become easier for us to track the status of acceptance testing — e-2-e client-specific tests.</li><li>Tests have become easier and quicker to write and maintain.</li><li>Now, if something changes, we don’t have to edit in multiple places — we just make the necessary corrections in one place on the internal Wikipedia.</li><li>A knowledge base has been established on the Wikipedia.</li><li>Tests have become more readable.</li><li>The team has freed up time for other activities.</li></ol><p>Sometimes it’s beneficial to rethink your processes and approaches. It’s important to remember that different situations require different solutions — if a certain approach worked well in a previous project, it doesn’t mean it will work equally well in a new project. Sometimes you have to deviate from your quality standards in specific areas to maintain the overall project quality.</p><p>Have you experienced similar situations at work? Share your experiences in the comments; it’s interesting to hear about your cases!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d174d9b3469d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Fiber & Concurrency Part 2]]></title>
            <link>https://medium.com/@jettycloud/react-fiber-concurrency-part-2-5e32e4dac96?source=rss-9ab6c9a6474f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e32e4dac96</guid>
            <category><![CDATA[react-fiber]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[rendering]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[JettyCloud]]></dc:creator>
            <pubDate>Mon, 02 Oct 2023 10:37:14 GMT</pubDate>
            <atom:updated>2023-10-02T10:37:14.991Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*axAVvPI4-rR4ibZYWb_7MA.png" /></figure><p>My name is <a href="https://medium.com/@dimaglazkoff">Dmitrii Glazkov</a>, I’m a Software Developer at JettyCloud.</p><p>There are many articles and reports that describe React Fiber, but unfortunately, they are no longer up-to-date. I decided to fix this and update information on the subject. Now I want to share the results of my work with you.</p><p>While preparing this article I mainly relied on the source code and debugger, so in this material you will find many references to code from the React repository. The topic is divided into two articles. <a href="https://medium.com/@jettycloud/react-fiber-concurrency-part-1-b9d287077d1b">The first article</a> explains the process of updating and making changes to the DOM. The second article is dedicated to the implementation of non-blocking rendering — Concurrent React.</p><p>If you haven’t read the first article, I recommend starting with it first, as the mechanism described in it is fundamental to the implementation of Concurrent React.</p><h3>React Fiber</h3><p>React Fiber solves two main tasks:</p><ol><li><strong>Incremental rendering process</strong> is the ability to split rendering work into parts. The concept and implementation here have largely remained the same, although there are some changes. I explain how the incremental rendering process works <a href="https://medium.com/@jettycloud/react-fiber-concurrency-part-1-b9d287077d1b">in my previous article</a>.</li><li><strong>Non-blocking rendering capability</strong>, where rendering should not block user interactions with the website and animation rendering. Here, on the contrary, the concept was developed and modified over a long period of time. It’s important to note that the implementation of the first aspect, incremental rendering, forms the basis for implementing the second aspect.</li></ol><p>Rendering in React is synchronous, and if there’s a need to render many elements, this process can take a significant amount of time, during which the browser may become unresponsive, and the user won’t be able to interact with our page. Next, we will explore how the React team addresses this challenge.</p><h3>History</h3><p>It might be useful to look at the history of the development of Concurrent React in order to draw a line between old articles and reports that described the asynchronous rendering process and its modern implementation.</p><p>At the time of the release of React Fiber, there was talk of task prioritization. Less priority tasks were deferred using <strong>requestIdleCallback</strong>, while more critical ones were executed using <strong>requestAnimationFrame</strong>. This approach aimed at achieving non-blocking rendering, allowing more critical tasks (like animations or user input) to be performed while less critical tasks were deferred. Lin Clark discusses this in her talk “<a href="https://youtu.be/ZCuYPiUIONs?t=1493">A Cartoon Intro to Fiber</a>” at React Conf 2017</p><p>However, the first result of this work was only shown in 2018 by Dan Abramov in his talk “<a href="https://www.youtube.com/watch?v=nLF0n9SACd4">Beyond React 16</a>”. In that talk, Dan demonstrated a prototype of what we now have as <strong>startTransition</strong>. You can see the example used in the talk <a href="https://github.com/facebook/react/tree/a20eea25197df0da80104917df414747eeab1ac9/fixtures/concurrent/time-slicing">here</a>. At that time, it was referred to as “<strong>Async Rendering</strong>.”</p><p>In the same year, Andrew Clark introduced the term “<strong>Concurrent React</strong>” in his talk “<a href="https://www.youtube.com/watch?v=ByBPyMBTzM0&amp;t=1841s">Concurrent Rendering in React</a>.”</p><p>Later, in 2019, this evolved into “<a href="https://www.youtube.com/watch?v=uXEEL9mrkAQ&amp;t=847s"><strong>Concurrent Mode</strong></a>,” and for the first time, an experimental package was provided that allowed developers to experiment with Concurrency.</p><p>Finally, in 2021, React version 18 <a href="https://www.youtube.com/watch?v=FZ0cG47msEk">was announced</a> along with “<a href="https://www.youtube.com/watch?v=FZ0cG47msEk"><strong>Concurrent Features</strong></a>.” So, after many years of presentations and previews of what they were working on, developers were finally able to use it starting with React version 18. The actual implementation differs significantly from what was initially announced with React Fiber.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NtSSF0u6qJZ6BUgaeqHAJw.png" /></figure><p>To summarize the distinction between old theories of non-blocking rendering and the modern implementation:</p><p>In modern React code, <strong>requestIdleCallback</strong> and <strong>requestAnimationFrame</strong> are not used for task prioritization. There is no internal logic for prioritizing updates. Instead, developers have the ability to manually mark updates as interruptible and non-urgent using “<strong>Concurrent Features</strong>.”</p><h3>Concurrent Features</h3><p>React is synchronous by default, but features have been added to help implement Concurrency. This means that now you can decide which updates should not be interrupted and which ones can be deferred, not requiring immediate rendering. Why would we want to interrupt updates? Firstly, to allow more prioritized updates to happen. Secondly, to give the browser the opportunity to perform rendering without blocking the entire page.</p><p>Concurrent Features:</p><ul><li>startTransition / useTransition</li><li>useDeferredValue</li><li>Suspense</li></ul><p>For example, you can separate updates into high-priority and low-priority updates by wrapping the low-priority update in <strong>startTransition</strong>:</p><pre>function handleChange(e){<br>  setHighPriorityUpdate(e.target.value);<br><br>  React.startTransition(() =&gt; {<br>    setLowPriorityUpdate(e.target.value)<br>  })<br>}</pre><p>Let’s examine how it works from the inside.</p><h3>React Concurrent</h3><p>As I’ve mentioned before, rendering in React remains synchronous by default. Rendering occurs using the <a href="https://github.com/facebook/react/blob/546fe4681c52de6a333a55cedb141c87b626425e/packages/react-reconciler/src/ReactFiberWorkLoop.js#L1989"><strong>workLoopSync</strong> loop</a>, which iterates through all the nodes in the <strong>workInProgress</strong> tree and performs rendering in the <strong>performUnitOfWork</strong> function. Rendering is the process of updating components and calculating differences between the previous and current renders to subsequently make changes to the DOM. I talked about the process <a href="https://medium.com/@jettycloud/react-fiber-concurrency-part-1-b9d287077d1b">in my previous article</a>.</p><pre>function workLoopSync() {<br>  while (workInProgress !== null) {<br>    performUnitOfWork(workInProgress);<br>  }<br>}</pre><p>In the case of rendering triggered by Concurrent Features, the situation is slightly different. Rendering is performed in the <a href="https://github.com/facebook/react/blob/4e3618ae41669c95a3377ae615c727f74f89d141/packages/react-reconciler/src/ReactFiberWorkLoop.js#L2227"><strong>workLoopConcurrent</strong> loop</a>.</p><pre>function workLoopConcurrent() {<br>  while (workInProgress !== null &amp;&amp; !shouldYield()) {<br>    performUnitOfWork(workInProgress);<br>  }<br>}</pre><p>The difference <strong>workLoopSync</strong> is based on checking the result function <a href="https://github.com/facebook/react/blob/v18.2.0/packages/scheduler/src/forks/Scheduler.js#L440"><strong>shouldYield</strong></a> — whether we should yield or not. If we shouldn’t yield, then we continue with the rendering work for the node. However, if <strong>shouldYield</strong> returns <strong>true</strong>, then we should <strong>interrupt</strong> rendering. Let’s now discuss when we should do it.</p><pre>function shouldYield(): boolean {<br>  const timeElapsed = getCurrentTime() - startTime;<br>  if (timeElapsed &lt; frameInterval) {<br>      return false;<br>  }<br>  return true;<br>}</pre><p><strong>timeElapsed</strong> represents the time taken for the current rendering. <strong>frameInterval</strong> is a constant set in the <a href="https://github.com/facebook/react/blob/v18.2.0/packages/scheduler/src/SchedulerFeatureFlags.js#L13">configuration file</a>, typically defaulting to 5. In other words, React allows <strong>5 milliseconds</strong> for rendering, and then it pauses this process.</p><p>Sidenote: Why 5 milliseconds? <a href="https://web.dev/rail/#animaciya-sozdavajte-kadr-za-10-ms">Quite likely</a> this value is related to the recommendations in RAIL regarding animation.</p><p>To understand what happens when we interrupt rendering, we need to go up the call stack to the <a href="https://github.com/facebook/react/blob/v18.2.0/packages/scheduler/src/forks/Scheduler.js#L515"><strong>performWorkUntilDeadline</strong></a> function.</p><pre>const performWorkUntilDeadline = () =&gt; {<br>  if (scheduledHostCallback !== null) {<br>    const currentTime = getCurrentTime();<br>    startTime = currentTime;<br><br>    let hasMoreWork = true;<br>    try {<br>      hasMoreWork = scheduledHostCallback(currentTime);<br>    } finally {<br>      if (hasMoreWork) {<br>        schedulePerformWorkUntilDeadline();<br>      } else {<br>        scheduledHostCallback = null<br>      }<br>    }<br>  }<br>};</pre><p>We can notice that <strong>hasMoreWork</strong> is involved here. It indicates if we need to do some rendering work. The value of this variable depends on the result of executing <strong>scheduledHostCallback</strong>, inside which <strong>workLoopConcurrent</strong> is called. And if we recall workLoopConcurrent and shouldYield, it becomes clear when hasMoreWork will be true or false. If more than <strong>5 milliseconds</strong> have passed during rendering, shouldYield will return true, and we should <strong>interrupt</strong> the <strong>workLoopConcurrent</strong> loop. If we have interrupted the loop but there is still rendering work remaining, the hasMoreWork variable will be true. Otherwise, it will be false.</p><p>What happens next? If there is more work to be done, we schedule it again using the <a href="https://github.com/facebook/react/blob/v18.2.0/packages/scheduler/src/forks/Scheduler.js#L550"><strong>schedulePerformWorkUntilDeadline</strong></a> function. Otherwise, we clear the data. Let’s now look at the function for scheduling new work.</p><pre>if (typeof localSetImmediate === &#39;function&#39;) {<br>  // Node.js and old IE.<br>  schedulePerformWorkUntilDeadline = () =&gt; {<br>    localSetImmediate(performWorkUntilDeadline);<br>  };<br>} else if (typeof MessageChannel !== &#39;undefined&#39;) {<br>  // DOM and Worker environments.<br>  const channel = new MessageChannel();<br>  const port = channel.port2;<br>  channel.port1.onmessage = performWorkUntilDeadline;<br>  schedulePerformWorkUntilDeadline = () =&gt; {<br>    port.postMessage(null);<br>  };<br>} else {<br>  // We should only fallback here in non-browser environments.<br>  schedulePerformWorkUntilDeadline = () =&gt; {<br>    localSetTimeout(performWorkUntilDeadline, 0);<br>  };<br>}</pre><p><strong>localSetImmediate</strong> will execute in a Node.js environment, while <strong>MessageChannel</strong> is used in web workers and modern browsers. It works similarly to setTimeout with a delay of 0, but without the minimum 4 milliseconds of delay.</p><p>With <strong>schedulePerformWorkUntilDeadline</strong>, we can delay the next execution of <strong>performWorkUntilDeadline</strong> and allow the browser to repaint the page. This way, React implements rendering that doesn’t block the repainting of the browser window’s content, and users don’t notice any page lag.</p><p>Concurrent features also allow interrupting the current rendering to execute another rendering triggered by a synchronous update. <a href="https://github.com/facebook/react/blob/v18.2.0/packages/react-reconciler/src/ReactFiberLane.new.js"><strong>Lanes</strong></a> are used to determine <strong>priority</strong>, and each <strong>Fiber Node</strong> stores <strong>lane</strong> values. Lane values are stored in <strong>binary format</strong>, so each Fiber Node can have multiple lane values. <strong>Lanes</strong> are set during <strong>beginWork</strong>. The <strong>childLanes</strong> field is also filled in at the moment of popup in <a href="https://github.com/facebook/react/blob/fdb368d9e7430b50b9c506e76ccd46bf0576ef9b/packages/react-reconciler/src/ReactFiberCompleteWork.js#L780"><strong>completeWork</strong></a> function. As a result, the <strong>Root</strong> node has information about the lane values of all its descendants.</p><p>The <a href="https://github.com/facebook/react/blob/0fb5b61ac6951a492242618e4ace6c1826335efc/packages/react-reconciler/src/ReactFiberLane.js#L201"><strong>getNextLanes</strong></a> function helps determine the most prioritized rendering that needs to be executed. This determination occurs during the rendering of the <strong>Root</strong> node. At this stage, we either continue rendering from where we left off previously or interrupt the current rendering and perform a more prioritized one.</p><p>Let’s conclude this part:</p><ul><li><strong>Concurrent Features</strong> allow marking updates as <strong>interruptible</strong> and <strong>non-urgent</strong>.</li><li>Rendering is divided into 5 milliseconds intervals with browser repainting and checking for urgent updates between intervals.</li><li>If an <strong>urgent</strong> update arrives, we <strong>interrupt</strong> the current <strong>rendering process</strong> and restart it after the urgent rendering is completed.</li><li>This way, long rendering processes won’t block the user’s browser, allowing them to continue interacting with the interface.</li></ul><h3>Profiling</h3><p>Now, let’s take a look at how what we’ve discussed works in practice. I’ve taken an example from Dan Abramov’s talk in 2018 as the basis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J_jkDwfTY1RlVJZj7Eza5A.png" /></figure><p>This example consists of an input field, and when you type into it, the charts get updated. The more characters you input, the heavier the charts rendering becomes.</p><pre>handleChange = e =&gt; {<br>        const value = e.target.value;<br>        const {strategy} = this.state;<br>        switch (strategy) {<br>            case &#39;sync&#39;:<br>                this.setState({value});<br>                break;<br>            case &#39;concurrent&#39;:<br>                this.setState({ inputValue: value });<br>                startTransition(() =&gt; {<br>                    this.setState({ graphicValue: value });<br>                });<br>                break;<br>            default:<br>                break;<br>        }<br>};</pre><p>In the case of synchronous rendering, the profiling results might look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1TyOmoJA4gLJUdB6UNhVvQ.png" /></figure><p>Based on this result, we can conclude that rendering was urgent and lasted for 21 milliseconds. The browser’s repaint started after React had completed all the rendering work.</p><p>Next, let’s look at the profiling results using Concurrent Features. If we return to the code of the handleChange function mentioned earlier, you’ll notice that in Concurrent mode, updating values for the input (<strong>inputValue</strong>) and the charts (<strong>graphicValue</strong>) is done separately. As a result, updating the input value remains urgent and synchronous, while updating the graphics value and the actual rendering of graphics is intermittent and not urgent (due to being wrapped in <strong>startTransition</strong>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dxOoEJ_kn4NUaPzZY4fVPA.png" /></figure><p>We can notice that the rendering process is now divided into roughly 5–10 millisecond intervals, with browser repaints occurring between these intervals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xnKaQE0awKlvqoCEu5XFzA.png" /></figure><p>Here, we’ve zoomed in the previous result to make it more noticeable how synchronous rendering (updating the input) is executed first, followed by rendering in Concurrent mode.</p><h3>Useful links</h3><ol><li><strong>React Concurrency, Explained: What useTransition and Suspense Hydration Actually Do</strong></li></ol><p><a href="https://www.youtube.com/watch?v=i-_6wyohduo">Video</a> | <a href="https://3perf.com/talks/react-concurrency">Article</a></p><p>I strongly recommend examining this report. It also covers the cons of Concurrent React, that I do not cover in my materials. To explore the topic more you can follow this link: <a href="https://3perf.com/talks/react-concurrency/#drawbacks">Drawbacks</a></p><p><strong>2. </strong><a href="https://www.youtube.com/watch?v=NZoRlVi3MjQ&amp;t"><strong>The Story of Concurrent React</strong></a></p><p><strong>3. </strong><a href="https://github.com/reactwg/react-18/discussions/64"><strong>What happened to concurrent “mode”? </strong><br></a>Here you can learn why the creators of Concurrent React refused the Concurrent Mode idea and switched to Concurrent Features.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e32e4dac96" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Fiber & Concurrency. Part 1]]></title>
            <link>https://medium.com/@jettycloud/react-fiber-concurrency-part-1-b9d287077d1b?source=rss-9ab6c9a6474f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9d287077d1b</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react-fiber]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[rendering]]></category>
            <dc:creator><![CDATA[JettyCloud]]></dc:creator>
            <pubDate>Mon, 25 Sep 2023 12:49:46 GMT</pubDate>
            <atom:updated>2023-10-03T07:45:46.982Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*axAVvPI4-rR4ibZYWb_7MA.png" /></figure><p>My name is <a href="https://medium.com/@dimaglazkoff">Dmitrii Glazkov</a>, I’m a Software Developer at JettyCloud.</p><p>There are many articles and reports on the web that describe React Fiber. Unfortunately, a lot of them are no longer relevant. I noticed this and decided to update the information on the subject and create a reliable overview of React Fiber. I mainly relied on the source code and debugger, so in this article you will find many references to code from the React repository. Now, I want to share the results of my work with you.</p><p>The topic is divided into two articles. In this article, I will talk about the process of updating and making changes to the DOM. <a href="https://medium.com/@jettycloud/react-fiber-concurrency-part-2-5e32e4dac96">The second article</a> is dedicated to the implementation of non-blocking rendering — Concurrent React (coming soon).</p><p>I want to note that the first article might not bring significant practical utility. However, the material described in it will help to understand the implementation of Concurrent React. This article will be particularly useful for those who want to delve into the workings of the tool from the inside, as well as extract interesting ideas for writing and structuring code.</p><h3>React Fiber</h3><p>React Fiber solves two main tasks:</p><ol><li><strong>Incremental rendering process</strong> — the ability to divide rendering work into parts. In this aspect, the concept and implementation have largely remained the same, although there are some changes.</li><li><strong>Non-blocking rendering</strong> <strong>capability</strong>, where rendering should not block user interactions with the website and the display of animations. Here, everything is the opposite: the concept took a long time to develop and evolve. Details about how this task was solved will be disclosed in <a href="https://medium.com/@jettycloud/react-fiber-concurrency-part-2-5e32e4dac96">my other article</a>. It’s important to note that the implementation of the first aspect — incremental rendering — serves as the foundation for implementing the second one.</li></ol><p>Rendering, in this context, refers to the process of updating components and calculating changes between previous and current renders to subsequently apply changes to the DOM.</p><p>Next, we will delve into how the React team tackled the first task. In this article, we will examine the incremental rendering process, but we’ll cover it within the scope of the entire update process: updating components and making changes to the DOM.</p><h3>Update Process</h3><p>The entire update process is divided into 2 phases:</p><ol><li><strong>The render phase</strong>, which is sometimes also referred to as <strong>reconciliation</strong>. In this phase, as mentioned before, React applies updates to components, compares the previous state of the application with the current one, and determines what update work needs to be done.</li><li><strong>The commit phase</strong>. Building upon the work is done in the previous phase, lifecycle methods and hooks are called, and the DOM is updated.</li></ol><p>To illustrate these phases, I’ll use an example. I will use an application implementing a simple counter.</p><pre><br>function CounterResult({ count }) {<br>  return (<br>      &lt;span&gt;{count}&lt;/span&gt;<br>  )<br>}<br><br>function Button({ onClick, children }) {<br>  return (<br>    &lt;button onClick={onClick}&gt;{children}&lt;/button&gt;<br>  )<br>}<br><br>function ClickCounter() {<br>  const [count, setCount] = useState(0);<br>  <br>  const handleClick = useCallback(() =&gt; {<br>    setCount((value) =&gt; value + 1)<br>  }, [])<br>  <br>  return (<br>    &lt;div&gt;<br>      &lt;Button onClick={handleClick}&gt;Click me!&lt;/Button&gt;<br>      &lt;CounterResult count={count} /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><h3>Reconciliation</h3><p>We won’t discuss this phase from the very beginning. Instead, I suggest we first grasp some basic concepts of the rendering process, so that the narrative can be smoother and more coherent as we proceed.</p><h3>React Elements</h3><p>If we imagine our example without using JSX, it will look like this:</p><pre>function CounterResult({  count }) {<br>  return React.createElement(&quot;span&quot;, null, count);<br>}<br><br><br>function Button({ onClick, children }) {<br>  return React.createElement(&quot;button&quot;, { onClick: onClick }, children);<br>}<br><br><br>function ClickCounter() {<br>  const [count, setCount] = useState(0);<br>  const handleClick = useCallback(() =&gt; {<br>    setCount(value =&gt; value + 1);<br>  }, []);<br>  return React.createElement(&quot;div&quot;, null, <br>    React.createElement(Button, {  onClick: handleClick }, &quot;Click me!&quot;), <br>    React.createElement(CounterResult, { count: count }));<br>}</pre><p>As you can notice each component will create and return a React Element. As a result of React’s work on our application, we will obtain 6 React Elements: <strong>ClickCounter</strong>, <strong>div</strong>, <strong>Button</strong>, <strong>button</strong>, <strong>CounterResult</strong>, <strong>span</strong>. Each one is a regular object that looks something like this:</p><pre>{<br>$$typeof: Symbol(react.element)<br>key: null<br>props: {}<br>ref: null<br>type: ClickCounter<br>}</pre><p>Each React Element carries information about the current state of each element of the application.</p><h3>Fiber Node</h3><p>A Fiber Node is a fundamental element in the React Fiber architecture. A Fiber Node is created from a React Element using <a href="https://github.com/facebook/react/blob/546fe4681c52de6a333a55cedb141c87b626425e/packages/react-reconciler/src/ReactFiber.js#L652">the createFiberFromElement function</a>. This isn’t the only function that creates a Fiber Node, but it’s the one used in our case. However, the actual instance of the Fiber Node is created deeper in <a href="https://github.com/facebook/react/blob/546fe4681c52de6a333a55cedb141c87b626425e/packages/react-reconciler/src/ReactFiber.js#L230">the createFiber function</a>. Here’s how it looks:</p><pre>function createFiber(tag: WorkTag, pendingProps: mixed, key: null | string, mod: TypeOfMode): Fiber {<br>  return new FiberNode(tag, pendingProps, key, mode);<br>}</pre><p>Let’s examine the structure of a Fiber Node. Here are <a href="https://github.com/facebook/react/blob/v18.2.0/packages/react-reconciler/src/ReactInternalTypes.js#L67">its main fields</a> that will help us later on:</p><pre>export type Fiber = {<br><br>//type Fiber Node react/packages/shared/ReactWorkTags.js<br>tag: WorkTag,<br><br>//Function, class, or tag associated with this Fiber Node<br>type: any,<br><br>//DOM node<br>stateNode: any,<br><br>//Fields for constructing the Fiber Tree<br>return: Fiber | null,<br>child: Fiber | null,<br>sibling: Fiber | null,<br><br>//Used to store information about various states and actions that need to be performed in the context of this node.<br>flags: Flags,<br>subtreeFlags: Flags,<br><br>//Reference to a Fiber Node in another tree. A pointer goes from the workInProgressTree to the currentTree and vice versa.<br>alternate: Fiber | null,<br>};</pre><h3>Fiber Tree</h3><p>By using the <strong>return</strong>, <strong>child</strong>, and <strong>sibling</strong> fields, we can construct the<strong> Fiber Tree</strong>. The Fiber Tree reflects the structure and state of our entire application. In the case of our example, it will look as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S3UOG6qubgIHHqoBJp1r2w.png" /></figure><h4>Side Note: Root</h4><p>React creates a fiber root object for each tree. The fiber root holds a reference to the Fiber Tree. The Fiber Tree starts with a special type of Fiber Node called “Root” and acts as the parent for your initial component.</p><p>But we won’t have just one, we’ll have two such trees: <strong>currentTree</strong> and <strong>workInProgressTree</strong>. The currentTree reflects the current visible state of our application, while the workInProgressTree reflects the new state that needs to be applied. During the render phase, the workInProgressTree and its nodes will be created and modified. Nodes in the workInProgressTree are created based on nodes in the currentTree using the <a href="https://github.com/facebook/react/blob/493f72b0a7111b601c16b8ad8bc2649d82c184a0/packages/react-reconciler/src/ReactFiber.js">createWorkInProgress</a> function. In this process, a Fiber Node for the workInProgressTree is created using the already familiar <strong>createFiber</strong> function.</p><h3>Incremental Rendering</h3><p>Now we can begin to understand how incremental rendering works. Its essence is as follows: we traverse each node in the workInProgressTree and perform some work on it. This way, rendering happens gradually, processing each node and having the ability to interrupt work before processing the next node.</p><p>It all starts with <a href="https://github.com/facebook/react/blob/493f72b0a7111b601c16b8ad8bc2649d82c184a0/packages/react-reconciler/src/ReactFiberWorkLoop.js#L1545">creating a Root node for the workInProgressTree based on the Root from the currentTree</a>. Here, we thank ourselves for the preparatory work we’ve done, as we already know that creating the Root node is done using the <strong>createWorkInProgress</strong> function. In the case of the initial rendering of our application, the Root node in the currentTree will be completely empty.</p><p>Next, we initiate a <a href="https://github.com/facebook/react/blob/546fe4681c52de6a333a55cedb141c87b626425e/packages/react-reconciler/src/ReactFiberWorkLoop.js#L1989">loop</a> to traverse the nodes in the workInProgressTree. At this point, we only have one such node — the Root — and we start with it.</p><pre>function workLoopSync() {<br>  while (workInProgress !== null) {<br>    performUnitOfWork(workInProgress);<br>  }<br>}</pre><p>In this loop, we invoke the <a href="https://github.com/facebook/react/blob/546fe4681c52de6a333a55cedb141c87b626425e/packages/react-reconciler/src/ReactFiberWorkLoop.js#L2256">performUnitOfWork</a> function until we have workInProgress nodes that need to be processed.</p><pre>function performUnitOfWork(unitOfWork: Fiber): void {<br>  const current = unitOfWork.alternate;<br><br>  const next = beginWork(current, unitOfWork, renderLanes);<br><br>  unitOfWork.memoizedProps = unitOfWork.pendingProps;<br>  if (next === null) {<br>    completeUnitOfWork(unitOfWork);<br>  } else {<br>    workInProgress = next;<br>  }<br>}</pre><p>The <strong>performUnitOfWork</strong> function carries out all the work on the Fiber Node associated with updating components and calculating changes between the previous render and the current one, for subsequent changes in the DOM. Executing this function can be divided into two stages: <strong>beginWork</strong> and <strong>completeUnitOfWork</strong>.</p><p>We will delve into these stages in detail later, but for now, I want to discuss what they have in common. Both functions fill the <strong>flags</strong> and <strong>subtreeFlags</strong> fields that exists in the Fiber Node. These <strong>flags</strong> and <strong>subtreeFlags</strong> determine various states and actions that need to be performed in the context of that node. All possible values for these fields are <a href="https://github.com/facebook/react/blob/v18.2.0/packages/react-reconciler/src/ReactFiberFlags.js">stored in the file</a>. Examples include:</p><ul><li><strong>Update</strong>: Indicates that the Fiber Node requires an update.</li><li><strong>Snapshot</strong>: Indicates that the <strong>getSnapshotBeforeUpdate</strong> hook needs to be called.</li></ul><p>It’s worth noting that these fields store binary values. So, Update is represented as 100, and Snapshot is represented as 10000000000.</p><p>Sidenote: You may have heard of “<strong>effects</strong>” and the “<strong>effects list</strong>,” but I assume this theory is outdated, as I couldn’t find any evidence of the effects list being formed during the render phase. Yes, Fiber has fields like <strong>nextEffect</strong>, <strong>firstEffect</strong>, and <strong>lastEffect</strong>, but they are not filled or used in the render phase, only in the commit phase. Thus, the assertion that an effects list is formed during the render phase, which is then traversed in the commit phase to perform actions on nodes, is not accurate.</p><h3>beginWork</h3><p>The <strong>beginWork</strong> function performs the call of a component and creates Fiber Nodes for its child nodes. By “call of a component,” I refer to the process of executing the component’s body. In class components, this process begins with calling the <strong>render()</strong> method. In functional components, it involves executing the component function itself. In our case, the call will be done for the <strong>ClickCounter</strong>, <strong>Button</strong>, and <strong>CounterResult</strong> nodes using the <strong>renderWithHooks</strong> function. The output gives us child React Elements. Then, Fiber Nodes are created for these child elements. Fiber Nodes are created based on React Elements.</p><p>We created React Elements at the moment of calling the component using the <strong>React.createElement</strong> function. I intentionally provided an example of our application without JSX to emphasize that React Elements are created within the return statement.</p><p>If we are creating a Fiber Node for the first time (meaning there’s no corresponding node in the currentTree for the current Fiber Node), then the creation happens using the <strong>createFiberFromElement</strong> function. However, if we are updating a Fiber Node (meaning there’s a corresponding node in the currentTree), then a node is created using the <strong>createWorkInProgress</strong> function, based on the node from the currentTree and the newly created React Element.</p><p>The process can be summarized as follows:</p><ol><li>The <strong>renderWithHooks</strong> function invokes the component, leading to the creation of child React Elements.</li><li>Child nodes of the current Fiber Node are created based on the React Elements and nodes from the currentTree.</li></ol><p>These two stages ensure the sequential construction of the workInProgressTree.</p><p>Additionally, during the execution process, we set values in the <strong>flags</strong> field.</p><p>Using <strong>bitwise OR</strong> (`flags |= Snapshot`), we can store multiple values in the <strong>flags</strong> field for a given node.</p><p>By the end of the <strong>beginWork</strong> process, our tree will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*95U_86stweWUTrXGsnNPww.png" /></figure><p>Value 1 represents PerformedWork — work has been performed on the node. This flag is set for class or functional components.</p><h3>completeUnitOfWork</h3><p>The <strong>completeUnitOfWork</strong> function is called not always, but only when <strong>next === null</strong>. Here, <strong>next</strong> refers to the next child node. Thus, the condition <strong>next === null</strong> tells us that the current node doesn’t have any child element that needs to be processed. In this case, the <strong>completeUnitOfWork</strong> function is triggered. This function performs the bubbling process up to the nearest node that has an unchecked sibling node. During this bubbling, we set the value for the <strong>subtreeFlags</strong> field as follows:</p><pre>subtreeFlags |= child.subtreeFlags;<br>subtreeFlags |= child.flags;</pre><p>This field contains flags for all of its descendants. Thanks to this, by looking at the parent node, we can understand the states and changes stored by its descendants.</p><p>Additionally, while executing <strong>completeUnitOfWork</strong>, <a href="https://github.com/facebook/react/blob/fdb368d9e7430b50b9c506e76ccd46bf0576ef9b/packages/react-reconciler/src/ReactFiberCompleteWork.js#L417">the changes that need to be made to the node are determined</a>. The modified DOM element is placed in the <strong>stateNode</strong> field, and the node is marked with an <strong>Update</strong> flag.</p><p>Next, I’ll provide an example of a tree obtained during the <strong>completeUnitOfWork</strong> process. However, this example will describe a situation where a button was pressed and the counter value changed from 0 to 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZFhTZD4ki8hgsyxscIpEOA.png" /></figure><p>The first time the bubbling starts from the <strong>button</strong> node, as it doesn’t have any child nodes that need processing. We bubble up to the <strong>Button</strong> node, which has an unchecked sibling node — <strong>CounterResult</strong>. The <strong>span</strong> node has flags = 100, which represents an <strong>Update</strong>. Thus, at the end of traversing the entire tree, the <strong>Root</strong> node knows that among its descendants, there are nodes with <strong>PerformedWork</strong> and <strong>Update</strong> flags.</p><p>With this, we conclude the explanation of the render phase and move on to the commit phase.</p><h3>Commit phase</h3><p>In this phase, we are already working with the <strong>finishedWork</strong> tree, which is the workInProgressTree from the render phase:</p><pre>const finishedWork = root.current.alternate;<br>root.finishedWork = finishedWork;</pre><p>During the commit stage, using the constructed tree and relying on the <strong>flags</strong> and <strong>subtreeFlags</strong> fields, we execute lifecycle methods, hooks, and update the DOM. The commit phase begins with the <a href="https://github.com/facebook/react/blob/546fe4681c52de6a333a55cedb141c87b626425e/packages/react-reconciler/src/ReactFiberWorkLoop.js#L2595">commitRoot</a> function, but the main logic is in <a href="https://github.com/facebook/react/blob/546fe4681c52de6a333a55cedb141c87b626425e/packages/react-reconciler/src/ReactFiberWorkLoop.js#L2622">commitRootImpl</a>. In this function, we’ll discuss four main sub-functions that are called in the following order:</p><ul><li><a href="https://github.com/facebook/react/blob/546fe4681c52de6a333a55cedb141c87b626425e/packages/react-reconciler/src/ReactFiberCommitWork.js#L373">commitBeforeMutationEffects</a> — Performs actions before updating the DOM, e.g., <strong>getSnapshotBeforeUpdate</strong>.</li><li><a href="https://github.com/facebook/react/blob/546fe4681c52de6a333a55cedb141c87b626425e/packages/react-reconciler/src/ReactFiberCommitWork.js#L2492">commitMutationEffects</a> — Performs DOM changes; rendering occurs later when the browser has available time.</li><li><a href="https://github.com/facebook/react/blob/546fe4681c52de6a333a55cedb141c87b626425e/packages/react-reconciler/src/ReactFiberCommitWork.js#L3111">commitLayoutEffects</a> — Executes <strong>useLayoutEffect</strong>.</li><li><a href="https://github.com/facebook/react/blob/546fe4681c52de6a333a55cedb141c87b626425e/packages/react-reconciler/src/ReactFiberWorkLoop.js#L3057">flushPassiveEffects</a> — Executes <strong>useEffect</strong>.</li></ul><p>Now, let’s understand how the <strong>flags</strong> and <strong>subtreeFlags</strong> fields help us. Suppose we have a value of 10000000000 in <strong>subtreeFlags</strong> — this is the Snapshot flag. Before executing <strong>commitBeforeMutationEffects</strong>, we can check the <strong>subtreeFlags</strong> of the Root node to determine if there are descendants that need to have <strong>getSnapshotBeforeUpdate</strong> performed on them. This check is done using <strong>bitwise AND</strong>: <strong>subtreeFlags &amp; Snapshot</strong>. Thus, we can progressively traverse the tree and eventually find the node we need.</p><p>The same applies to our example. When executing <strong>commitMutationEffects</strong>, we need to make changes to the DOM. How do we find the nodes that need to be updated? We check the condition <strong>subtreeFlags &amp; Update</strong> to realize if there are descendants that need to be updated. In this way, we traverse the entire tree and reach our <strong>span</strong> node.</p><h3>Conclusion</h3><p>We’ve discussed how incremental rendering works, helping implement concurrency by breaking rendering into parts. This allows us to perform rendering not all at once but in pieces, continually checking for urgent updates that need rendering and allowing the browser to render without blocking it. For more details, read <a href="https://medium.com/@jettycloud/react-fiber-concurrency-part-2-5e32e4dac96">the next part</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9d287077d1b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Join QA Party: a lively event for testers in Tbilisi]]></title>
            <link>https://medium.com/@jettycloud/join-qa-party-a-lively-event-for-testers-in-tbilisi-f5d222462b9?source=rss-9ab6c9a6474f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5d222462b9</guid>
            <category><![CDATA[meetup]]></category>
            <category><![CDATA[events]]></category>
            <category><![CDATA[qa]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[tbilisi]]></category>
            <dc:creator><![CDATA[JettyCloud]]></dc:creator>
            <pubDate>Mon, 18 Sep 2023 10:34:48 GMT</pubDate>
            <atom:updated>2023-09-18T10:34:48.814Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-SmHSyUU-GksDHb7UkQVVQ.jpeg" /></figure><p>On September 27th, we’re throwing <a href="https://tkt.ge/en/show/14810/qa-party">JettyCloud’s QA Party</a> — a professional event with a dash of fun and play. We invite QA Engineers who are hungry for exchanging useful and applicable knowledge and exciting atmosphere of live events to join us.</p><p>The gathering will take place in Bukhari Stand Up Club right in the vibrant city center of Tbilisi. Get yourself a drink and get ready to listen to tech talks from leading engineers of Georgian and international IT companies.</p><p>Did we mention that there will be gifts? We partnered up with some awesome local brands and companies to bring you something you’ll surely enjoy: one free drink, quizzes, gifts for work-life balance and networking. Language: Russian.</p><h3>What we’re going to talk about</h3><p><strong>Natalia Yakhina, Quantori: Data QA: what, who &amp; why?</strong></p><p>Natalya’s presentation aims to briefly describe the specifics of data quality: why data quality matters, what quality dimensions exist, how to assess the data quality and finely who are the engineers ensuring the high level of data quality.</p><p><strong>Ivan Lobyshev, Data Art: Pandora box of the requirements testing</strong></p><p>QAs are not sure that they have checked everything? The project timeline is disrupted due to a high number of improvements or inaccurate estimations? The QA team lacks a full understanding of the product’s business logic? It’s difficult to identify what can be affected by new functionality, and management rejects all suggestions to improve processes. All of these issues can be addressed through requirements testing! Ivan will open this Pandora’s box and discuss the importance of requirements testing, requirements-related bugs, various approaches to requirements testing, the benefits of this event, and related topics. Whether you are currently facing these challenges in your project, tend to optimize tasks to be more efficient, or are interested in building, reviewing, or enhancing QA processes, this is a relevant topic for you.</p><p><strong>Stanislav Kosarev, Xunison: How to build a lab for IoT in Tbilisi</strong></p><p>Stas will talk about how they managed to set up a lab in Tbilisi. The report is planned to contain a lot of tech meat, python and a little physics. The speaker will share the problems encountered during creation, as well as solutions to problems.</p><p>Get your ticket on <a href="https://tkt.ge/en/show/14810/qa-party">tkt.ge</a>.</p><h3>Organizer</h3><p><a href="https://www.jettycloud.com/">Jetty Cloud</a> is a Georgian IT company. We take part in the development of a UCaaS communications tool. It’s our passion and pleasure to contribute to knowledge exchange in the IT community. That’s why we have a rich history of organizing professional events and covering topics from soft skills to hardcore development.</p><h3>Partners</h3><p><a href="https://gara.ge/">IT Garage </a>is an international fintech company developing a system of high-load investment services. They offer their employees opportunities for career growth, skill development, and are constantly looking for new team members.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5d222462b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Frequent job changes for a beginner QA specialist: pros and cons]]></title>
            <link>https://medium.com/@jettycloud/frequent-job-changes-for-a-beginner-qa-specialist-pros-and-cons-1b85c2741d74?source=rss-9ab6c9a6474f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b85c2741d74</guid>
            <category><![CDATA[it-career]]></category>
            <category><![CDATA[careers]]></category>
            <category><![CDATA[qa]]></category>
            <category><![CDATA[job-hunting]]></category>
            <dc:creator><![CDATA[JettyCloud]]></dc:creator>
            <pubDate>Tue, 11 Jul 2023 12:09:21 GMT</pubDate>
            <atom:updated>2023-07-11T12:09:21.461Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mAtv-QvouL6xyn1IvluFzQ.png" /></figure><p>My name is Georgiy Rusanov, and I work as a Senior QA Automation at JettyCloud. I have been with this company for over two years, but I left my first three positions after 10–11 months.</p><p>I have encountered many entry-level professionals who were afraid to seek new opportunities after the first 6–12 months of work, and recruitment specialists that filter out such candidates. In this article, I will share my experience with frequent job changes and try to change the perception of QA engineers with such work history. Is it good or bad for a beginner QA engineer to change jobs frequently? Should a Junior QA engineer hold on to their first job for as long as possible? Is it right to reject candidates based on their resume if they have switched companies multiple times within the first couple of years of work?</p><p>This experience is unlikely to be relevant to cases where someone has worked at one place for only 2–3 months since I don’t believe a person can fully immerse themselves in the processes and technologies of a new workplace within such a short period.</p><h3>Why should a young QA specialist enter the job market?</h3><p>Imagine that you are a QA engineer who just landed your first job and are immersing yourself in the magical world of IT. And then, after 6 to 8 months, the moment of a performance review arrives, with a potential revision of your modest (in most cases) salary. At this point, you realize that the first step of your career journey has been successfully completed. Now the choice is yours: either continue working calmly in your current position or start attending job interviews in search of better opportunities. I personally lean towards a few reasons why it makes sense for a young specialist to enter the job market:</p><ol><li><strong>Increase in compensation</strong>: In most cases, the salary growth within the same company will be lower compared to a new job opportunity.</li><li><strong>Search for well-established processes</strong>: It’s no secret that a streamlined process is a difficult goal to achieve. It’s challenging to work in a company with poor processes and a lack of willingness to improve them.</li><li><strong>More pleasant work environment: </strong>We are all different. Some prefer to discuss only work-related matters with team-mates, while others enjoy going to a bar with their coworekrs after work several times a week. A suitable work environment can significantly improve your job satisfaction.</li><li><strong>Different/more challenging tasks</strong>: Sometimes, it’s hard to determine during an interview whether you will encounter challenging tasks. Don’t hesitate to ask questions during the interview about the future scope of tasks, growth opportunities, and dedicated time for non-routine assignments. If you end up realizing that you made the wrong choice, don’t hesitate to search for another opportunity. The probationary period works both ways, and the company may not pass it either.</li><li><strong>Change in technology stack/direction</strong>: This is relevant if, for example, you are a QA Automation specialist and want to learn a more popular programming language to enhance your market demand. Or if you want to move from game development to the world of enterprise with a larger number of job vacancies.</li><li><strong>Change in work format</strong>: Remote work, full-time office, hybrid arrangements, etc.</li></ol><h3>What guided me in changing jobs</h3><p>I changed jobs for various reasons from the list above. First and foremost, it was for the sake of salary increase. The salary review at my first job resulted in a 10% raise, but I noticed that my salary was below the market rate based on job vacancy websites. Since I couldn’t ask for a higher salary without arguments, I had to attend several interviews.</p><p>They went well, and within a week, I received three offers with salaries 1.5 times higher. To my surprise, even my current employer agreed to raise my salary to that level. However, a couple of days later, I received two offers with salaries that doubled my current one, and I decided to move to a new job. It was my first lesson about the salary market in the IT industry.</p><p>After working for about 9 months in my second job, I realized that I was tired of the full-time office routine, so I went back to the job market. I quickly found a job with a hybrid work model, a pleasant team, and a 25% higher salary.</p><p>I then worked for another 10 months and fulfilled my basic needs with the increased income. At that point, my wife and I started considering a long-term journey and the life of digital nomads. This time the job search took more time and was more challenging due to salary expectations, the desire for fully remote work, and the “frequent” job changes, as perceived by some HR professionals. However, in the end, I found my current job and after the end of the probation period became more flexible with my whereabouts.</p><h3>The advantages of frequent job changes</h3><p>I have identified the following benefits of changing jobs:</p><ol><li><strong>Transition to a more convenient work format.</strong> In my case, it was a transition from office work to full remote work. I don’t deny the benefits of interacting with colleagues in an office, but I’m happy to have the opportunity to travel while working and visit different countries without interrupting my work process.</li><li><strong>Income growth.</strong> Perhaps I’m mistaken, but not only my experience speaks of a faster salary growth through changing companies compared to growth within one company.</li><li><strong>Working in companies with different processes. </strong>I began to understand what questions to ask interviewers during interviews. In which companies I want to work and in which ones I don’t. Also, I started to understand why some people choose to stay in companies for less money but with well-established processes.</li><li><strong>Getting to know a large number of great people and professionals. </strong>Changing jobs doesn’t mean you can’t stay in touch with former colleagues. Some people also fear that the new teams they join will be worse, but that’s not the case. There are plenty of great people around, and it’s not that difficult to find them.</li><li><strong>Significantly expanding my technological stack.</strong> Now I’m easily and fearlessly ready to learn new technological domains. During my first jobs I had a chance to work with the following technologies:</li></ol><ul><li>First job: C#, Selenium, RestSharp, TeamCity, YouTrack, Upsource.</li><li>Second job: Java, JUnit, Selenide, Cucumber, Allure, Jenkins, HP ALM, Jira, GitHub, TestRail.</li><li>Third job: JavaScript for UI tests, TypeScript for API tests, MockJs, Gitlab CI, Docker.</li><li>Current job: Java, TestNG, JUnit, Rest-assured, WireMock, Allure, Jenkins, Gitlab CI, K8S.</li></ul><h3>The disadvantages of frequent job changes</h3><ul><li><strong>Relationships with HR. </strong>During my last job change, several HR representatives wrote to me that they wouldn’t consider my candidacy due to frequent job changes. It can be unpleasant, but such opinions exist. I don’t believe it’s worth fighting against or trying to prove something to someone, especially to someone you don’t know. In such cases, I simply thanked them for their response and moved on to explore other job openings and interview invitations.</li><li><strong>Slower grade advancement. </strong>Progressing within one company can sometimes be faster than switching between companies.</li><li><strong>Superficial knowledge of the tech stack.</strong> Since I changed programming languages along with my job changes, I didn’t have enough time to delve deep into each language during my employment. But since I work in QA, I have lower coding requirements compared to developers. Which is why I started writing my first automated tests on the second or third day of work.</li><li><strong>Changing the team.</strong> Some people prefer to work not with just colleagues but with friends. It’s understandable that it’s challenging to build strong friendships in a short period of time. However, I still maintain contact with several colleagues from my previous jobs. We meet, we chat, and even invite each other to work in our respective companies.</li></ul><h3>What I learned from this experience</h3><p>As for me, the abovementioned drawbacks are insignificant, and the advantages outweigh them significantly. Changing the tested business domain, technological stack, and processes provides a valuable perspective on the product. It allows me to understand my weaknesses, areas for growth, and possible directions for improving the testing of a project. I also realized that the average tester doesn’t need to have a deep knowledge of code in 90% of cases, and transitioning between languages is relatively easy. Test code is not the same as application code, so there’s no need to worry or try to learn code at the level of a developer before attempting to find a new job.</p><p>Everything mentioned above represents my personal viewpoint on how one can build their career and is not an urging to take action. If you enjoy your team, are satisfied with your salary and tasks, and overall things are going well, then find joy in your work and continue to grow and develop.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b85c2741d74" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing the HTTP client, or how we work with Open Source]]></title>
            <link>https://medium.com/@jettycloud/optimizing-the-http-client-or-how-we-work-with-open-source-b4e230623d07?source=rss-9ab6c9a6474f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4e230623d07</guid>
            <category><![CDATA[hackney]]></category>
            <category><![CDATA[erlang]]></category>
            <category><![CDATA[cpu]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[jiffy]]></category>
            <dc:creator><![CDATA[JettyCloud]]></dc:creator>
            <pubDate>Thu, 04 May 2023 12:01:44 GMT</pubDate>
            <atom:updated>2023-05-04T12:01:44.741Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VBfe6U25yBNj8cwnrs8ZIg.png" /></figure><p>My name is <a href="https://medium.com/u/eddc805ec291">Aleksei Poliakov</a>, and I am a software engineer at JettyCloud. Our team is working on a service in charge of the signaling part of audio-video conferences (hereinafter referred to as “meeting”) in the Erlang programming language. Like many other companies, we use Open Source in our projects.</p><p>A problem in one of these open source projects prevented us from scaling our service. To solve it, I had to localize the error in the Open Source project’s code and fix it. I describe this in more detail in the article.</p><h3>About the service and its problems</h3><p>The service itself is an Erlang application that handles incoming SIP connections (the signaling part) to connect users to a meeting. The load on the service is more than 10,000 sessions per day and this number continues to increase due to the growth of the number of users. To understand how this affects our component, we created our own performance tests. Here’s what they consist of:</p><ul><li>Loader — a node that generates the specified load (load profile);</li><li>Load profile — various parameters with which we run tests (number of participants in the meeting, total number of sessions, session duration, number of sessions per second, and others);</li><li>The component itself — a configured and launched application;</li><li>Mocks. They emulate the work of the necessary services as if we were accessing real services during session processing.</li></ul><p>Typically, we run the tests with 3 participants in the meeting, but due to the increasing load, we started using tests with a larger number of participants: 100, 250, 500, 1000. During one such test with 1000 participants in one meeting, we discovered a problem with stability and session processing: the number of successful sessions differed from the number we had specified and awaited, the majority of sessions were unsuccessful and ended with errors, while the CPU is not fully loaded.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZGZY-P_ONJszc7Y1n0jiwA.png" /></figure><ul><li>Session count (400) less than expected (1000);</li><li>Cpu is not fully loaded;</li><li>Counts of errors is increasing.</li></ul><h3>Working on the problem</h3><p>First of all, we started using a profiler and figuring out the difference between a test with 3 participants and a test with 1000 participants. The main difference in load was the HTTP requests and processing of responses. The size of an HTTP message with 1000 participants turned out to be ~1MB.</p><p>Participant information is transmitted in JSON format, so it made sense to look for the problem in JSON processing. This assumption was also confirmed by the profiler (cprof), which showed that the number of calls to the jsx_decoder function was in the first place.</p><pre>cprof:analyze().             <br>{47687548,<br> [{jsx_decoder,23722488,<br>               [{{jsx_decoder,count,3},15463315},<br>                {{jsx_decoder,string,5},2419530},<br>                {{jsx_decoder,count,5},1194890},<br>                {{jsx_decoder,string,4},1016514},<br>                {{jsx_decoder,value,4},808796},<br>                {{jsx_decoder,maybe_done,4},808463},<br>                {{jsx_decoder,colon,4},762575},<br>                {{jsx_decoder,key,4},627225},<br>                {{jsx_decoder,integer,2},284481},<br>                {{jsx_decoder,object,4},136220},<br>                {{jsx_decoder,array,4},75224},<br>                {{jsx_decoder,number,5},60356},<br>                {{jsx_decoder,finish_number,5},60356},<br>                {{jsx_decoder,done,4},1332},<br>                {{jsx_decoder,start,4},529},<br>                {{jsx_decoder,decoder,3},529},<br>                {{jsx_decoder,&#39;-decoder/3-fun-0-&#39;,4},529},<br>                {{jsx_decoder,resume,6},381},<br>                {{jsx_decoder,incomplete,6},381},<br>                {{jsx_decoder,incomplete,...},381},<br>                {{jsx_decoder,...},381},<br>                {{...},...},<br>                {...}]}</pre><p>We switched to a faster decoder <a href="https://github.com/davisp/jiffy">jiffy</a>, which was four times faster than <a href="https://github.com/talentdeficit/jsx">jsx</a> on our mini-benchmark. The overall number of cprof calls was reduced by 2 times, but this did not solve the problem globally.</p><p>Next, we returned to profiling: we used all the available profiling tools for Erlang (cprof, eprof, fprof, msaac). As a result, we found that the Scheduler was hitting 100%, while the dirty CPU was around 50%. This means that the problem wasn’t connected to jiffy, as it operates on dirty schedulers, and they were not loaded. The normal schedulers however were loaded, so we went on looking for the problem elsewhere.</p><pre>scheduler:utilization(3).<br>[{total,0.5254140209643313,&quot;52.5%&quot;},<br> {weighted,1.0508280419286626,&quot;105.1%&quot;},<br> {normal,1,1.0,&quot;100.0%&quot;},<br> {normal,2,1.0,&quot;100.0%&quot;},<br> {normal,3,1.0,&quot;100.0%&quot;},<br> {normal,4,1.0,&quot;100.0%&quot;},<br> {cpu,5,0.0,&quot;0.0%&quot;},<br> {cpu,6,0.06587171307467785,&quot;6.6%&quot;},<br> {cpu,7,0.0713839890347901,&quot;7.1%&quot;},<br> {cpu,8,0.0662483866511102,&quot;6.6%&quot;}]</pre><p>We decided to investigate the http client. We use <a href="https://github.com/benoitc/hackney">hackney http client</a> so we further explored it to understand if there was a problem there. A simple comparison of hackney with curl helped to identify the problem: the request through hackney was executed several times slower.</p><pre>curl: Total size: 1301.7705078125KB<br>100 requests, total time: 2.566435s<br><br>hackney: Total size: 1301.7705078125KB<br>100 requests, total time: 9.756432s</pre><p>In order to further investigate the issue, I delved into the hackney code, and then identified a problem with packet processing, particularly with chunked encoding.</p><pre>without chunks, Total size: 1301.7705078125KB<br>100 requests, total time: 0.649146s<br><br>Total size: 1301.7705078125KB, chunk size: 1024, chunks: 1302<br>100 requests, total time: 0.461806s<br><br>Total size: 1301.7705078125KB, chunk size: 1024000, chunks: 2<br>100 requests, total time: 9.556485s</pre><p>As it turned out, the mocks in our tests did not specify the Content-Length http header for the responses, so they were returned as chunk-encoded. A simple modification of the mock using Content-Length solved the problem in our tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZhzggY7NBpBAPA6WaffXoA.png" /></figure><p>The CPU graph still doesn’t look perfect, but the number of sessions is stable and there are minimal errors caused by delays within the network.</p><p>Some people have already encountered the optimization problem when transferring large chunks in the hackney repository, so additional information that was obtained was added to the <a href="https://github.com/benoitc/hackney/issues/690">issue</a>.</p><h3>Solution</h3><p>Since we cannot guarantee that we will always receive data only with Content-Length, and this library is used in several projects and even in multiple teams, meaning that fixing the issue will be helpful for other people too. So I decided to study the hackney code myself and fix the problem with chunked encoding.</p><p>After studying the code of the HTTP client, I discovered the problem. It was due to poor packet processing organization: upon receiving a new batch of data in the HTTP client, they were immediately sent for processing. In the case of chunked encoding, the overhead was quite significant (buffer concatenation, reading the size, checking that the chunk was passed completely), so I optimized it to read and pass already known data size for processing. The results were as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MFdfMWi0oPrlliJm0MmXKA.png" /></figure><p>The execution time of the request was reduced significantly (depending on the chunk size) and was no longer dependent on the chunk size. Also, the results of the profiler showed that:</p><p>The number of function calls to handle the HTTP session decreased significantly because the processing is now performed on a certain portion of data, rather than on every packet.</p><p>Before fix:</p><pre>FUNCTION                                      CALLS        %  TIME  [uS / CALLS]<br>--------                                         -----  -------  ----  [----------]<br>prim_inet:recv0/3                               1833     0.24     427  [      0.23]<br>hackney_http:transfer_decode/2                  1838     0.25     444  [      0.24]<br>hackney_http:te_chunked/2                       1838     0.27     477  [      0.26]<br>hackney_http:read_size/1                        1838     0.28     499  [      0.27]<br>prim_inet:async_recv/3                          1833     0.29     514  [      0.28]<br>hackney_response:read_body/3                       6     0.33     594  [     99.00]<br>io_lib_fread:fread/4                            3676     0.35     624  [      0.17]<br>lists:reverse/1                                 5530     0.40     707  [      0.13]<br>io_lib_fread:fread_unsigned/7                   1838     0.43     762  [      0.41]<br>io_lib_fread:fread_digits/4                    11938     0.51     900  [      0.08]<br>erts_internal:port_control/3                    1839     1.49    2655  [      1.44]<br>hackney_http:read_size/3                       11938     1.86    3317  [      0.28]<br>erlang:setelement/3                             7421     7.52   13374  [      1.80]<br>hackney_http:execute/2                          1845    81.92  145728  [     78.99]<br>--------------------------------------------  ------  -------  ------  [----------]<br>Total:                                        108568  100.00%  177886  [      1.64]</pre><p>After fix:</p><pre>FUNCTION                                      CALLS        %  TIME  [uS / CALLS]<br>--------                                      -----  -------  ----  [----------]<br>erlang:demonitor/2                               29     0.64    33  [      1.14]<br>io_lib_format:build_limited/5                   144     0.66    34  [      0.24]<br>erlang:setelement/3                             133     0.85    44  [      0.33]<br>hackney_bstr:&#39;-to_lower/1-lbc$^0/2-0-&#39;/2        260     1.01    52  [      0.20]<br>hackney_http:read_size/3                         95     1.03    53  [      0.56]<br>io_lib_format:collect_cseq/2                     48     1.07    55  [      1.15]<br>dict:fold_seg/4                                  51     1.14    59  [      1.16]<br>erts_internal:open_port/2                         1     1.14    59  [     59.00]<br>io:execute_request/3                             25     1.28    66  [      2.64]<br>io_lib_format:indentation/2                    1028     1.45    75  [      0.07]<br>io_lib_format:cdata_to_chars/1                 1028     3.10   160  [      0.16]<br>erts_internal:port_control/3                     17    14.33   740  [     43.53]<br>hackney_response:read_body/3                      6    15.67   809  [    134.83]<br>hackney_http:execute/2                           23    28.20  1456  [     63.30]<br>--------------------------------------------  -----  -------  ----  [----------]</pre><p>The final results before and after:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZGZY-P_ONJszc7Y1n0jiwA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H62Zx1l9AcXDutjTc8Kbsw.png" /></figure><p>The total number of sessions remained stable, CPU load was predictable and awaited, and the number of errors was minimal (they were caused by network errors).</p><h3>To sum up</h3><p>In case of optimization problems, the first step is to identify the root cause and localize it, which can be done by data analysis and profilers. It is also important to remember that problems can often hide even in the most common Open Source projects. When faced with such a problem, do not hesitate to report it, and improving a third-party project will make an invaluable contribution to the development of the Open Source community.</p><p>Initially, the problem with hackney was reported and subsequently fixed by our own efforts. A MR was opened in the <a href="https://github.com/benoitc/hackney/pull/710">hackney repository</a> and at the moment it has also been merged into the master branch, which allows all users of this library to avoid the problem we encountered.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4e230623d07" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making Sense of Kubernetes CPU Requests And Limits]]></title>
            <link>https://medium.com/@jettycloud/making-sense-of-kubernetes-cpu-requests-and-limits-390bbb5b7c92?source=rss-9ab6c9a6474f------2</link>
            <guid isPermaLink="false">https://medium.com/p/390bbb5b7c92</guid>
            <category><![CDATA[gitops]]></category>
            <category><![CDATA[cpu-limits]]></category>
            <category><![CDATA[cpu-requests]]></category>
            <category><![CDATA[kubernetes-resource]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[JettyCloud]]></dc:creator>
            <pubDate>Mon, 20 Mar 2023 13:36:19 GMT</pubDate>
            <atom:updated>2023-03-23T11:43:45.639Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lXjRvR4yQjE81zSATonNMQ.png" /></figure><p>Armen Shakhbazian is a Software Engineer at JettyCloud. Our company takes part in the development of an American UCaaS solution RingCentral.</p><p>For the last year Armen’s team has been moving services of RingCentral customers to Kubernetes and, as many other people going through the same process, had to deal with resource management: how to properly specify requests and limits for CPU and RAM to get good resource utilization and avoid performance issues.</p><p>In this article Armen will examine what «requests» and «limits» mean, how they translate to OS primitives and how they are enforced. In conclusion, he’ll give some useful metrics to monitor as well as a couple of recommendations on how to calculate requests and limits for your apps. Each section of this article has links to other articles and papers, so you can deeper explore given topics.</p><p>It will be beneficial for readers to have prior experience with Kubernetes and Linux, as some fundamentals are covered very briefly, just to establish common vocabulary. Furthermore, in this article Armen will focus on CPU, since other resources are relatively straight-forward.</p><h3>Project’s specifics</h3><p>Before we begin, a couple words about the project I worked on while writing this article. Our department at JettyCloud develops back-end services for RingCentral’s collaboration tool. For the last couple of years we have been moving backend services and infrastructure to GitOps and Kubernetes, and so far we deployed several clusters, hundreds of nodes and a couple thousands of pods.</p><p>At this scale, under-utilization of server resources can be costly, so we are very much motivated to not over-provision our infrastructure. On the other hand, we deal with a pretty diverse zoo of services performing a variety of tasks. Carelessly allocated resources can lead to poor user experience and, in some cases, cascade failures.</p><h3>Resource Management Basics</h3><p>Kubernetes allows specifying how much CPU/RAM a single Pod needs and how to restrict usage of these resources for a given Pod. This is done via Requests and Limits under the Resources section.</p><pre>apiVersion: v1<br>kind: Pod<br>metadata:<br>  name: my-app<br>spec:<br>  containers:<br>  - name: app<br>    image: my.private.registry/my-app<br>    resources:<br>      requests:<br>        memory: &quot;64M&quot;<br>        cpu: &quot;250m&quot;<br>      limits:<br>        memory: &quot;128M&quot;<br>        cpu: &quot;500m&quot;</pre><p>Before examining how requests and limits are enforced, let’s get familiar with units they are measured in. The example above specifies 250 millicores and 64 megabytes as requests for container application and 500 millicores/120 megabytes as limits.</p><h4>Memory Units</h4><p>Memory is measured in bytes, and units are pretty straight-forward. Kubernetes allows SI suffixes like k, M, G, T for kilobyte, Megabyte, Gigabyte and Terabyte respectively. As well as Ki, Mi, Gi, Ti for kibibyte, Mebibyte, Gibibyte and Tebibyte — which is a power of 2 units.</p><h4>CPU Units</h4><p>CPU resources are measured, you guessed it, in CPU units. 1 CPU unit is equivalent to 1 physical (or virtual, depending on where cluster runs) core. To specify fractions of CPU, you can use millicore units, where 1 CPU = 1000m.</p><p>Since CPU is a compressible resource, it is very unintuitive what this unit corresponds to, and, to make things more confusing, the meaning of requests and limits are slightly different.</p><blockquote><strong>CPU is an absolute unit</strong>, meaning that 1 CPU is the same no matter how many cores a Node has.</blockquote><h4>Requests and Scheduling</h4><p>Kubernetes uses the requests section of resources to schedule Pods on Nodes and guarantee that the Pod will receive the requested amount of resources.</p><p>Actually, resources are specified for each container in Pod, but for the sake of simplicity we assume that our Pods have only one container. Kubernetes uses total value for a Pod when scheduling of Pods on Nodes happens.</p><p>For example, let’s assume we have the following 3 Pods:</p><ul><li>App 1: 250m CPU and 512M of Memory</li><li>App 2: 300m CPU and 512M of Memory</li><li>App 3: 350m CPU and 768M of Memory</li></ul><p>When Kubernetes attempts to schedule Pods on a Node with 1 vCPU and 2G RAM, all pods will fit, since there is enough resources for them:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*No2pOkQfghL3BfYN_1tzZA.png" /></figure><p>But what if we change the request for App 3, so that now it requires 1G of memory? Now Kubernetes will not be able to schedule that Pod to Node since there is not enough resources:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*WI9wax299Gdg6Fe0SzD8Ug.png" /></figure><p>This is pretty simple, and with RAM it is obvious how memory is distributed to Pods according to their requests. But what about the CPU? What does 250m even mean? Welp, let’s find out and take a look into the abyss of Linux CPU scheduler.</p><h4>CPU Requests, CPU Shares and CFS</h4><p>To allocate resources to containers of Pod, Kubernetes uses <strong>Сgroups and CFS</strong> (completely fair scheduler) on Linux. Roughly speaking, all processes/threads of a container run in a distinct Cgroup, and CFS allocates CPU resources to these Cgroups according to specified resource requests (bear with me, it will be clear… eventually).</p><p>However, CFS operates with something called <strong>CPU Shares</strong>, and not CPU Units of Kubernetes. To convert CPU Units to CPU Shares, Kubernetes equates 1 CPU to 1024 CPU shares. Meaning that a Pod with 500m CPU requests will be given 512 CPU Shares. And a Node with 6 CPUs has 6144 CPU Shares total.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*zgt65NvfDHfHjkE8fnMuZg.png" /></figure><p>… ok. <strong>But what does CPU Shares mean?</strong> What does it mean for a Pod to have 512 shares? Left out of any context, it means nothing. Shares are a relative unit used by CFS to allocate CPU resources in time of contention.</p><p>When Pods do nothing or very little work and CPU is mostly idle, CFS does not care how many shares each Cgroup has. But when multiple Cgroups have runnable tasks, and there are not enough CPU resources, CFS makes sure each Cgroup get CPU time relative to how many shares they have. And, since Kubernetes computes shares from CPU units, it guarantees that a Pod receives requested CPU resources.</p><p>…&gt;_&lt;. <strong>But what are «CPU resources»?</strong> How much CPU is 500m or 512 shares?</p><p>So, not going too deep into CFS internals, it works like this: CFS runs a task (thread) for a short time. When the task is interrupted (or a scheduler tick happens) the task’s CPU usage is accounted for: the (short) time it just spent using the CPU core is added to its CPU usage.</p><p>Once CPU usage for that task gets high enough so that another task becomes the least run, it picks that new task to schedule and the current task is pre-empted.</p><p>For example, 4 Pods, each with one container and single-threaded app, on a Node with 2 vCPU:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*NNLjjZqi_dNDnXqWIqsYgQ.png" /></figure><p>1.5ms is the minimum scheduler period in which a single task will run (/proc/sys/kernel/sched_min_granularity_ns) — e.g. task is given at least 1.5 ms to run, but can use less. And remember that shares make sense only in time of contention, so we assume all apps are Runnable for all intervals.</p><p>For representation’s sake, it is better to operate with bigger periods, like 100ms or 1s.</p><p>With this in mind, lets define CPU requests:</p><blockquote>A CPU requests unit can be understood as the percentage of a given CPU period that is guaranteed to Pod.</blockquote><p>E.g.: a 750m CPU for a period of 100 ms means that a POD is guaranteed to have 75 ms of CPU time each 100 ms (on one or multiple cores). A 5000m CPU for a period of 1s means that a Pod is guaranteed to have 5 s of CPU each 1 s (1 s on each of 5 cores).</p><p>It does not mean that if POD uses less resources than it requested, the CPU will remain idle. If another Pod is runnable at that time, CFS will schedule that Pod.</p><p><strong>That logic of scheduling can be extrapolated for multithreaded apps, as they are in most cases.</strong> To reiterate, each POD container gets its own Cgroup, and threads/processes of the container are tasks in that Cgroup.</p><p>CFS ensures each Cgroup gets CPU time according to its shares, and each task within that Cgroup also gets enough CPU time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*FV5LRHcg3ebNFnz3d4pxEQ.png" /></figure><h4>Summary</h4><p>Kubernetes guarantees that each pod gets CPU/RAM according to its requests. <strong>If Kubernetes does not have enough resources on Nodes, it will fail to schedule Pod.</strong></p><p>Memory resources are straightforward and are defined in bytes, Kubernetes makes sure that a Node has enough memory to provide for scheduled Pods according to their requests.</p><p>To calculate CPU requests, Kubernetes converts CPU units to CPU shares, <strong>where 1 CPU = 1024 shares.</strong> It then ensures that each Node has enough shares to guarantee CPU time for each POD.</p><p>These CPU shares have meaning only in relation to total shares on a Node and are used by linux CFS to distribute CPU resources across Pods.</p><p><strong>To make sense of CPU units, one can think of them as a percentage of a given CPU period that is guaranteed to POD</strong>. E.g.: 150 m CPU for a 100 ms period means that a Pod is guaranteed to have 15 ms CPU time each 100 ms period. 4 CPU for 1 s period means that Pod is guaranteed to have 4 s of CPU time each 1 s period = 1 s on each of 4 CPU cores.</p><h4>Links</h4><ul><li><a href="https://www.batey.info/cgroup-cpu-shares-for-kubernetes.html">CPU Shares for Kubernetes</a></li><li><a href="https://mechpen.github.io/posts/2020-07-25-k8s-cpu/index.html">Kubernetes CPU Requests Explained</a></li><li><a href="https://engineering.squarespace.com/blog/2017/understanding-linux-container-scheduling">Understanding Linux Container Scheduling</a></li><li><a href="https://www.kernel.org/doc/Documentation/scheduler/sched-design-CFS.txt">Kernel.org: CFS Design</a></li><li><a href="https://www.cs.mtsu.edu/~waderholdt/6450/papers/cfs.pdf">Towards Achieving Fairness in Linux Scheduler</a></li><li><a href="https://people.ece.ubc.ca/sasha/papers/eurosys16-final29.pdf">Linux Scheduler: A Decade of Wasted Cores</a></li></ul><h3>Limits and Throttling</h3><p>Kubernetes uses limits to restrict max resource consumption for a Pod. For memory, it is pretty simple: <strong>if an application attempts to allocate more memory than specified in Limits — it will be killed by OOMKiller.</strong></p><p>CPU Limits, on the other hand, are enforced via throttling. <strong>When an application attempts to use more CPU than it is limited to — CFS will throttle it.</strong></p><h4>CFS Periods and Quotas</h4><p>As for requests, CFS operates on a level of Cgroups. For each Cgroup limits are defined by two configurable parameters:</p><ul><li><strong>cpu.cfs_quota_us</strong> — CPU time in microseconds available to cgroup in a period, computed from Limits value.</li><li><strong>cpu.cfs_period_us</strong> — accounting period in microseconds after which allocatable resources are refilled, by default is 100 ms.</li></ul><p><strong>To compute the quota, Kubernetes equates 1 CPU to 1 full period.</strong> E.g.: if cfs_period_us is 100ms, then 1CPU is 100ms, 2500m CPU is 250ms and 750m CPU is 75ms.</p><p>For various performance and efficiency reasons, CFS tracks quota usage for each Cgroup and each core. In other words, each Cgroup has a pool of allocatable CPU resources equal to cfs_quota_us and refilled in cfs_period_us. Within Cgroup each CPU also has a pool of resources, and it is filled from Cgroup pool in 5 ms slices (default of sched_cfs_bandwidth_slice_us).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*4dKqNfGfjUEr-05W3KsDvQ.png" /></figure><p>Do not confuse slice size with how much time a thread actually runs! 5 ms is the size of a slice in which the CPU pool is refilled. But threads can consume only fractions of that time, e.g. sub-millisecond amount. To properly distribute quota across threads, unused resources from the CPU pool returned to the Cgroup pool. <strong>It’s also worth remembering that threads are throttled only when they are in a Runnable state</strong> — idle or waiting threads will not be scheduled and not be throttled.</p><blockquote>Now we can define what a CPU Limit is<strong>: CPU Limit can be understood as the percentage of each scheduler CPU period (100ms) that Pod cannot exceed.</strong></blockquote><p>E.g.: The limit of 750 m CPU means that each 100 ms period a Pod cannot use more than 75 ms of CPU time. 2.5 CPU means that each 100ms period a Pod can use only 250 ms of CPU time (think multi-core system).</p><h4>More Cases of Throttling</h4><p><strong>Setting insufficient CPU limits can cause unexpected throttling.</strong> In most cases, it affects latency, specifically tail latency.</p><p>There are many factors that affect throttling probability aside from limits:</p><ul><li>Overall system utilization (or under-utilization).</li><li>Number of threads in Cgroup (= in container = in Pod).</li><li>Incoming load (e.g. request rate).</li><li>IO latency.</li></ul><p>Not to mention tunables like cpu.cfs_period_us / sched_cfs_bandwidth_slice_us and in-app configuration (something like GC params).</p><p>Here is an example when, depending on how the scheduler assigns threads, a request can be throttled and have additional latency or fit in and be processed without issues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*lqmDjdrXvxDoYSUkgn9jTg.png" /></figure><p>Another case is bursts in CPU usage, which is more prominent in apps with a large amount of threads. For example, let’s take a look at Pod with Node.JS application. In cluster mode and with some native modules it can spawn over 50 threads: v8 and libuv threads for master and worker processes, rd-kafka threads for each worker etc. In some unfortunate cases when most of these threads have work to do, quota can be quickly eaten, and that Pod will be throttled — hence p95 latency will spike.</p><p>There are less obvious reasons for throttling stemming from CFS implementation:</p><ul><li>When returning unused resources from the CPU pool to Cgroup pool, CFS can reserve 1ms. This seems to be a tiny amount, but with numbers of cores and fast threads it can shove a noticeable amount from quota.</li><li>Since throttling is computed on a per-CPU pool, CFS can throttle threads a bit even when overall Cgroup quota is available.</li><li>There are still open issues in the Kubernetes repository related to unexpected throttling.</li><li>Some solutions, like burstable bandwidth control, cannot be configured from Kubernetes yet.</li></ul><h3>When and How to Avoid Throttling</h3><p><strong>First, one shall understand that throttling by itself is not an issue</strong>, it should be avoided only when it causes problems in application behavior (think spikes in tail latency). For example, assume we have a service that does some background job or batch processing. If this service gets throttled from time to time it will most likely be fine: no latency for clients, no guarantees broken and so on.</p><p>On the other hand, if we have a service that handles incoming requests from clients and returns response «synchronously», throttling can affect the client experience — it may cause high latency spikes which will be perceived by clients as slowdown or glitches.</p><p>Now, let’s assume we’ve monitored our service, saw some latency degradation and CPU throttling, and we are determined to eliminate said throttling. Here is what can be done:</p><h4>1. Adjust or Remove CPU Limits</h4><p>There are many articles on the internets suggesting that removing CPU limits are bad idea, but most of them give unsatisfying or wrong reasons:</p><p><strong>«Without limits, the container can use all the CPU resources available on the Node» — this is incorrect</strong>.</p><p>Firstly, as described in previous sections, the scheduler will always do its best to provide each Pod a requested amount of CPU time. So, if CPU requests are set correctly, there is no chance that some glitchy Pod will consume all CPU.</p><p>Secondly, Kubernetes reserves some amount of CPU time for the system and its services (kube-proxy, etc.). So the Node will never end up in an unresponsive situation. Things may slow down, but will remain functioning.</p><p><strong>«Without setting limits equal to requests, you cannot get Guaranteed QoS class» — this is correct.</strong></p><p>However, Guaranteed QoS classes have no advantages from CPU perspective, it is only for incompressible resources like Memory. Over-provisioning of CPU requests does not worth eliminating the slight chance of Pod being killed during RAM contention. It is much better to set sensible Memory Limits.</p><p>Some valid reasons to keep CPU Limits:</p><ol><li><strong>Actually limiting CPU usage.</strong> If you provide a service to run 3rd-party code, or bill by resource usage, using Kubernetes to enforce limits might be an option.</li><li><strong>Predictable behavior.</strong> For example, multiple latency-sensitive services can be scheduled on the same Node and work fine because there are free CPUs and pods can easily exceed their requests. After some deployment, configuration of Pods on that Node may change and suddenly there is not enough free CPU, scheduler does not allow Pods to exceed their requests and unexpected degradation occurs. Limits make such cases more obvious, since we can observe throttling in case of unexpected CPU demands.</li><li><strong>Testing.</strong> CPU Limits allow understanding how much of a CPU service actually needs and make proper calculation for production.</li><li><strong>Predictable CPU utilization.</strong> There are some reasons to desire CPU utilization less or equal to 70–80%, including queueing theory, CPU cache pollution and networking internals (but I’m out of my depth here and this is mostly my guesses).</li></ol><p>In general, it is safe to set the CPU limit x2 or x3 of CPU requests, as long as you carefully calculate these requests.</p><h4>2. Control Threading in Application</h4><p>Let’s again take Node.JS for example. Although the mantra goes like: «Node.JS is single-threaded», it refers to JavaScript code execution. Node.JS apps have libuv thread pool for some I/O and sync task processing, v8 threads for JavaScript processing and GC. Moreover, native libraries like node-rdkafka will spawn its own thread pools, and finally cluster mode will have master/worker processes with their separate threads. All in all, Pods with Node.JS app can have over 50 threads.</p><p>For golang apps, you might want to configure the GOMAXPROCS variable, since by default it calculated from the number of logical CPUs.</p><p>The same goes for Java services: there are threads for GC, thread pools for networking and for database connections.</p><p>By default, many thread pools (in Node.JS/Java/Go/etc) calculate their size depending on the number of CPU cores. Despite being in a container with limited CPU quota, processes will observe all cores on a Node.</p><p>All of these threads share the same quota and will create unnecessary contention and context switches, which may lead to throttling. It is recommended to adjust thread-pools in application for containerized execution.</p><h4>3. Adjust CFS tunables on Nodes</h4><p>Default cpu.cfs_period_us of 100ms can be too high, and lowering these values can have a positive effect on throttling. There are some recommendations, for example <a href="https://www.slideshare.net/try_except_/optimizing-kubernetes-resource-requestslimits-for-costefficiency-and-latency-highload">from zolando</a> to experiment with these knobs. As well as <a href="https://rigtorp.se/low-latency-guide/">low latency tuning guide</a> for Linux kernel. This should be done with performance testing and careful understanding. Generally, previous options should be enough to eliminate throttling in most cases.</p><h3>Summary</h3><p><strong>Kubernetes uses limits to restrict maximum resource consumption of a Pod.</strong> If a Pod uses more Memory than its configured limit — that Pod gets OOMKilled. If a Pod uses more CPU than its configured limit, it gets throttled.</p><p>CPU limit unit can be understood as the percentage of each scheduler CPU period (100 ms) that a Pod cannot exceed. E.g.: limit of 750 m CPU means that each 100 ms period POD cannot use more than 75 ms of CPU time.</p><p>Throttling may occur for various reasons, many of them can be obscure and require deep understanding of scheduler, application as well as Node state.</p><h3>Links</h3><ul><li><a href="https://www.alibabacloud.com/blog/how-to-use-cpu-management-policies-reasonably-to-improve-container-performance_599140?spm=a2c65.11461447.0.0.7dbe38229yL1oS">How to Use CPU Management Policies Reasonably to Improve Container Performance</a></li><li><a href="https://danluu.com/cgroup-throttling/">The container throttling problem</a></li><li><a href="https://engineering.indeedblog.com/blog/2019/12/cpu-throttling-regression-fix/">Unthrottled: How a Valid Fix Becomes a Regression</a></li><li><a href="https://news.ycombinator.com/item?id=24351566">HN thread on CPU Limits</a></li><li><a href="https://engineering.linkedin.com/blog/2016/11/application-pauses-when-running-jvm-inside-linux-control-groups">JVM GC and CFS Throttling</a></li><li><a href="https://lwn.net/Articles/844976/">The burstable CFS bandwidth controller</a></li><li><a href="https://docs.kernel.org/scheduler/sched-bwc.html">Kernel.org: CFS Bandwidth control</a></li><li><a href="https://storage.googleapis.com/pub-tools-public-publication-data/pdf/36669.pdf">CPU Bandwidth Control on CFS</a></li><li><a href="https://folk.ntnu.no/rakeshk/pubs/SBACPAD22.pdf">Mitigating Unnecessary Throttling in Linux CFS Bandwidth Control</a></li></ul><h3>Metrics to Monitor</h3><p>Monitoring of a Pod resource usage is critical to estimate and adjust resource requests and limits. It is also important to do it properly, peeking at the right metrics to track.</p><h4>Memory</h4><p><strong>Absolute memory usage per Pod:</strong> simply monitor container_memory_working_set_bytes value.</p><pre>sum(container_memory_working_set_bytes{cluster_name=&quot;$cluster&quot;, namespace=&quot;$namespace&quot;, pod_name=~&quot;^$app-.*&quot;, container_name!=&quot;POD&quot;}) by (pod_name)</pre><p><strong>Relative to Requests:</strong> ratio of container_memory_working_set_bytes / kube_pod_container_resource_requests_memory_bytes</p><pre># for pod<br>sum(container_memory_working_set_bytes{cluster_name=&quot;$cluster&quot;, namespace=&quot;$namespace&quot;, pod_name=~&quot;^$app-.*&quot;, container_name!=&quot;POD&quot;}) by (pod_name) / sum(kube_pod_container_resource_requests_memory_bytes{cluster_name=&quot;$cluster&quot;, namespace=&quot;$namespace&quot;, pod_name=~&quot;^$app-.*&quot;, container_name!=&quot;POD&quot;}) by (pod_name)) &gt; 0</pre><p><strong>Relative to Limits:</strong> ratio of container_memory_working_set_bytes / kube_pod_container_resource_limits_memory_bytes</p><pre>sum(container_memory_working_set_bytes{cluster_name=&quot;$cluster&quot;, namespace=&quot;$namespace&quot;, pod_name=~&quot;^$app-.*&quot;, container_name!=&quot;POD&quot;}[1s]) by (pod_name) / sum(kube_pod_container_resource_limits_memory_bytes{cluster_name=&quot;$cluster&quot;, namespace=&quot;$namespace&quot;, pod_name=~&quot;^$app-.*&quot;, container_name!=&quot;POD&quot;}) by (pod_name)) &gt; 0</pre><h4>CPU</h4><p>As noted previously, CPU requests/limits make sense as a percentage of some period. Given that, to monitor CPU usage we can use the increase of container_cpu_usage_seconds_total in 1s as a good representation of the actually used CPU time.</p><p>Usage in CPU Units: irate(container_cpu_usage_seconds_total)</p><pre>sum(irate(container_cpu_usage_seconds_total{cluster_name=&quot;$cluster&quot;, namespace=&quot;$namespace&quot;, pod_name=~&quot;^$app-.*&quot;, container_name!=&quot;POD&quot;}[1s])) by (node, pod_name)</pre><p>Usage in Percentage on Node: irate(container_cpu_usage_seconds_total) / kube_node_status_allocatable_cpu_cores — will show familiar % of CPU usage on node.</p><pre>sum(irate(container_cpu_usage_seconds_total{cluster_name=&quot;$cluster&quot;, node=~&quot;$node&quot;, container_name!=&quot;POD&quot;, pod_name=~&quot;^$app-.*&quot;}[1s])) by (node) / on(node) group_left() kube_node_status_allocatable_cpu_cores{cluster_name=&quot;$cluster&quot;, node=~&quot;$node&quot;} OR on() vector(0)</pre><p>Relative to Requests: irate(container_cpu_usage_seconds_total) / kube_pod_container_resource_requests_cpu_cores</p><pre>sum(irate(container_cpu_usage_seconds_total{cluster_name=&quot;$cluster&quot;, namespace=&quot;$namespace&quot;, pod_name=~&quot;^$app-.*&quot;, container_name!=&quot;POD&quot;}[1s])) by (pod_name) / sum(kube_pod_container_resource_requests_cpu_cores{cluster_name=&quot;$cluster&quot;, namespace=&quot;$namespace&quot;, pod_name=~&quot;^$app-.*&quot;, container_name!=&quot;POD&quot;}) by (pod_name)) &gt; 0</pre><p>Relative to Limits: irate(container_cpu_usage_seconds_total) / kube_pod_container_resource_limits_cpu_cores</p><pre>sum(irate(container_cpu_usage_seconds_total{cluster_name=&quot;$cluster&quot;, namespace=&quot;$namespace&quot;, pod_name=~&quot;^$app-.*&quot;, container_name!=&quot;POD&quot;}[1s])) by (pod_name) / sum(kube_pod_container_resource_limits_cpu_cores{cluster_name=&quot;$cluster&quot;, namespace=&quot;$namespace&quot;, pod_name=~&quot;^$app-.*&quot;, container_name!=&quot;POD&quot;}) by (pod_name)) &gt; 0</pre><p>Throttling: container_cpu_cfs_throttled_periods_total / container_cpu_cfs_periods_total</p><pre>sum(rate(container_cpu_cfs_throttled_periods_total{cluster_name=&quot;$cluster&quot;, namespace=&quot;$namespace&quot;, pod_name=~&quot;^$app-.*&quot;} / container_cpu_cfs_periods_total{cluster_name=&quot;$cluster&quot;, namespace=&quot;$namespace&quot;, pod_name=~&quot;^$app-.*&quot;})) by (pod_name)</pre><p>Values of throttling are collected from cgroup/cpu.stat:</p><ul><li>nr_periods = container_cpu_cfs_periods_total — number of elapsed bandwidth control periods (cpu.cfs_period_us) when Cgroup tasks were runnable</li><li>nr_throttled = container_cpu_cfs_throttled_periods_total — number of periods in which tasks of Cgroup were throttled</li><li>throttled_time = container_cpu_cfs_throttled_seconds_total — sum total amount of time individual threads within the Cgroup were throttled</li></ul><p>These metrics are a good foundation for application observability. It is recommended to monitor these values and adjust Requests/Limits if necessary.</p><h3>To sum up</h3><p>I hope that after reading this article you have a better understanding of CPU resources in Kubernetes, how Requests are computed and balanced and how Limits are enforced.</p><p>As a wrap up, here are some recommendations for you to have smooth sailing with kubernetes:</p><p><strong>1. Understand the threading model of your app and adjust it for the containerized environment.</strong></p><p><strong>For Node.JS apps: </strong>do not use cluster modules as it creates unnecessary threads. Experiment with the number of libuv and v8 threads.</p><p><strong>For JVM apps:</strong> tune thread-pool and GC settings.</p><p><strong>For Golang apps</strong>: tune GOMAXPROCS or simply use <a href="https://github.com/uber-go/automaxprocs">automaxprocs</a> package from Uber.</p><p><strong>2. Measure CPU usage, set enough CPU Requests to handle prod traffic at peak time.</strong></p><p>Do performance testing, measure CPU usage and set CPU requests accordingly to handle peak time traffic. A good starting point is to have peak time CPU usage around 70–80% of CPU Requests. Do not over-provision to account for all spikes — that is what CPU Limits for.</p><p><strong>3. Set CPU Limits for applications based on Requests.</strong></p><p>For latency-sensitive applications — think handling client requests — set Limits to be x2-x4 of Requests. Note that Grafana dashboards do not have enough granularity, and you will miss some spikes of CPU usage, so it is recommended to observe CPU throttling values and minimize them.</p><p>For background applications — think cron jobs or async event handling — set reasonable Limits x1.5-x2 of Requests. Requests/Limits combination should be such to comfortably handle peak time traffic and account for some extra load.</p><p><strong>4. Add more metrics to apps, measure as much as you can and make it visible on monitoring dashboards.</strong></p><p>Metrics collected with node-exporter and such are not granular enough and may miss spikes of load/latency.</p><p>Collect in-app metrics correctly utilizing sliding-windows, interpolation and other techniques to make spikes visible. Don’t rely on averages, make tail-latencies visible — collect at least p50, p75, p99 quantiles. If Incoming requests severely vary in size/processing time — make sure they are collected into separate buckets or counters, so they don’t mask outliers and spikes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=390bbb5b7c92" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>