Connect with us

LINKEDIN

Costwiz: Saving cost for LinkedIn enterprise on Azure

Published

on

costwiz:-saving-cost-for-linkedin-enterprise-on-azure

Authors: Deven Walia, Vivek Subramaniam, Simon Desowza, and Karthik Subramanian

Cloud services have completely changed the way we approach infrastructure management. It’s now much easier to manage large infra requirements that have traditionally demanded an amalgamation of teams like DBA, Infra-SRE, Onprem-SMEs, network managers, and access control managers working together. However, the ease of these processes can lead to over-provisioning and under-utilization of cloud resources, resulting in increased operating expenses. Without careful monitoring and accountability in place, organizations risk getting swept away by soaring costs, compromising their ability to enhance the member and customer experience.

That’s why we built Costwiz, a tool that allows us to reduce costs by helping teams keep an eye on budgets and over-provisioned or under-utilized resources. Costwiz provides a unified experience that helps leaders drive more accurate forecasting of Azure budgets at LinkedIn with resource ownership detection, accountability, expedited remedies, and holistic data visibility (via custom dashboards). In this blog post, we will share our progress, challenges, and lessons learned from our Costwiz journey.

How Costwiz works

Costwiz detects and stops cloud cost anomalies as they occur to avoid unpleasant billing surprises. To identify where suboptimal spending is occurring, it ingests cost-cutting recommendations from Azure Advisor, an Azure service that is constantly analyzing resource utilization and other metrics to help ensure an optimized Azure deployment. Costwiz automates this process to alert teams of cost-saving options and proactively save money while giving teams deep visibility into your cloud costs.

Costwiz creates accountability by notifying organization owners to assign these recommendations to engineers or SREs and tracking the workflow of a recommendation. If a recommendation is not remediated in a set timeframe, Costwiz escalates the issue to the assigned person’s team and shares a summary email to organization leaders. It also helps aid decision-makers with the information they need around resource utilization details, its current cost in Azure, recommended action, potential savings, assigned engineers, and more in a unified UI.

Advertisement
free widgets for website

Our approach to building Costwiz

For dashboards and alerts through regular emails, we decided to use native reporting tools available to us like Power BI to help us scale quickly. These tools expose the right set of data without us having to worry about engineering efforts for dedicated reporting UI or a workflow for email alerts and reporting dashboards. This allowed us to concentrate on other business problems and optimization efforts that needed attention.

Costwiz application and workflow management system

For the initial rollout, we built a single-page app for users to perform actions on their recommendations (as seen in Figure 1). The landing page lists all the resource recommendations along with metadata around resource owners (Azure security groups), recommendation message, current lifecycle status of the recommendation, due date, assigned engineer, last action message in terms of comments, and a history modal option to check the timeline of actions taken. Furthermore, engineers can access more information about subscription details, the total number of escalations, and the last escalation date.

Managers will have a custom view based on their login token, giving extended visibility into all recommendations assigned to their organization.

Advertisement
free widgets for website
  • Screenshot of the Costwiz application view

Figure 1: Costwiz application view 

While the application gives customers a way to perform relevant actions, under the hood the lifecycle of a Costwiz recommendation is maintained as a state grammar, and allowed state movements are described in the following diagram (Figure 2). 

Advertisement
free widgets for website
  • Diagram of State grammar for recommendation lifecycle management

Figure 2: State grammar for recommendation lifecycle management

Costwiz pluggable framework design

Costwiz’s modular framework can be easily integrated into different systems with minimal code and configurations. The main components that drive the Costwiz workflow are as follows:

  1. App configurations: The static configurations must be fed to the Costwiz workflow by the client system utilizing the pluggable framework.

  2. Data providers: The core input data for which the workflows should be executed and other supporting data required are fed to the system by data providers. We have support for data to be fetched from the database currently which can be easily extended to files, external caches, API call results, etc.

  3. Workflow execution: Once each pluggable workflow receives input from a data provider, they execute various stages of the workflow and produce outcomes like storing results to the database, escalating, alerting owners, etc.

  4. Notification providers: This component takes the responsibility of sending out notifications and alerts via emails, Slack, etc., based on particular workflow requirements.

These components can be classified into providers and core workflow methods. To support this, we implemented a Python SDK library, which provides abstractions for the relevant providers. The client system can utilize this package and invoke the workflow methods with provider implementations. An example of a pluggable workflow can be seen in Figure 3.

Advertisement
free widgets for website
  • Image of Pluggable Framework Design

Figure 3: Pluggable Framework Design

The SDK library-based implementation aims to evolve into a decentralized, platform-agnostic workflow framework. It is an installable service with storage, deployment infrastructure templates, configuration management, monitoring, and a default user interface for the Costwiz portal. The goal is to enable consumer onboarding with minimal technical and operational dependencies.

Costwiz data platform

Costwiz relies on a robust and high-performing central data platform for its operations. Instead of point-to-point integrations, the platform is built on Extract, Transform, Load (ETL) principles to handle data from various source systems. 

The Extract phase utilizes Azure Data Factory to manage data ingestion from sources like Azure Kusto Clusters, Delta Live Tables in Azure Databricks, LinkedIn’s internal REST endpoints, and Azure Data Lake. Data connections are secured through Azure Key Vaults and network connectivity is protected by LinkedIn’s NACL control. This helped us quickly ramp various source-sink combinations because the data factory integrates with hundreds of data storage systems via linked services. Also, the data factory provides scheduling, pipeline dependency management, and alerts out of the box.

