<?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 Remitly on Medium]]></title>
        <description><![CDATA[Stories by Remitly on Medium]]></description>
        <link>https://medium.com/@kristir_54163?source=rss-2e94d94a4a9d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9BYe7-IzeuhBrY7F0Hanrg.png</url>
            <title>Stories by Remitly on Medium</title>
            <link>https://medium.com/@kristir_54163?source=rss-2e94d94a4a9d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 16:02:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kristir_54163/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[Fighting Fraud with Machine Learning at Remitly]]></title>
            <link>https://medium.com/remitly/fighting-fraud-with-machine-learning-at-remitly-698cdd4e2030?source=rss-2e94d94a4a9d------2</link>
            <guid isPermaLink="false">https://medium.com/p/698cdd4e2030</guid>
            <dc:creator><![CDATA[Remitly]]></dc:creator>
            <pubDate>Wed, 09 Feb 2022 17:00:21 GMT</pubDate>
            <atom:updated>2022-02-09T17:00:21.268Z</atom:updated>
            <content:encoded><![CDATA[<p>Author(s): Jake Weholt, Fangyan Chen, Matthew Drury</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aAj3ak6S3Z7HVkSS" /></figure><p>Remitly customers send billions of their hard-earned dollars home each year. Hidden amongst these customers are bad actors attempting to defraud Remitly and the customers we work hard to protect. To help combat fraudulent activity, Remitly deploys a variety of methods, some of which rely on sophisticated machine learning models. This blog post will focus on the machine learning tools and techniques used by Remitly’s machine learning team to protect our customers.</p><h3>Framing the problem</h3><p>While many machine learning tools are available to fight fraud, we’ve chosen to frame fraud mitigation as a binary classification problem. Transactions are labeled either <strong>fraud </strong>(1) or <strong>not fraud </strong>(0), and a variety of features are used for machine learning models to learn the differences between the two.</p><p>Fraud mitigation at Remitly is an entire system with many layers, one of which contains a machine learning model that produces the probability a transaction is fraudulent, i.e<em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*a9yh65JO_FuEHZBX4EyYxw.png" /></figure><p>where X is the feature vector describing each transaction, y is the binary target representing whether the transaction is fraudulent, and f is the machine learning model. The output of this model is then used as input into our mitigation decisions.</p><h3>Clean Fraud Labels</h3><p>Clean labels are the key to developing valuable fraud machine learning models. Unfortunately, gathering clean labels can be quite challenging because most of the time we will never know how a transaction should truly be labeled. For example, some fraudulent transactions will slip through and never be labeled as fraudulent, depriving our model of valuable signal. Additionally, any transaction that Remitly declines will never actually be sent, which means it will never be caught/labeled.</p><p>Noisy labels introduce unique challenges to the right hand side of the equation introduced above: uncertainty around the correctness of the target variable <strong>Y </strong>itself.</p><p>Thankfully there are ways to navigate these challenges despite the difficulties outlined above. One positive, albeit unintuitive observation is that certainty across all labels is not uniform. In effect, we are <em>more </em>certain about the correctness of some positive labels over others. Using labels we are highly certain about, we can increase certainty around labels that we are uncertain about. In other words, we can use a small dataset that we are highly confident about to inform us about the overall dataset that we are less certain about. This is a process known as <a href="https://en.wikipedia.org/wiki/Stratified_sampling">stratified sampling</a>, and can be used when you can ensure that your small dataset is an unbiased representation of your larger dataset. Below is an example of this process in action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_8UBEyT82YduRu7r" /></figure><h3>Feature Engineering</h3><p><em>Feature engineering </em>is the process of transforming raw data into model features that increase model performance. The goal is to build features that help our models learn the underlying structure of the problem we are trying to solve. In our case, that means finding/creating features that separate our classes (“is fraud” vs. “is not fraud”) so that our models can successfully distinguish between the two.</p><p>Feature engineering can be simple, like taking the square root of a particular series, or very complex, like combining data from multiple sources or imputing missing values. Regardless of how features are engineered, the overall goal is the same: create features that reduce fraudulent transactions.</p><p>Below is an example of how simple feature transforms can improve model performance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/0*fS8fM3IMh_wlu9GV" /></figure><p>Above we see labels plotted as a function of raw date. There seems to be some sort of pattern, but it isn’t clear what the pattern is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/0*uNZDSFS1XvLMMa8C" /></figure><p>By plotting the labels as a function of month instead of raw date, and once we do this, the pattern becomes much clearer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/0*9idlY1PYRov4gP7h" /></figure><p>If we go a step further and build individual models using these features (one model for “raw date” only, and another model for “month” only), we can see that using “month” as a feature instead of “raw date” gives us a considerable performance lift.</p><p>Feature engineering is one of the powerful tools we use to capture complicated customer dynamics at Remitly, where we serve a broad customer base whose behavior naturally varies. Fraudsters tend to camouflage themselves among legitimate customers and rapidly shift their behaviors to avoid detection. These factors create unique challenges for feature engineering:</p><ol><li>It’s difficult to find patterns from readily available data that can distinguish fraudsters from legitimate customers.</li><li>Such patterns are <a href="https://en.wikipedia.org/wiki/Stationary_process">non-stationary</a>.</li></ol><p>Looking back on the equation introduced at the beginning of this post, it’s not difficult to see that these challenges form around finding the best feature vector X to distinguish between fraudulent transactions and legitimate ones. To address these challenges, Remitly invests heavily in feature engineering.</p><p>Remitly’s machine learning engineers spend the majority of their time rapidly developing, simulating, and experimenting to improve upon the current suite of features. Rapid development is the key to capturing emerging fraud trends, and thorough experimentation ensures we are developing features that provide lift, without overfitting. Additionally, through feature experimentation and simulation we can estimate how our models will behave in production. This gives us better insight into the tradeoffs we are making when deploying a new model version.</p><h3>Metrics</h3><p>Understanding and measuring how our customers are impacted by machine learning is the key to managing the tradeoffs associated with deploying our models.</p><p>In fraud mitigation, there is a tradeoff between a smooth customer experience and fraud losses. Stricter fraud enforcement leads to increased false positives, pushing too many non-fraudsters into a potentially bad experience. These experiences could lead to customers canceling their transactions or leaving Remitly. Less strict fraud enforcement leads to increased false negatives, which can cause headaches for the customers who were defrauded and increases fraud losses for Remitly.</p><p>To measure these tradeoffs we use traditional metrics such as <strong><em>precision</em></strong><em> </em>(what proportion of the flagged transactions are actually fraudulent?) and <strong><em>recall</em></strong><em> </em>(of all fraudulent transactions, what proportion did we catch?).</p><p>In general, we ignore <strong><em>accuracy </em></strong>as a model metric. Using accuracy to measure model success for binary classification models with imbalanced data is a misleading view into model performance. For instance, if our data set includes 16 transactions, 15 of which are non-fraudulent, simply predicting “not fraud” for every transaction gives us 93.75% accuracy. This sounds great, but we didn’t actually catch any fraudsters. Below, we show this example in greater detail, including the precision and recall scores which can be used to catch this issue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/0*IQeAsA0sgPfGIGBJ" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/0*KJwSJLnX-IP8aNAh" /></figure><h3>The Rare Event Problem</h3><p>Fraudulent activity is rare in comparison to non-fraudulent activity. This behavior disparity leads to <em>class imbalance,</em> which is a fancy term that means positive fraudulent cases out number negative cases by a very large amount in the data.</p><p>When datasets are distributed this way, models have far fewer data points of comparison to find distinguishing patterns between negative and positive classes. Imagine a dataset with one hundred fraudulent transactions and 50,000 non-fraudulent transactions. The ability to find distinguishing patterns is limited by the amount of information contained in one-hundred fraudulent data points. Adding any more non-fraudulent points wouldn’t help when searching for distinguishing patterns useful to a model.</p><p>Rare classes of interest make for difficult machine learning problems, because small probabilities are difficult to estimate accurately. Most (but not all) machine learning classifiers, when trained on very imbalanced data, will bias toward underestimating the probability of the rare class (see <a href="https://gking.harvard.edu/files/0s.pdf">King and Zeng: <em>Logistic Regression in Rare Events Data</em></a>). This model behavior manifests as a model that predicts “is not fraud” a lot more than it predicts “is fraud”. To make matters trickier, if we are doing our jobs properly and providing a strong defensive barrier between Remitly and fraudsters, observed fraud will get rarer over time because (a) as our models improve, fewer fraudulent transactions get past our system, and (b) fraudsters gravitate toward easy paydays, so strong defenses force fraudsters to commit fraud elsewhere (a problem called <em>adverse selection </em>in some disciplines<em>)</em>.</p><p>Several steps can be taken to mitigate the risks from class imbalance:</p><ul><li>Consider models that optimize <a href="https://en.wikipedia.org/wiki/Scoring_rule#Proper_scoring_rules">proper scoring rules</a> (gradient boosting is particularly useful here)</li><li>Resample/reweight your data to even out the count of positive/negative labels.</li><li>Choose the appropriate model evaluation metrics.</li></ul><h3>Summary</h3><p>In this post we explored the challenges of using machine learning to fight fraud, specifically the difficulties of generating clean labels for training, the value of feature engineering to create better models, the importance of using the correct evaluation metrics for measuring model performance, and finally the rare event problem and why it makes building valuable models difficult. Thank you for following along and we hope this post gives you inspiration to fight fraud in your own domain!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=698cdd4e2030" width="1" height="1" alt=""><hr><p><a href="https://medium.com/remitly/fighting-fraud-with-machine-learning-at-remitly-698cdd4e2030">Fighting Fraud with Machine Learning at Remitly</a> was originally published in <a href="https://medium.com/remitly">Remitly</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Driven (Technical) Debt Reduction]]></title>
            <link>https://medium.com/remitly/data-driven-technical-debt-reduction-bf7e42a431a6?source=rss-2e94d94a4a9d------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf7e42a431a6</guid>
            <dc:creator><![CDATA[Remitly]]></dc:creator>
            <pubDate>Thu, 03 Feb 2022 17:07:01 GMT</pubDate>
            <atom:updated>2022-02-04T23:01:39.359Z</atom:updated>
            <content:encoded><![CDATA[<p>Author: <a href="/service/mailto:ryanb@remitly.com">Ryan Burrows</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ay0ry6YSgn5cAaI5" /></figure><p>In software development, we often use the term <strong>technical debt</strong> as a metaphor to describe shortcuts taken to more quickly get the product to a point where it can begin solving real problems. Like financial debt, it can be a valuable tool: borrow some development effort from the future to start earning today, with a plan to repay that effort (plus interest!) at a later time. Most developers I’ve worked with have had a similar concept of this, but the important, yet often unanswered, question is <em>when</em> should it be paid back? Our focus at Remitly is on creating peace of mind for our customers; although we may take on technical debt to be more proactive here on their behalf, how do we ensure these tradeoffs don’t come back to ultimately undermine that goal?</p><p>In the past ten years, Remitly has grown from a handful of developers working on a single codebase to dozens of <a href="https://blog.crisp.se/wp-content/uploads/2012/11/SpotifyScaling.pdf">squads</a>, each responsible for building and maintaining their own portion of the product. We purposefully keep our squads small and flexible so that they can be organized to meet the ever-evolving needs of our customers. We also know that <a href="https://en.wikipedia.org/wiki/Conway%27s_law">software systems will naturally want to be structured like the organization’s communication structure</a>. Goals or focus may change as the business grows, at which point squads may change or split, system ownership may change, and technical debt or future designs may be lost in the process. In these scenarios, a data-driven approach enables teams to reflect and prioritize paying down this debt based on accurate, recent data, not only historical context.</p><p>At the beginning of this year, our team was established to address this topic for some of Remitly’s critical but aging monolithic systems. After preliminary analysis, we identified dozens of distinct business domains represented in these systems and set out to start decoupling the most impactful ones. There are many ways to use data to assess the value of technical debt — aligned with our values of customer centricity and our focus on creating peace of mind for our customers, we used likelihood and reality of negative customer impact to create a risk-based model.</p><h3>Measuring the risk of technical debt</h3><p>To decide where to focus our efforts, we first needed to figure out which of these domains to target. We identified two distinct categories to model in our data:</p><ol><li><strong>Coupling</strong> — Highly coupled systems are more error prone as changes or performance issues in one area can inadvertently impact others, perhaps in surprising ways.</li><li><strong>Ownership</strong> — With so many domains represented, some hadn’t been a recent focus. With this loss of focus is an increased risk for bugs to be inadvertently introduced.</li></ol><p>To measure the coupling of our system, we looked at file change frequency and the correlation between changes to that file and changes to others. Adam Tornhill, author of the excellent <a href="https://pragprog.com/titles/atevol/software-design-x-rays/">Software Design X-Rays</a>, has put together a project called <a href="https://github.com/adamtornhill/code-maat">code-maat</a> that we were able to use to extract this information from our projects’ git histories (specifically see the “sum of coupling” metric). We also used code-maat to identify which files have the most distinct authors — using that as a proxy for which files do not have clear ownership. We took both these metrics, along with how frequently files are to change and came up with a number to represent how much risk there was for errors in a given file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2bqBMfnYJDbCDXm9" /><figcaption>A visualization of the coupling between some files (the real files have sensible names)</figcaption></figure><p>We took this concept and combined it with the size of the file, the complexity of the file (<a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.68.3558&amp;rep=rep1&amp;type=pdf">based on indentation</a>), and the business domains that it was most related to, then derived a metric to represent the risk reduction potential of code in each of the domains we had identified earlier.</p><p>To understand how the code impacted the empirical reliability of our systems, we wanted to understand how impactful outages these domains would be. Remitly has maintained a <a href="https://wa.aws.amazon.com/wat.concept.coe.en.html">COE</a> process and kept track of these types of events; to estimate the impact of an outage in each domain, we reviewed the past year of these reports and made a table mapping the domain where the error occurred to the number of customers that were affected by that error, how long it took us to find and resolve the error, and the cost to the business as result of the error. We combined all of these together, per domain, to come up with a sense of magnitude for how significant an error in each domain would be.</p><p>Once we had these two numbers we were able to combine them (along with a few other factors, such as whether other squads were already working on decoupling this domain) to prioritize which areas we should focus on first.</p><h3>Results</h3><p>After completing this analysis we were able to publish a prioritization for decoupling these domains along with our rationale. The resulting list was both surprising and validating — of the top five domains identified, likely three of them would have been on top of our list based on instinct alone, whereas the other two were non-obvious.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kjlqLgNhyzHC7Hq3" /></figure><p>Does this kind of work sound interesting to you? <a href="https://careers.remitly.com/"><strong>Come work with us</strong></a> — Our team is hiring and so are many others at Remitly!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf7e42a431a6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/remitly/data-driven-technical-debt-reduction-bf7e42a431a6">Data Driven (Technical) Debt Reduction</a> was originally published in <a href="https://medium.com/remitly">Remitly</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Remitly Engineering Metrics: The Discovery]]></title>
            <link>https://medium.com/remitly/remitly-engineering-metrics-the-discovery-c310e4d43978?source=rss-2e94d94a4a9d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c310e4d43978</guid>
            <category><![CDATA[growth]]></category>
            <category><![CDATA[velocity]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[metrics]]></category>
            <dc:creator><![CDATA[Remitly]]></dc:creator>
            <pubDate>Wed, 11 Aug 2021 21:36:59 GMT</pubDate>
            <atom:updated>2021-08-12T22:41:39.184Z</atom:updated>
            <content:encoded><![CDATA[<p>Author: Karim Meghji, CTO</p><p><strong>The Challenge: Moving Fast without Breaking Things</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CZH0NyuA7viR0-99" /></figure><p>As Remitly’s CTO, I have a responsibility to ensure our software engineering teams can deliver value to our customers and get their work done at optimal velocity. As a FinTech company, that’s not always easy. At Remitly, we treat our compliance, security and regulatory responsibilities with the utmost importance given the peace of mind they bring to our customers. With that said, these areas can introduce necessary friction to our engineering work. We’ve also continued to grow our team globally to keep pace with our business, and our technology and systems have continued to grow and mature as well. As a result, we’ve noticed an increase in organic friction due to more complex systems and a more complex organization. With both of these points in mind, we set off to better understand how we could counter these effects and enable an “and” outcome. How will we hold a high bar on compliance, security, and regulations, continue to grow our team, continue to grow and mature our systems AND reduce friction and optimize velocity across teams? This post is about the journey, which we are still on…and so expect some followup posts. :-)</p><p><strong>First, Some Basics</strong></p><p>Contemporary engineering metrics in use today were inspired by manufacturing metrics. You’ll hear talk about things like Lead Time, Cycle Time, Throughput, etc. which all have origins in measuring various stages of manufacturing processes. It makes sense if you think about it — we plan the work, we do the work, we check that the work is correct, and then we ship the work to customers. Measuring these steps (and their sub steps) can help us more clearly identify bottlenecks, roadblocks and non-optimized aspects of doing engineering work. Of course the bigger question is so what? Similar to how agile software development has embraced a number of “lean manufacturing” concepts, our hypothesis has been that <strong>if we optimize software engineering velocity, we can build more things that have the potential to add value to our product and for our customers</strong>. Key is the concept of “optimization” vs. “maximization”. Implicit in optimization is the inclusion of other factors, for example Quality. Just as in manufacturing you don’t want to produce a higher volume of poor quality products, neither do we when we are building software. So in some circumstances we may speed up engineering velocity but in other areas we may hold engineering velocity stable while improving another aspect (i.e. compliance, security, regulatory requirements, quality etc.).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*j-UODWcHfh7Adsl7" /></figure><p><strong>So What Have We Done?</strong></p><p>As a <a href="https://www.remitly.com/us/en/home/values">Data Driven</a> company that thrives on learning and <a href="https://www.remitly.com/us/en/home/values">Continuous Improvement</a>, we started by looking for easy ways to measure engineering velocity” with a supposition that by just starting to measure Engineering Velocity we would learn a lot, not only about where friction exists in our Engineering Pipeline (processes, systems, technical debt, dependencies across teams etc.) but also about how to approach improvement in the area of engineering velocity overall. And what we found was a growing industry of tools to measure various aspects of engineering velocity. We decided to engage with two companies that had different approaches to this domain and used different techniques to bring engineering metrics to life; our goals were to:</p><ul><li>Run pilots and learn about the metrics in a hands-on fashion</li><li>Learn what measures were valuable or inadequate</li><li>Understand industry benchmarks and how to use them in our day to day work</li><li>Learn how to think about using metrics as “guardrails” for goal setting <em>(or said another way, using them as a “healthy” state of a metric that we want to attain and then sustain)</em></li></ul><p>We rolled out both tools in pilot form to a subset of engineering managers and leaders and held multiple feedback sessions where everybody had equal time to share their thoughts on what they liked and concerns they had about rolling out engineering metrics to all engineering managers and engineers at Remitly. We also solicited feedback on these two tools specifically. Finally, we followed the same process with our executive team (they weren’t using the tools so we summarized the metrics approach and our learnings) to hear their feedback given 1) the importance of optimizing engineering velocity for the growth of the business AND 2) the protection of our customers through our compliance, security and regulatory programs. That leads us to where we are on this journey!</p><p><strong>What’s Next?</strong></p><p>Based on all of the feedback we gathered, we decided to continue working with both tools as they seemed to complement each other well. We will continue our roll out more broadly to all engineering managers and engineers as part of continued learning and improving our understanding of how these metrics work and how we can optimize engineering velocity at a company and team level over the next quarter. We decided to initially focus on cycle time and have set up a guardrail target for this measure which Jordan (our VP of Engineering) and I will pay attention and study more closely. Furthermore, we will do the following:</p><ul><li>Establish baselines of the these metrics at a team level,</li><li>Learn about opportunities to improve our engineering processes and rituals,</li><li>Find hot spots where we should reduce our technical debt</li><li>Learn more about the quantitative impact of having engineers focused and uninterrupted</li><li>Learn more about the impact of cross-team dependencies and work</li><li>Look more closely at other measures (aside from cycle time or broader engineering metrics) that connect engineering velocity to customer and business outcomes at a team level.</li></ul><p>Bringing metrics and measurements in a more complete way to Remitly engineering is long overdue. It enables us to drive toward better outcomes from one of our most precious resources, our people. By understanding the friction and challenges our engineers face everyday we can improve all aspects of the software development pipeline, from tools, to code, professional development, time management, project management, and possibly more. I am personally excited to take this step and in a more quantitative light connect what engineers do everyday to customer and business value.</p><p>Check back for my next blog post as I’ll report back on progress, what we’ve learned, and where we’ll go next!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c310e4d43978" width="1" height="1" alt=""><hr><p><a href="https://medium.com/remitly/remitly-engineering-metrics-the-discovery-c310e4d43978">Remitly Engineering Metrics: The Discovery</a> was originally published in <a href="https://medium.com/remitly">Remitly</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CPU Usage Demystified]]></title>
            <link>https://medium.com/remitly/cpu-usage-demystified-cccda6780e47?source=rss-2e94d94a4a9d------2</link>
            <guid isPermaLink="false">https://medium.com/p/cccda6780e47</guid>
            <category><![CDATA[cpu]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Remitly]]></dc:creator>
            <pubDate>Tue, 20 Jul 2021 00:08:44 GMT</pubDate>
            <atom:updated>2021-08-12T00:16:29.303Z</atom:updated>
            <content:encoded><![CDATA[<p>Author: Łukasz Marszał, Infrastructure Engineer</p><p>We all monitor CPU usage of our applications. When we see low cpu usage, we are tempted to to decrease resources or put more workloads on the machine — but is that the right approach? In this article I’ll attempt to answer this question.</p><h3>What is cpu usage?</h3><p>When talking about cpu usage you usually see a nice graph saying “your app is using 50% cpu”. But what does that actually mean?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1bslmk3KNJCQntgs" /></figure><p>If you zoom in close enough you’ll see that CPU usage is in fact 0 or 1. Your app is either scheduled on a cpu (e.g., processing http request) or idle. So how is that nice graph being calculated? Operating systems provide a metric called “cpu usage seconds” (number of seconds your process is being executed) — you calculate the rate of that in time and you receive the percentage.</p><p>So does this mean that unless I’m using 100% cpu, my app is performing at the optimal level? No.</p><h3>Inter arrival rate</h3><p>Let’s assume you have an app — say an http server — running on a single CPU computer, and each request takes 20ms cpu time to execute.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*T3HuqgkJO-IuQ4Zm" /></figure><p>What happens if your app receives 2 requests (A and B) in the 100ms window? Each of them will take 20ms and your cpu consumption will be 40%. That’s great — that’s the optimal performance.</p><p>But what if request B arrives only 10ms after request A? Well — your cpu is still busy processing request A, so request B will have to wait an extra 10ms. Your cpu consumption is still 40% (40ms out of 100ms window), but now your response times are 20ms and 30ms (sic!).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tBZ-Tf9-WiWwVHcP" /></figure><p>30ms is not so bad — but what if yet another request arrives 10ms later? You theoretically have plenty of headroom, but it’ll take 40ms to process it. And what if all three arrive at the same time? It’ll take 60ms to process the slowest one.</p><h3>Waiting time</h3><p>This all reminds me of waiting for a bus — you never know if it’ll be late and if so, by how much. Yet, everyone makes it to work on time. People are sometimes 5min late, sometimes 5min early — but rarely is someone 1h late.<br>It’s the same with the inter arrival rate. Unless you have a very busy server (e.g., a natural catastrophe or first snow) it’s quite unlikely that incoming requests will have to wait long.</p><p>But “unlikely” and “long” do not sound very scientific.</p><p>Assuming your inter arrival rate and processing time is a random variable, you should be able to tell its distribution. Let’s assume it’s a Poisson Distribution — which is likely for human-facing interfaces. As in the previous example — let’s assume that your request needs on average 20ms of a single cpu to be processed. Now let’s use an M/M/c queueing model to do the math. For those who want to read more I recommend <em>A.O. Allen (IBM)</em> article called “<em>Queueing Models of Computer Systems</em>” from 1980.</p><p><strong>Simulation of 1 instance, 1 processor:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8DXZAy4nXyesR_CuzSbb1A.png" /></figure><p>As you can see — even with 60% cpu utilization your mean response time (P50) grows significantly over its minimum. P90 grows even faster. And as CPU utilization is getting closer to 100%, response times are growing exponentially.</p><p>When you compare this with your service-level-objectives (SLO) you’ll actually see what “not so busy”, “unlikely” and “long” mean.</p><h3>More resources or more replicas?</h3><p>Let’s play with M/M/c models a little bit more. Let’s check if it’s better to add more cores to your machine or add more replicas of the same size? The assumption here is that your LoadBalancer would use the round-robin algorithm for distributing requests.</p><p><strong>Simulation of 40 RPS, multiple instances, 1 core per instance:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SaslGH94uhRgvyppVONEeg.png" /></figure><p><strong>Simulation of 40 RPS, 1 instance, multiple cores:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DOXadiHC6bUuqDTMrkYnuw.png" /></figure><p>Assuming your SLO for P90 is 35ms you’ll either need five 1-CPU instances or one 2-CPU instance. So the bigger instance wins. Also — when using bigger instances, they’ll be better utilized.</p><p>To explain this phenomenon you may want to imagine a queue in a store with two checkouts. If there are two separate queues (two instances behind LoadBalancer) you may choose a queue that goes slower. If there’s only one queue for the two of them you’ll be served faster (variances in processing time and arrival time matters less).<br>More detailed explanations can be found in Allen or other queueing theory publications.</p><h3>Summary</h3><p>Unfortunately for us the model used for calculations above is too simple for almost all current computer software. There’s a lot more than a CPU that affects processing time, limits your throughput and causes queueing — databases and other dependencies, memory and networking to name a few. Nevertheless, regardless of this limitation it’s close enough to reality that the above presented symptoms (but not exact numbers) actually do occur in production.</p><p>The important takeaways are that (1) your app may be underperforming even though your CPU consumption is way within the norms. (2) P90 increase may be one of the first symptoms of application performance problems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cccda6780e47" width="1" height="1" alt=""><hr><p><a href="https://medium.com/remitly/cpu-usage-demystified-cccda6780e47">CPU Usage Demystified</a> was originally published in <a href="https://medium.com/remitly">Remitly</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>