<?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 Mateusz Trojak on Medium]]></title>
        <description><![CDATA[Stories by Mateusz Trojak on Medium]]></description>
        <link>https://medium.com/@mateusz.trojak?source=rss-c3190f05dbce------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*f3kVbG7qREM6IAjU.</url>
            <title>Stories by Mateusz Trojak on Medium</title>
            <link>https://medium.com/@mateusz.trojak?source=rss-c3190f05dbce------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 21:50:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mateusz.trojak/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[Carbon Footprint in the Cloud]]></title>
            <link>https://medium.com/brainly/carbon-footprint-in-the-cloud-be2b046d2991?source=rss-c3190f05dbce------2</link>
            <guid isPermaLink="false">https://medium.com/p/be2b046d2991</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[sustainability]]></category>
            <category><![CDATA[greenhouse-gas-emissions]]></category>
            <category><![CDATA[carbon-footprint]]></category>
            <category><![CDATA[cloud]]></category>
            <dc:creator><![CDATA[Mateusz Trojak]]></dc:creator>
            <pubDate>Mon, 13 Feb 2023 10:04:34 GMT</pubDate>
            <atom:updated>2023-02-15T09:50:39.805Z</atom:updated>
            <content:encoded><![CDATA[<h4>Working in a cloud-based environment gives technology-oriented companies a lot of freedom, improves development speed, and helps with fast delivery of products. On the other hand, technology is impacting our environment, for example by increasing CO₂ emissions.</h4><p>Before moving forward, we need to understand some basic concepts related to greenhouse gas emissions.</p><h3><strong>Greenhouse Gas Protocol</strong></h3><p>The <a href="https://ghgprotocol.org/">GHG Protocol</a>¹ was developed at the end of the XX century, right about the time when society started to think about global climate change and what impact we have on it. GHG Protocol establishes a global standardized framework to help measure and manage greenhouse emissions.</p><p>The GHG framework proposed <a href="https://plana.earth/academy/what-are-scope-1-2-3-emissions">3 scopes</a>² of gas emission:</p><p><em>Scope 1<br></em>Direct emissions from company-owned and controlled resources. It includes vehicles owned by a company, heating sources, any industrial processes that produce CO₂ and other gasses.</p><p><em>Scope 2<br></em>Indirect emissions (owned), including purchased electricity, steam, heat, and cooling.</p><p><em>Scope 3<br></em>Indirect emissions (not owned) includes all other emissions not included in <em>Scope 2</em>, and it’s directly connected with company operations. More information can be found on<a href="https://plana.earth/academy/what-are-scope-1-2-3-emissions"> the Planet Earth website</a>², but in general, this scope is directly related to the cloud.</p><h3><strong>What is the carbon footprint?</strong></h3><p>Carbon footprint is one of the most well-known metrics when it comes to measuring sustainability. As most technology-oriented activities (transportation, manufacturing, energy production, and consumption, etc.) release carbon dioxide into the atmosphere, it’s important to measure it and look for opportunities to lower its volume.</p><p><a href="https://www.nature.org/en-us/get-involved/how-to-help/carbon-footprint-calculator/">The Nature Conservancy</a>³ definition of carbon footprint:</p><blockquote>“<em>A Carbon Footprint is the total amount of greenhouse gasses (including carbon dioxide and methane) that are generated by our actions (CO₂e).”</em></blockquote><p>Having some knowledge about greenhouse gas emission definitions, let’s move on to carbon footprint in the cloud.</p><h3><strong>Carbon Footprint in the Cloud</strong></h3><p>As the subject of carbon footprint is receiving more focus every year, Cloud providers are continuously working in that area to better track, measure, and lower emissions of greenhouse gasses.</p><p>In 2022 AWS added a <em>Sustainability</em> pillar in the <a href="https://aws.amazon.com/architecture/well-architected/">Well-Architected framework</a>⁴. This helps companies make decisions to build and implement infrastructure with the lowest possible carbon footprint. A good example here is that organizations can choose where infrastructure will be deployed (AWS Region) based on the <a href="https://sustainability.aboutamazon.com/around-the-globe?energyType=true">green energy</a>⁵ data.</p><p>It’s worth mentioning that main cloud providers are getting more and more transparent in their gas emission activities and sustainability in general (e.g., <a href="https://sustainability.aboutamazon.com/">AWS</a>⁹ and <a href="https://cloud.google.com/blog/topics/sustainability">Google</a>¹⁰). They are working to replace their electricity supply chains by building their own wind or solar farms. This will help to lower CO₂ emissions and address Scope 3 emissions from Greenhouse Gas Protocol.</p><p>It’s not only cloud providers that see benefits in sharing carbon footprint information with their customers. SaaS-based companies like <a href="https://blog.cloudflare.com/understand-and-reduce-your-carbon-impact-with-cloudflare/">Cloudflare</a>⁶, <a href="https://www.snowflake.com/en/company/overview/sustainability-at-snowflake/">Snowflake</a>⁷ or <a href="https://www.cscglobal.com/service/about/esg-charter/">CSC Global</a>⁸ are committed to sustainability by proactively working on reducing CO₂ emissions and giving customers an overview of their own gas emissions.</p><h3><strong>Measuring Carbon Footprint in the Cloud</strong></h3><p>To understand the carbon footprint of a given solution, it is important to track and measure it. Cloud providers offer tools to track carbon footprint generated by customers. This is a good example of how sustainability awareness can grow in organizations, companies, and corporations.</p><p>In 2022, AWS introduced its <a href="https://aws.amazon.com/blogs/aws/new-customer-carbon-footprint-tool/">Customer Carbon Footprint Tool</a>¹¹ which helps organizations to track their carbon footprint. It’s a rather general overview and lacks advanced features but knowing AWS, we can expect that it will develop over time.</p><figure><img alt="AWS Customer Carbon Footprint Tool" src="https://cdn-images-1.medium.com/max/1024/0*xd0WnlG-3ZlMGQXk" /><figcaption>AWS Customer Carbon Footprint Tool</figcaption></figure><p>In 2021, Google Cloud introduced a <a href="https://cloud.google.com/carbon-footprint">Carbon Footprint</a>¹² panel where customers can get even more granular information about their carbon emissions. This information panel helps track greenhouse emissions based on a Google Cloud project or a specific service.</p><figure><img alt="Google Cloud Carbon Footprint" src="https://cdn-images-1.medium.com/max/1024/0*t4X283HM3tBz4jx4" /><figcaption>Google Cloud Carbon Footprint</figcaption></figure><p>There are also open source tools like <a href="https://www.cloudcarbonfootprint.org/">Cloud Carbon Footprint</a>¹³ which in one place gathers metrics for major cloud vendors (AWS, Azure, Google Cloud) and brings even more visibility and trackability. This type of solution gives organizations the opportunity to implement observability and measurement of CO₂e on a team or product level.</p><figure><img alt="Cloud Carbon Footprint" src="https://cdn-images-1.medium.com/max/1024/0*YMIX9zyZ1427pivK" /><figcaption>Cloud Carbon Footprint</figcaption></figure><h3><strong>Why this is important</strong></h3><p>There are 2 dimensions with respect to why managing and measuring greenhouse emissions are important for organizations:</p><p><em>Future of the planet<br></em>How our actions as humans impact our environment and how technology can help us to achieve better sustainability etc.</p><p><em>Regulations<br></em>In the case of Europe-based companies, the European Union, as a part of <a href="https://single-market-economy.ec.europa.eu/single-market/european-standards/ict-standardisation_en">ITC standardization</a>¹⁴<em>, </em>prepared a <a href="https://joinup.ec.europa.eu/collection/rolling-plan-ict-standardisation/cloud-and-edge-computing-0">taxonomy</a>¹⁵ for sustainable activities. As the European Commission <a href="https://finance.ec.europa.eu/sustainable-finance/tools-and-standards/eu-taxonomy-sustainable-activities_en">wrote</a>¹⁶:</p><blockquote>“<em>The EU taxonomy would provide companies, investors and policymakers with appropriate definitions for which economic activities can be considered environmentally sustainable</em>.”</blockquote><p>This means that companies will have to take into account sustainability as a part of their business responsibility, provided by transparency in decisions and actions.</p><h3><strong>Final thoughts</strong></h3><p>Sustainability isn’t a buzzword anymore, and the complexity of this multidimensional issue isn’t a simple equation. As legal regulations are getting more important in the greenhouse gas emissions area and societal awareness is getting better around sustainability topics, cloud providers look for more opportunities to implement solutions to decrease carbon footprint.</p><p>This article just tackles the subject of carbon footprint in the cloud. A number of other dimensions and deeper analysis shows that this subject needs better understanding, definitions, and overall transparency.</p><h4>Sources</h4><p>[1] <a href="https://ghgprotocol.org/">https://ghgprotocol.org/</a></p><p>[2] <a href="https://plana.earth/academy/what-are-scope-1-2-3-emissions">https://plana.earth/academy/what-are-scope-1-2-3-emissions</a></p><p>[3] <a href="https://www.nature.org/en-us/get-involved/how-to-help/carbon-footprint-calculator/">https://www.nature.org/en-us/get-involved/how-to-help/carbon-footprint-calculator/</a></p><p>[4] <a href="https://aws.amazon.com/architecture/well-architected/">https://aws.amazon.com/architecture/well-architected/</a></p><p>[5] <a href="https://sustainability.aboutamazon.com/around-the-globe?energyType=true">https://sustainability.aboutamazon.com/around-the-globe?energyType=true</a></p><p>[6] <a href="https://blog.cloudflare.com/understand-and-reduce-your-carbon-impact-with-cloudflare/">https://blog.cloudflare.com/understand-and-reduce-your-carbon-impact-with-cloudflare/</a></p><p>[7] <a href="https://www.snowflake.com/en/company/overview/sustainability-at-snowflake/">https://www.snowflake.com/en/company/overview/sustainability-at-snowflake/</a></p><p>[8] <a href="https://www.cscglobal.com/service/about/esg-charter/">https://www.cscglobal.com/service/about/esg-charter/</a></p><p>[9] <a href="https://sustainability.aboutamazon.com/">https://sustainability.aboutamazon.com/</a></p><p>[10] <a href="https://cloud.google.com/blog/topics/sustainability">https://cloud.google.com/blog/topics/sustainability</a></p><p>[11] <a href="https://aws.amazon.com/blogs/aws/new-customer-carbon-footprint-tool/">https://aws.amazon.com/blogs/aws/new-customer-carbon-footprint-tool/</a></p><p>[12] <a href="https://cloud.google.com/carbon-footprint">https://cloud.google.com/carbon-footprint</a></p><p>[13] <a href="https://www.cloudcarbonfootprint.org/">https://www.cloudcarbonfootprint.org/</a></p><p>[14] <a href="https://single-market-economy.ec.europa.eu/single-market/european-standards/ict-standardisation_en">https://single-market-economy.ec.europa.eu/single-market/european-standards/ict-standardisation_en</a></p><p>[15] <a href="https://joinup.ec.europa.eu/collection/rolling-plan-ict-standardisation/cloud-and-edge-computing-0">https://joinup.ec.europa.eu/collection/rolling-plan-ict-standardisation/cloud-and-edge-computing-0</a></p><p>[16] <a href="https://finance.ec.europa.eu/sustainable-finance/tools-and-standards/eu-taxonomy-sustainable-activities_en">https://finance.ec.europa.eu/sustainable-finance/tools-and-standards/eu-taxonomy-sustainable-activities_en</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be2b046d2991" width="1" height="1" alt=""><hr><p><a href="https://medium.com/brainly/carbon-footprint-in-the-cloud-be2b046d2991">Carbon Footprint in the Cloud</a> was originally published in <a href="https://medium.com/brainly">Brainly Technology Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Cost Optimization]]></title>
            <link>https://medium.com/@mateusz.trojak/aws-cost-optimization-54d1a51e136?source=rss-c3190f05dbce------2</link>
            <guid isPermaLink="false">https://medium.com/p/54d1a51e136</guid>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Mateusz Trojak]]></dc:creator>
            <pubDate>Mon, 07 May 2018 11:09:53 GMT</pubDate>
            <atom:updated>2018-05-07T11:09:53.990Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Amazon Web Services (AWS) offer great solutions for any IT company. AWS requires no hardware, and gives opportunity to focus directly on a product rather than on infrastructure, maintenance, or upgrades. But using AWS solutions at</em><a href="https://brainly.com/"><em> Brainly</em></a><em> scale, where the number of EC2 running hours can exceed 900k each month, can become very expensive, making constant cost optimization a critical necessity. Let’s see how this can be done.</em></p><h4>Choose EC2/RDS Instances Carefully</h4><p>The first and most obvious rule is to use EC2 and RDS instances in accordance with their respective purposes.<a href="https://aws.amazon.com/ec2/instance-types/"> Amazon AWS</a> offers a number of different EC2 instance types based on the desired usage:</p><ul><li><a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/general-purpose-instances.html">General Purpose</a> — Good for all-around instances. The t2 type is perfect for usage with Auto Scaling Groups.</li><li><a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/compute-optimized-instances.html">Compute Optimized </a>— Perfect for heavily computed operations, ML interfaces, media transcoding, and web servers.</li><li><a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/memory-optimized-instances.html">Memory Optimized</a> — Good for heavy-memory-usage solutions like Redis, Cassandra, MongoDB, Spark, etc.</li><li><a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/accelerated-computing-instances.html">Accelerated Computing </a>— Provides access to hardware-based computing accelerators such as Graphics Processing Units (GPUs) or Field Programmable Gate Arrays (FPGAs).</li><li><a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/storage-optimized-instances.html">Storage Optimized</a> — Good for any solution which needs to be able to have tens of thousands of IOPs like logs or data-processing data.</li></ul><p>Similar to EC2 Instances, Amazon provides three dedicated<a href="https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Concepts.DBInstanceClass.html"> RDS Instances</a> groups:</p><ul><li>Standard DB</li><li>Memory Optimized DB</li><li>Burstable Performance DB</li></ul><p><em>Pros:</em> Cost savings optimized performance based on needs.<br><em>Cons:</em> You need to know your stack prior to starting infrastructure. Proper stack planning is a must.</p><h4>Use EC2 Auto Scaling</h4><p><a href="https://aws.amazon.com/ec2/autoscaling/">AWS EC2 Auto Scaling</a> monitors application and scale if needed to provide the best performance at the lowest possible costs. There are several metrics which can be used to scale EC2 instances up or down (<em>Fig. 1.</em>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*BQ8_GAX2uqSkB82SFT86kQ.png" /><figcaption>Fig. 1. Metric types used by AWS ASG</figcaption></figure><p>Currently the most-used metric at Brainly apps is CPU Utilization. Scaling Policy measures the AVG amount of CPU Usage for the entire Auto Scaling Group and scales resources accordingly.</p><p><em>Fig. 2.</em> shows 5 different Auto Scaling Groups from the last 5 months. Spikes are directly related to traffic and time of day. Because there are fewer requests, there is a lower number of running instances during Winter Holidays.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pLAnAoDkGrqF7e8fl1wZmQ.png" /><figcaption>Fig. 2. 5 different ASG Groups size graph for last 5 months</figcaption></figure><p>In the above graph we are using 2 types of instances:</p><ul><li>t2.micro — Perfect for apps which don’t require a lot of resources but can handle traffic while scaled horizontally.</li><li>c4.large — Used to process Gearman Job Server queues. For additional savings we are using them as a part of the AWS Spot Fleet.</li></ul><p><em>Pros:</em> Money and resources saving<br><em>Cons:</em> Not all applications can use ASG, so proper planning is a must.</p><h4>Use EC2 Reservations</h4><p>EC2 Reserved Instances (RIs) are one of most popular methods for lowering infrastructure costs. The whole idea behind RIs is to commit to an estimated usage of EC2 instances.</p><p>There are 3 types of EC2 reservations available in<a href="https://aws.amazon.com/ec2/pricing/reserved-instances/"> AWS</a>:</p><ul><li><strong>No Upfront Reservation</strong> — No Upfront RIs offer a significant discount (typically about 30%) compared to On-Demand prices. You pay nothing upfront but commit to pay for the Reserved Instance over the course of the Reserved Instance term. This option is offered with a one year term.</li><li><strong>Partial Upfront Reservation</strong> — Partial Upfront RIs offer a higher discount than No Upfront RIs (typically about 60% for a three-year term). You pay for a portion of the Reserved Instance up front, and then pay for the remainder over the course of the one- or three-year term.</li><li><strong>All Upfront Reservation</strong> — All Upfront RIs offer the highest discount of all of the RI payment options (typically about 63% for a three-year term). You pay for the entire Reserved Instance term (one or three years) with one upfront payment and receive the best effective hourly price.</li></ul><p>Amazon allows users to check RI Coverage to help identify instance hours that are not covered by RIs and to highlight opportunities for savings.</p><p>As described in<a href="https://medium.com/engineering-brainly/ci-cd-at-scale-fdfb0f49e031"> a previous article</a>, the Brainly platform is heavily based on<a href="https://docs.aws.amazon.com/autoscaling/ec2/userguide/AutoScalingGroup.html"> AWS Autoscaling Groups</a>. Thus, the number of running EC2 instances is heavy related to traffic and the number of requests. <em>Fig. 3.</em> shows<a href="https://aws.amazon.com/about-aws/whats-new/2017/03/discover-savings-opportunities-by-using-the-new-reserved-instance-coverage-reports-in-aws-cost-explorer/"> RI coverage</a> graph in a ten-month timeframe. Spikes represent a number of request-changes during a night/day period and, as can be seen after doing proper reservations, RI coverage hits almost 100%. Assuming that we are using No Upfront Reservations, costs can be lowered by 30%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FXCBoH0Ff630Uo_r_TIT1w.png" /><figcaption>Fig. 3. EC2 RI Coverage for 10 months</figcaption></figure><p><em>Pros:</em> Lower costs up to 63% when compared to On-Demand instances.<br><em>Cons:</em> Can be problematic if you choose Standard Offering Class.</p><h4>Use RDS Reservations</h4><p>AWS also provides<a href="https://aws.amazon.com/rds/reserved-instances/"> reservations for RDS instances</a>. This solution works similar to the EC2 Reservations with similar savings ratios.</p><p><em>Fig. 4.</em> shows RI coverage across a 12-month timeframe. In this case RI coverage is lower because of dynamic stack changes. More reservations will be done after infrastructure stabilisation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2s8bs2X6H95rhIPBZ4yMlw.png" /><figcaption>Fig. 4. RDS RI Coverage for 12 months</figcaption></figure><p><em>Pros:</em> Lowers costs up to 63% in comparison to On-Demand instances.<br><em>Cons:</em> Can be problematic if infrastructure is dynamic.</p><h4>Use Spot Instances</h4><p><a href="https://aws.amazon.com/ec2/spot/">Amazon EC2 Spot Instances</a> optimize costs on the AWS and can scale an application’s throughput up to 10X for the same budget. By using Spot Instances when launching EC2 instances, up to 90% can be saved when comparing to on On-Demand prices.</p><p>The whole idea of<a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-spot-instances.html"> Spot Instances</a> is to use AWS unused EC2 capacity. “<em>The hourly price for a Spot Instance (of each instance type in each Availability Zone) is set by Amazon EC2, and adjusted gradually based on the long-term supply of and demand for Spot Instances.</em>”</p><p>One of the main differences between Spot and On-Demand instances is that Spot instances can be stopped immediately. Amazon EC2 provides a Spot Instance interruption notice, which gives the instance a two-minute warning before it is interrupted. This warning is given once the declared maximum price for EC2 instance is exceeded.</p><p><em>Fig. 5.</em> Shows some of the latest Spot Requests with a max price of $0.05/h, while the regular price stands at $0.113/h. This means that until AWS sets the price of the c4.large instance at $0.05/h, we will pay less than 40% of the On-Demand price. Once the max price is exceeded, the Spot Instance will be closed after 2 minutes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZCCXx1luvn56ePzqA10LlQ.png" /><figcaption>Fig. 5. List of active Spot Requests</figcaption></figure><p>While there is a clear price advantage, Spot instances should be used carefully and only in certain specific scenarios.</p><p><em>Pros:</em> Lowers costs up to 90% in comparison to On-Demand instances.<br><em>Cons:</em> Needs to be planned carefully</p><h4>Keep Eye on a New EC2 Generations</h4><p>Another advantage to using AWS Platform is that Amazon provides regular updates. Besides introducing amazing new ML services, AWS is also focusing on their core service: EC2.</p><p>As we were using Mesos instances based on c4.2xlarge instances, the main struggle for us was the speed of the network connection on Mesos Agents. Because of network speed limit, microservices running on Mesos Agents started throttling. To prevent that, more instances of Mesos needed to be initiated to automatically generate cost increases. Fortunately, AWS introduced a new generation of EC2 Compute Instances c5 last year.</p><p>Direct comparison on <em>Fig. 6.</em> shows that c5.2xlarge have a 14.51% better rate of performance, faster internet, and 14.29% lower pricing than c4.2xlarge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NpRp0DkGTPREtPzE4O1GIg.png" /><figcaption>Fig. 6. c4.2xlarge vs c5.2xlarge</figcaption></figure><p>Upgrading Mesos Agents to c5 family gives us a performance boost, which automatically translates to a lower number of running agent instances while keeping running Mesos Jobs on the same level (<em>Fig. 7.</em>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1SlbgRLYv2x2Rt0c-e-KNA.png" /><figcaption>Fig. 7. Number of running Mesos Agents. Black line shows average number of Mesos Agents.</figcaption></figure><p><em>Pros:</em> Improved performance, usually better pricing.<br><em>Cons:</em> Keep an eye on already existing reservations. This can be problematic for No Upfront Reservations.</p><h4>Optimize CloudWatch Costs</h4><p><a href="https://aws.amazon.com/cloudwatch/">Amazon CloudWatch</a> is a monitoring service for AWS cloud resources and applications run on AWS. The clear advantage of having a high quantity of metrics gives an ability to monitor infrastructure very precisely.</p><p><em>Fig. 8.</em> shows an example of CloudWatch Metrics for one Mesos Cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fs-UvzaaoNiwnRzjZE3H-A.png" /><figcaption>Fig. 8. Example Amazon CloudWatch Metrics</figcaption></figure><p>Each<a href="https://aws.amazon.com/cloudwatch/pricing/"> request to CloudWatch</a> costs money. The more requests, the greater the expenditure. In Brainly’s case, the most important metrics are:</p><ul><li>RDS-related Metrics</li><li>CPU Credit Balance for EC2 instances</li><li>Size of EC2 Auto Scaling Groups</li><li>Summary costs per AWS Account</li></ul><p>Once we started working on cost optimization, we decided to change the frequency of gathering data from CloudWatch. As one example, the request for EC2 Auto Scaling group size was changed from req/10s to req/60s. This frequency is sufficient to spot any unexpected ASG behaviour and also lowers costs significantly.</p><p>For January we did about 153M requests to CloudWatch. After optimization we were able to limit it to 46M requests in February and March. Also the amount of<a href="https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutLogEvents.html"> PutLogsEvents</a> was significantly lower. As seen in <em>Fig. 9.</em>, after those changes costs were cut nearly in half.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V8ybG5WfLLXwrPD3tYYtBA.png" /><figcaption>Fig. 9. Amazon CloudWatch costs before and after optimization.</figcaption></figure><p><em>Pros:</em> It’s good to gather a lot of metrics…<br><em>Cons:</em> …but requesting too much information from CloudWatch can be costly.</p><h4>Plan Logs Carefully</h4><p>Proper logging is a must at any scale. This allows us to monitor the health of the infrastructure, generate alarms when needed, compare old data with a new, and see any improvement or degradation within a specific timeframe.</p><p>At Brainly we extensively use<a href="https://www.elastic.co/webinars/introduction-elk-stack"> ELK Stack</a>. It’s used for storing application logs, microservices logs, third-party apps logs etc. ELK is a great and flexible solution for storing any kind of data, but at scale logging stack needs to be planned carefully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ry5kL20GQmo0e88exsocWQ.png" /><figcaption>Fig. 10. Example Metrics from ElasticSearch shown in Grafana</figcaption></figure><p>The main goal with ELK stack is to have all available logs stored for 2 or 3 months. Regarding some critical metrics we need to be able to store them for a minimum of one year with fast and easy access.</p><p><em>Fig.11.</em> shows table before and after ELK optimization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*CASwhq6JGN5kYUaVfbTKlA.png" /><figcaption>Fig. 11. ELK Stack Before and After Optimization</figcaption></figure><p>The main optimization includes:</p><ul><li>Introduce Aggregation for the most heavy metrics (i.e. access logs).</li><li>Disable indexing on fields which are not searchable.</li><li>Additional Elasticsearch configuration tweaks.</li></ul><p><em>Fig. 12.</em> Shows Elasticsearch cluster CPU usage before and after optimization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gHD6TnlnAqFLej3OO6acdg.png" /><figcaption>Fig. 12. Elasticsearch CPU Usage Before and After Optimization</figcaption></figure><p><em>Pros:</em> It’s good to gather a lot of metrics…<br><em>Cons:</em> …but monitoring infrastructure can be costly at a large scale.</p><h4>Conclusions</h4><p>In this article I tried to describe some best practices which can lower AWS Costs. There are a number of solutions for optimizing AWS Cloud costs: Preferred Pricing, which can be negotiated by large customers, decisions regarding using AWS-dedicated solutions, and ELB vs ALB at scale, etc. The only rule is to make our customers happy while not exceeding the company budget. That’s why the journey for improvements and savings will never end.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54d1a51e136" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CI/CD at Scale]]></title>
            <link>https://medium.com/@mateusz.trojak/ci-cd-at-scale-fdfb0f49e031?source=rss-c3190f05dbce------2</link>
            <guid isPermaLink="false">https://medium.com/p/fdfb0f49e031</guid>
            <category><![CDATA[continuous-integration]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[continuous-delivery]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Mateusz Trojak]]></dc:creator>
            <pubDate>Mon, 19 Mar 2018 06:02:55 GMT</pubDate>
            <atom:updated>2018-03-19T09:27:17.693Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Brainly’s Devops describe their best practices and favourite tools for maintaining continuous integration and continuous delivery at an immense global scale.</em></p><p>Brainly serves a staggering global user-base, with tens of millions of students visiting the platform each month in dozens of markets worldwide. At that scale, delivering new code as rapidly and seamlessly as possible poses significant challenges to the entire production team. For Brainly’s developers, the key challenge is to release new code multiple times each day across two development pipelines. Except when new features or improvements are launched, each and every deployment must occur entirely in the background, without any of Brainly’s 100 million users noticing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nVdxGrGJ4UgWz37-." /><figcaption>Fig 1. <em>Number of Nginx request to all Brainly markets. At this amount of traffic reliable CI/CD solution is must.</em></figcaption></figure><h3>A Two-Stack Challenge</h3><p>The current Brainly stack is comprised of two main sub-stacks, and because of language, purpose, and physical location, each of these stacks requires a different deployment pipeline.</p><ol><li><strong>The Monolithic Stack</strong> contains frontend and backend applications written in PHP, Node.js, and React.</li><li><strong>The Microservices Stack</strong> contains services running on Mesos and orchestrated by Marathon.</li></ol><p>In the first part of this post, we’ll take a look at how we manage the monolithic or applications stack, and in the second part we’ll drill into the details of maintaining CI and CD in the microservices stack.</p><h3>The Monolithic Stack</h3><h3>TeamCity: Our Platform of Choice</h3><p>We choose <a href="https://www.jetbrains.com/teamcity/">TeamCity</a> for our CI/CD orchestration platform. It has exceptional configuration flexibility, offers just enough plugins for our needs, and allows us both to integrate with external authentication tools and predefine Meta Runners (custom build definitions). Most of the jobs running on TeamCity Agents are triggered in dedicated docker images, allowing us to maintain discrete sub-environments for each build type. This build isolation frees us from the concern of affecting other builds that might have different requirements. Since the entire provisioning process of the TeamCity Server/Agent is done by Ansible, we can add new Agents quickly, simply, and with full automation, and requires nothing more than having a docker installed on Agent.</p><h3>Continuous Integration in 4 Steps</h3><p>We stick to a simple and effective four-step process to maintain CI across Brainly’s applications.</p><ol><li>Developers write code and push it to the feature branch on Github</li><li>Several Commit Checkers are defined as Github webhooks, with checks executed internally on TeamCity</li><li>After all checks are passed, we initiate Code Review</li><li>When Code Review is passed, the branch is merged into the master</li></ol><h3>Continuous Delivery in 4 Solutions</h3><p>We spent months testing a range of setups before migrating from bare-metal servers to AWS. Ultimately, we chose t2.micro instances to run the Brainly Applications Stack, and gave each application its own dedicated AWS Autoscaling Group (ASG) to allow us to manage the size of the application automatically and to maintain a dynamic infrastructure based on a number of requests. In general, a larger number of requests correlates to higher avg CPU usage of the ASG and a higher number of running EC2 (AWS Elastic Computing) instances. In our case, ASG can be treated as a dedicated process, with each EC2 instance treated as a thread of this process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6d84ZvaSg-gopjgp." /><figcaption>Fig 2. <em>Brainly apps size, as managed by AWS ASG for PL market (7 days).</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IXTHQ0L9o46lFOiu." /><figcaption>Fig 3. <em>Brainly apps size, as managed by AWS ASG for all markets (7 days).</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wLW_hZqQXrFquREP." /><figcaption>Fig 4. <em>Brainly apps size, as managed by AWS ASG for all markets with deploy information (7 days).</em></figcaption></figure><p>We’ve mapped out some of our sizing data above, in <em>Fig. 2, 3</em>, and <em>4</em>. As <em>Fig. 2 </em>demonstrates, the number of ASG instances is directly related to traffic, with dips in traffic occuring on weekends, when fewer students are using the Brainly portal. <em>Fig. 3</em> shows similar effects in the same time range, and includes ASG activity across all markets. In <em>Fig. 4</em>, we’ve included information about application deployments, with about 70 occurring each week.</p><p>Each production environment has both frontend and backend application stack elements. As developers work, they face more than a thousand ASG instances, giving rise to a pressing need for a reliable deployment mechanism capable of fulfilling 4 core requirements.</p><ol><li>Deploy code across all ASG instances as rapidly as possible</li><li>Ensure that each instance serves the latest version of the application</li><li>Deploy code discretely, with no errors, downtimes, or user interruption</li><li>Allow code to revert rapidly to a previous version in the event of any problems</li></ol><h4>1. Deploying Code Rapidly</h4><p>The most pressing challenge in meeting these requirements was to maintain the ability to deploy rapidly to hundreds of EC2 instances. First, we needed to know where exactly to deploy. Although we use Terraform to provision the entire platform, we’ve chosen not to use it during deployment itself. Terraform does not provide a list of ASG instances directly, so we use Ansible in these cases, since it provides information about all running EC2 instances through an <a href="https://github.com/ansible/ansible/blob/devel/contrib/inventory/ec2.py">EC2 external inventory script </a>.¹ The list contains all ASG groups with running instances, allowing us to extract needed data from it easily and quickly. In just a few seconds, we’re able to obtain information about all running instances across three zones in one AWS region.</p><h4>2. Ensuring that the Latest Version of the Application is Served</h4><p>The next challenge was to design a rapid deployment process. Having hundreds of running EC2 instances requires responding to any given problem with an immediate solution. Fortunately, Ian Barfield from <a href="https://www.addthis.com/">AddThis</a> offers a readymade solution to this challenge through <a href="https://github.com/addthis/ssync">ssync</a>, a recursive wrapper around the rsync unix tool. He describes ssync as a “divide-and-conquer file copying tool to multiple destination hosts,” capable of “transfers to N remote machines in log N iterations” (see <em>Fig. 5</em>, below).²</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZV7UcKTPUoQaXmpq." /><figcaption><em>Figure 5. ssync’s divide-and-conquer file copying tool</em></figcaption></figure><p>Thanks to the ssync tool, copying application code across hundreds of instances takes no more than a few minutes. (For more information on ssync, check out this <a href="https://www.addthis.com/blog/2013/10/08/open-sourcing-ssync-an-out-of-the-box-distributed-rsync">blog post</a>.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YcXzuAJ9nts0K9EM." /><figcaption>Fig 6. <em>Average Applications Deploy Time</em></figcaption></figure><h4>3. Maintaining the Latest Version of the Application</h4><p>The next requirement was maintaining the application in its newest version for each EC2 instance. Each application serves a health check while running, and during deployment the health-check endpoint of the AWS Elastic Load Balancer is updated to the most recent deployed app version. As a result, if even one ASG instance fails to have the most recent code version, ELB will terminate that instance and begin again with a clean one. When the new instance starts, it downloads the newest application version from a dedicated S3 bucket and auto-setup environment. This entire process takes about 20 seconds. After the health check implemented by the app ELB is deemed to be passing, the instance is marked as running and can begin fielding requests.</p><h4>4. Ensuring Prompt Reversion</h4><p>The final requirement was to enable rapid rollback in the event of any problems. For each application there is always a few previous app version stored directly on the EC2 instance and S3. During deployment, code is also pushed to the front instances. Each app version is stored in a folder with the version as a name and with a symlink pointing to the newest version. If and when a critical issue occurs and there is no time for redeployment, a revert build is initiated manually. This build sets the symlink to the previous version, or to a version chosen by the developer who initiated the build. The ELB health check is also switched back to the desired version. This protocol allows us to avoid wasting time pushing code to all instances. The entire process takes about 20 seconds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IKfxeo5-ZaeinJhP." /><figcaption>Figure 7. <em>Average Applications Redeploy Time</em></figcaption></figure><h3>The Application Deployment Pipeline</h3><p>Once PR has been merged to the master, TeamCity triggers a final set of code tests. At that point, the package is built and sent to several staging environments, initiating a sequence of Functional Tests on Staging. If the tests are passed, we begin the task of sending code to all markets and updating the content of the dedicated S3 bucket with the newest application package. During rush hours, deployment to 12 markets takes less than 10 minutes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8W-3lP9a1Mbqc1AZ." /><figcaption>Figure 8. <em>Brainly Applications Deploy Pipeline</em></figcaption></figure><h3>The Microservices Stack</h3><h4>Maintaining Continuous Integration in the Microservices Stack</h4><p>Brainly has over 100 microservices, each one of which requires an individual approach. Since there are only 3 applications, it’s nevertheless quite easy to set up CI on the internal TeamCity. For microservices, we decided to use Travis for all CI requirements, so that every PR prior to the merge-to-master step must to pass a Travis Check/Build in addition to Code Review.</p><h4>Maintaining Continuous Delivery in the Microservices Stack</h4><p>We deploy microservices to production about 10 times each day, just as we do in the Brainly Applications stack. We’ve vastly simplified the deployment and scaling processes by creating all microservices in Docker. Automation orchestration, which we achieve with Marathon, is also relatively simple.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jSsfcrpfQbP7YCVt." /><figcaption>Figure 9. <em>Brainly MIcroservices Deploy Pipeline</em></figcaption></figure><p>The first challenge was to automate the process of deploying the apps. Since the number of Build Configurations in Teamcity is limited, we decided to set up only one Build for all microservices. This build is orchestrated by a Brainly internal microservices stack and is integrated with each microservice build through Github Webhook. Once the commit-to-master branch of service is complete, Build in TeamCity is triggered. At that point, two repositories are cloned: ‘<em>ci-declaration</em>’ and Infrastructure as a Code. It contains both: logic behind deploying code and set of variables needed by given microservice i.e. database addresses, lists of Memcached instances, and so forth. The general idea behind <em>ci-declaration</em> is to parse the <em>.deploy.yml</em> file, which is available in all microservices. Once the build has begun, microservice repository is also cloned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rJOKxtcfBAwZW17d." /><figcaption>Figure 10. <em>Average Microservice Deploy Time</em></figcaption></figure><p>We use a custom YAML file, <em>.deploy.yml</em>, to deploy microservices with Travis-like syntax.</p><p>For all microservices, we had to create a dedicated auto-deployment mechanism with the possibility of predefining custom deploy steps.</p><p>Build steps are defined as top-level elements (such as <em>build</em>, <em>deploy</em>, or <em>after_build</em>) and must always contain a valid configuration:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bcfca2d032cf9eaab5251af6088d58a9/href">https://medium.com/media/bcfca2d032cf9eaab5251af6088d58a9/href</a></iframe><p>The above example is a simple CI configuration with customized steps to build and deploy the application to Marathon. Thanks to <em>.deploy.yml</em>, we’re able to tweak microservices extensively. In a basic configuration we can set up any or all of the following:</p><ul><li>Number of instances</li><li>Whether instances are autoscaling or their number is fixed</li><li>Amount of CPU and RAM usage per instance</li><li>How service should commence</li><li>Whether service is publicly available</li><li>Nginx timeouts per microservice</li><li>Health check endpoint of microservice used by Mesos</li><li>Additional env variables</li><li>Custom domain name for microservice</li><li>Placement in Mesos cluster or Marathon group</li></ul><p>This flexibility allows our development team to initiate and modify microservices without ever touching Mesos or Marathon. Take, for instance, this example of Grafana running as a microservice:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43b97def696ba56eb1d554443da0cb1c/href">https://medium.com/media/43b97def696ba56eb1d554443da0cb1c/href</a></iframe><p>Once <em>.deploy.yml</em> is parsed, <em>ci-declaration</em> triggers a docker build for microservice. After the docker image is created locally on the TeamCity agent, it’s then send to the Brainly Internal Docker Repository. Once uploaded, <em>.deploy.yml</em> is translated to Marathon API format and the job signals the presence of either a new microservice or a new version of a microservice. Marathon then orchestrates Mesos Agents to download the newest docker image and initiate the microservice. At the same time, information is sent to an open-source application called <strong>Ołówek</strong>.</p><p><em>Oł</em><a href="https://github.com/brainly/olowek"><em>ówek</em></a><strong> ³ </strong>[ɔˈwuvɛk] is a Brainly-created application designed to configure Nginx with applications deployed on Mesos and Marathon. Olówek works very similarly to a consul-template, but since our microservices stack is exceptionally dynamic we required something faster and more customized to our stack.</p><p>After deploy, service is propagated automatically by Marathon to specific Mesos clusters. As with the Brainly Application, we decided to provide an auto-scaling mechanism for microservices, so that when traffic is lower there will be fewer instances of running microservices, allowing us to set up AWS Autoscaling for Mesos Agents. In turn we reduced the resources needed to handle lower traffic, resulting in meaningful costs reductions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1cEJexLXJDx4OB0t." /><figcaption>Figure 11. <em>Number of running microservices instances (left Y axis) and corresponding number of Mesos Agents (right X Axis).</em></figcaption></figure><h4>Conclusion</h4><p>Operating at scale comes with immense responsibility and tends to require labor-intensive customized solutions, since off-the-shelf tools rarely address all of the challenges that arise when deploying at scale. At Brainly, we’ve learned that in about 80% of cases it’s best to create specific features internally, even if it takes longer. In-house customization simplifies any future customizations, and at Brainly’s global scale that simplicity is an outright necessity.</p><h4>Notes</h4><p>¹ <a href="https://github.com/ansible/ansible/blob/devel/contrib/inventory/ec2.py">https://github.com/ansible/ansible/blob/devel/contrib/inventory/ec2.py</a><br>² <a href="https://www.addthis.com/blog/2013/10/08/open-sourcing-ssync-an-out-of-the-box-distributed-rsync/">https://www.addthis.com/blog/2013/10/08/open-sourcing-ssync-an-out-of-the-box-distributed-rsync/</a><br>³ <a href="https://github.com/brainly/olowek">https://github.com/brainly/olowek</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fdfb0f49e031" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>