Transformations take place in Azure Databricks, where data undergoes quality checks, processing, and reformatting into Parquet format for efficient storage and adherence to ACID principles. 

In the Load phase, business views are created from raw source data and loaded into storage systems such as Azure SQL Server, Azure Cosmos DB, and Azure Data Lake. This data is then ready to be utilized by different actors in the next phase, including Power BI for dashboards and reports, the Costwiz application UI, and Costwiz processors in the form of Azure Functions.

Advertisement
free widgets for website

The entire data platform (as shown in Figure 4) is monitored for errors, and alerts are configured to be sent to Costwiz administrators using Azure App Insights, Azure Monitor, and Azure Log Workspaces. This ensures the reliability and stability of the platform.

  • Diagram of Costwiz data platform

Figure 4: Costwiz data platform overview

Data watermarking

Watermarking is a method used to track the point at which data has been ingested in a table. ETL processes must determine where to pick up the next batch of data. We evaluated various watermarking strategies and decided on Auxiliary metadata driven watermarking. The following section provides a comparative analysis of these strategies:

Advertisement
free widgets for website

1.  Aux metadata table driven watermarking:

  • Involves obtaining two values: left watermark and right watermark.

  • The left watermark is retrieved from an auxiliary database, representing the watermark value from the previous pipeline run.

  • The right watermark is extracted from the data source, indicating the latest data record at the time of the current pipeline’s run.

  • Copy activity in Azure Data Factory is configured to copy records between these two watermarks, using where clauses in the source data query.

  • The right watermark is saved in the auxiliary database.

2.  Sink driven watermarking:

  • Similar to aux metadata driven watermark. But the left watermark is obtained directly from the sink table itself.

  • The right watermark is extracted from the data source, representing the latest data record at the time of the current pipeline’s run.

  • Copy activity is provisioned to copy records between these two watermarks.

3.  Change tracking information driven watermarking:

  • Relies on change tracking information available at the source.

  • The source table is configured to enable change tracking with appropriate change retention policies.

  • Change tracking versions (CHANGE_TRACKING_CURRENT_VERSION) are utilized.

  • These tracking versions are passed to the copy activity to filter data at the source, and the corresponding tracking version is updated for subsequent pipeline runs.

Pros and Cons of each strategy:

1.  Aux metadata table driven watermarking:

Advertisement
free widgets for website
  • Pros: Agnostic of sink type, pipeline idempotent, independent of the sink datastore type.

  • Cons: Dependency on an auxiliary store (e.g., SQL DB), additional operational cost due to the auxiliary component.

2.  Sink driven watermarking:

  • Pros: No requirement for an auxiliary store, performant as the source provides the delta records to ingest.

  • Cons: Tightly coupled to the sink datastore type, may be complex and costly for certain sink datastores like file-based storage.

3.  Change tracking information driven watermarking:

  • Pros: Pipeline idempotent, relies on source-provided delta records.

  • Cons: Limited to data sources that support change tracking, dependence on change tracking information.

Integration with Azure resource provisioners

LinkedIn utilizes provisioners in its Azure deployments to manage resource provisioning, network infrastructure, and data plane deployment. Provisioners offer benefits such as standardized resource tags, ownership identification, version-controlled infrastructure code files, and simplified developer experience. 

Costwiz integrates with the provisioners, enabling the application to display these details. Assigned engineers can access IaC repo links to refer to the code used for resource deployment and incorporate recommended configurations for optimal sizing. 

In the future, we may introduce deeper integrations involving deployment gating, where provisioners can leverage Costwiz’s cost trend data to evaluate cost quota usage and enforce constraints or approval processes before resource deployment.

Advertisement
free widgets for website

Escalation mechanism

  • Image of the escalation mechanism phases

Figure 5: Escalation mechanism phases

Making people aware of cost optimizations is one thing, but ensuring they act on them is a different challenge. We saw the need for accountability from day one and to accomplish that, we designed escalation engines. The escalation engine is a workflow designed to ensure accountability and action on cost optimizations. It consists of three phases: Collect, Process, and Act (as described in Figure 5).

In the Collect phase, relevant datasets are gathered, including Azure resource recommendations, internal organization hierarchy data from LinkedIn, and subscription scoped configurations.

Advertisement
free widgets for website

The escalation process includes the following key points:

  1. Notification Cadence: Notifications are sent at specified intervals. For example, assigned engineers receive daily notifications excluding weekends, while level 1 managers can be notified twice a week.

  2. Escalation Hierarchy: The maximum management level in the hierarchy is defined for incrementally looping in individuals. This ensures that higher-level managers are involved as needed.

  3. Maximum Escalations: The maximum number of escalations attempted is determined. Once this limit is reached, the recommendation’s lifecycle ends, and it is no longer considered.

  4. Default CC: Organizations have the option to delegate all Costwiz notifications to specific individuals, such as an on-call team. This configuration allows those designated persons to be copied on all notifications related to their subscriptions.

During the Process phase, policies are evaluated, and exceptions are made for certain executives who are excluded from escalation notifications, such as the CEO and their direct reports. An email allow list is dynamically updated daily to account for any recent changes in the organization hierarchy.

In the Act phase, notifications are aggregated based on the sender’s ID to prevent excessive emails. The maximum number of notifications a person can receive per day is limited to three, even in cases where they have recommendations, escalations for their direct reports, and escalations for their skip-level reports.

The engine records audit records for every decision it makes. These records track whether a notification was attempted, succeeded, failed, or if the maximum number of escalations has been reached. The engine uses these audit records to evaluate if enough time has passed since the last notification based on the configured cadence for that subscription.

Resource ownership identification

The ultimate factor that defines the success of Costwiz workflows is their ability to hold resource owners accountable and drive them to take appropriate actions. This factor is directly related to the ability of Costwiz to determine resource ownership and notify the right owners. Initially, we started by relying on ownership data received from an internal team but that accounted for merely 10% of the total relevant resources with recommendations and hence we decided to explore options and build our own system for this purpose. Further, the public cloud itself doesn’t handle this use case particularly well (for example, audit logs only go back 90 days).

Advertisement
free widgets for website

In an ideal scenario, anyone provisioning a resource should responsibly add some standard tags to the resources followed across the organization which easily identifies the main owners but this is not easily achievable from the first day of cloud adoption. Until we streamline the process to manage resources across the organization, we identified the following sources to retrieve ownership information.

  1. Resource tags

  2. Resource group tags

  3. Provisioner (internal resource management teams) details

  4. Resource activity logs

  5. RBAC (Role assignments in Azure resource groups and subscriptions)

We implemented the base ownership system in a modular way which can be extended with multiple processors for each source mentioned above. The flow diagram of the ownership system is described in Figure 6.

Advertisement
free widgets for website
  • Diagram of the resource ownership identification

Figure 6: Resource ownership identification

We incrementally added the processors for each source based on the coverage and fine tuned them to achieve accuracy. 

  • We started with parsing provisioner details in resources and then processed the tags in resources and resource groups. This covered less than 40% of the total resources.

  • Scanning the activity logs was challenging as the time to scan the last 30 days logs for a single resource took more than 30 seconds easily. Our initial idea was to scan for the last three months but to increase accuracy by relying on recent data, we settled on a 30-day window.

  • Retrieving the role assignments for RBAC processors using Azure’s SDKs was quicker than scanning the activity logs but the roles were assigned at the resource group and subscription level which diluted the accuracy of ownership at the resource level.

This ownership system was primarily built for Costwiz consumption but after realizing its practical utility, we extended the system to a centralized ownership service and exposed REST APIs to compute/get owners which can be utilized by external teams as per their requirements.

Some of the metrics we observed in the process are summarized below in the metrics visibility section.

Why cleanup Costwiz sandbox resources?

When our Productivity Engineering Group started our Azure journey, there were lots of small ad-hoc POCs (Proof of Concepts) and experiments conducted on Azure around resource scalability, feasibility, learning, and more. Because of these experiments, there were many resources created but then most of them were not cleaned up when those POCs were completed. This resulted in high net cost on all the Azure subscriptions that we have owned, which resulted in just the sandbox subscriptions itself costing around 45% of our allocated Azure budget for the group at one point.

The solution

We implemented automated cost optimization on Azure by cleaning up unused resources in our Sandbox subscriptions. Resources are cleaned up based on a time-to-live (TTL) value, and users need to extend the TTL if they want to keep the resource beyond the expiry date. The focus is on sandbox resources, which should be short-lived and removed once their purpose is served.

Advertisement
free widgets for website

To onboard a subscription, we gather information from owners regarding TTL settings, exclusions, and notification preferences. Users are expected to create a resource group for their POCs under their sandbox subscription and place resources within it.

Expiry dates are added as Azure Tags to resource groups, with a default value of 2 weeks. The users of those resource groups would be identified through Azure activity logs and are notified at regular intervals before the expiry date, and notifications are consolidated to avoid spam. These notifications are sent at T-14, T-7, T-2, and T-1 days and these can be tweaked as per the onboarding configuration.

On the expiry date, resource groups are deleted, excluding certain default groups used for setting up the monitoring, and networking infra. Azure keyvaults found under a resource group are first moved to a common resource group before deleting the resource group as with soft delete enabled keyvaults, we would have not been able to create another keyvault with the same name for 60 days from the date of deletion.

Azure Resource Manager APIs are used for resource management, and alerts are sent for any deviations or errors.

The process is divided into three jobs, providing flexibility in execution as described in Figure 7.

Advertisement
free widgets for website
  • Diagram of Sandbox resources clean up process

Figure 7: Sandbox resources clean up process

Metrics and Impact

Cost metrics

So far, Costwiz has shown recommendations for 12K Azure resources and 4.29K (approx 36%) of those resources have been reclaimed (data shown in Figure 8).

Another way to consume this metric is to understand that if these 4.29k resources were still running today, they would add a considerable amount to our opex, every single month.

Advertisement
free widgets for website

Further, splitting these resources into their resource types, we see the following matrix.

  • Graph of the cost metrics

Figure 8: Cost metrics

The following are some of our highlights and learnings:

Advertisement
free widgets for website
  • VMSS resources attributed the maximum percentage (82.7%) for closure of optimization actions.

  • Relatively speaking, few database resources (Sql server – 18%, Database accounts – Cosmos Db – 28.3%) got reclaimed compared to other resource types. This essentially means that the owner teams are much more likely to opt for downsizing their database accounts and would keep them functional instead of deleting these resources.

  • Also worthy of note here is Database accounts – Cosmos Db (Azure resource type – microsoft.documentdb/databaseaccounts) of which 28.3% got acted upon but they contributed only 4% to the potential savings thus implying a relatively large number of resources with very less potential for savings were reclaimed (typically pointing towards unused database accounts).

How has this process created the craft for continuous optimizations in cloud deployments?

The cost of Azure Sandbox Subscriptions reduced to 5% of our total Azure net spend for the group from 45% and remained consistently around that mark. Overall Azure spend growth became organic as the footprint increased while Costwiz continued to identify and eliminate unutilized sandbox subscriptions.

Conclusion

Costwiz has had a profound impact on the way we see Azure costs. We have learned what engineering personnel expect when they are tasked with rightsizing their resources. In fact, the Costwiz – Azure provisioner integration was ideated as part of providing the most exact information around a resource. It is intended to make it easy to use for engineers to be able to quickly check IaC code for resources and make suggested changes there.

Another major learning we have is that surfacing recommendations is a pure engineering challenge and is relatively easy as compared to actually getting people to act on their assigned tasks creating accountability. To make this even better, our escalation mechanism has proved to be very efficient at creating the required traction by looping in business owners and engineering leaders to get the right attention to inefficiencies.

Acknowledgements

Thanks to the team of Vivek Subramaniam, Deven Walia, Karthikeyan Subramanian, Simon Desowza, Brajesh Jaishwal, Vikram Mandyam, Sharath Channamallappa, and Alagarsamy A who ideated, designed, and got this to implementation understanding the urgency to control cloud costs; and thanks to our advisors Brandon Duncan and Brent Cochran who helped us to understand complex cloud costing model during this journey; and thanks to our leaders Balaji R and Balaji Vappala for the opportunity who encouraged and guided us during the entire course of this effort and make us realize the impact continuously. Special thanks to Ritesh Kini and the team who are our partners from the Cloudfit team in Microsoft.

Advertisement
free widgets for website

Topics

Advertisement
free widgets for website
See also  Ocelot: Scaling observational causal inference at LinkedIn
Continue Reading
Advertisement free widgets for website
Click to comment

Leave a Reply

Your email address will not be published.

LINKEDIN

Career stories: Influencing engineering growth at LinkedIn

Published

on

By

career-stories:-influencing-engineering-growth-at-linkedin

Since learning frontend and backend skills, Rishika’s passion for engineering has expanded beyond her team at LinkedIn to grow into her own digital community. As she develops as an engineer, giving back has become the most rewarding part of her role.

From intern to engineer—life at LinkedIn

My career with LinkedIn began with a college internship, where I got to dive into all things engineering. Even as a summer intern, I absorbed so much about frontend and backend engineering during my time here. When I considered joining LinkedIn full-time after graduation, I thought back to the work culture and how my manager treated me during my internship. Although I had a virtual experience during COVID-19, the LinkedIn team ensured I was involved in team meetings and discussions. That mentorship opportunity ultimately led me to accept an offer from LinkedIn over other offers. 

Before joining LinkedIn full-time, I worked with Adobe as a Product Intern for six months, where my projects revolved around the core libraries in the C++ language. When I started my role here, I had to shift to using a different tech stack: Java for the backend and JavaScript framework for the frontend. This was a new challenge for me, but the learning curve was beneficial since I got hands-on exposure to pick up new things by myself. Also, I have had the chance to work with some of the finest engineers; learning from the people around me has been such a fulfilling experience. I would like to thank Sandeep and Yash for their constant support throughout my journey and for mentoring me since the very beginning of my journey with LinkedIn.

See also  Solving Espresso’s scalability and performance challenges to support our member base

Currently, I’m working with the Trust team on building moderation tools for all our LinkedIn content while guaranteeing that we remove spam on our platform, which can negatively affect the LinkedIn member experience. Depending on the project, I work on both the backend and the frontend, since my team handles the full-stack development. At LinkedIn, I have had the opportunity to work on a diverse set of projects and handle them from end to end. 

Advertisement
free widgets for website

Mentoring the next generation of engineering graduates

I didn’t have a mentor during college, so I’m so passionate about helping college juniors find their way in engineering. When I first started out, I came from a biology background, so I was not aware of programming languages and how to translate them into building a technical resume. I wish there would have been someone to help me out with debugging and finding solutions, so it’s important to me to give back in that way. 

I’m quite active in university communities, participating in student-led tech events like hackathons to help them get into tech and secure their first job in the industry. I also love virtual events like X (formally Twitter) and LinkedIn Live events. Additionally, I’m part of LinkedIn’s CoachIn Program, where we help with resume building and offer scholarships for women in tech.

Advertisement
free widgets for website

Influencing online and off at LinkedIn

I love creating engineering content on LinkedIn, X, and other social media platforms, where people often contact me about opportunities at LinkedIn Engineering. It brings me so much satisfaction to tell others about our amazing company culture and connect with future grads. 

See also  How LIquid Connects Everything So Our Members Can Do Anything

When I embarked on my role during COVID-19, building an online presence helped me stay connected with what’s happening in the tech world. I began posting on X first, and once that community grew, I launched my YouTube channel to share beginner-level content on data structures and algorithms. My managers and peers at LinkedIn were so supportive, so I broadened my content to cover aspects like soft skills, student hackathons, resume building, and more. While this is in addition to my regular engineering duties, I truly enjoy sharing my insights with my audience of 60,000+ followers. And the enthusiasm from my team inspires me to keep going! I’m excited to see what the future holds for me at LinkedIn as an engineer and a resource for my community on the LinkedIn platform.

Advertisement
free widgets for website

About Rishika

Rishika holds a Bachelor of Technology from Indira Gandhi Delhi Technical University for Women. Before joining LinkedIn, she interned at Google as part of the SPS program and as a Product Intern at Adobe. She currently works as a software engineer on LinkedIn’s Trust Team. Outside of work, Rishika loves to travel all over India and create digital art. 

Editor’s note: Considering an engineering/tech career at LinkedIn? In this Career Stories series, you’ll hear first-hand from our engineers and technologists about real life at LinkedIn — including our meaningful work, collaborative culture, and transformational growth. For more on tech careers at LinkedIn, visit: lnkd.in/EngCareers.

Advertisement
free widgets for website
    Continue Reading

    LINKEDIN

    Career Stories: Learning and growing through mentorship and community

    Published

    on

    By

    career-stories:-learning-and-growing-through-mentorship-and-community

    Lekshmy has always been interested in a role in a company that would allow her to use her people skills and engineering background to help others. Working as a software engineer at various companies led her to hear about the company culture at LinkedIn. After some focused networking, Lekshmy landed her position at LinkedIn and has been continuing to excel ever since.

    How did I get my job at LinkedIn? Through LinkedIn. 

    Before my current role, I had heard great things about the company and its culture. After hearing about InDays (Investment Days) and how LinkedIn supports its employees, I knew I wanted to work there. 

    While at the College of Engineering, Trivandrum (CET), I knew I wanted to pursue a career in software engineering. Engineering is something that I’m good at and absolutely love, and my passion for the field has only grown since joining LinkedIn. When I graduated from CET, I began working at Groupon as a software developer, starting on databases, REST APIs, application deployment, and data structures. From that role, I was able to advance into the position of software developer engineer 2, which enabled me to dive into other software languages, as well as the development of internal systems. That’s where I first began mentoring teammates and realized I loved teaching and helping others. It was around this time that I heard of LinkedIn through the grapevine. 

    Advertisement
    free widgets for website

    Joining the LinkedIn community

    Everything I heard about LinkedIn made me very interested in career opportunities there, but I didn’t have connections yet. I did some research and reached out to a talent acquisition manager on LinkedIn and created a connection which started a path to my first role at the company. 

    See also  Open Sourcing Venice – LinkedIn’s Derived Data Platform

    When I joined LinkedIn, I started on the LinkedIn Talent Solutions (LTS) team. It was a phenomenal way to start because not only did I enjoy the work, but the experience served as a proper introduction to the culture at LinkedIn. I started during the pandemic, which meant remote working, and eventually, as the world situation improved, we went hybrid. This is a great system for me; I have a wonderful blend of being in the office and working remotely. When I’m in the office, I like to catch up with my team by talking about movies or playing games, going beyond work topics, and getting to know each other. With LinkedIn’s culture, you really feel that sense of belonging and recognize that this is an environment where you can build lasting connections. 

    Advertisement
    free widgets for website

    LinkedIn: a people-first company 

    If you haven’t been able to tell already, even though I mostly work with software, I truly am a people person. I just love being part of a community. At the height of the pandemic, I’ll admit I struggled with a bit of imposter syndrome and anxiety. But I wasn’t sure how to ask for help. I talked with my mentor at LinkedIn, and they recommended I use the Employee Assistance Program (EAP) that LinkedIn provides. 

    I was nervous about taking advantage of the program, but I am so happy that I did. The EAP helped me immensely when everything felt uncertain, and I truly felt that the company was on my side, giving me the space and resources to help relieve my stress. Now, when a colleague struggles with something similar, I recommend they consider the EAP, knowing firsthand how effective it is.

    Advertisement
    free widgets for website
    See also  LinkedIn’s GraphQL journey for integrations and partnerships: How we accelerated development by 90%

    Building a path for others’ growth

    With my mentor, I was also able to learn about and become a part of our Women in Technology (WIT)  WIT Invest Program. WIT Invest is a program that provides opportunities like networking, mentorship check-ins, and executive coaching sessions. WIT Invest helped me adopt a daily growth mindset and find my own path as a mentor for college students. When mentoring, I aim to build trust and be open, allowing an authentic connection to form. The students I work with come to me for all kinds of guidance; it’s just one way I give back to the next generation and the wider LinkedIn community. Providing the kind of support my mentor gave me early on was a full-circle moment for me. 

    Working at LinkedIn is everything I thought it would be and more. I honestly wake up excited to work every day. In my three years here, I have learned so much, met new people, and engaged with new ideas, all of which have advanced my career and helped me support the professional development of my peers. I am so happy I took a leap of faith and messaged that talent acquisition manager on LinkedIn. To anyone thinking about applying to LinkedIn, go for it. Apply, send a message, and network—you never know what one connection can bring! 

    Advertisement
    free widgets for website

    About Lekshmy

    Based in Bengaluru, Karnataka, India, Lekshmy is a Senior Software Engineer on LinkedIn’s Hiring Platform Engineering team, focused on the Internal Mobility Project. Before joining LinkedIn, Lekshmy held various software engineering positions at Groupon and SDE 3. Lekshmy holds a degree in Computer Science from the College of Engineering, Trivandrum, and is a trained classical dancer. Outside of work, Lekshmy enjoys painting, gardening, and trying new hobbies that pique her interest. 

    See also  Solving Espresso’s scalability and performance challenges to support our member base

    Editor’s note: Considering an engineering/tech career at LinkedIn? In this Career Stories series, you’ll hear first-hand from our engineers and technologists about real life at LinkedIn — including our meaningful work, collaborative culture, and transformational growth. For more on tech careers at LinkedIn, visit: lnkd.in/EngCareers.

    Advertisement
    free widgets for website

    Topics

    Continue Reading

    LINKEDIN

    Solving Espresso’s scalability and performance challenges to support our member base

    Published

    on

    By

    solving-espresso’s-scalability-and-performance-challenges-to-support-our-member-base

    Espresso is the database that we designed to power our member profiles, feed, recommendations, and hundreds of other Linkedin applications that handle large amounts of data and need both high performance and reliability. As Espresso continued to expand in support of our 950M+ member base, the number of network connections that it needed began to drive scalability and resiliency challenges. To address these challenges, we migrated to HTTP/2. With the initial Netty based implementation, we observed a 45% degradation in throughput which we needed to analyze then correct.

    In this post, we will explain how we solved these challenges and improved system performance. We will also delve into the various optimization efforts we employed on Espresso’s online operation section, implementing one approach that resulted in a 75% performance boost.

    Espresso Architecture

    Advertisement
    free widgets for website
    • Graphic of Espresso System Overview

    Figure 1.  Espresso System Overview

    Figure 1 is a high-level overview of the Espresso ecosystem, which includes the online operation section of Espresso (the main focus of this blog post). This section comprises two major components – the router and the storage node. The router is responsible for directing the request to the relevant storage node and the storage layer’s primary responsibility is to get data from the MySQL database and present the response in the desired format to the member. Espresso utilizes the open-source framework Netty for the transport layer, which has been heavily customized for Espresso’s needs. 

    Need for new transport layer architecture

    In the communication between the router and storage layer, our earlier approach involved utilizing HTTP/1.1, a protocol extensively employed for interactions between web servers and clients. However, HTTP/1.1 operates on a connection-per-request basis. In the context of large clusters, this approach led to millions of concurrent connections between the router and the storage nodes. This resulted in constraints on scalability, resiliency, and numerous performance-related hurdles.

    See also  Migration madness: How to navigate the chaos of large cross-team initiatives towards a common goal

    Scalability: Scalability is a crucial aspect of any database system, and Espresso is no exception. In our recent cluster expansion, adding an additional 100 router nodes caused the memory usage to spike by around 2.5GB. The additional memory can be attributed to the new TCP network connections within the storage nodes. Consequently, we experienced a 15% latency increase due to an increase in garbage collection. The number of connections to storage nodes posed a significant challenge to scaling up the cluster, and we needed to address this to ensure seamless scalability.

    Resiliency: In the event of network flaps and switch upgrades, the process of re-establishing thousands of connections from the router often breaches the connection limit on the storage node. This, in turn, causes errors and the router to fail to communicate with the storage nodes. 

    Performance: When using the HTTP/1.1 architecture, routers maintain a limited pool of connections to each storage node within the cluster. In some larger clusters, the wait time to acquire a connection can be as high as 15ms at the 95th percentile due to the limited pool. This delay can significantly affect the system’s response time.

    Advertisement
    free widgets for website

    We determined that all of the above limitations could be resolved by transitioning to HTTP/2, as it supports connection multiplexing and requires a significantly lower number of connections between the router and the storage node.

    We explored various technologies for HTTP/2 implementation but due to the strong support from the open-source community and our familiarity with the framework, we went with Netty. When using Netty out of the box, the HTTP/2 implementation throughput was 45% less than the original (HTTP/1.1) implementation.  Because the out of the box performance was very poor, we had to implement different optimizations to enhance performance.

    See also  From the Economic Graph to Economic Insights: Building the Infrastructure for Delivering Labor Market Insights from LinkedIn Data

    The experiment was run on a production-like test cluster and the traffic is a combination of access patterns, which include read and write traffic. The results are as follows:

    Advertisement
    free widgets for website
    Protocol QPS Single Read Latency (P99) Multi-Read Latency (P99)
    HTTP/1.1 9K 7ms 25ms

    HTTP/2 5K (-45%) 11ms (+57%) 42ms (+68%)

    On the routing layer, after further analysis using flame graphs, major differences between the two protocols are shown in the following table.

    CPU overhead HTTP/1.1 HTTP/2
    Acquiring a connection and processing the request 20% 32% (+60%)
    Encode/Decode HTTP request 18% 32% (+77%)

    Improvements to Request/Response Handling

    Reusing the Stream Channel Pipeline

    One of the core concepts of Netty is its ChannelPipeline. As seen in Figure 1, when the data is received from the socket, it is passed through the pipeline which processes the data. Channel Pipeline contains a list of Handlers, each working on a specific task.

    Advertisement
    free widgets for website
    • Diagram of Netty Pipeline

    Figure 2. Netty Pipeline

    In the original HTTP/1.1 Netty pipeline, a set of 15-20 handlers was established when a connection was made, and this pipeline was reused for all subsequent requests served on the same connection. 

    However, in HTTP/2 Netty’s default implementation, a fresh pipeline is generated for each new stream or request. For instance, a multi-get request to a router with over 100 keys can often result in approximately 30 to 35 requests being sent to the storage node. Consequently, the router must initiate new pipelines for all 35 storage node requests. The process of creating and dismantling pipelines for each request involving a considerable number of handlers turned out to be notably resource-intensive in terms of memory utilization and garbage collection.

    Advertisement
    free widgets for website

    To address this concern, a forked version of Netty’s Http2MultiplexHandler has been developed to maintain a queue of local stream channels. As illustrated in Figure 2, on receiving a new request, the multiplex handler no longer generates a new pipeline. Instead, it retrieves a local channel from the queue and employs it to process the request. Subsequent to request completion, the channel is returned to the queue for future use. Through the reuse of existing channels, the creation and destruction of pipelines are minimized, leading to a reduction in memory strain and garbage collection.

    • Sequence diagram of stream channel reuse
    See also  Social Networking Sites Market 2020 (COVID-19 Worldwide Spread Analysis) by Key Players ...

    Figure 3. Sequence diagram of stream channel reuse

    Addressing uneven work distribution among Netty I/O threads 

    When a new connection is created, Netty assigns this connection to one of the 64 I/O threads. In Espresso, the number of I/O threads is equal to twice the number of cores present. The I/O thread associated with the connection is responsible for I/O and handling the request/response on the connection. Netty’s default implementation employs a rudimentary method for selecting an appropriate I/O thread out of the 64 available for a new channel. Our observation revealed that this approach leads to a significantly uneven distribution of workload among the I/O threads. 

    Advertisement
    free widgets for website

    In a standard deployment, we observed that 20% of I/O threads were managing 50% of all the total connections/requests. To address this issue, we introduced a BalancedEventLoopGroup. This entity is designed to evenly distribute connections across all available worker threads. During channel registration, the BalancedEventLoopGroup iterates through the worker threads to ensure a more equitable allocation of workload

    After this change, during registering of a channel, an event loop with the number of connections below the average is selected.

    Advertisement
    free widgets for website
    private EventLoop selectLoop() {  int average = averageChannelsPerEventLoop();  EventLoop loop = next();  if (_eventLoopCount > 1 && isUnbalanced(loop, average)) {    ArrayList list = new ArrayList<>(_eventLoopCount);    _eventLoopGroup.forEach(eventExecutor -> list.add((EventLoop) eventExecutor));    Collections.shuffle(list, ThreadLocalRandom.current());    Iterator it = list.iterator();    do {      loop = it.next();    } while (it.hasNext() && isUnbalanced(loop, average));  }  return loop; } 

    Reducing context switches when acquiring a connection 

    In the HTTP/2 implementation, each router maintains 10 connections to every storage node. These connections serve as communication pathways for the router I/O threads interfacing with the storage node. Previously, we utilized Netty’s FixedChannelPool implementation to oversee connection pools, handling tasks like acquiring, releasing, and establishing new connections. 

    However, the underlying queue within Netty’s implementation is not inherently thread-safe. To obtain a connection from the pool, the requesting worker thread must engage the I/O worker overseeing the pool. This process led to two context switches.  To resolve this, we developed a derivative of the Netty pool implementation that employs a high-performance, thread-safe queue. Now, the task is executed by the requesting thread instead of a distinct I/O thread, effectively eliminating the need for context switches.

    Improvements to SSL Performance

    The following section describes various optimizations to improve the SSL performance.

    Offloading DNS lookup and handshake to separate thread pool

    During an SSL handshake, the DNS lookup procedure for resolving a hostname to an IP address functions as a blocking operation. Consequently, the I/O thread responsible for executing the handshake might be held up for the entirety of the DNS lookup process. This delay can result in request timeouts and other issues, especially when managing a substantial influx of incoming connections concurrently.  

    To tackle this concern, we developed an SSL initializer that conducts the DNS lookup on a different thread prior to initiating the handshake. This method involves passing the InetAddress, that contains both the IP address and hostname, to the SSL handshake procedure, effectively circumventing the need for a DNS lookup during the handshake.

    Advertisement
    free widgets for website

    Enabling Native SSL encryption/decryption

    Java’s default built-in SSL implementation carries a significant performance overhead. Netty offers a JNI-based SSL engine that demonstrates exceptional efficiency in both CPU and memory utilization. Upon enabling OpenSSL within the storage layer, we observed a notable 10% reduction in latency. (The router layer already utilizes OpenSSL.)  

    To employ Netty Native SSL, one must include the pertinent Netty Native dependencies, as it interfaces with OpenSSL through the JNI (Java Native Interface). For more detailed information, please refer to https://netty.io/wiki/forked-tomcat-native.html.

    Improvements to Encode/Decode performance

    This section focuses on the performance improvements we made when converting bytes to Http objects and vice versa. Approximately 20% of our CPU cycles are spent on encode/decode bytes. Unlike a typical service, Espresso has very rich headers. Our HTTP/2 implementation involves wrapping the existing HTTP/1.1 pipeline with HTTP/2 functionality. While the HTTP/2 layer handles network communication, the core business logic resides within the HTTP/1.1 layer. Due to this, each incoming request required the conversion of HTTP/2 requests to HTTP/1.1 and vice versa, which resulted in high CPU usage, memory consumption, and garbage creation.

    To improve performance, we have implemented a custom codec designed for efficient handling of HTTP headers. We introduced a new type of request class named Http1Request. This class effectively encapsulates an HTTP/2 request as an HTTP/1.1 by utilizing wrapped Http2 headers. The primary objective behind this approach is to avoid the expensive task of converting HTTP/1.1 headers to HTTP/2 and vice versa.

    For example:

    Advertisement
    free widgets for website
    public class Http1Headers extends HttpHeaders {   private final Http2Headers _headers;    ….  } 

    And Operations such as get, set, and contains operate on the Http2Headers:

    Advertisement
    free widgets for website
    @Override public String get(String name) {  return str(_headers.get(AsciiString.cached(name).toLowerCase()); } 

    To make this possible, we developed a new codec that is essentially a clone of Netty’s Http2StreamFrameToHttpObjectCodec. This codec is designed to translate HTTP/2 StreamFrames to HTTP/1.1 requests/responses with minimal overhead. By using this new codec, we were able to significantly improve the performance of encode/decode operations and reduce the amount of garbage generated during the conversions.

    Disabling HPACK Header Compression

    HTTP/2 introduced a new header compression algorithm known as HPACK. It works by maintaining an index list or dictionaries on both the client and server. Instead of transmitting the complete string value, HPACK sends the associated index (integer) when transmitting a header. HPACK encompasses two key components: 

    1. Static Table – A dictionary comprising  61 commonly used headers.

    2. Dynamic Table – This table retains the user-generated header information.

    The Hpack header compression is tailored to scenarios where header contents remain relatively constant. But Espresso has very rich headers with stateful information such as timestamps, SCN, and so on. Unfortunately, HPACK didn’t align well with Espresso’s requirements.

    Upon examining flame graphs, we observed a substantial stack dedicated to encoding/decoding dynamic tables. Consequently, we opted to disable dynamic header compression, leading to an approximate 3% enhancement in performance.

    Advertisement
    free widgets for website

    In Netty, this can be disabled using the following:

    Http2FrameCodecBuilder.forClient()    .initialSettings(Http2Settings.defaultSettings().headerTableSize(0));

    Results

    Latency Improvements

    Advertisement
    free widgets for website
    P99.9 Latency HTTP/1.1 HTTP/2
    Single Key Get 20ms 7ms (-66%)
    Multi Key Get 80ms 20ms (-75%)

    We observed a 75% reduction in 99th and 99.9th percentile multi-read and read latencies, decreasing from 80ms to 20ms.

    • Image of Latency reduction after HTTP/2

    Figure 4. Latency reduction after HTTP/2

    We observed similar latency reductions across the 90th percentile and higher.  

    Advertisement
    free widgets for website

    Reduction in TCP connections

      HTTP/1.1 HTTP/2
    No of TCP Connections 32 million 3.9 million (-88%)

    We observed an 88% reduction in the number of connections required between routers and storage nodes in some of our largest clusters.

    Advertisement
    free widgets for website
    • Image of the Total number of connections after HTTP/2

    Figure 5. Total number of connections after HTTP/2

    Reduction in Garbage Collection time

    We observed a 75% reduction in garbage collection times for both young and old gen.

    Advertisement
    free widgets for website
    GC HTTP/1.1 HTTP/2
    Young Gen 2000 ms 500ms (+75%)
    Old Gen 80 ms 15 ms (+81%)
    • Image that shows the reduction in time for GC after HTTP/2

    Figure 6. Reduction in time for GC after HTTP/2

    Waiting time to acquire a Storage Node connection

    HTTP/2 eliminates the need to wait for a storage node connection by enabling multiplexing on a single TCP connection, which is a significant factor in reducing latency compared to HTTP/1.1.

      HTTP/1.1 HTTP/2
    Wait time in router to get a storage node connection 11ms 0.02ms (+99%)
    • Image of the reduction is wait time to get a connection after HTTP/2

    Figure 7. Reduction is wait time to get a connection after HTTP/2

    Conclusion

    Espresso has a large server fleet and is mission-critical to a number of LinkedIn applications. With HTTP/2 migration, we successfully solved Espresso’s scalability problems due to the huge number of TCP connections required between the router and the storage nodes. The new architecture also reduced the latencies by 75% and made Espresso more resilient. 

    Advertisement
    free widgets for website

    Acknowledgments

    I would like to thank my colleagues Antony Curtis, Yaoming Zhan, BinBing Hou, Wenqing Ding, Andy Mao, and Rahul Mehrotra who worked on this project. The project demanded a great deal of time and effort due to the complexity involved in optimizing the performance. I would like to thank Kamlakar Singh and Yun Sun for reviewing the blog and providing valuable feedback. 

    We would also like to thank our management Madhur Badal, Alok Dhariwal and Gayatri Penumetsa for their support and resources, which played a crucial role in the success of this project. Their encouragement and guidance helped the team overcome challenges and deliver the project on time.

    Advertisement
    free widgets for website

    Topics

    Continue Reading

    Trending