<?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 Engineering Team on Medium]]></title>
        <description><![CDATA[Stories by Engineering Team on Medium]]></description>
        <link>https://medium.com/@ziprecruiter.engineering?source=rss-1fefe5dc18b0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*VTwhX9TRzaa4g9dfahgOZA@2x.png</url>
            <title>Stories by Engineering Team on Medium</title>
            <link>https://medium.com/@ziprecruiter.engineering?source=rss-1fefe5dc18b0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 08:06:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ziprecruiter.engineering/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[Named Entity Recognition (NER) of Short & Unstructured Job Search Queries]]></title>
            <link>https://medium.com/@ziprecruiter.engineering/named-entity-recognition-ner-of-short-unstructured-job-search-queries-6b265ec0fb?source=rss-1fefe5dc18b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b265ec0fb</guid>
            <category><![CDATA[search]]></category>
            <category><![CDATA[query-understanding]]></category>
            <category><![CDATA[named-entity-recognition]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Engineering Team]]></dc:creator>
            <pubDate>Mon, 16 Oct 2023 17:46:13 GMT</pubDate>
            <atom:updated>2023-10-16T17:46:13.017Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to build datasets and test multiple ML model combinations to best perform in your domain.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mgUpmOznbIQXJhpe06L0Lw.png" /></figure><p>When you type a query into the search bar on ZipRecruiter’s job marketplace, like “Registered Nurse AGPCNP” or “ Salesforce analyst” you expect to receive results in line with what you meant. Providing the most relevant results in a well-prioritized order gives our users confidence in the platform, reduces drop-off, and ultimately shortens the time it takes them to secure a job.</p><p>Deciphering this intent has been a long-standing challenge for search engine developers and is quite adequately solved in many domains. For job marketplaces, however, there are still multiple challenges: queries are very short and unstructured, choosing the right machine learning (ML) model is not straightforward, and the train/test data is extremely noisy and hard to get.</p><p><strong><em>Spoiler alert </em></strong><em>— although using BiLSTM as the context encoder has become the standard way of solving NER problems in our context, and perhaps yours, it actually was not the top performer</em>.</p><p>Our discoveries have made a significant impact on different parts of our search technology. Below, we elaborate on the key considerations and decisions that can help you do the same.</p><h3>Named Entity Recognition — the right technique for the job</h3><p>Named Entity Recognition (NER) is a ML technique used to identify specific known words or phrases (named entities) within input text data, and categorize them according to predefined groups (entity types).</p><p>A job seeker who searches for “Remote Python Developer” has expressed three distinct intents: job type, skill, and job title. By detecting each of these, we can better surface jobs matching most or all of the intents. Identifying different entity types also supports downstream uses like query classification and provides valuable features for Semantic Retrieval and Learning To Rank models.</p><p>To understand job seeker intent we set out to identify 7 entity types as shown in Figure 1.</p><p><strong>Entity Type Group</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*eTKlm05oXiq8bgAJTqBo7w.png" /><figcaption><em>Figure 1. Chosen groups for search query entity type classification</em></figcaption></figure><h3>Manual annotating train/test data sets is costly, lengthy, and error prone</h3><p>Any NER task requires hundreds of thousands of annotated, or labeled, training data. As you can imagine, getting such a large amount of data annotated correctly poses a couple of serious challenges, especially in job search queries that are typically short and low on context.</p><ul><li><strong>Skill-company synonymy — </strong>For the query “Marketing Salesforce”, tagging the “Salesforce” token (or word) as <em>skill </em>versus <em>company </em>can be tough — the meaning is ambiguous.</li><li><strong>Requires domain expertise </strong>— While annotating “Certified Nurse Assistant”, a naive annotator could tag “Certified Nurse” as a <em>job title </em>and “Assistant” as a <em>generic title with seniority implied</em>. On the other hand, domain expert annotators would tag the entire query as a <em>job title </em>because they understand that “Certified Nurse” and “Certified Nurse Assistant” are not part of the same hierarchy — they’re actually two totally different jobs.</li><li><strong>Social geographic context — </strong>Contextual knowledge of local norms affects query tagging. Annotators based in the US, for example, may tag “before and after school” and “for students” as <em>job types </em>while non-US annotators would not identify any entities in a query.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*GSRHYrjkr7aaHEx6" /><figcaption><em>Figure 2. The three main challenges in annotating job search query data correctly</em></figcaption></figure><p>We knew it would be very expensive and could take years for us to get the amount of job search queries we needed for annotation to a satisfactory level. Even a <a href="https://sdm-dsre.github.io/pdf/named_entity.pdf">TripleLearn Framework</a>, which requires less annotated training data (~20k queries), would still require lots of annotation and create an operational bottleneck.</p><p>We ultimately decided to get a few thousand queries manually annotated as test data, but for training our models we needed a more creative solution.</p><h3>Quickly building a training set by augmenting taxonomy with heuristics</h3><p>ZipRecruiter maintains an extensive yet non-exhaustive taxonomy of different entity types for internal uses such as parsing job posts and resumes. To build a robust training set we decided to complement our taxonomy with some practical, common-sense heuristics and set up a system to automatically tag historical queries.</p><p>When designing heuristics, it is important to think through how the tagged information, i.e. the intent identified, can be used downstream to retrieve results. In our case, many <em>job titles </em>contain some granular information within them such as skill, industry, seniority, etc. For example, “Senior Java Developer” is a <em>job title </em>that also hints at “Java” as a skill (<em>area of interest/specialty</em>), and “Senior” as a <em>seniority level</em>. Therefore, breaking a query down into overlapping subsets is useful.</p><p>These are the steps we followed:</p><h3>Stage 1: Tagging</h3><ol><li><strong>Breaking up each query — </strong>we generate different n-grams for each query where n is between 1 and the number of tokens in the query. For example, for the query “work from home”: we generate tri-grams (‘work from home’), bi-grams (‘from home’, ‘work from’), and uni-grams (‘work’, ‘from’, ‘home’).</li><li><strong>Auto-tagging with existing taxonomy </strong>— As we attempt to find each n-gram in our taxonomy list and tag it accordingly, we give preference to the longer n-gram matches and try to match for them first. This enables us to annotate “work from home” as a <em>job type</em> rather than wrongly annotating “home” as a <em>job type</em>.</li><li><strong>Apply heuristics — </strong>here are some examples of the heuristics we created:</li></ol><ul><li>If a query contains ‘inc’ or ‘ltd’, like “Python Inc” or “Creative Services LTD”, then tag that entire query as a <em>company</em>.</li></ul><pre>if query.contains(&#39;inc&#39; or &#39;ltd&#39;) =&gt; {<br> query_tag = company <br> return query_tag <br>}</pre><ul><li>Only break a<em> job title</em> into granular entities if the resulting granular tags help provide more information, i.e. more than one additional tag. For example, a job title like “Leasing Consultant” can have “Consultant” as a granular <em>job title </em>tag and no tag for “Leasing”. This doesn’t give us additional information than when “Leasing Consultant” was tagged entirely as a job title. But a query for ‘Python Developer’ would get auto-tagged first as a job title (the longest bi-gram) and then broken down because ‘Python’ provides a <em>skill </em>entity type and ‘Developer’ provides a job title entity type.</li><li>If an n-gram was heuristically tagged as a <em>company </em>with the rest of the tokens being totally un-tagged, we would remove the <em>company </em>tag. This helps us correct cases like “Electric Vehicle”, and “Gas Stations” which had “Electric” and “Stations” tagged as a company (because there are companies under those names) but left out the real intent of the query.</li></ul><p><strong><em>Ultimately, the heuristics you build should follow logic relevant to the domain you’re working in and assembled in a sequence that results in the most effective outcome.</em></strong></p><h3>Stage 2: Selecting tagged queries for train/test sets</h3><p>After the tagging stage, each query can be seen to be made up of an Entity Type Sequence (ETS), meaning a combination of any 1 or more entity types. So for example, the “junior developer” query would be a Seniority-Job Title ETS.</p><ol><li>We selected all the queries tagged by the most frequent ETS such that each ETS has at least 1k queries.</li><li>We further sorted them by frequency and kept the top 5k most frequent queries from each ETS. If an ETS had less than 5k queries, we select all the queries.</li><li>From the remaining 300k queries, we then randomly sample to get our heuristically labeled “train set” (220k) and “validation set” (75k), as well as a “random test set” (1k) for which we got human annotations. In addition, since getting it right most of the time is crucial, we created another “frequent test set” (1.2k) containing the most frequent user queries and sent that for human annotation too.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oJtCe8YBjb1nPbDn" /><figcaption><em>Figure 3. Selecting train and test data sets</em></figcaption></figure><p>Before moving forward, we ran the two human-annotated test sets through the auto-heuristics-tagger. This is important to ensure our models learn from trustworthy data. Overall, the auto-tagging performed well on the frequent queries (Precision =73.10%, Recall = 80.21%), but less so for the random test set (Precision = 58.3%, Recall = 45.49%). These results make sense — ZipRecruiter’s taxonomy is compiled to cover the frequent queries very well. For the first round of this product, we found this totally acceptable.</p><h3>The 3 top requirements from our NER model</h3><p>Traditionally NER models are built for natural language tasks where the data is often sentences or even paragraphs of text. However, in our case, the search queries are usually shorter than five words and the density of the entity type within them is extremely high. The chosen model architecture would have to deal with this successfully.</p><p>Moreover, job search queries do not always exhibit natural language patterns. While search queries like “Customer Service” or “Information Technology” will not make sense if the order of the words is swapped, there are many search queries where swapping will not change the meaning. For example, “Python Software Engineer” and “Software Engineer Python” represent the same meaning when a job seeker is looking for a “Software Engineer” job that requires “Python” as a programming skill. The ideal model should be resilient to phrase order permutations. To test for this we combined the random and frequent test sets and identified a subset of roughly 1k queries (non-reversed set) that could be reversed (reversed set).</p><p>Finally, speed is of the essence. We needed the model’s training speed to satisfy our deployment schedules, and since we intended to serve the model as a real-time inference engine for dealing with uncommon queries, the inference speed had to satisfy tight production SLAs.</p><p>We set out to experiment with various neural network architectures and select the one that would best capture the unique characteristics of our use case while effectively balancing the trade-off between accuracy and latency.</p><h3>Encoders and Decoders to capture contextual information</h3><p>An encoder-decoder architecture is very useful for NER models. Before the raw sequence enters the encoder, it is converted into numerical representations using various techniques to fully utilize the natural language features hidden in the sequence. The encoder is responsible for encoding the surrounding contextual information into each token, and the decoder is responsible for decoding the surrounding contextual information for each token into tag predictions.</p><h3>Step 1: Choosing an embedder</h3><p>There are many ways to convert a raw input sequence to numeric representations. These include:word-level embedding, character-level embedding, natural language features, and contextualized embedding from large unsupervised language models.</p><p>Although natural language features and contextualized embedding can potentially help the model learn a better representation of the input sequence, they’re a bit sluggish so we excluded them on the basis of our strict latency requirements and other engineering constraints.</p><p>For the word embedding, we chose to use ZipRecruiter’s in-house pre-trained word2vec model. This embedder is trained on co-searches (meaning what a user searched for right after the initial search) in order to make the frequently co-searched queries, as well as words that share similar surrounding words, closer in the hyperdimensional space.</p><h3>Step 2: Choosing an encoder</h3><p>To encode the surrounding contextual information of the query into each token, we chose to experiment with convolutional neural networks (CNN), recurrent neural networks (RNN), and Transformers.</p><ul><li><strong>CNNs </strong>aggregate a fixed window of information together to generate each token representation. It performs reasonably well on job search queries because the input sequence is usually short so the windowed aggregation can cover most parts of the query.</li><li><strong>RNNs </strong>aggregate information in one direction, either from left to right or from right to left. It is naturally designed for natural language tasks, where the human naturally reads the text in one direction. Although RNNs are usually slower than CNNs, they tend to perform better on similar tasks. We experiment with the bidirectional LSTM (BiLSTM) to mitigate the risk of only capturing the past information in future states because the ordering of the phrase could be insignificant. Remember our non-reversed set that could be reversed?!</li><li><strong>Transformers </strong>aggregate information smartly by upweighting surrounding token representations that are important to each token, giving the mechanism its famous name — self-attention. A single-layer transformer block is also more computationally efficient than RNN when leveraging pre-trained models for downstream tasks. This is because the transformer processes the entire sequence at once, unlike RNN. During testing, we chose the default architecture of a transformer without leveraging the huge pre-trained models. This gave us a fair comparison to other architectures in their ability to capture contextual information in the search queries.</li></ul><h3>Step 3: Choosing a decoder</h3><p>To decode the surrounding contextual information into predictions, we experimented with two widely used decoders:</p><ol><li>Multi-Layer Perceptron (MLP) with Softmax</li><li>Linear-Chain Conditional Random Fields (CRF)</li></ol><p>MLP with Softmax has been the standard method in classification. However, it does not rely on any surrounding information to make the prediction, but instead independently predicts the entity based on the encoded information which encapsulates the dependency.</p><p>Usually, CRF decoders combined with many encoders can yield much better results than MLP + softmax. One small drawback of default CRF implementation is that the prediction is done by utilizing a beam-search-like decoding process, which does not produce any probability measure of being in every hidden state. To produce such probability measures, an approximation can be done by computing the marginal probabilities of each token and utilizing the cross-entropy loss to train the CRF. We used the viterbi decoding CRF to leverage the natural CRF loss for model training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*SI2zO70LG8Ba4aEd" /><figcaption><em>Figure 4. Schematic of the way different encoder and decoder types relate to contextual information</em></figcaption></figure><h3>F1 Macro: Our chosen model evaluation metric</h3><p>We used the common F1 score as our accuracy evaluation metric because it balances precision and recall. The F1 score is drawn towards the lowest between the two thus remaining unbiased nor overly-compromising on either.</p><p>We decided to use a macro averaging scheme because micro and frequency-weighted schema both suffer from class imbalance problems that naturally exist in our data. Thus, our models were evaluated based on a <em>class-level</em> macro F1 score, denoted as F1macro-CLASS, (where the classes refer to B, I, or O in the <a href="https://en.wikipedia.org/wiki/Inside%E2%80%93outside%E2%80%93beginning_(tagging)">BIO tagging scheme</a>) and an <em>entity type </em>level macro F1 score with a strict matching scheme, denoted as F1macro-ENTITY.</p><p>Although we won’t go into it.</p><p>In addition, we also measured precision and recall independently because their importance to downstream tasks varies depending on the use case. Recall can be more important if the search engine uses tags only as a way to identify the existence of entity types within the query. On the other hand, precision can be more significant if the search engine filters the result sets based on the predicted tags.</p><h3>CNN+CRF model performs best for short job search queries</h3><p>Overall we created 10 encoder-decoder model combinations and tested them all against our random and frequent test sets as well as the reversed and non-reversed sets. We also measured training and inference speeds.</p><p><strong>The CNN+CRF model yielded the best overall blend of performance, inference speed, and resilience to reversed phrase ordering.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JeLjVKkclC5JK6PD" /><figcaption><em>Figure 5. Performance results for 10 encoder-decoder model models. CNN+CRF performs best on frequent queries with good train and inference speeds.</em></figcaption></figure><p>In under 9 months, and with the enthusiastic and committed support of our colleagues, we were able to release a highly influential feature to production that deals with most user queries.</p><p>That being said, we are aware of the model’s limitations. Dealing with rare search queries and identifying an ever-evolving space of companies and workplaces is still not perfect.</p><p>Besides expanding the training data with human annotations and more intricate heuristics, we will be exploring training language models on entire job descriptions as well as incorporating knowledge graphs. What’s more, as we continue to personalize our service, the ability to identify the background of a specific user placing a query may help resolve ambiguities. For example, for a job seeker who works in the software industry, “Salesforce” could be resolved as a <em>company </em>tag, while for a job seeker who works in the marketing industry “Salesforce” could be resolved as a <em>skill</em>.</p><p>To dive deeper and see more of the results <a href="https://drive.google.com/file/d/1RIVLhpQSBqiZ7aYmi1SgcWdOaEswlR37/view">view the full paper here</a>.</p><p><strong><em>If you’re interested in working on solutions like these,</em></strong><a href="https://www.ziprecruiter.com/careers"><strong><em> visit our Careers page</em></strong></a><strong><em> to see open roles.</em></strong></p><p>* * *</p><p>[1] Zhiheng Huang, Wei Xu, and Kai Yu. 2015. Bidirectional LSTM-CRF Models for Sequence Tagging. CoRR abs/1508.01991 (2015). arXiv:1508.01991 <a href="http://arxiv.org/abs/1508.01991">http://arxiv.org/abs/1508.01991</a></p><p>[2] Note the distinction between implementing <a href="https://medium.com/mlearning-ai/how-to-automate-job-searches-using-named-entity-recognition-part-1-16c150acafa0">NER on job <em>descriptions</em></a> with much richer information versus short search queries.</p><p><strong>About the Authors:</strong></p><p><a href="https://www.linkedin.com/in/ishrivas/">Ishan Shrivastava</a> and <a href="https://www.linkedin.com/in/hengda-shi/">Hengda Shi</a> are Data Scientists on the Job Search team at ZipRecruiter. They find life at ZipRecruiter very fulfilling as it combines ‘The Three Essentials’: (1) freedom to build cutting edge tech, (2) the leverage to impact a broad spectrum of people, and the (3) fun of doing it with others, in a team-oriented culture where camaraderie and supportive growth are cultivated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DeikRLUq5tW8LZLx" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jT-R2STMyzVbnutS" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b265ec0fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3 Powerful Features of ZipRecruiter’s Search]]></title>
            <link>https://medium.com/ziprecruiter-tech/3-powerful-features-of-ziprecruiters-search-188d783ab32e?source=rss-1fefe5dc18b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/188d783ab32e</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[search]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Engineering Team]]></dc:creator>
            <pubDate>Mon, 02 Oct 2023 16:02:55 GMT</pubDate>
            <atom:updated>2023-10-02T16:02:55.612Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OXr1V6np7YPw9BoSeEV2Bg.png" /></figure><p><em>The intricacies of autosuggest, how even low yield queries continue the journey, and considerations when ranking the results page.</em></p><p><a href="#1825">1. Autosuggest search with popularity sorting</a></p><p><a href="#7cd8">1.1 Why autosuggest?</a></p><p><a href="#098d">1.2 Ranking autosuggest results by popularity in a given timeframe</a></p><p><a href="#fb1c">1.3 What you suggest affects your brand — filter it</a></p><p><a href="#9a61">2. Ensuring results for job-scarce locations or positions</a></p><p><a href="#dce6">2.1 The Related Searches feature and predictive model</a></p><p><a href="#d623">2.2 Measuring the impact of Related Searches</a></p><p><a href="#a27d">3. Ranking search results with GBDT and predicted CTR</a></p><p><a href="#d264">3.1 Step 1 — Decision tree scoring</a></p><p><a href="#2627">3.2 Step 2 — Predicted click-through-rates (CTRs)</a></p><p><a href="#ee95">3.3 Ranking results is the single most influential driver of engagement</a></p><p><a href="#3634">4. Zip’s balance between quick testing and robust pipelines</a></p><p>On ZipRecruiter’s job marketplace, the search bar is a popular starting point for job seeker journeys. It enables effortless interaction with our massive database of jobs, salaries and career insights, yet its complexity is often taken for granted.</p><p>Because we have millions of job listings currently active across the US, helping each person cut to the chase and find the right employment opportunity as quickly and hassle free as possible, is our core value proposition.</p><p>The Search Development team constantly improves the search experience and we’re excited to share 3 features that have contributed to making our product so successful. These methodologies can be applied to any search tool in almost any domain.</p><h3>1. Autosuggest search with popularity sorting</h3><h3>1.1 Why autosuggest?</h3><p>Perhaps the most common feature of any search these days is autosuggest. A user starts typing and 10 relevant suggestions pop up based on the letters thus far input. It may seem like a given, but let’s recap the ‘why’ for a moment.</p><p>The rationale is simple — anticipate what the user wants, help with standard phrasing, and provide examples of an expanded range of possibilities. In this way, we save a job seeker’s time while educating and adding value.</p><p>As it turns out, many users are in exploration mode — not exactly sure what they want or how to describe it. So, a few tips along the way are very useful. When a user types in ‘data’ they’ll quickly see options for ‘data entry’, ‘data analyst’, ‘data scientist’, ‘data engineer’, and more. If they’re not sure what a data scientist is or how much they’d make, <a href="https://www.ziprecruiter.com/career/Data-Scientist/What-Is-How-to-Become">the career pages will help them learn more</a>.</p><p>Additionally, our research shows that autosuggest promotes a job seeker’s confidence in the system. When a user sees their intended search as part of the suggestion list, they know they’re on the right track, and by choosing from a system-suggested term we avoid embarrassing outcomes with no results.</p><p>To gain more insight, we launched two autosuggest variants with the same suggestions but in a different order. We found that people tended to click on whatever was higher on the list. There seems to be an intuitive assumption that whatever’s at the top is in some way ‘better’.</p><blockquote><strong>People tend to click on whatever is higher on the autosuggest list</strong></blockquote><p>The cherry on top is that some users who choose from the suggestion list may add even more words, thereby increasing the accuracy of their search and the likelihood to end up applying for a job.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/0*bQUR6ApWzRL019sc" /><figcaption><em>Image 1 — ZipRecruiter’s autosuggest tool with highlighting, popularity ranking, and multiple intent types.</em></figcaption></figure><h3>1.2 Ranking autosuggest results by popularity in a given timeframe</h3><p>For the upgraded version of our search bar, we used an out-of-the-box open-source tool called <a href="https://opensearch.org/">OpenSearch</a> which text-matches the input string to an existing search index.</p><p>When developing the new search bar, we took advantage of an OpenSearch feature which allows weighting the suggested results for sorting purposes. In our case, we chose to sort suggestions based on how popular they were amongst user searches in the last 2 weeks.</p><blockquote><strong>We sort suggestions based on the last 2 weeks’ popularity</strong></blockquote><p>The logic behind this is that popular suggestions are more likely to be useful for the most people. For example “work from home” is a more popular search query than “wordpress developer” or “water polo instructor”. So, given the letter “w”, we prioritize the first option in order to serve the most people.</p><p>We chose 2 weeks as the ideal window to capture behavior and create the search index after some hyper-parameter-tuning. Analyzing our data revealed that 14 days is the shortest period to catch all <em>head </em>and <em>torso </em>queries as well as a good fraction of the trailing <em>tail</em>. Head queries are searched all the time (e.g. ‘entry level’ or ‘full time’), torso queries are searched very often (e.g. ‘nurse practitioner’ or ‘warehouse driver’) and tail queries are quite unique (e.g. ‘remote senior python engineer’). A shorter time period would mean missing out on tail queries and for a longer time period we wouldn’t be adding much value but just lengthening the training run time (which is typically 30–60 minutes).</p><p>In addition, we expanded the search index from only job titles to more fields, like companies, skills, job type (e.g. full time, part time, or remote), workplaces (e.g. hospital, movie theater), and industries. Notice some of these examples in Image 1.</p><p>As far as the UI goes, we made sure to follow autosuggest best practices like highlighting differences, keeping the list short, emphasizing the cursor location, and avoiding scrollbars.</p><h3>1.3 What you suggest affects your brand — filter it</h3><p>The results of our initial pilot made it clear that what we suggest affects not only the user experience but also the way our brand is perceived, and even how we influence the job market. Filtering out terms you don’t want suggested to a user, even though they may be ‘frequent’, is crucial for providing a professional world-class experience. Examples would be curses or legally questionable jobs.</p><p>These four filters clean up our historical query database prior to autosuggest index building:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9Un2LP4JxzVn7RZb" /><figcaption><em>Image 2 — Data pipeline and filtering for autosuggest</em></figcaption></figure><ol><li><strong>Infrequent queries </strong>— the core of our autosuggest is popularity, so the first thing we do is filter out queries with less than k=5 unique users in the given period.</li><li><strong>Un-tagged queries — </strong>Overall, we avoid suggesting queries for which we know it will be hard to produce very relevant results. One type of tough-to-serve queries are the ‘entity-less’ ones — those in which we can’t discern a clear job title, skill, company or other entity. For example, although the intention in a search for ‘good pay’ is clear to a human, the query doesn’t contain a string that fits into any of our entity categories. Our Query Tagger algorithm (which you can read about in an upcoming post) reviews the queries from the last <em>n</em> weeks (n=2 in our case), filtering out those in which we can’t identify any entity. This is a data quality check to balance between popular queries and our ability to serve them. Of course, a user will still be able to type ‘good pay’ voluntarily, and the results page will be based on text matching alone. Ideally, we could serve a list prioritized based on salaries, for example, but dealing with unique (yet surprisingly frequent) queries is an entirely separate project.</li><li><strong>Inappropriate or disallowed words </strong>— We maintain an internal taxonomy of common words or phrases that are recognizable in our field. Queries with these words are obviously allowed and augmented with a periodically updated list of additional “valid” and “invalid” words curated during data exploration. For instance, an additional allowed phrase was “ventilating” as in “heating ventilation and air conditioning technician” which we realized is indeed a frequently searched and valid term title that simply hadn’t made it into the company’s taxonomy yet, for whatever reason. Explicitly disallowed autosuggestions include phrases referring to illegal or unethical work which if ever appeared in real job postings, we avoid actively suggesting.</li><li><strong>Transposed phrases and similarities </strong>— In order to keep all the 10 suggestions that pop up (or down) distinct and useful, we identify transposed phrases and highly similar ones, and show the only most popular version.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IMdIFqvzxJn2vnyx" /><figcaption><em>Image 3 — Popularity ranked autosuggest lifts CTR by 6% versus no autosuggest.</em></figcaption></figure><blockquote><strong>Thanks to popularity sorting, smart filtering and adding multiple entity types to our autosuggest, we achieved a 6% lift in autosuggest engagement over the out-of-the box autosuggest system.</strong></blockquote><p>Looking forward, we are considering incorporating the CTR of actual job descriptions related to the specific input query already in the autosuggest ranking. Meaning, suggesting in the query input stage based on how likely people are to click on a link to a job post on the search results page.</p><h3>2. Ensuring results for job-scarce locations or positions</h3><h3>2.1 The Related Searches feature and predictive model</h3><p>Some specific searches or locations don’t produce many results. For example, a “Proctor” position in “Redding, CA” may only have a handful of job listings or none at all. For us at ZipRecruiter, finding opportunities for everyone, especially those in job scarce areas, is a must. If people are willing to be flexible, Search must be too.</p><p>We created the ‘Related Searches’ feature which appears on sparse results pages and offers new search suggestions that are guaranteed to produce at least 5 results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*T9hb-Um5McF36tOE" /><figcaption><em>Image 4 — Related Searches feature on a low yield results page.</em></figcaption></figure><p>The Related Searches are produced by one of the following two algorithms:</p><ol><li><strong>Order aware algorithm </strong>— A machine learning model takes into account previous users’ sequence of behavior <strong><em>in the time domain </em></strong>to predict what a job seeker might want to search for next, given their current search query. The vast scale of historical search data that we’ve collected over the years is key to achieving robust predictions.</li><li><strong>Order un-aware algorithm — </strong>A separate algorithm produces potential queries semantically similar to the low yield query. Any company with a search history database of any size can offer this.</li></ol><p>The resulting static lookup tables hold all related positions to each of the most frequent ‘low result’ queries. ‘Low result’ queries with less than 5 active job listings are removed and the remaining ‘related results’ are ordered by descending popularity (or frequency).</p><p>Interestingly, thus far our A/B testing has shown no noticeable difference in performance between these two models. Therefore, a given user will be served Related Search results from one of the models at random.</p><h3>2.2 Measuring the impact of Related Searches</h3><p>When testing the impact of the Related Searches feature we measured the likelihood of a user to click on a job during their search session, in three use cases. These use cases differ in the amount of jobs displayed around the Related Searches box.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6tpIen5_qacA_vwPVitRdg.png" /><figcaption>Image 5 — Impact of the Related Search model on click likelihood for three use cases</figcaption></figure><p>As you can see, although the usefulness of this feature is clear for zero to five jobs, above six it had no significant impact on user experience. The reason for this is that if a user’s journey is going well, i.e. they’ve been served many relevant jobs, they probably won’t be starting a new search.</p><p>We are aware, however, that our UI design choice may have impacted case #3. During testing we chose to insert the Related Searches box after the 5th result even on pages with many more results. Perhaps users just kept scrolling and if we had put the Related Searches at the end, it would have drawn more engagement.</p><h3>3. Ranking search results with GBDT and predicted CTR</h3><p>For any typical query, we fetch up to 1,000 jobs listings. The order in which they are presented influences which listing the user will engage with. Ideally, we want to serve the most fitting and likely successful results first.</p><h3>3.1 Step 1 — Decision tree scoring</h3><p>Behind the scenes, a gradient boosted decision tree (GBDT) machine learning model takes into account different parameters related to the job listing and the user’s query, to come up with a score within a fixed range, say [-5,5]. Some examples of the parameters are: salary offered, employment type (part-time, full-time, remote), distance from job, text match of job, and semantic match of job. The score signifies the ‘relevance’ of each position to the query intent and the higher the score the higher a listing should be in the ranking.</p><p>In essence, we have a series of decision trees with yes/no questions. For a question like ‘Is the salary of this job greater than 80k?’ the model continues down a different decision branch depending on the answer. The next question may be ’Is this job less than 5 miles from the user’s location?’ and so it goes. Each node, or question, adds a value and the outcome is the score.</p><h3>3.2 Step 2 — Predicted click-through-rates (CTRs)</h3><p>Although the previous step may seem enough, it is only one side of the coin. Besides the relevance of a listing to the user’s query, business purposes require us to calculate the likelihood a user will click on any listing (i.e. CTR) after they see the results, and preemptively incorporate that likelihood into the ranking.</p><p>It turns out that a direct correlation between the [-5,5] range to CTR can’t be made. People searching ‘registered nurse’, ‘truck driver’ or ‘work from home’ could each result in the exact same GBDT score for a given job listing, but not have the same CTR after they saw the results. Usually, vague queries like ‘full time’ have lower CTRs than specific ones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uar4guRBosFI1BRm" /><figcaption>Image 6 — different search queries have very different baseline click-through-rates</figcaption></figure><p>To solve this, we use the known CTRs for millions of historical queries to set a baseline for the specific query at hand. This combined with the GBDT ranking and business considerations gives the ultimate search result ranking.</p><h3>3.3 Ranking results is the single most influential driver of engagement</h3><p>When we tested the impact of a serving search results ranked by a ML model versus a rudimentary text scoring method, we saw an astounding 7% lift in the ‘Impression Set CTR’ metric. This means the likelihood that after a user searches for something, they’ll click on at least one of the search results.</p><p>This was a huge success and one of the biggest engagement lifts we’ve seen from a single feature.</p><h3>4. Zip’s balance between quick testing and robust pipelines</h3><p>All of these features rely either on a ML model, a trending query and behavior dataset, or the current active job dataset, all of which require refreshing in some periodic cadence.</p><p>At Zip, we strive to build PoCs fast and test them quickly! Once the value and impact of a feature is clear, we then set out to plan a more robust training pipeline and cadence for refreshing our models and datasets.</p><p>Obviously, this has to be balanced with other priorities. So, to decide when the time is right to start building a recurring training pipeline, we always have a primary metric. As long as that metric is exhibiting lift relative to the original baseline, we’re good as is.</p><p><strong><em>If you’re interested in working on solutions like these,</em></strong><a href="https://www.ziprecruiter.com/careers"><strong><em> visit our Careers page</em></strong></a><strong><em> to see open roles.</em></strong></p><p><strong>About the Author</strong></p><p>Ritvik Kharkar has been a Data scientist on ZipRecruiter’s Search team for over 2 years where he builds ML models and tools that improve how jobs are served to users. He loves digging into new challenging projects every day, and is passionate about producing data science videos on his <a href="https://www.youtube.com/c/ritvikmath">YouTube channel</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yK9_eP9Zl0b8jJhH" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=188d783ab32e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ziprecruiter-tech/3-powerful-features-of-ziprecruiters-search-188d783ab32e">3 Powerful Features of ZipRecruiter’s Search</a> was originally published in <a href="https://medium.com/ziprecruiter-tech">ZipRecruiter Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monitoring Kubernetes Cluster Health on AWS Spot Instances — Part 3]]></title>
            <link>https://medium.com/ziprecruiter-tech/monitoring-kubernetes-cluster-health-on-aws-spot-instances-part-3-cfbd33656ef3?source=rss-1fefe5dc18b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/cfbd33656ef3</guid>
            <dc:creator><![CDATA[Engineering Team]]></dc:creator>
            <pubDate>Wed, 27 Sep 2023 10:23:49 GMT</pubDate>
            <atom:updated>2023-09-29T17:08:20.560Z</atom:updated>
            <content:encoded><![CDATA[<h3>Monitoring Kubernetes Cluster Health on AWS Spot Instances — Part 3</h3><h4>How ZipRecruiter uses open source tools to monitor a Kubernetes infrastructure built on discounted AWS Spot instances</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wN8CRK6qZrLAPS6bXfdFOA.png" /></figure><p><em>This is Part 3 of a series of posts outlining ZipRecruiter’s use of </em><a href="https://aws.amazon.com/ec2/spot/"><em>AWS Spot instances</em></a><em>. In this series, we hope to highlight the benefits of using Spot Instances and how we go about doing so. We’ll talk about the tools we use to deploy to Spot, the way we monitor the health of our systems there, and how we write fault-tolerant applications.</em></p><p>In <a href="https://medium.com/@ziprecruiter.engineering/scaling-safely-on-aws-spot-using-the-cluster-autoscalers-priority-expander-part-2-fe5aa4998bd2">Part Two</a>, we shared how our move to AWS Spot instances in conjunction with Kubernetes has saved us a lot of money. Here, we explain how we monitor our Kubernetes clusters running on these ephemeral instances.</p><p>With a few open source tools, some straight-forward Prometheus queries and Grafana we can visualize spot interruptions and the health of our cluster, and get alerted right away if things become unstable due to large-scale spot reclamations.</p><h3>The Challenge: Monitoring Kubernetes clusters built on ephemeral infrastructure</h3><p>At ZipRecruiter we have built our entire engineering infrastructure, from prod to dev to test, on AWS Spot instances, cutting our compute bill down to a fraction of what it would be if we used the typical On Demand EC2 instances. As with any engineering solution, there are always trade-offs, and in our case, the tradeoff is that our EC2 instances may be reclaimed by AWS at any time.</p><p>For a while, because we had built such a resilient and smoothly running infrastructure, we were unaware that reclamations were happening at all. We didn’t experience any site outages, any data loss, etc. However, over time reports of subtle issues started coming in. Highly available services would lose connectivity for a few seconds, entire Spark jobs would disappear unexpectedly, and latency of HTTP requests would suddenly increase. We were experiencing Spot reclamations on a larger scale than expected.</p><p>We realized that we needed to keep track of these large reclamations so we could react appropriately by changing the priority of the different node types, for example. In this article I’ll show you a few simple Prometheus queries we use to monitor the size of our fleet, including important information like the types of instances on which they’re built on and what availability zones they exist in.</p><h3>First: How do we get the cluster data?</h3><p>We use two open source tools to extract this data from our cluster: <a href="https://github.com/prometheus-operator/kube-prometheus">kube-prometheus</a> and <a href="https://github.com/kubernetes/kube-state-metrics">kube-state-metrics</a>.</p><p>Kube-prometheus is part of the Prometheus Operator project, a Prometheus-independent effort to make it easy to manage Prometheus on Kubernetes. Direct from the README, “This repository collects Kubernetes manifests, Grafana dashboards, and Prometheus rules combined with documentation and scripts to provide easy to operate end-to-end Kubernetes cluster monitoring with Prometheus using the Prometheus Operator.” How to set up kube-prometheus is beyond the scope of this article, but it’s worth noting that installing it is straightforward, and you can find quickstart instructions in the repository readme.</p><p>One important thing that kube-prometheus provides for us is a tool called kube-state-metrics. The README explains: “kube-state-metrics (KSM) is a simple service that listens to the Kubernetes API server and generates metrics about the state of the objects. It is not focused on the health of the individual Kubernetes components, but rather on the health of the various objects inside, such as deployments, nodes and pods.”</p><p>Kube-state-metrics provides all kinds of useful metrics that I won’t go into here, but there’s some <a href="https://github.com/kubernetes/kube-state-metrics/tree/main/docs">fantastic documentation</a> to learn more. One metric that is particularly useful for us is <a href="https://github.com/kubernetes/kube-state-metrics/blob/main/docs/node-metrics.md">kube_node_labels</a>. The Kubernetes Operations, a tool for provisioning clusters (also known as kOps), applies quite a few useful labels to nodes that contain information about its deployment in AWS. By looking at a node’s labels we can easily see its instance type, its region, its availability zone and more.</p><p>Kube-state-metrics simply converts non-alpha characters in Kubernetes resource labels to underscores in Prometheus metric labels, so a metric label like node.kubernetes.io/instance-type becomes label_node_kubernetes_io_instance_type. So for example, counting nodes of a given instance type is as simple as querying using that label:</p><pre>count(kube_node_labels{label_node_kubernetes_io_instance_type=&quot;r5dn.metal&quot;})</pre><p>Being able to query metrics based on these AWS-specific labels is all we need to make some useful graphs and alerts.</p><h3>Next: What information do we care about?</h3><p>Now that we see how we can access the information, the next thing to figure out is what information we care about.</p><h4>Node Count</h4><p>The first thing that is useful is a simple node count. This is nothing more than the answer to “how many nodes are currently running in our cluster?” We also want to know counts for each instance group, region, availability zone and instance type. This makes it very easy to identify if we skew any particular way. When we notice that AWS just reclaimed (or has a tendency to frequently reclaim) nodes of a given instance type, or in a certain availability zone, this serves as a signal that we should switch to a different instance type or diversify.</p><h4>Young Nodes</h4><p>We also want to know how many young nodes we have. Young nodes are an indication that the cluster has recently grown, or that nodes have been recently replaced. A sharp uptick is generally a sign of a large Spot reclamation, whereas a steady increase is generally a sign of healthy cluster scaling.</p><h4>Spot Interruptions</h4><p>The next thing we care about is spot rebalance or interruptions. The node termination handler publishes events about ITNs (Instance Termination Notifications). You can read more about them <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-instance-termination-notices.html">here</a>, but for our purposes all you need to know is that ITNs are events that are published by AWS two minutes before a spot node is reclaimed. Ideally, in those two minutes, you have time to properly drain your node and shut down in a predictable way. This is a task for the AWS Node Termination Handler, which you can read more about <a href="https://github.com/aws/aws-node-termination-handler">here</a>.</p><h4>Spot Interruption Percentage</h4><p>Perhaps even more importantly, we want to know the percentage of our fleet that received an ITN at any given time. Our concern is losing a high percentage of our fleet. If all of a sudden 10 nodes receive INTs, on a 200 node cluster we don’t even flinch. But if our cluster has 20 nodes at the time, we just lost half our cluster and stability has been affected.</p><h3>Finally: How do we get this data?</h3><p>Now that we know where to find this data in Prometheus, as well as what type of information we’re looking for, we can form some fairly straightforward Prometheus queries to fetch this data. Prometheus’ query language is called <a href="https://prometheus.io/docs/prometheus/latest/querying/basics/">PromQL</a>, and while it can get quite complicated, you won’t need advanced PromQL knowledge to understand what we’ll show here.</p><p>Let’s tackle the easiest one first: <strong>Node Count</strong>. This is achieved by counting all node labels with the role “node”. You produce a list of them with this simple query:</p><pre>kube_node_labels{label_kubernetes_io_role=&quot;node&quot;}</pre><p>Then, use the count function. Easy as pie.</p><pre>count(<br>  kube_node_labels{label_kubernetes_io_role=&quot;node&quot;}<br>)</pre><p>We also want to know some more information about where and what our instances are so we can easily visualize how our nodes are balanced across type, location and instance group. We do this using a <a href="https://prometheus.io/docs/prometheus/latest/querying/operators/#aggregation-operators">by clause</a> that includes the labels we want to break down by.</p><pre>count by(<br>  label_node_kubernetes_io_instance_type,<br>  label_topology_kubernetes_io_zone,<br>  label_kops_k8s_io_instance_group<br>)(<br>  kube_node_labels{label_kubernetes_io_role=&quot;node&quot;}<br>)</pre><p>Using this query in Grafana gives us a graph that makes it easy to see our cluster size, as well as the balance of nodes across availability zones. We can easily identify scaling events, and in one case we identified a bug that caused unnecessary scaling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fR4eiraFcA2ObO47" /><figcaption><em>Image 1. A spike in the node count alerted us to unnecessary scaling.</em></figcaption></figure><p>Next up: <strong>Young Node Count</strong>. As mentioned above, we want to know if there’s a spike in new nodes. This is often because of scale-up, but a sharp spike in young nodes might be indicative of a large Spot reclamation.</p><p>We start by joining a list of nodes to their creation date, and then subtract that number from the current time to find their age. Note that the kube_node_created metric is provided by kube-prometheus. Simply join it to that metric on the “node” label using <a href="https://prometheus.io/docs/prometheus/latest/querying/operators/#vector-matching">group_left</a>.</p><pre>time() -<br>  kube_node_labels{label_kubernetes_io_role=&quot;node&quot;}<br>  * on(node) group_left kube_node_created</pre><p>We can then filter out nodes that are older than our desired age. In our specific case, we want to know about nodes younger than one hour, or 3600 seconds.</p><pre>(<br>  time() -<br>    kube_node_labels{label_kubernetes_io_role=&quot;node&quot;}<br>    * on(node) group_left kube_node_created<br>) &lt;= 3600</pre><p>And, as we did before, wrap that with a count to get the total number of nodes less than an hour old.</p><pre>count(<br>  (<br>    time() -<br>      kube_node_labels{label_kubernetes_io_role=&quot;node&quot;}<br>      * on(node) group_left kube_node_created<br>  ) &lt;= 3600<br>)</pre><p>Also just like with node count, we break young node count down by instance type, availability zone and instance group. This makes it easy to identify when we’ve lost spot instances of a single type, in a single zone or when we’re scaling up in a single zone. Just like before, a simple by clause does the trick.</p><pre>count by(<br>  label_kops_k8s_io_instance_group,<br>  label_node_kubernetes_io_instance_type,<br>  label_topology_kubernetes_io_zone<br>)(<br>  (<br>    time() - kube_node_labels{label_kubernetes_io_role=\&quot;node\&quot;}<br>    * on(node) group_left kube_node_created<br>  ) &lt;= 3600<br>)</pre><p>This query can be used to create a graph that makes it easy to see where we have young nodes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bJjBcj6spzsG6U-e" /><figcaption><em>Image 2. Monitoring young nodes reveals where we’ve lost node types or zones.</em></figcaption></figure><p>The third thing we care about is <strong>Spot Rebalances or Interruptions</strong>. For the sake of brevity, we’ll only talk about spot interruptions, though we care about both spot interruptions and rebalance recommendations. A rebalance is essentially AWS moving our spot instances to a location that has a lower likelihood of interruption (read more about it <a href="https://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-capacity-rebalancing.html">here</a>). We account for both by adjusting any of the below queries to check for either taint like this:</p><pre>key=~&quot;aws-node-termination-handler/(spot-itn|rebalance-recommendation)&quot;</pre><p>Just like how we joined the kube_node_created metric when looking for young nodes above, we can join the kube_node_spec_taint metric to look for specific taints. In our case, we want taints with the value “spot-itn” (or “rebalance-recommendation,” see above).</p><pre>kube_node_labels{label_kubernetes_io_role=&quot;node&quot;}<br>  and on(node) <br>kube_node_spec_taint{key=~&quot;aws-node-termination-handler/spot-itn&quot;}</pre><p>We add max_over_time to look backwards an hour and check if any nodes had this taint. And then, of course, wrap that with a count to get the total nodes at any given minute.</p><pre>count(<br>  max_over_time((<br>    kube_node_labels{label_kubernetes_io_role=&quot;node&quot;}<br>      and on(node)<br>    kube_node_spec_taint{key=~&quot;aws-node-termination-handler/spot-itn&quot;}<br>  )[1h:1m])<br>)</pre><p>Just as with Node Count and Young Node count, we also want this information broken down by instance group, instance type and availability zone, so we add our now-familiar by clause.</p><pre>count by(<br>  label_kops_k8s_io_instance_group,<br>  label_node_kubernetes_io_instance_type,<br>  label_topology_kubernetes_io_zone<br>)(<br>  max_over_time((<br>    kube_node_labels{label_kubernetes_io_role=&quot;node&quot;}<br>      and on(node)<br>    kube_node_spec_taint{key=&quot;aws-node-termination-handler/spot-itn&quot;}<br>  )[1h:1m])<br>)</pre><p>This gives us data for a graph that makes it easy to identify large-scale spot interruptions or rebalance events.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5EFr7tzZPuIHWGrR" /><figcaption><em>Image 3. Monitoring Spot instance interruption notices or rebalancing.</em></figcaption></figure><p>And finally, we want to know the <strong>Spot Rebalance or Interruption Percentage</strong>. These queries are a bit longer, but they build on what was previously shown.</p><p>Getting the interruption percentage is as easy as dividing our spot interruption query by the total number of nodes, and then multiplying that by 100 to get a percentage:</p><pre>count( <br>  max by (node) (<br>    max_over_time(<br>      kube_node_labels{label_kubernetes_io_role=&quot;node&quot;}<br>        and on(node)<br>      kube_node_spec_taint{key=~&quot;aws-node-termination-handler/spot-itn&quot;}<br>    ))[1h:1m])<br>  )<br>)<br>/ max_over_time((<br>    count(<br>      max by (<br>        node<br>      )(<br>        kube_node_labels{label_kubernetes_io_role=&quot;node&quot;}<br>      )<br>    )<br>  )[1h:1m]) * 100</pre><p>Like usual, we want to break this down by instance group and zone, so we sprinkle in the by clauses:</p><pre>count by(<br>  label_kops_k8s_io_instance_group,<br>  label_topology_kubernetes_io_zone<br>)(<br>  max by(<br>    label_kops_k8s_io_instance_group,<br>    label_topology_kubernetes_io_zone,<br>    node<br>  )(<br>    max_over_time((<br>      kube_node_labels{label_kubernetes_io_role=&quot;node&quot;}<br>        and on(node)<br>      kube_node_spec_taint{key=~&quot;aws-node-termination-handler/spot-itn&quot;}<br>    )[1h:1m])<br>  )<br>)<br>/ max_over_time((<br>    count by(<br>      label_kops_k8s_io_instance_group,<br>      label_topology_kubernetes_io_zone<br>    )(<br>      max by(<br>        label_kops_k8s_io_instance_group,<br>        label_topology_kubernetes_io_zone,<br>        node<br>      )(<br>        kube_node_labels{label_kubernetes_io_role=&quot;node&quot;}<br>      )<br>    )<br>  )[1h:1m]) * 100</pre><p>Building a graph with this data makes it easy to identify when a large percentage of a fleet is lost, what that percentage was, and where that loss happened.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uJh2_ituh2ijcrL9" /><figcaption><em>Image 4. Percentage of Spot instance interruption notices or rebalances.</em></figcaption></figure><p>With these four metrics across type, group and zone you’ll have all the data you need to identify shifts in your cluster makeup. Now, assuming you and your team don’t want to be alternating shifts staring at the graphs, you want to carefully set up alerts for various types of anticipated scenarios and even foresee what you can’t foresee. All that and more in Part 4 — Setting AWS Spot Instance Scale Alerts.</p><p><strong><em>If you’re interested in working on solutions like these, </em></strong><a href="https://www.ziprecruiter.com/careers"><strong><em>visit our Careers page</em></strong></a><strong><em> to see open roles.</em></strong></p><h3>About the Author</h3><p>Matt Finkel is a Senior Software Engineer on ZipRecruiter’s Core (SRE) team. Amongst many other things, his team is responsible for helping build and maintain the Kubernetes-on-AWS infrastructure that ZipRecruiter relies on for web apps, machine learning, and everything in between.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZtAO3xcWIRJVBryI" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cfbd33656ef3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ziprecruiter-tech/monitoring-kubernetes-cluster-health-on-aws-spot-instances-part-3-cfbd33656ef3">Monitoring Kubernetes Cluster Health on AWS Spot Instances — Part 3</a> was originally published in <a href="https://medium.com/ziprecruiter-tech">ZipRecruiter Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scaling Safely on AWS Spot Using the Cluster Autoscaler’s Priority Expander — Part 2]]></title>
            <link>https://medium.com/ziprecruiter-tech/scaling-safely-on-aws-spot-using-the-cluster-autoscalers-priority-expander-part-2-fe5aa4998bd2?source=rss-1fefe5dc18b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe5aa4998bd2</guid>
            <dc:creator><![CDATA[Engineering Team]]></dc:creator>
            <pubDate>Tue, 05 Sep 2023 12:13:54 GMT</pubDate>
            <atom:updated>2023-10-30T11:01:46.849Z</atom:updated>
            <content:encoded><![CDATA[<h3>Scaling Safely on AWS Spot Using the Cluster Autoscaler’s Priority Expander — Part 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aXbzX0lFVab1pqWB5b0bVA.png" /></figure><h4>How ZipRecruiter uses instance type prioritization and automatic node-group scaling to save money and avoid massive reclamations</h4><p><em>This is Part 2 of a series of posts outlining ZipRecruiter’s use of </em><a href="https://aws.amazon.com/ec2/spot/"><em>AWS Spot instances</em></a><em>. In this series, we hope to highlight the benefits of using Spot Instances and how we go about doing so. We’ll talk about the tools we use to deploy to Spot, the way we monitor the health of our systems there, and how we write fault-tolerant applications.</em></p><p>In <a href="https://medium.com/@ziprecruiter.engineering/cost-saving-and-two-way-scaling-with-aws-spot-instances-part-1-33ef85c868d1">Part One</a>, we shared how our move to AWS Spot instances in conjunction with Kubernetes has saved us a lot of money. In Part Two below, we explain how we use the Cluster Autoscaler and its Priority Expander configuration to safely scale out on Spot instances.</p><p>We outline how simple it can be to tell Kubernetes that we want to try to scale using the cheaper Spot instances first, but fall back to the more reliably available On-Demand if we can’t get what we need (and we’ll show the configuration required to do so).</p><h3>Challenge #1 — Scaling low cost cloud compute instances in response to K8s node scaling</h3><p>We’re trying to scale out our platform on cloud infrastructure that is, by its very nature, not reliably available. Most of the time, this is not an issue. When one type of Spot instance is not available, we can fall back to another. But, what if there are not any Spot instances available at all? We need a fall-back in case that we can’t get the compute power to satisfy our immediate needs.</p><p>To explain how we prioritize the cheaper Spot instances but fall back to other more reliable, more expensive instances, we must first talk briefly about the Cluster Autoscaler.</p><h3>Kubernetes Cluster Autoscaler</h3><p>The Cluster Autoscaler is a built-in component of Kubernetes that is responsible for automatically keeping your cluster running at the proper size by increasing or decreasing the number of nodes that are available for pods to run on. The Cluster Autoscaler is an app that runs as a regular deployment in the cluster, keeping an eye on resource usage and adjusting the number of nodes when necessary. It adjusts the number of nodes based on two conditions:</p><ol><li>There are pods that are failing to run in the cluster due to insufficient resources (so add nodes)</li><li>There are nodes in the cluster that are underutilized for an extended period (so remove nodes)</li></ol><p>The Autoscaler makes these adjustments by changing the size of the auto scaling groups in the backing cloud provider. In our case, it knows to communicate with the AWS API and adjust the Auto Scaling Group that our nodes are running in. Simply put, if we need more Kubernetes nodes, the AWS API is used to increase the size of an Auto Scaling Group, more EC2 instances start to satisfy the requested size of the Auto Scaling group, and these instances then join the cluster as new nodes.</p><p>The next challenge is to prioritize scaling on Spot instances, and when none are available fall back to On Demand instances. This is where the Cluster Autoscaler’s priority-based expander configuration comes into play.</p><h3>Challenge #2 — Prioritizing when Spot instances are unavailable</h3><p>To understand the usefulness of the priority-based expander, we must first understand a concept specific to Kubernetes called “node groups.” Node groups are simply a way of creating groups of nodes within your cluster, which can be very useful for segmenting the way you want your pods to be scheduled. Perhaps you want a group of nodes that handle web requests, and another group of nodes that run your databases. Perhaps you want a group of nodes in each of your data centers.</p><p>In our case we wanted a group of Spot instances and a group of On Demand instances. ZipRecruiter actually has several node groups for Spot instances, and several for On Demand instances, so that we can have a selection of each in different AWS availability zones. The Cluster Autoscaler can grow or shrink either of these node groups as needed, increasing and decreasing the amount of Spot or On Demand instances we have available.</p><p>Without any configuration, the cluster will select a random node group to scale up. This might be fine if we have our node groups spread across redundant data centers, or in some similar configuration where we don’t necessarily care which node group our new node comes from. In our case, however, we want to tell the cluster to attempt to scale up the Spot node group before we scale up the more expensive On Demand node group, and this is where we apply the priority-based expander configuration.</p><h3>Easy configuration of the priority-based expander</h3><p>The Cluster Autoscaler’s priority-based expander configuration is fairly straightforward. It is a Kubernetes ConfigMap with a specific name “cluster-autoscaler-priority-expander,” that allows us to pass a list of node groups, selected using a regex, and assigned a weight. Higher numbers are considered higher priority.</p><p>Let’s take a look at a very simple but real-world example that we use in production:</p><pre>apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>  name: cluster-autoscaler-priority-expander<br>data:<br>  priorities: |-<br>    50:<br>      - spot.*<br>    10:<br>      - .*</pre><p>In this example, we see the regex “spot.*” is given a higher priority than the match-anything regex, “.*”. Having a list of regexes for a given weight gives us a lot of flexibility in how we can select node groups. In our case, we have several node groups that launch nodes on Spot instances.</p><p>By using a regex, we can say that we want all node groups that start with “spot.” to have the priority weight 50, and all other node groups have the priority 10. This way, when the Cluster Autoscaler tries to expand, it will first try to scale out any of the Spot instance node groups, and after that it will use anything else. In our case, “anything else” means On Demand instance node groups.</p><h3>An example: Black Friday</h3><p>The Cluster Autoscaler priority expander’s easy configuration came in handy late last year during Black Friday weekend. During this week, AWS traffic increases considerably because the many retailers and e-tailers that host there scale up their services to prepare for the increase in web traffic. They generally do so by increasing the number of On Demand EC2 instances they have available to them. This means that available Spot capacity decreases considerably (remember that Spot instances are spare AWS capacity). As you can imagine, if we depended solely on Spot instances to run our infrastructure, this would be a problem for us.</p><p>We anticipated this issue ahead of time, and made the decision that we were willing to pay more in order to ensure the stability of our platform by moving our infrastructure from Spot instances to On Demand instances, rather than regularly scheduling jobs on Spot instances, only to have them reclaimed after a short period of time.</p><p>Thanks to our configuration of the Cluster Autoscaler’s priority expander, doing this was extremely simple: We changed the regex for the priority 50 entry to match our On Demand node group instances. After that we slowly rebooted the nodes one by one, which brought them all up on On Demand. When the week was over we simply reverted the ConfigMap commit to change it back, and our clusters moved back to Spot instances.</p><p>If you’re curious about the cluster autoscaler priority expander, you can <a href="https://github.com/kubernetes/autoscaler/blob/master/cluster-autoscaler/expander/priority/readme.md">read more here</a>.</p><h3>Next, in part 3: Monitoring Spot instances</h3><p>In <a href="https://medium.com/ziprecruiter-tech/monitoring-kubernetes-cluster-health-on-aws-spot-instances-part-3-cfbd33656ef3">Part 3</a> we’ll talk about monitoring. Because Spot instances are not reliably available, we need to keep track of what’s going on in our clusters. We’ll show the ways that we monitor and alert on the current condition of our clusters, to ensure our high level of availability.</p><p><strong><em>If you’re interested in working on solutions like these, </em></strong><a href="https://www.ziprecruiter.com/careers"><strong><em>visit our Careers page</em></strong></a><strong><em> to see open roles.</em></strong></p><h3>About the Author</h3><p>Matt Finkel is a Senior Software Engineer on ZipRecruiter’s Core (SRE) team. Amongst many other things, his team is responsible for helping build and maintain the Kubernetes-on-AWS infrastructure that ZipRecruiter relies on for web apps, machine learning, and everything in between.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gubYONxOdWrQJIpl" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe5aa4998bd2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ziprecruiter-tech/scaling-safely-on-aws-spot-using-the-cluster-autoscalers-priority-expander-part-2-fe5aa4998bd2">Scaling Safely on AWS Spot Using the Cluster Autoscaler’s Priority Expander — Part 2</a> was originally published in <a href="https://medium.com/ziprecruiter-tech">ZipRecruiter Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Protobuf: The Most Powerful Schema]]></title>
            <link>https://medium.com/ziprecruiter-tech/protobuf-the-most-powerful-schema-4417b08a4642?source=rss-1fefe5dc18b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/4417b08a4642</guid>
            <category><![CDATA[schema]]></category>
            <category><![CDATA[protobuf]]></category>
            <dc:creator><![CDATA[Engineering Team]]></dc:creator>
            <pubDate>Thu, 17 Aug 2023 16:16:30 GMT</pubDate>
            <atom:updated>2023-08-17T16:16:30.599Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why You Should Migrate To Protobuf — The Ultimate Schema</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KQbVZf895DJSz7W6xQqhrg.png" /></figure><h3>ZipRecruiter uses protobuf to create a singular source-of-truth schema. It’s our Rosetta Stone for communicating between programming languages, data, and humans.</h3><p>We all are familiar with data. We live and breathe it, whether it’s short lived in an API or an ever growing big data store. To effectively understand the meaning and proper use for any type of data, both programs and humans must have a clear description of the data’s structure and meaning — a schema. This may sound straightforward, but it’s actually not trivial to achieve consistently.</p><p>Our mission at ZipRecruiter is to actively connect job seekers to their next great opportunity. This involves crunching terabytes of sensitive information and producing insights, matches, and recommendations that are trustworthy and safe. Knowing how to use every bit of data we have is crucial to our clients’ careers and businesses.</p><p>Here I cover why we chose protobuf as ZipRecruiter’s singular schema, and give some tips on how to ensure successful implementation at scale.</p><h3>Data without context is meaningless and even dangerous</h3><p>To work effectively together, programs and people need context. Without context, we’re all exposed to wrong use and misguided conclusions. First and foremost, a schema lists the defined fields and their type, but simply stating that a field contains a string isn’t enough. What do we put in there: first names, URLs, email content, email addresses? Think about how many meaningful dates are used to describe a person’s career.</p><p>There is a serious amount of explanation that should accompany each data field. This gives engineers context of where these fields come from, how they should be used when read, and links to other related documents.</p><p>The importance of context increases the longer data is in use. Imagine 3 years of cumulative data used to train ML models which recommend job postings based on your resume. The collection instances are long forgotten, so information describing the collection method and meaning is crucial if we wish to reach useful and trustworthy conclusions.</p><h3>JSON, XML and GoogleSheets aren’t great schema solutions</h3><p>There are three common solutions which developers use to create schemas: JSON, XML and GoogleSheets. None are great.</p><p>JSON and XML create what I call data-swamps; the less-trustworthy, less-fresh version of Data Lakes. Querying JSON logs is a fairly inefficient and slow process that locks out all other processes until it’s finished. One also has to manually assert the schema at runtime which is a hassle for busy humans. If there are bugs in any collected data you will only find out hours later, and when a datapoint collected months ago lacks a required field, there is nothing you can do about it. This could bias machine learning models to make unreliable inferences.</p><p>Querying XML is even less efficient than JSON. What’s more, describing XML schemas is complicated and often doesn’t work in many programming languages.</p><p>Endless GoogleSheet schemas, on the other hand, are error prone, inconsistent, not machine usable, not scalable, and easily forgotten. Although these are better than no schema at all, when descriptions are added it is usually not clear when they took effect, and when things are removed it isn’t clear if the code has been updated to match.</p><p><a href="https://developers.google.com/protocol-buffers">Protocol Buffers</a>, or protobuf, was released by Google and overcomes many of these weaknesses.</p><h3>Protobuf’s unique value is in cross-system cross-language communication</h3><p>The major value we find in protobuf as our schema is that it allows different systems to interchange data while using a common and singular definition of that data. Preventing, for example, accidentally sending a string as a number. Proto is definitely not the only option for this functionality; others use Thrift, Avro, or OpenAPI for similar use cases. We went with Protobuf mostly due to prior positive experience with the Protobuf tooling.</p><p>This isn’t trivial. Once you have more than one programming language in a system, funneling data through them correctly is crucial. Some languages, like Python, don’t require definition of variables. Without a schema, any meaning coming into Python would be lost.</p><p>Furthermore, protobuf is useful for remote procedure calling (RPC) and we use it to both define the interface and the data exchanged over that interface. In that sense, it is as if the schema for the data is an interface too.</p><p>Protobuf also offers more efficient and better structured real-time encoding and serialization than JSON. While JSON might be faster when data is predominantly strings, protobuf will outperform with mixed data types.</p><p>This is an example of how to define a data structure, called ‘message’, in protobuf:</p><pre>//<br>// Organization is used to represent various legal entities within the JSR (Job Seeker Representation):<br>// companies worked for, consortia providing accreditation, etc.<br>//<br>message Organization {<br>  reserved 1, 2;<br>  <br>  // The physical location of the organization.<br>  Location location = 3;<br><br>  // A contact point for communications with the organization.<br>  ContactPoint contact = 4;<br><br>  // The name of the organization. The raw name as supplied in the original<br>  // JSR is here, as well as the possible canonical name derived from a<br>  // source such as Dun &amp; Bradstreet.<br>  //<br>  // Syntax: free-form.<br>  //<br>  // Missing value: empty string.<br>  string name = 5;<br><br>  // This is a textual description of the organization.<br>  //<br>  // Syntax: free-form. (May include &quot;rich text&quot;.)<br>  //<br>  // Missing value: empty string.<br>  string description = 6;<br>}</pre><p>In addition, protobuf can be used as a schema even when storing and encoding data in other formats, like Apache Parquet or other Spark oriented formats such as Delta Lake. To apply a protobuf schema to a Spark dataset we use <a href="https://github.com/scalapb/sparksql-scalapb">scalapb</a>.</p><h3>Protobuf helps developers use data correctly</h3><p>We humans are the-other-side-of-the-schema, if you will. In any development organization with more than a handful of engineers, communication is crucial. A clear schema helps eliminate misunderstandings and avoid misuse of data that can influence not only the product, but also the business and company reputation.</p><p>With protobuf we can add comments to each field so that other engineers and analysts can understand what that bit of data actually is, where it came from, what its limitations are, how to use it, and how not to use it.</p><p>These comments are not ‘regular’ programming comments. They are very clearly attached to data structures, or ‘messages’. The comments flow through the system such that when you are literally typing code the annotations will pop up, no matter what system or language is being used.</p><p>Here is an example of how we add annotations to protobuf messages:</p><pre>// ip_address allows correlating user behavior across sessions or browsers.<br>//<br>// Classified as Tracking Data.<br>//<br>// See<br>// &lt;link to internal explanation document&gt;<br>// for more detail.<br>string ip_address = 1 [(common.proto.data.classification) = CLASSIFICATION_TRACKING ];</pre><p>And this is what it looks like when the variable is pulled in a coding environment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vCS9vryvuSLpwEGz" /></figure><p>Another great feature of protobuf is that changes to the schema are clearly documented, with implications tracked, and if something goes wrong, it is easy to back track and find the source. For example, when deprecating a field it is best practice to include what should be used instead:</p><pre>// viewer_id was replaced with built_for_viewer_id.<br>reserved &quot;viewer_id&quot;;<br><br>// viewer_property_id was replaced with built_for_viewer_realm.<br>reserved &quot;viewer_property_id&quot;;<br><br>// built_for_viewer_id was replaced with built_for_viewer_identity.viewer_id.<br>reserved &quot;built_for_viewer_id&quot;;<br><br>// built_for_viewer_realm was replaced with built_for_viewer_identity.viewer_realm.<br>reserved &quot;built_for_viewer_realm&quot;;<br><br>common.proto.marketplace.v1beta1.Identity built_for_viewer_identity = 25;</pre><p>Tagging sensitive information: an underexplored use-case for protobuf</p><p>Public awareness with regards to how businesses manage Personally Identifiable Information, or PII, is growing at record pace, and GDPR/ CCPA/ CCPR regulations are in full effect. An email address, for example, is personal information that we need to be able to protect, and also find if a user asks for a deletion.</p><p>Protobuf elegantly supports this subtle subject by decorating or annotating fields with extra info that is computer readable. At ZipRecruiter, we annotate PII fields with sensitivity classifications so that engineers and the programs handling the data are all aware what data is PII. We have built systems that monitor and prevent misuse by setting retention periods, access permissions, and preventing copying.</p><p>Here is a slightly simplified example of classifying a field’s sensitivity:</p><pre>string email = 25 [(zr.data.classification) = CLASSIFICATION_PERSONAL ];<br>// The annotation above is a protobuf extension, defined as follows this:<br><br>syntax = &quot;proto2&quot;;<br>import &quot;google/protobuf/descriptor.proto&quot;;<br>package zr.data;<br>enum Classification {<br>  CLASSIFICATION_NON_PERSONAL = 0;<br>  CLASSIFICATION_TRACKING = 1;<br>  CLASSIFICATION_PERSONAL = 2;<br>  CLASSIFICATION_SENSITIVE = 3;<br>}<br><br>extend google.protobuf.FieldOptions {<br>  // classification is which of our Personal Data Classification<br>  // a field falls under. See &lt;internal_url_here&gt; for definitions.<br>  optional Classification classification = 999999;<br>}</pre><p>While many seasoned engineers are well aware of the benefits and method of using protobuf, a whole generation of developers has yet to capitalize on its value.</p><p><strong><em>If you’re interested in working on solutions like these,</em></strong><a href="https://www.ziprecruiter.com/careers"><strong><em> visit our Careers page</em></strong></a><strong><em> to see open roles.</em></strong></p><p><strong>About the author:</strong></p><p>Frew Schmidt is a Senior Staff Software Engineer on ZipRecruiter’s Job Seeker Experience team, where he develops Zip’s core infrastructure.</p><p>“It’s inspiring,” says Frew, “when your company’s goal and business model are perfectly aligned with the needs of its users — finding great jobs. We’re changing lives every day.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-8bp3RD3uhT8X_yL7m0SlQ.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4417b08a4642" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ziprecruiter-tech/protobuf-the-most-powerful-schema-4417b08a4642">Protobuf: The Most Powerful Schema</a> was originally published in <a href="https://medium.com/ziprecruiter-tech">ZipRecruiter Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cost Saving and Two-Way Scaling With AWS Spot Instances — Part 1]]></title>
            <link>https://medium.com/ziprecruiter-tech/cost-saving-and-two-way-scaling-with-aws-spot-instances-part-1-33ef85c868d1?source=rss-1fefe5dc18b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/33ef85c868d1</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[marketplaces]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Engineering Team]]></dc:creator>
            <pubDate>Sun, 13 Aug 2023 09:54:19 GMT</pubDate>
            <atom:updated>2023-10-30T11:02:41.751Z</atom:updated>
            <content:encoded><![CDATA[<h3>Cost Saving and Two-Way Scaling With AWS Spot Instances — Part 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3TK8B7F4fw20lRC2PSKFrA.png" /></figure><p>ZipRecruiter’s migration from a monolith to Kubernetes microservices increased reliability and deployment speed. But that was just the beginning.</p><p><em>This is Part 1 of a series of posts outlining ZipRecruiter’s use of </em><a href="https://aws.amazon.com/ec2/spot/"><em>AWS Spot Instances</em></a><em>. In this series, we hope to highlight the benefits of using Spot Instances and how we go about doing so. We’ll talk about the tools we use to deploy to Spot, the way we monitor the health of our systems there, and how we write fault-tolerant applications.</em></p><p>ZipRecruiter’s smart marketplace actively connects between millions of job seekers and employers using machine learning models, resume tools, personalized apps, and more. All of these run on cloud computing clusters that process hundreds of millions of requests per day, and rack up a hefty bill. Hence, finding the most cost-effective way to utilize cloud services is crucial.</p><p>In this blog series, we outline how we put AWS Spot instances to work at ZipRecruiter. We’re not the first company to do it, but <em>the way </em>we do it and <em>the scale we achieve </em>are noteworthy and certainly uncommon!</p><h3>Migrating from monolith to K8s microservices enabled new use of the cloud</h3><p>During our early days, ZipRecruiter’s whole system ran as a single monolith–combining user interface, data access, and all other code–that was deployed directly to AWS EC2 On-Demand instances. This was an easy, flexible, and relatively cheap way to bootstrap our new service. But, as our success continued and ZipRecruiter grew, our app became increasingly difficult to deploy in a safe way and scale out at an appropriate speed.</p><p>It was time to modernize and move to a microservices-based infrastructure. After some research, the open source Kubernetes platform was chosen. As many know, it is an industry-standard solution for managing large, scalable, containerized workloads and microservices.</p><p>Anyone who has or is planning to make this transition knows that breaking down a monolith into smaller microservice applications that are deployed separately from one another, but continue to work together, is not a straightforward task. It becomes even more difficult when you’re already operating at scale. The entire ZipRecruiter tech team worked hard to make this major change happen without affecting performance or reliability, all in parallel to their regular responsibilities.</p><p>Once we completed the move to Kubernetes, the benefits were immediate. Releasing code to production is now much safer because we can deploy in much smaller chunks. Our velocity is greatly increased because we no longer carry the risk of updating an entire monolith every time a feature goes out.</p><p><strong>To give you an idea of how easy and safe it is to push code to production, last week we deployed 701 different apps to production, and we did it 1068 times with zero downtime.</strong></p><h3>Spot vs On-Demand Instances</h3><p>Traditionally, when you want to run something in the AWS cloud, you purchase <a href="https://aws.amazon.com/ec2/pricing/on-demand/">EC2 On-Demand Instances</a>. These instances are virtual servers that run in the AWS cloud, available in a variety of different levels of compute power and designed for different tasks. They are long-lived, and barring some sort of hardware failure, will keep chugging along, dedicated to you for as long as you ask them to be. They are purchased by the hour, have no contract commitment and can be launched as needed. Before migrating to Kubernetes, our packaged monolith was deployed to these long-lived EC2 On-Demand servers.</p><p>In conjunction with EC2 On-Demand Instances, we also used something called <a href="https://aws.amazon.com/ec2/pricing/reserved-instances/">EC2 Reserved Instances</a>. These instances are virtual servers, no different than EC2 On-Demand instances, but they provide a discounted hourly rate in exchange for an agreed-upon usage, and allow us to specify a capacity reservation for EC2 instances. If we knew the minimum amount of EC2 instances that it would take to run our monolith, then it made sense to sign a contract ahead of time to pay for that capacity in exchange for a discount.</p><p>Even after moving the majority of our infrastructure to Kubernetes and AWS Spot, we still use EC2 Reserved Instances as we continuously balance stability and cost. Once you’re spending hundreds of thousands or millions of dollars as we do, cost and resource management require a sophisticated, multi-faceted approach. In the next blog post in this series, we’ll talk about how easy it is to configure our Kubernetes clusters to fall back to EC2 Reserved Instances when EC2 Spot instances are not available in the capacity or for the duration that we need.</p><p>AWS Spot Instances are also EC2 instances, but they run on an AWS data center’s “spare” capacity. This spare capacity exists because AWS makes sure to have extra space available for new customers to start up, and for existing customers to grow.</p><p>Because there is always some amount of datacenter capacity that is unused, there is capacity that AWS is not making money from. Not wanting to leave an opportunity unmonetized,, they decided to offer this spare capacity at a fraction of the cost, with a very important tradeoff: your instance could be shut down at any time with a two minute warning. This is known as a reclamation, and it’s done so that the same compute power can be offered to an On-Demand customer or another spot bidder who is requesting it and willing to pay more. This cheaper, reclaimable spare capacity is called AWS Spot.</p><p>Setting aside the reclamation tradeoff, Spot instances are no different than normal EC2 On-Demand instances. They run on the same hardware and are generally available in all the same familiar instance types that we already know and use.</p><h3>Two lessons from switching to Spot instances</h3><p>After we got our Kubernetes stable on EC2 On-Demand instances, we set out to utilize the much lower cost AWS Spot instances instead. Here are two things we’ve learned after using Spot in production for some time.</p><h3>1. You won’t always be able to get the instance type you want</h3><p>While running on On-Demand instances, we had specific instance types that we preferred. We learned after moving to Spot that we had to be open to many more instance types, because the ones we preferred were not always available.</p><p>One example is specifically needing instances with fast SSD. We responded to this issue by configuring our clusters to create new nodes based on a prioritized list of instance types. We’ll cover this configuration in Part 2 of this series.</p><h3>2. Spot reclamations can happen in large groups</h3><p>This problem can be made worse at times when AWS customers have larger needs and use more On-Demand instances. Black Friday weekend is the biggest example, when online retailers need to order more On-Demand instances to respond to increased shopping traffic.</p><p>To deal with this we added monitoring that tracks node age and Spot interruptions. We get alerted if there are large reclamations. Since these reclamations are always of a single instance type, we can respond by adjusting the priority list mentioned above so that the cluster scales up using nodes that are more available. We’ll cover this monitoring in Part 3 of this series.</p><h3>Reaping the benefits of AWS Spot — cost and two-way scalability</h3><p>The most obvious benefit is financial. Cheaper infrastructure now means we continue to save more and more money as we scale to handle ZipRecruiter’s continuing product success. This is also important as we proceed to grow our machine learning infrastructure to a massive scale. We can continue to get bigger and bigger with the confidence that we’re doing so in a cost-efficient way, though, of course, paying less for the same compute resource is just one piece of the cost-efficiency puzzle.</p><p>Another notable benefit is that we can reliably scale both up and down. We scale up and down depending on the time of day, so that we’re not wasting money on a giant unused cluster at night (US time) when we’re not serving nearly as many requests. We scale up and down when we have large workloads, be it processing a large chunk of data or training a new ML model.</p><p>Because our infrastructure is tolerant of Spot reclamations, we have the bonus of being confident that we can scale our clusters in both directions for other, unrelated reasons.</p><p><strong>At its peak last week, our production cluster had 371 nodes, and just a few hours later it was down to 180 nodes. About half the size, which roughly translates to half the cost.</strong></p><p>We are a tech company and everything we do depends on compute power. As we become increasingly data focused, the ability to scale our compute power more efficiently and cost effectively directly impacts the success of our business.</p><h3>Next, in Part 2</h3><p>No road to success is without bumps! We continue to adapt as we learn more about using AWS Spot in a real-world, scaled-out, highly-available yet high-fault environment, where Kubernetes nodes may disappear at any time, with little warning.</p><p>In <a href="https://medium.com/ziprecruiter-tech/scaling-safely-on-aws-spot-using-the-cluster-autoscalers-priority-expander-part-2-fe5aa4998bd2">part 2</a>, we outline our use of the Kubernetes Cluster Autoscaler and how it came in handy for Black Friday.</p><p>Stay tuned!</p><p><strong><em>If you’re interested in working on solutions like these, </em></strong><a href="https://www.ziprecruiter.com/careers"><strong><em>visit our Careers page</em></strong></a><strong><em> to see open roles.</em></strong></p><h3>About the Author</h3><p><strong>Matt Finkel </strong>is a Senior Software Engineer on ZipRecruiter’s Core (SRE) team. Amongst many other things, his team is responsible for helping build and maintain the Kubernetes-on-AWS infrastructure that ZipRecruiter relies on for web apps, machine learning, and everything in between.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FXeNJ9vBxJg74Egw" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33ef85c868d1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ziprecruiter-tech/cost-saving-and-two-way-scaling-with-aws-spot-instances-part-1-33ef85c868d1">Cost Saving and Two-Way Scaling With AWS Spot Instances — Part 1</a> was originally published in <a href="https://medium.com/ziprecruiter-tech">ZipRecruiter Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multimodal Learning for Employment Marketplace Recommendation]]></title>
            <link>https://medium.com/ziprecruiter-tech/multimodal-learning-for-employment-marketplace-recommendation-ee67bdbede53?source=rss-1fefe5dc18b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee67bdbede53</guid>
            <category><![CDATA[software-engineer]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[recommendation-system]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Engineering Team]]></dc:creator>
            <pubDate>Thu, 20 Jul 2023 07:31:27 GMT</pubDate>
            <atom:updated>2023-07-20T07:31:27.335Z</atom:updated>
            <content:encoded><![CDATA[<p>ZipRecruiter reveals its powerful ML matching architecture, suitable for most bi-directional recommendation needs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XJKapta1zOnJM_W0XmQRew.png" /></figure><p>ZipRecruiter has built one of the world’s largest, online, double-sided job marketplaces. It enables job-seekers to find their next great career opportunity, and helps employers discover the best available candidates for their open positions. A key feature of our marketplace is making ‘the search’ as efficient as possible.</p><p>To that end, our recommendation team is responsible for actively generating optimal matches between job-seekers and jobs using advanced machine learning tools. The current system has increased job seeker engagement by 12% and boosted their satisfaction, with a similar effect for employers.</p><p>Here, we’ll outline how challenges in our data and the nature of our marketplace influenced model development, and then dive into the loss-function and symmetrization intricacies of our unique learning architecture. Anyone building a recommender system, especially for two or more market sides that require recommendations, will potentially find this useful.</p><h3>Model requirements in light of 4 main challenges</h3><p>Generating great matches requires overcoming substantial challenges related to the nature of our marketplace and the structure of the data.</p><h4>1. Optimizing for real-time inference on big-data</h4><p>Our marketplace consists of a large volume of entities which directly affect the way our models operate and perform. In fact, we have more than 36 million resumes and over 12 million active job postings to match. Job-seekers and employers generate a very large quantity of events describing the interactions between them containing hundreds of millions of applications, clicks, searches, hires, and rating signals per year. In terms of recommendation use cases, these numbers correspond to billions of potential entity pair matches.</p><p>At this massive scale, suggesting high-quality matches to our users requires an efficient and scalable inference mechanism to calculate a meaningful matching score for every pair of entities.</p><p>To illustrate this, let’s consider the case of recommending the next best job to a given job-seeker. A naive solution may include an ML model that for each potential job receives job-seeker input data like resume, past activity etc., and produces a relevance score for it (higher relevance score corresponds to a better match). However, this design depends directly on the modeling choice and its associated computational complexity where the inference model is called with the entire job-seeker input.</p><p>Instead, we can optimize our model to act on an encoded entity representation in the form of an embedding in a semantic vector space thus enabling the use of a simple <strong>scalar product calculation</strong> and achieving scalable and more efficient real-time inference.</p><h4>2. Maintaining performance with extremely diverse and dynamic data</h4><p>Another big challenge is related to the rich and non-stationary nature of the marketplace which includes seasonality patterns of job openings and diverse job titles. Our modeling solutions need to accommodate the high level of diversity inherent to the marketplace entities.</p><p>Data in real-world applications typically exhibit long-tailed distributions, where attributes are dominated by a small portion of values, while all the other values are associated with only a few samples each.</p><p>To better understand this, let’s look at the “<em>job title”</em> attribute. Obviously, “<em>job title”</em><strong><em> </em></strong>plays an extremely important role in representing the job entity. However, most titles are associated with only a fraction of the job-postings and thus relevant for only a small cohort of job-seekers. It is non-trivial to properly represent tens of thousands of unique job titles in the training process when each individually has a very low probability to appear in the data, thus potentially leading to poor model performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BGIXTRcICk6_ecS3" /><figcaption><em>Figure 1: Most titles are rare and appear only within a fraction of the job listings. This makes the training of machine learning models extremely challenging.</em></figcaption></figure><p>In the chart above, “Data Scientist” jobs are roughly 0.1% of all available jobs. This means that collecting enough data and training a model in a way that all the attribute values are sufficiently represented becomes very difficult.</p><p>In addition, new entities are continuously generated and removed from the marketplace, creating a dynamic and evolving environment. As a result, our models need to constantly adapt to maintain their performance and accurate predictions. The following plot shows the amount of new jobs being added each day during a period of 3 months. Having a constant influx of new jobs implies that our model is required to perform accurate predictions for unseen classes at inference time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bsCzUMYMGWjKGk-d" /><figcaption><em>Figure 2: The number of new jobs added to the marketplace each day maintains its magnitude.</em></figcaption></figure><p>Poor entity representation during training and the high relative appearance of new entities during inference time dictates a need for <strong>zero-shot</strong> capabilities. This essentially means that our model will be able to accurately represent new entities in the online environment without the need to explicitly see them during training.</p><h4>3. Multi-faceted complexity requires context-aware modeling</h4><p>The nature of the data stems from the entities’ representations in the marketplace. Both the job-seeker and the job posting are primarily unstructured text based and uniquely express their author’s nuanced details, which frequently exhibits personal statements or taste. Large processing and modeling overhead is generated from the following data complexity characteristics:</p><ul><li><strong>Unstructured </strong>— The entities are mostly <strong>unstructured textual data</strong> meaning that the data is designed for humans and not for machines. Visual perception plays an important role which results in a lack of order and common structure that could be utilized.</li><li><strong>Non-standard format for recurring parameters </strong>— In addition, entities do not follow specific design conventions or rules. For example, the format of the “skills level” may involve numbers, visual scale or simply a word.</li><li><strong>Creative titles </strong>— Employers often take the liberty to be creative and come up with improper language phrases, slang and even superlative adjectives as part of the full job title. We are all familiar with titles like — “Rockstar Java Developer” and “Ninja Sales Representative”.</li><li><strong>Domain specific jargon </strong>— Certain professions make use of unique jargon which requires domain expertise, so it’s not always possible to extract their inherent meaning. For example, the abbreviations in the nursing profession include — LPN, LVN, RN, NP and many many more.</li><li><strong>Context aware terminology </strong>— Similarly, some terms may receive their true meaning only within the context of their entity. For example, “MD” can represent both “Medical Doctor” and “Managing Director”.</li><li><strong>Diverse sources</strong> — Our data originates from multiple sources, namely, job-seekers, employers and the marketplace itself. Job-seekers are mainly characterized by information parsed from their resume, like employment history, education, skills and more. Jobs, on the other hand, are characterized by title and various attributes extracted from the job description. These include desired skills, education level, benefits, location and whether it is an in-person or remote job. Keep in mind, many of the displayed jobs are collected from the web, and as a result, we don’t have access to the employer’s original metadata pertaining to the job. For the marketplace, we have all the engagement data generated on our platform which represents the interactions between the job-seekers and the employers (e.g. searches, impressions, clicks, applications, interest signals, hiring signals…)</li></ul><p>These complexities suggest a <strong>context aware </strong>modeling scheme. One relevant architecture is attained by constructing a <strong>pre-trained encoder</strong> that will provide a unique and independent representation for each entity type. As we shall see later on, this choice enables more diverse and flexible utilization in downstream modeling applications.</p><h4>4. Symmetrically balancing competing stakeholder objectives</h4><p>Generating recommendations in a multi-sided marketplace introduces significant optimization challenges. These challenges naturally arise from the marketplace structure and the associated global business goals.</p><p>To get a sense of what this means, consider job recommendations that we provide to a job-seeker. Even though this action essentially faces one side of the marketplace, we cannot ignore the other side’s objectives and how they are affected by them. For example, if we suggest a potentially relevant job to a candidate, even though we estimate that the employer is <em>un</em>likely to be interested, we might generate a wrong prioritization in which the less relevant candidates are recommended to the employer over relevant ones, and eventually affect the employers’ overall satisfaction. In other words, the optimization of our recommendation models needs to take into account the various entity objectives, whereas, naively optimizing for only a single marketplace side might lead to greedy behavior and eventually to inevitably suboptimal performance. As we shall see, we are able to avoid this by leveraging other job-seekers’ activity to form a more balanced job-seeker to job score matrix.</p><p>In addition to the obvious entities objectives, as the marketplace manager, ZipRecruiter has its own metrics that require optimization which usually serve more global business goals. These can, for example, balance the marketplace or introduce fairness into our ranking mechanism. Fortunately, these objectives can sometimes be modeled separately from those “entity-facing” objectives.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YVXy2P3iwJDeZ6-m" /><figcaption><em>Figure 3: </em>Multiple objectives in ZipRecruiter’s marketplace.</figcaption></figure><p>As suggested above, we approach this problem at the optimization level directly. In order to incorporate the desired behavior and, by design, achieve balance between the marketplace’s different entity-facing objectives, our <strong>multimodal multi-task </strong>model is optimized using a <strong>self-regularized dual loss function</strong>. As we shall see later on, this loss imposes symmetry considerations in the form of two-sided calibration of the two optimization tasks, which is necessary for producing a well behaved and calibrated model.</p><h3>Learning similarity and balancing with pre-trained encoders</h3><p>For machine learning models, achieving good generalization depends highly on their ability to represent the data. By explicitly introducing relational inductive bias amongst the marketplace entities, based on their semantic similarity, we are able to impose constraints on their relationships and interactions in a learning process. This structure will hopefully enable the model to learn meaningful representations and better capture same-entity as well as cross-entity semantic similarities.</p><h4>Pre-trained encoders for same-entity similarity learning</h4><p>In order to define what semantic similarity <em>within the same entity type </em>is, we can exploit the information encoded in the interactions between job-seekers and jobs. When a job-seeker reviews a job and decides that it is relevant for them, they can go ahead and apply for it.</p><p>Considering all the relevant jobs that the job seeker applied to, we can safely assume that these jobs are similar to each other in their meaning to that specific job-seeker. This similarity concept provides us valuable information and can be used for learning an appropriate job representation metric. While similar jobs should be close to each other, non-similar jobs should be far away from each other.</p><p>The same idea can also be applied in the case of two job-seekers who apply to a given job. In this scenario, the two job-seekers who received a positive rating (thumbs-up) from the employer are considered similar and should be close. However, unlike the job similarity case, employer feedback can also provide explicit negative feedback in which job-seekers can receive a negative rating (thumbs-down). As we shall see later on, this has an implication on the modeling choice for each case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*n4dgZGOShxZLrk8WqYoR9Q.png" /><figcaption><em>Figure 4: Exploiting the implicit semantic structure of the interactions between the entities, we are able to construct an entity self-similarity framework and have a consistent way of learning their latent representations.</em></figcaption></figure><p>This entity self-similarity framework essentially provides a way to project the learned semantic similarity and use it as a solid building block for modeling cross entity relations and performing inference on unseen instances.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*IOz5hPrTDB__XQz6qtY0Rg.png" /><figcaption><em>Figure 5: Cross-entity inference tries to utilize the learned latent representations to infer the similarity between two unseen different entities.</em></figcaption></figure><p>Since the ultimate goal is to predict which jobs are most suited for a given job-seeker, we need to infer cross-entity similarity. This kind of similarity metric learning is difficult to optimize directly within a single modeling architecture.</p><p>After understanding the need for pre-trained encoders and how they are built for imposing the required semantic similarity we can proceed to define their specific structure.</p><h4>Job Encoder</h4><p>The purpose of this encoder is to model the similarity of two distinct jobs based on the fact that a given job-seeker has applied to both of them. We chose to model similar jobs using a <strong>siamese network in which the optimization itself is based on a contrastive focal loss</strong>.</p><p>In practice, we collect job pairs that were co-applied by the same job-seeker. During model training, these pairs serve as the positive examples in the data. Figure 6 depicts the architecture of the model where the objective is to learn the parameters of the encoder function <em>f</em> -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*AevVsf2A_4BC1SNLPIy0OQ.png" /></figure><p>Using a regular softmax-based contrastive loss may result in a very small value for the temperature parameter which represents a too narrow probability distribution, eventually leading to overconfident predictions. This means that due to the dominance of easy examples, the model would only learn the portion of easy pairs in the data. Conversely, the advantage of a <strong><em>focal loss </em></strong>formulation is that it prevents such a scenario and provides more weight to the hard misclassified pairs in the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/0*NkGAQOd1jeXC4BBP" /><figcaption><em>Figure 6: Using the standard contrastive loss might learn the ratio of easy pairs in the data. Combining it with focal loss enables the model to focus on the more interesting pairs of co-applications.</em></figcaption></figure><h4>Resume Encoder</h4><p>Similar considerations are applied for learning the job-seeker’s resume encoder. There is, however, one major difference. In this scenario, the informative signal is generated by the employer who posted the job. If the employer finds the job-seeker relevant for the job they can provide positive feedback by selecting a thumbs-up (👍) indicating that the employer may be interested in initiating a hiring process with this candidate. On the other hand, if the job-seeker is not relevant for the job, the employer might provide a negative signal using a thumbs-down (👎).</p><p>A natural approach is to use a triplet loss function. This loss learns a similarity metric by enforcing the distance between a pair of similar job-seekers to be smaller than a pair of job-seekers that are not similar. In our framework, similar corresponds to a pair of job-seekers who received a thumbs-up from a specific employer on a certain job while non-similar corresponds to a pair of job-seekers in which one of them got a thumbs-up while the other got a thumbs-down. In addition, since most jobs have more thumbs-down than thumbs-up, we are able to enrich the training data with multiple negative samples associated with every positive sample.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8IEqSkRyCEzm5956" /><figcaption><em>Figure 7: A triplet loss function enforces proximity between job seekers for a specific job who have both received a thumbs-up from the employer.</em></figcaption></figure><h3>Learning to infer across entities — the modeling architecture</h3><p>So far, we’ve described how we are able to model similarity within the same entity type, i.e. job-to-job and job-seeker-to-job-seeker, which allows the representation and even predict relations between unseen entities. In order to model the cross-entity semantic relation between job-seekers and jobs, we now need to combine the relevant pieces and establish the mechanism for learning the similarity between different entity types.</p><p>This mechanism should have two central components that will represent the two marketplace modalities. For the jobs modality, the representation of a job remains static throughout the job’s life and does not depend on any interaction occurring in the marketplace. As such, we can already make use of our existing pre-trained job encoder.</p><p>For the job-seeker modality, the formulation is less trivial. To understand better, let’s recall that our objective is to build a job recommendation model for job-seekers. This means that a similarity score between a job-seeker and a job should designate how relevant the job is to that specific job-seeker. Although the word ‘relevance’ in this context may require a stricter definition, we can assume that it is implicitly indicated as <strong>the willingness of the job-seeker to engage with this job</strong>. In light of that, having only the resume representation of a job-seeker is not enough and we will need to construct a model that will encompass all the available information we have about the job-seeker and produce a complete job-seeker representation. This may include contextual information like the resume and relevant engagement data like the searches, applications, employer’s interest signals and more.</p><h4>Model Architecture</h4><p>Our chosen architecture needs to incorporate both static resume data as well as the job-seeker’s time-dependent recent activity. As described above, the resume is represented by a pre-trained encoder, however, processing the job-seeker activity is slightly more complex.</p><p>Modeling time-dependent data is usually done by employing an appropriate sequence aware architecture, like RNN or transformer. In our case, the job-seeker’s sequence consists of not only explicit job interactions (e.g. clicks, applications) but also searches conducted on ZipRecruiter’s homepage or mobile application. For job interactions we can leverage the fact that we have a consistent and independent way of representing jobs. Thus, using the pre-trained job encoder we can feed our model with the relevant embedding vectors along with a dedicated encoding designating the distinct interaction type -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*6yhPer6tqYFQSNXxEJDf_g.png" /></figure><p>Transforming searches into suitable embedding vectors naturally requires a different approach. In a search, a job-seeker has entered free text, often without grammatical structure, which represents specific intentions. These searches are accompanied by a location specifying where the job-seeker is looking for a job.</p><p>However, since searches do not have clear correspondence to actual jobs, constructing a pre-trained encoder is not relevant. Hence, a straightforward solution would be to simply build a dedicated search encoder which will be optimized as part of the full model and to match its output with the job encoder. In order to do that, we take advantage of the query structure which mostly consists of professional terms, like desired job titles or industries, relevant skills set or even abstract job characteristics, like ‘remote’, ‘entry level’, etc.</p><p>We start by mapping the search query to a set of meaningful terms by extracting and standardizing them according to a given taxonomy. Then, we calculate a weighted average over the token dimension which yields a query level embedding representation. The weighted average is based on a modified self-attention mechanism -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*HAw8Y0l0HU579qLp4w7Btg.png" /></figure><p>Now we are able to combine job-seekers’ searches with their job interactions and maintain the structure of the sequence. In order to combine the job-seeker’s past activity representation with their resume we use a feed-forward block to receive a unified single job-seeker embedding.</p><p>Our task is then to predict the next applied job by the job-seeker given their associated information. Recalling our efficiency considerations for using scalar product calculations over our massive available data, we can finally define the complete model architecture.</p><p>Given a job-seeker and job pair which are connected by an apply, we project the job-seeker representations onto the dual space of the job embedding space using their corresponding encoders and then calculate their scalar product. As the representations are L2 normalized, their dot product represents a similarity score that is monotonic in the estimated probability of the job-seeker to apply for the job.</p><h3>Loss Function</h3><p>Optimizing for similarity between pairs of entities naturally pushes us toward using a contrastive loss. This way, the model can learn to bring the representation of similar entities closer to one another and separate non-related pairs. Since we optimize for job-seekers, each one of them contributes a contrastive loss term of the form -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*t9SPr0c7BEFWc_skrhwxsA.png" /></figure><p>Where <em>i</em> represents the <em>i</em>-th (job-seeker, job) pair indicating an application, 𝒱 represents a set of sampled jobs, sᵢ is a given job-seeker, 𝝉 represents a temperature parameter, and the dot represents a scalar multiplication between the embedding vectors.</p><p>Summing for all job-seekers in a batch we obtain</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*6gcwCU7_CybEr4uPGOHi1Q.png" /></figure><p>where <em>S_batch</em> represents the set of job-seekers in the batch.</p><p>However, this loss form is mainly optimized for one side of the marketplace and, as we specified before, this might lead to undesired behavior of the model. Therefore, we need to balance our optimization process and account also for the jobs side of the marketplace.</p><p>Looking at the loss equation above, we can observe that the one-sided optimization actually comes from the softmax normalization term. Here, for each job-seeker we sample jobs so the probability distribution is defined over the chosen jobs. This suggests that we should symmetrize the loss function and construct a similar loss term for the jobs side that will define a probability distribution over the job-seekers. Mathematically, this can be formulated by -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*_B3zHsZL72cF-JpScjZQ-g.png" /></figure><p>Thus, we can define the dual-contrastive loss function which imposes that additional structure into the model -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/1*ymLUgUKwymKsvU0oluyEnQ.png" /></figure><p>Usually, building the contrastive loss pairs is based on the sample batch entities. First, we sample <em>n</em> positive pairs, that is, a job-seeker and a job that are connected by an actual application. Then, we can sample random pairs out of those n pairs and use them as the negative pairs. That way we can batch these pairs together in a simple and efficient manner for the model to use. Thus, we have <em>N</em> positive pairs and <em>(N² — N)</em> random negative pairs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*MLEAlU1kWPP66lH34fukPg.png" /><figcaption><em>Figure 8: Matrix representation of a training batch. The diagonal designates the positive pairs.</em></figcaption></figure><p>In a matrix form, each row corresponds to a single job-seeker loss term where the <em>(i, i)</em> pair is the numerator while the entire row composes the normalization term. Therefore, summing rows produces the complete loss (ℒₛ). Following the same logic for the columns yields the Jobs loss (ℒᵥ).</p><p>Examining the job-seeker loss, we observe that the batch may include duplicate jobs which effectively decrease the coverage jobs and affect the estimated distribution. Therefore, we can reconsider the normalization term and instead of being restricted to the jobs that appear in the batch we can exploit the fact that jobs are represented by a pre-trained encoder and uniformly sample as many jobs as we like from the available job corpus. Note that such a sample differs from in-batch sampling which follows the training set job distribution governed by more interacted jobs. This corpus reflects the potential space of jobs, i.e.:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*_GT1sZlH3WiFARaqiJRGsw.png" /></figure><p>This consideration, however, is not applicable for the second loss. This is because sampling job-seekers from a corpus requires us to perform inference for every such job-seeker, in addition to the job-seekers already in the batch, which might significantly affect the model performance.</p><p>In practice, in order to increase learning capacity and reduce bias, in each iteration, we build two similarity matrices and simply sample the corresponding negative pairs independently for each task. For suggesting jobs to job-seekers we sample from the entire job corpus, whereas for the opposite recommendation direction we sample them directly from the batch.</p><p>Here, the suggested job loss has a straightforward probabilistic interpretation which is the probability that a job-seeker will apply for the job while the second loss term has the probabilistic interpretation of the probability that a given job will be applied to by a job-seeker. This formulation essentially makes the training more stable and leads to better model performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GfF9CDQfCzFH4Vkm" /><figcaption><em>Figure 9: Bringing all components together for a complete modeling system.</em></figcaption></figure><h3>Results and Future Development</h3><p>After building the first version of the entire modeling framework we A/B tested it on several recommendation applications facing job-seekers. The results showed a significant improvement in compute performance, an overall 12% lift in job-seeker engagement, and over 18% increase in satisfaction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Q6M-aCZ231WHS-YK" /><figcaption><em>Figure 10: AB tests results. The new model variants demonstrate clear lift in performance.</em></figcaption></figure><p>We continue to develop this model, and an advanced and improved version currently powers the recommendations for many of ZipRecruiter’s core products.</p><p>Going forward, we are developing a graph neural networks (GNN) model that will serve as the base modeling framework for recommendations. Ideally, using a GNN we will be able to simultaneously perform link prediction between different entity types within a single embedding space and model all these similarities and attributes together. This will open the door to including more signals such as how employers acted upon suggestions from our platform regarding job-seekers.</p><p><strong><em>If you’re interested in working on solutions like these, </em></strong><a href="https://www.ziprecruiter.com/careers"><strong><em>visit our Careers page</em></strong></a><strong><em> to see open roles.</em></strong></p><p><strong>About the author:</strong></p><p>Nadav Barkai is a Data Science and Engineering manager on ZipRecruiter’s Recommendation’s team. Leveraging his vast background in physics and complex algorithm development, he leads a mixed team of data scientists and engineers in building the matching and recommendation models at the heart of ZipRecruiter’s smart employment marketplace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/306/1*nyN5w8ZkTQCJ8jCZcpMv_Q.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee67bdbede53" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ziprecruiter-tech/multimodal-learning-for-employment-marketplace-recommendation-ee67bdbede53">Multimodal Learning for Employment Marketplace Recommendation</a> was originally published in <a href="https://medium.com/ziprecruiter-tech">ZipRecruiter Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why and How We Use Prometheus to Monitor Kubernetes]]></title>
            <link>https://medium.com/ziprecruiter-tech/why-and-how-we-use-prometheus-to-monitor-kubernetes-9da1f11fd39d?source=rss-1fefe5dc18b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/9da1f11fd39d</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[site-reliability-engineer]]></category>
            <category><![CDATA[prometheus]]></category>
            <dc:creator><![CDATA[Engineering Team]]></dc:creator>
            <pubDate>Wed, 10 May 2023 10:35:37 GMT</pubDate>
            <atom:updated>2023-05-10T10:35:37.884Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VceuVz2LvIhAXuoRGPMn2Q.png" /></figure><h4>ZipRecruiter’s journey from Icinga and Graphite to cloud-native open-source monitoring</h4><p>Site Reliability Engineers and other operators constantly monitor their systems to ensure they are healthy and functioning. This can be as simple as glancing at a laptop’s screen to see that it’s still turned on, or as complex as having an entirely separate distributed monitoring system running alongside the main business system.</p><p>Icinga is one such monitoring system that has provided great service to organizations for over a decade, <a href="https://www.ziprecruiter.com/">ZipRecruiter</a> included. However, as we moved our production services (along with our development and staging environments) to Kubernetes (K8s), Icinga was no longer the best choice for monitoring.</p><p>Here we cover the reasoning that led us to Prometheus, and some hard earned insights on how to implement successfully.</p><h3>Icinga’s server-centric model clashes with K8s’ fluid nodes</h3><p><a href="https://github.com/Icinga/icinga2">Icinga</a> is a popular open source monitoring tool that evolved from <a href="https://en.wikipedia.org/wiki/Nagios">Nagios</a>, originally known as NetSaint. It was designed in the days when one installed and configured servers, deployed software onto them, and let it run that way for months or years at a time. Icinga has the “server” as a central piece of its data monitoring model, and adding new servers requires regenerating Icinga’s configuration and restarting its instances.</p><p><a href="https://kubernetes.io/">Kubernetes</a>, however, manages compute power with much less of a unique, long-term identity view. Instead of condemning “these 5 servers to run the web site, these 2 to run the databases, etc.” now and forevermore, K8s deals with a pool of “nodes”, as interchangeable servers.</p><p>The Kubernetes Scheduler can choose to migrate workloads across the nodes. For example, when using cloud servers (such as <a href="https://aws.amazon.com/pm/ec2/">AWS EC2</a> as we do at ZipRecruiter), Kubernetes can determine that some nodes are under-utilized, decommission a few, and move any remaining workload from the to-be-terminated nodes to continuing nodes with available capacity. Icinga’s ability to monitor processes in this fluid approach is very limited.</p><h3>A cumbersome workaround with Icinga merited a new solution</h3><p>Before Kubernetes, we were running our server software directly on EC2 instances. Although Icinga has some rudimentary performance data collection features built into it, we had chosen <a href="https://en.wikipedia.org/wiki/Graphite_(software)">Graphite</a> to collect and store metrics about our services. We used these metrics both for dashboard displays on <a href="https://en.wikipedia.org/wiki/Grafana">Grafana</a>, and for alerts via Icinga.</p><p>We had an Icinga plug-in to query Graphite metrics and alert when they exceeded a specified threshold. We’d also added some extra bells and whistles to support slightly greater complexity in the Graphite queries it could execute, but it wasn’t very flexible. Our alerts had to be shoe-horned into “pseudo-hosts” in order to fit Icinga’s rigid preconceptions, even when we were querying metrics that had been aggregated across all pods providing a service.</p><p>Since Kubernetes emits its own metrics in a format intended to be consumed by <a href="https://prometheus.io/">Prometheus</a>, moving away from Graphite was only logical; but there are other reasons too.</p><figure><img alt="Monitoring architecture. Side-by-side diagrams comparing Icinga and Graphite in the old system, to Prometheus AlertManager and Prometheus Metrics Database in the new system, using Grafana Dashboards as the user interface in both designs." src="https://cdn-images-1.medium.com/max/1024/1*LgzSbqRKuQ-bpopSmbG3Pg.png" /></figure><h3>Graphite vs. Prometheus — hierarchical metrics vs. unstructured labels</h3><p>There are several conceptual differences between Prometheus and Graphite. First, Graphite uses hierarchical names for metrics, while Prometheus uses an unstructured set of labels (key/value pairs). If one Graphite time series is named “service.$hostname.responsetime.$appname” and another is named &quot;response.$appname.$hostname&quot; it’s quite hard to write a query that combines both time series in any sensible way.</p><p>In Prometheus, each label on a time series is an independent dimension, and a query can join two time series on a set of labels, regardless of what other labels the two series might not have in common. So in Prometheus you could have “service_response{host=$hostname, app=$appname, other=$thing}” (where “host”, “app”, and “other” are the labels) and “other_kind_of_response{category=$cat, appname=$appname, server=$hostname}” and you can easily join the two time series on whichever labels you choose.</p><h3>Graphite vs. Prometheus — system push vs. monitor pull</h3><p>Another difference between Graphite and Prometheus is how they collect information. <strong>Graphite is push-driven</strong>; that is, the application code connects to the Graphite server and sends it metrics. This can be done over a TCP connection, or via connectionless UDP packets. Both methods have their respective advantages and drawbacks.</p><p>UDP is high-performance, but it can be difficult to manage your network to reliably deliver UDP packets under all conditions, and if UDP packets end up getting dropped, it can be challenging to determine why. TCP is designed to be reliable, but Graphite requires your source of metrics to connect to the monitoring system to push metrics to it. This means that if the monitoring system goes down, it can affect the performance of the system being monitored, and also means that it’s more difficult to have redundant instances of the monitoring system.</p><p>With <strong>Prometheus’ pull-driven approach</strong>, the system being monitored doesn’t have to do anything other than respond to requests on a specific port, serving its current set of metrics. The monitoring system(s) can scrape the system being monitored as frequently or infrequently as they choose. Scraping in this way is significantly more scalable. Applications can update metrics as frequently as needed and it won’t put any additional load on Prometheus, and if a Prometheus instance goes away, the application won’t care. You can have more than one Prometheus instance scraping the same application, and the application won’t care, or even need to know.</p><h3>Dealing with High Cardinality in Prometheus</h3><p>Despite Graphite’s aforementioned drawbacks, it does have two advantages over Prometheus that we had to deal with. First, Graphite doesn’t care how finely you subdivide your time series, since each leaf of its hierarchical structure is stored in its own file on disk. Prometheus, on the other hand, keeps all labels of a given time series together, and can run into performance problems (and even crash) with labels having “high cardinality”, meaning a time series has too many different values of labels. As a result, we had to be more careful with the cardinality of our Prometheus metrics than we had been with Graphite.</p><h3>3 guidelines to limit metric cardinality in Prometheus</h3><ul><li><strong>Avoid server specific labels — </strong>We avoid using ephemeral data like IP addresses or node names as labels, because these come and go, and over time can gradually add up to very high cardinality.</li><li><strong>Avoid application specific labels — </strong>We also avoid high-cardinality application data like the names or ids of employers, job-seekers, or jobs in our metric labels, because we have hundreds of thousands to many millions of these, and we don’t need to monitor metrics at such a detailed granularity.</li><li><strong>Group web data labels — </strong>Even for http status codes, we try to only use the first digit as a metric label. We can track 3xx redirects versus 4xx user errors versus 5xx server errors, but not the details of exactly which of maybe 20 specific status codes we served.</li></ul><p><strong><em>The general rule of thumb we follow for any one metric is to keep the product of the cardinalities of all the labels for that metric under a thousand.</em></strong></p><p>In this example:</p><pre>{host=$hostname, app=$appname, other=$thing}</pre><p>this would mean (number of hostnames * number of appnames * number of other things) &lt; 1,000.</p><h3>Storing metrics over long time periods in Prometheus is RAM intensive</h3><p>The second advantage of Graphite is that it is designed to store metrics over long time periods, aggregating data over longer intervals as the data gets older. Prometheus doesn’t have this capability. It stores its data at a single sampling frequency for a fixed amount of time, and then deletes old data past that point.</p><p>We currently store 30 days of metrics sampled every 15 seconds for most purposes. In a few cases we recently added a lot of RAM and disk space to a few of our Prometheus instances so we could increase the retention period to 120 days, in order to see month-over-month trends for capacity planning purposes.</p><p>There are several projects that claim to add longer-term storage to Prometheus. We are watching these projects mature, and hope to implement one of them soon. This will allow us to migrate the last few use cases where we still use Graphite to store metrics over a span of a year or more.</p><h3>Serverless cloud meta-monitoring of multiple Prometheus instances</h3><p>Our philosophy at ZipRecruiter is that every development team is responsible for their application’s maintenance and functionality for the entirety of its lifecycle. This means that when our SREs chose Prometheus as the main monitoring system, they made sure that each team could create their own instances and alert themselves if something goes wrong.</p><p>However, the SRE team did set up <em>meta-</em>monitoring systems to watch <em>all </em>the Prometheus instances. If a considerable amount of alerts pop up it is likely that there is a broader issue and the SRE team can intervene for a cross organizational solution.</p><p>We achieve this by using <a href="https://aws.amazon.com/lambda/">AWS lambda</a> to run code serverless in the cloud, and not Prometheus itself.</p><p>This is the main skeleton of the golang code that runs in AWS Lambda, and is configurable to check Prometheus and AlertManager instances, as well as checking arbitrary http or tcp services.</p><pre>package main<br><br>import (<br>    &quot;context&quot;<br>    &quot;fmt&quot;<br>    &quot;net&quot;<br>    &quot;net/http&quot;<br>    &quot;os&quot;<br>    &quot;sync&quot;<br>    &quot;time&quot;<br><br>    &quot;github.com/aws/aws-lambda-go/lambda&quot;<br>    &quot;github.com/aws/aws-sdk-go/service/secretsmanager&quot;<br><br>    &quot;ziprecruiter-internal/common/go/aws/session&quot;<br>    &quot;ziprecruiter-internal/common/go/buildinfo&quot;<br>    &quot;ziprecruiter-internal/common/go/config&quot;<br>    &quot;ziprecruiter-internal/common/go/errutil&quot;<br>    &quot;ziprecruiter-internal/common/go/interfaces&quot;<br>    &quot;ziprecruiter-internal/common/go/log&quot;<br>    &quot;ziprecruiter-internal/monitoring/meta/internal/checkers&quot;<br>)<br><br>func main() {<br>    ctx := context.Background()<br>    l := log.New(&quot;@tag&quot;, &quot;monitoring--meta&quot;)<br>    log.SetStandardLoggerOutput(l)<br>    defer log.PanicMessagesTo(ctx, l)<br><br>    log.Info(ctx, l, &quot;starting up metamonitoring version &quot;+buildinfo.GitCommit)<br><br>    var c configuration<br>    if err := config.Read(&amp;c); err != nil {<br>     fmt.Printf(&quot;Couldn&#39;t load config: %s\n&quot;, err)<br>     os.Exit(1)<br>    }<br><br>    cs := buildCheckers(c.Metamon.Monitors, c.Metamon.HistorySize)<br><br>    sess, err := session.New(session.Options{Region: c.Pagerduty.APIKeySecretRegion})<br>    if err != nil {<br>     log.Err(ctx, l, errutil.Wrap(err, &quot;couldn&#39;t create an AWS session&quot;))<br>     os.Exit(1)<br>    }<br><br>    asm := secretsmanager.New(sess)<br>    pdik, err := lookupPagerdutyIntegrationKey(asm, c.Pagerduty.APIKeySecretName, c.Pagerduty.ServiceID)<br>    if err != nil {<br>     log.Err(ctx, l, err)<br>     os.Exit(1)<br>    }<br><br>    log.Info(ctx, l, &quot;successfully loaded pagerduty integration key&quot;)<br><br>    log.Info(ctx, l, &quot;starting lambda function handler&quot;)<br>    lambda.Start(func(ctx context.Context) error {<br>     checkAll(ctx, l, pdik, cs, c)<br>     return nil<br>    })<br>}<br><br>func buildCheckers(ms []monitor, sz int) []checkers.CheckFailer {<br>    cs := make([]checkers.CheckFailer, 0)<br>    for _, m := range ms {<br>     switch m.Type {<br>     case &quot;alertmanager&quot;:<br>      cs = append(cs, checkers.Alertmanager(m.Label, m.Host, m.Insecure, m.Peers, sz))<br>     case &quot;prometheus&quot;:<br>      cs = append(cs, checkers.Prometheus(m.Label, m.Host, m.Namespace, m.Insecure, sz))<br>     case &quot;http&quot;:<br>      cs = append(cs, checkers.HTTP(m.Label, m.Host, m.Insecure, sz))<br>     case &quot;tcp&quot;:<br>      cs = append(cs, checkers.TCP(m.Label, m.Host, sz))<br>     }<br>    }<br>    return cs<br>}<br><br>func checkAll(ctx context.Context, l interfaces.Logger, pagerdutyKey string, cfs []checkers.CheckFailer, cfg configuration) {<br>    client := &amp;http.Client{}<br>    client.Transport = &amp;http.Transport{<br>     Proxy: http.ProxyFromEnvironment,<br>     DialContext: (&amp;net.Dialer{<br>      Timeout:   1 * time.Second,<br>      KeepAlive: 30 * time.Second,<br>     }).DialContext,<br>     ForceAttemptHTTP2:  true,<br>     MaxIdleConns:       100,<br>     IdleConnTimeout:    90 * time.Second,<br>     TLSHandshakeTimeout:   10 * time.Second,<br>     ExpectContinueTimeout: 1 * time.Second,<br>    }<br>    wg := sync.WaitGroup{}<br><br>    wg.Add(len(cfs))<br>    log.Info(ctx, l, &quot;running checkers&quot;, &quot;count&quot;, len(cfs))<br>    for _, cf := range cfs {<br>     go func(c checkers.Checker) {<br>      pctx, cancel := context.WithTimeout(ctx, time.Duration(cfg.Metamon.Timeout)*time.Second)<br>      defer cancel()<br><br>      c.Check(pctx, l, client)<br>      wg.Done()<br>     }(cf)<br>    }<br><br>    log.Info(ctx, l, &quot;waiting for all checkers to complete&quot;)<br>    wg.Wait()<br>    log.Info(ctx, l, &quot;checkers finished&quot;)<br><br>    wg.Add(len(cfs))<br>    log.Info(ctx, l, &quot;evaluating history&quot;, &quot;count&quot;, len(cfs))<br>    for _, cf := range cfs {<br>     go func(f checkers.Failer) {<br>      fi := f.Failure(cfg.Metamon.MaxFailureWindow)<br>      dl := log.WithDetails(l, &quot;pagerduty_dedupe_key&quot;, fi.DedupeKey)<br>      if fi.Failures &gt;= cfg.Metamon.MinFailureThreshold {<br>       // Trigger alert<br>       log.Info(ctx, dl, &quot;triggering alert&quot;, &quot;triggering_failure&quot;, fi)<br>       if err := emitPagerdutyEvent(cfg, pagerdutyKey, true, fi); err != nil {<br>        log.Err(ctx, dl, err)<br>       }<br>      } else if fi.Failures == 0 {<br>       // Resolve alert<br>       log.Info(ctx, dl, &quot;resolving alert&quot;)<br>       if err := emitPagerdutyEvent(cfg, pagerdutyKey, false, fi); err != nil {<br>        log.Err(ctx, dl, err)<br>       }<br>      } else {<br>       log.Info(ctx, dl, &quot;within failure window, waiting for more observations&quot;, &quot;failure_progress&quot;, fi)<br>      }<br>      wg.Done()<br>     }(cf)<br>    }<br><br>    log.Info(ctx, l, &quot;waiting for all evaluations to complete&quot;)<br>    wg.Wait()<br>    log.Info(ctx, l, &quot;evaluations finished&quot;)<br>}</pre><h3>4 Key insights for a successful migration to Prometheus</h3><ol><li><strong>Take it slow — </strong>We made the transition from Icinga to Prometheus fairly slowly, like one should when deploying any new service.</li><li><strong>Teach </strong>— We gave each team their own Prometheus server, and provided extensive examples of how to configure alerts using the Prometheus AlertManager.</li><li><strong>Auto-discover </strong>— We make sure to label every application in Kubernetes with the team it belongs to. A simple code auto-discovers Kubernetes services that expose a metrics port, and adds them to the Prometheus instance belonging to the labeled team. See the example ServiceMonitor manifest below.</li><li><strong>Monitor stragglers and give them a deadline </strong>— As applications were re-structured to run in Kubernetes, their developers also wrote Prometheus alerts for them, and removed the old Icinga alerts. Eventually, very few useful alerts remained in Icinga that weren’t duplicated in Prometheus, and we gave their owners a month to migrate their alerts before we shut down Icinga and Graphite.</li></ol><p>Example ServiceMonitor manifest:</p><pre>apiVersion: monitoring.coreos.com/v1<br>kind: ServiceMonitor<br>metadata:<br>  labels:<br>    core.zr.org/team: myteam<br>  name: app-monitor<br>spec:<br>  endpoints:<br>    - honorLabels: true<br>      port: http-metrics<br>    - honorLabels: true<br>      port: https-metrics<br>      scheme: https<br>      tlsConfig:<br>        insecureSkipVerify: true<br>  jobLabel: app.kubernetes.io/name<br>  namespaceSelector:<br>    any: true</pre><p><strong>At ZipRecruiter building is just half the path to success</strong>; monitoring and maintenance at scale are equally important and the systems we create to do so are equally as innovative. A big part of this is using open source projects that allow us to tailor and tweak things to our specific needs.</p><p><strong><em>If you’re interested in working on solutions to problems like these, please </em></strong><a href="https://www.ziprecruiter.com/careers"><strong><em>visit our Careers page</em></strong></a><strong><em> to see open roles.</em></strong></p><p><strong>About the Author<br></strong>Jeremy is a Senior Software Engineer at ZipRecruiter, with decades of experience in search engine advertising, game development, and even mainframes. He loves the challenge of creating tools and infrastructure that allow others to build, deploy, and manage their systems while scaling with ZipRecruiter’s rapid growth.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*KVZ-IaTZzW7e8ahjmSAuyw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9da1f11fd39d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ziprecruiter-tech/why-and-how-we-use-prometheus-to-monitor-kubernetes-9da1f11fd39d">Why and How We Use Prometheus to Monitor Kubernetes</a> was originally published in <a href="https://medium.com/ziprecruiter-tech">ZipRecruiter Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Step-By-Step Introduction to Go Concurrency]]></title>
            <link>https://medium.com/ziprecruiter-tech/an-introduction-to-go-multiprogramming-bdc2f9fdaf80?source=rss-1fefe5dc18b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/bdc2f9fdaf80</guid>
            <category><![CDATA[ziprecruiter]]></category>
            <category><![CDATA[dev]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Engineering Team]]></dc:creator>
            <pubDate>Tue, 14 Mar 2023 17:19:58 GMT</pubDate>
            <atom:updated>2023-03-14T18:35:04.290Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="A modernist green background, with the text “A Step-by-Step Introduction to Go Concurrency, Joe McMahon, Senior Software Engineer, ZipRecruiter”." src="https://cdn-images-1.medium.com/max/1024/1*n2cnYkrIUkva62pAAYKBkg.png" /></figure><p><em>Expert tips and examples that will get you started with goroutines: smartly managing resources, sharing state the right way, and safely coordinating execution</em></p><p>At ZipRecruiter, we frequently need to coordinate multiple streams of asynchronously-supplied input data, incoming at rates ranging from near real-time to significantly delayed (multiple minutes to access). On top of that we want to present a single canonical API endpoint that provides a consistent and up-to-date view of the combined data.</p><p>Go provides great tools which allow us to run and coordinate multiple processes easily and as simply as possible. Let’s look at some techniques that you could use to do the same.</p><h3>What is concurrency?</h3><p>If you’re not familiar with this idea, think of it as being able to write code that performs like the staff of a restaurant. A team of people each performing different jobs: from the executive chef who oversees the whole operation and creates the menu, to the line cooks who handle actual cooking, to dishwashers, servers and bussers, and everything in between.</p><p>Each job is separate but all of them depend on each other to get the food ordered, prepared properly, served in a timely manner, and to keep everything clean and ready for customers. It’s critical that everyone gets their specific job done independently, communicates clearly, and stays in sync with the rest of the team — it doesn’t matter how great the sous chef is if the dishes aren’t getting washed! Concurrency allows you to break up a programming process into multiple semi-independent parts in much the same way.</p><p>There are multiple tools built right into Go that provide coordination and communication between independently executing code paths. For concurrency–independent execution–Go provides <em>goroutines.</em> For direct communication between independent processes, Go provides <em>channels.</em> For coordination of operations, Go provides the sync library.</p><h3>Goroutines for independent execution of tasks</h3><p><em>Goroutines</em> are independently-executing pieces of code, organized as functions. To create a goroutine, simply call a regular Go function with the go keyword in front of a function call:</p><pre>go someFunction()</pre><p>Be aware that Go’s concurrency model is <em>completely unlike</em> processes or threads! Goroutines are managed solely by the Go runtime and have nothing that identifies them, so you can’t kill, cancel, or join a goroutine<strong>;</strong> it runs independently, manages its own memory, and can only terminate if it executes a return. Threads or processes have IDs and programmatic interfaces specifically meant to allow other processes to control them, but goroutines do not. In Go, independent execution is truly independent: a goroutine alone controls its own execution and termination.</p><p>In addition, having Go itself manage the independent tasks means that we incur less overhead; a context switch at the OS level, whether of a process or a thread, requires significantly more CPU and memory resources; within the Go runtime, it’s only necessary to save the current execution point, and switch the pointer to the current stack! (If you’re interested in the details of how the Go runtime manages goroutines, <a href="https://medium.com/a-journey-with-go/go-what-does-a-goroutine-switch-actually-involve-394c202dddb7">this article</a> is a great guide.)</p><p>The sledgehammer approach to controlling <em>all</em> of your goroutines is to simply exit your main program, but the only thing this allows you to do is immediately terminate everything! There’s no guarantee of what state the summarily-terminated goroutines are in — halfway through a database update? Partially done writing out a large file? This can lead to hard-to-reproduce problems and is <em>very</em> much <em>not </em>recommended.</p><p>Goroutines appear to their callers to be quite like regular functions. From the parent’s standpoint, a goroutine acts like a function call that just instantaneously returns without returning a value. Once running, however, goroutines actually continue until they <em>block</em>: by doing a system call, allocating memory on the stack, specifically yielding control with runtime.Gosched(), or reading or writing a <em>channel</em>.</p><p>It is necessary to ensure that your goroutines do periodically yield control to allow the rest of your program to run. A goroutine that never yields control locks out all of the rest of your Go program until it exits.</p><p>Naturally, goroutines consume resources when they run: memory, CPU time, filehandles, and so on. Therefore you should always know exactly what a goroutine’s predicted lifetime is, even if it’s “start as soon as the main program begins executing, and terminate just before it exits”.</p><p>Goroutines that do a single thing and exit immediately may not need to be managed directly, but any goroutine that sets itself up to execute for more than a single operation should be communicating with its parent and under its parent’s control to avoid tying up extra memory and running when they’re no longer needed.</p><h3>Go’s channels turn the traditional multiprogramming model on its head</h3><p>In the traditional multiprogramming model, we expect to share a small bit of memory and synchronize access to it to communicate between processes using <em>locks</em> and <em>semaphores</em>. This is <em>communicating by sharing state</em>:</p><p>A: asks for write access to the shared lock, waits for it. Writes state into shared memory.</p><p>B: asks for read access to the shared lock, waits for it. Reads state from shared memory.</p><p>Go’s <em>channels</em> turn that paradigm on its head. Instead of sharing state to communicate, Go’s model <em>communicates to share state</em> by providing a means to write that state into a typed <em>channel</em>, to be read by another goroutine.</p><p>Using a channel, no memory is shared directly; the communication is done by transferring the communicated data from the originator to the recipient. This significantly simplifies things that shared memory complicates: Who owns the data? Who is responsible for managing the shared memory? How does the runtime handle the shared memory if one of the sharers fails or exits?</p><p>In Go, the originator provides the data to be shared, which it owns, to the Go runtime. The runtime <em>copies</em> that data into the channel and manages it until the channel is read, at which time the memory’s ownership is transferred to the reader. At no time is there memory with multiple potential owners depending on its state.</p><p>The Go runtime handles synchronization of access to the channel, blocking and unblocking goroutines as necessary. This drastically simplifies multiprogramming, as the programmer no longer has to manage access to the memory that contains the shared state, or be concerned about ownership or serializing access, monitor mutexes, or be concerned with the bookkeeping needed; the Go runtime handles it all.</p><h3>Basic syntax and operations with Go channels</h3><p><em>Channels</em> are data structures built into the Go language and handled by the Go runtime. They provide a <em>typed</em> path for data into or out of a goroutine — the typing is important, as this reduces boilerplate code needed in other languages to validate the data — and perform a read or write as a single operation synchronized by the runtime itself.</p><p>Because channels are a language-level primitive type, and also because the data they accept is also typed, it’s easy for the Go compiler to check that the reader and writer are in agreement as to what’s in the channel at compile time.</p><p>Rather than having to treat a channel as if it were a file, requiring more boilerplate code, Go provides the &lt;- operator to read or write from a channel.</p><pre>var sample chan int<br>sample = make(chan int)<br><br>sample &lt;- 2   // write to channel sample<br><br>i := &lt;-sample // read from channel sample<br>              // and assign to i, declaring i as well<br>close(sample) // no more writes permitted to channel<br>              // (runtime exception if you try!)<br>              // all further reads returns the zero value immediately</pre><p>Note the simplicity of the whole process: we declare the channel’s type and then create it, and the &lt;- operator shows you which way the data flows.</p><p>Channels like the one in the example above are <em>unbuffered</em>; that is, they can contain exactly <em>one</em> item of the type they were declared with. If a goroutine attempts to write another item to an unbuffered channel before the previous one is read, the writing goroutine <em>blocks</em> and yields control to the next available goroutine as determined by the Go runtime.</p><pre>c &lt;- 5        // c is now full; if another write to c occurs,<br>              // this goroutine would block<br><br>value := &lt;- c // block on read until something else writes c;<br>              // if c already contains something, this goroutine<br>              // reads it and continues.<br>              // if c is closed, this goroutine gets the zero value and<br>              // continues.<br>              // if c contains nothing, this goroutine blocks.<br><br>&lt;-c           // read whatever is in c, but discards it.<br>              // (blocks until c is written or closed)</pre><p>If we want to be able to write more than one item to a channel at once, we can create a <em>buffered channel:</em></p><pre>nonBlocker := make(chan string, 2) // space for two strings<br><br>nonBlocker &lt;- &quot;foo&quot; // doesn&#39;t block (1)<br>nonBlocker &lt;- &quot;bar&quot; // doesn&#39;t block (2)<br>nonBlocker &lt;- &quot;baz&quot; // blocks!</pre><p>Buffered channels are useful for cases when the consumer is slower than the producer. Buffering the channel allows the producer to queue items up for the consumer, but automatically throttles the producer by blocking it when the channel is full, allowing the consumer to catch up.</p><h3>Monitoring multiple channels with select and case</h3><p>Here’s an example diagram of one goroutine, <strong>C</strong>, controlled by two others (<strong>A</strong> and <strong>B</strong>). C can’t do anything until one or the other of <strong>A</strong> or <strong>B</strong> writes to one of the work channels.</p><p>As written, this code has a serious shortcoming: if <strong>B</strong> writes before <strong>A</strong>, <strong>B</strong> blocks until <strong>A</strong> has <em>also</em> written to its channel, since <strong>C</strong> looks at <strong>A’</strong>s work channel first. This means that <strong>A</strong> and <strong>B</strong> are no longer independent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/0*-df23DkwWGh7AJC4" /></figure><p>We can solve this problem with two more native Go primitives, select and case. Using select, we can monitor multiple channels at once without any dependency on order. Here’s how we’d rewrite the code above to use select and case:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/0*iW9ofmlsnesomnNB" /></figure><p>When <strong>C</strong> reaches the select, it checks <em>both</em> channels to see if <em>either</em> is ready (i.e., has had data written into it). If one has and the other has not, then the case associated with the ready channel is executed. If neither is ready, <strong>C</strong>’s execution simply continues until it yields control. If both are ready, the Go runtime picks one at random and <strong>C</strong> executes the matching case. (A select is most often run in a loop so everyone gets a chance to be “heard”.)</p><p>There are two special cases for select:</p><ul><li>If a channel is set to nil, trying to read that channel would block permanently, so it’s skipped inside a select (a read from a nil channel outside a select will lock up your program!)</li><li>If a channel is <em>closed</em>, all reads of that channel always succeed, returning the zero value of the channel’s type (e.g., if it was a chan int, the value would be zero; if it were a chan string, then it would return a null string, and so on).</li></ul><p>These special cases apply immediately for all readers of a channel at once, because channels are hooked directly into the Go runtime. This allows us to use the “all reads succeed on close” rule to send a signal to a number of goroutines simultaneously by passing them all the <em>same</em> channel. Each goroutine receiving the signal channel includes it in a select. When a controlling goroutine wants to simultaneously send all of them a signal via that channel, it simply closes it, causing all of the controlled goroutines to see a successful read on the channel, and take whatever action is appropriate.</p><p>Note that once a channel is closed, we can’t reopen it, so closing a channel is best used for a one-time signal, such as “please exit now”.</p><h3>Building a worker goroutine</h3><p>Let’s take this idea, along with select, and build out the skeleton of a worker goroutine. We want a goroutine that can</p><ul><li>Start and run until told to terminate</li><li>Accept a value and execute some operation independently</li></ul><p>We’ll create a goroutine that takes two channels as arguments: one that will provide a value to be operated on, and another that will be used just to control execution.</p><pre>func readTillStopped(cmd &lt;-chan int, stop &lt;-chan struct{}) {<br>  for {<br>    select {<br>    case &lt;-stop: // If we get a value, exit<br>      return<br>    case i := &lt;-cmd: // run task if we get a value<br>      // We pass in the stop channel so that the complex<br>      // task can choose to stop early and yield control<br>      // if it’s signaled.<br>      // Note also that if this function blocks (read or<br>      // memory allocation), then other goroutines will<br>      // automatically get control.<br> doComplexTaskThatCanBeInterrupted(i, stop)<br>    }<br>  }<br>}</pre><p>We’d start the goroutine like this:</p><pre>cmd := chan int<br>stop := chan struct{}<br>go readTillStopped(cmd, stop)</pre><p>This will fire off the goroutine; the service goroutine will get control, execute the select, and if no input is available, return control to the Go runtime.</p><p>To execute a command, we’d do this in the main program:</p><pre>cmd &lt;- someInt</pre><p>Here are the steps that will occur:</p><ol><li>The main program blocks immediately because this is a write to an unbuffered channel.</li><li>The Go runtime would look for another goroutine ready to execute, and would find readTillStopped ready to run because cmd has a value ready to be read.</li><li>readTillStopped’s select would get control, and the i := &lt;- cmd would execute, reading the value and passing it to doComplexTaskThatForcesYield.</li><li>The Go runtime would then see that the main program was ready to execute again (the value was read from the channel, so it is no longer blocked), and it could then proceed.</li></ol><p>To stop execution, the main program would execute</p><pre>close(stop)</pre><p>Now execution goes like this:</p><ol><li>close() is a system call, so the main program blocks until it completes, handing control to the Go runtime.</li><li>The closed stop channel makes any goroutine reading from it immediately eligible to run (as we said, a closed channel immediately succeeds and returns its zero value), so runTillStopped is eligible to execute and gets control.</li><li>It executes the case &lt;- stop which causes it to return (and therefore exit).</li><li>An exited goroutine loses control (obviously, as there is no more code to execute), and the goroutine which executed the main function (or any other goroutine) becomes eligible to run again, since the close has completed.</li></ol><h3>Simplifying our worker with context</h3><p>Since this task we did by hand of setting up the stop channel and closing it to stop a goroutine is a very common operation, Go provides the context library to make this easier.</p><p>A context contains, among other things, a hidden channel that goroutines can monitor to see if it’s time to go away. Instead of creating and passing a channel to subsidiary goroutines, we pass a context instead:</p><pre>// Create a context with context.Background since we weren’t<br>// given one to start with. If we have a context, we can reuse it<br>// so it’s shared down the tree of dependent goroutines.<br>ctx, cancel := context.WithCancel(context.Background())<br><br>// It’s convention to pass the context as the first parameter.<br>go somefunction(ctx, otherParameters)</pre><p>In the subsidiary goroutines, we’ll now monitor &lt;- ctx.Done() to see if we should exit.</p><p>When the primary goroutine wishes to terminate all the subsidiary goroutines it has passed the context to, it executes ctx.cancel() to do so.</p><h3>Being a better citizen in the runtime</h3><p>Our code will <em>work</em> as written, but it has some shortcomings. What if we want to do something more like an HTTP server, where we launch a monitor program that executes completely independent of the main program? If we follow our previous architecture, that would look something like this:</p><pre>// First cut at a monitor. See below about its shortcomings.<br>func runnerTry1(ctx context.Context, cmd &lt;-chan Cmd, p struct Params) {<br>  for {<br>    select {<br>    case &lt;-ctx.Done():<br>      cleanup(p)<br>      return<br>    case default:<br>      // processing must use a select{} to read the channel if we want<br>      // to not have it block until commands are available!<br>      processing(cmd)<br>    }<br>  }<br>}</pre><p>Note the use of case default: this is “if I don’t have anything else to do, do this”. This ensures that if we haven’t been stopped, we run the processing function…but that may not work out if the processing function doesn’t do something that forces the goroutine to yield! If it doesn’t, then all the other goroutines will be starved and never get control back.</p><p>Also, we’re going to loop hard here, calling processing() every time around until &lt;-ctx.Done() fires. This will probably consume a lot more resources than we actually need to use. How can we slow this down?</p><p>We could add a call to time.Sleep or runtime.Gosched() to force a context switch:</p><pre>func runnerTry1(ctx context.Context, cmd &lt;-chan Cmd, p struct Params) {<br>  for {<br>    select {<br>    case &lt;-ctx.Done():<br>      cleanup(p)<br>      return<br>    case default:<br>      processing(cmd)<br>      time.Sleep(5 * time.Second) // system call, so we yield to the runtime<br>    }<br>  }<br>}</pre><p>But this is kind of clunky, because it forces a hard minimum wait between “am I done?” checks. If we’ve launched a lot of runnerTry1 goroutines, it might take a considerable amount of time for them all to wake up and notice that everything is done.</p><p>We can rescue ourselves from this with time.Ticker, which creates a channel of its own and a goroutine that writes to it whenever the interval expires.</p><pre>// Create a new ticker struct: every five minutes, write to the<br>// internal channel. The writer will block if the channel isn’t read, // and won’t write more wakeup events. <br>t := time.NewTicker(5 * time.Minute)<br><br>// Wait for ticker to go off – the value in the channel is unimportant,<br>// only “is there something there” matters. Once the channel is read,<br>// the write can write to it again.<br>&lt;-t.C<br><br>// Stop the ticker. Turns off the writer and closes the channel.<br>t.Stop()</pre><p>We simply monitor that channel and do our processing when the timer goes off:</p><pre>func runnerTry2(ctx context.Context, p Params) {<br>  t := Newticker(5 * time.Minute)<br>  for {<br>    select {<br>    case &lt;-t.C:       // Timer pop<br>      processing(p)<br><br>    case &lt;-ctx.Done(): // Finished<br>      t.Stop()         // stop timing<br>      cleanup(p)       // anything this routine needs to finish up<br>      return           // stop the worker<br>    }<br>  }<br>}</pre><p>This fixes our hard loop, and ensures that we exit as soon as possible after the context is canceled: if we’re waiting for the timer to pop, we exit the moment the context is canceled; if we’re executing processing(), we exit as soon as it completes.</p><p>We still have the same weakness as before, though: the main routine <em>tells</em> the dependent goroutines to exit, but it doesn’t <em>know</em> they have. We can get around this by using another function from the Go sync library: sync.waitgroup.</p><h3>Waitgroups for multi-goroutine cancellation</h3><p>A waitgroup uses shared memory to communicate — the opposite of a channel. Waitgroups are needed for the case where a single parent goroutine needs to coordinate the shutdown of multiple child goroutines. It’s used like this:</p><ul><li>The main program creates a waitgroup, and passes a <em>pointer</em> to it to each subsidiary goroutine. (Recall that in Go, if we simply passed the waitgroup, Go’s call mechanism would create a <em>copy</em> of the value in the waitgroup and pass it, and the waitgroup wouldn’t be shared.)</li><li>Each time we want to launch another goroutine to be added to this waitgroup, we first call wg.Add() to add it to the ones we’re waiting for.</li></ul><p>The parent program, when it wants to be sure that all these goroutines have exited:</p><ul><li>Signals cancellation to all of the children via a shared context</li><li>Executes Wait() on the (shared) waitgroup, telling the children to shut themselves down</li><li>Yields control until all the child goroutines have finished and removed themselves from the waitgroup</li><li>Receives control again and proceeds once all of the children have exited.</li></ul><p>With a context and a waitgroup, we can now build out an architecture with as many service goroutines as we like, being sure that we will wait for them all to exit before we terminate, and that they’ll exit as quickly as possible:</p><p>In our main program:</p><pre>// Set up cancel context and waitgroup <br>var wg sync.Waitgroup  // automatically is zero,<br>                              // no one waiting<br><br>// Create the new context and a cancel() function for it.<br>ctx, cancel := context.WithCancel(context.Background())<br><br>// Launch services<br>// Start goroutines: context to cancel, wg to listen<br>for (i := 1; i &lt;= workerCount; i++) {<br>  wg.Add(1)<br>  go monitor(ctx, &amp;wg)<br>}</pre><p>And in our monitor goroutine:</p><pre>func monitor(ctx context.Context, wg *sync.WaitGroup) {<br>  defer wg.Done()  // If we exit this block, say we stopped<br>  <br>  t := time.Ticker(2 * time.Minute)<br>  for {<br>    select {<br>      case &lt;-ctx.Done(): // You told me to stop<br>             t.Stop()   // Shut down dependent goroutine<br>             return   // Exit, triggering defer<br>            case &lt;-t.C:<br>              doMyOperation() // Timer went off, do our thing<br>    }<br>  }<br>}</pre><p>Note the use of defer here. For those not as familiar with Go, defer says “when I exit this block, execute the function I passed to defer”. In this case, it means that we mark an item in the waitgroup done as soon as the function returns, so when we execute the case &lt;-ctx.Done, we stop our timer, return, and in the process of returning, mark this item off the list of things to wait for.</p><p>When we want to shut things down, the main program does</p><pre>cancel()<br>wg.Wait()</pre><p>This closes the cancel channel, which signals all the subsidiary goroutines to stop, and then waits for them all to remove themselves from the waitgroup.</p><h3>Serializing access to data structures</h3><p>Synchronized access to data structures in Go is still best handled with mutexes and/or semaphores. I won’t go deep into the implementation of these — if you’re interested in that, I highly recommend reading these articles on <a href="https://levelup.gitconnected.com/deep-understanding-of-golang-mutex-9964b02c56e9">How to Implement a Golang Mutex</a> and <a href="http://www.golangpatterns.info/concurrency/semaphores">the implementation of semaphores using only channels</a>.</p><p>Go provides a Mutex type via the sync class. We can use this type for synchronizing access, but it’s notable that the package documentation for sync explicitly states that you <em>should not</em> do this, but use only the Once (ensure something is done only once) and WaitGroup (wait for a number of things to finish, as described above) types. The documentation <a href="https://pkg.go.dev/sync#pkg-overview">recommends</a> that any other synchronization should be done via channels unless you’re writing really low-level library code.</p><p><strong><em>If you’re interested in working on solutions like these,</em></strong><a href="https://www.ziprecruiter.com/careers"><strong><em> visit our Careers page</em></strong></a><strong><em> to see open roles.</em></strong></p><h4>About the author:</h4><p>Joe McMahon is a Senior Software engineer on ZipRecruiter’s Employer Data team.There’s always another interesting challenge and new technology to keep Joe on his toes as he helps employers find great candidates. You can hear more from Joe as Equinox Deschanel on his Monday internet radio music show, Etheric Currents, on <a href="https://radiospiral.net/">radiospiral.net</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*hsk9cWjY1ISEBNmlpODa1w.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bdc2f9fdaf80" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ziprecruiter-tech/an-introduction-to-go-multiprogramming-bdc2f9fdaf80">A Step-By-Step Introduction to Go Concurrency</a> was originally published in <a href="https://medium.com/ziprecruiter-tech">ZipRecruiter Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[8 Steps to Becoming a Software Engineering Team Manager]]></title>
            <link>https://medium.com/ziprecruiter-tech/8-steps-to-becoming-a-software-engineering-team-manager-da7b060d4b63?source=rss-1fefe5dc18b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/da7b060d4b63</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[company-culture]]></category>
            <category><![CDATA[getting-a-job]]></category>
            <category><![CDATA[software-engineer]]></category>
            <category><![CDATA[career-advice]]></category>
            <dc:creator><![CDATA[Engineering Team]]></dc:creator>
            <pubDate>Mon, 07 Nov 2022 06:24:55 GMT</pubDate>
            <atom:updated>2022-11-07T06:24:55.669Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/794/0*DVLg1lxsBVwOQ8ez.jpg" /></figure><p><strong><em>This article shares some insight into the organizational culture within the ZipRecruiter Tech Team. If you’re interested in learning and growing in an environment like this, please </em></strong><a href="https://www.ziprecruiter.com/careers/engineering"><strong><em>visit our Careers page</em></strong></a><strong><em> to see open roles.</em></strong></p><p>I recently completed the transition from software engineer to the team manager at ZipRecruiter, the fastest-growing job marketplace in America.* It took me just under 3 years, including an unanticipated delay thanks to a certain virus you may have heard of.</p><p>This shift was a dream come true for me, and the result of a well-structured career path. A series of stepping stones, laid down by my manager, helped me prepare for the responsibilities of leading a team of six developers, with varying skills and ages, across multiple time zones.</p><p>Now, after a year of management, I’m glad to share key insights and recommendations for anyone inspired to lead as a technical team manager.</p><h3>1. Ask yourself if you really want to be a manager — ‘find your why’</h3><ul><li>Being a manager isn’t for everyone. If you’re on the management track just because it’s the only way up the corporate ladder, you might be in for a disappointment.</li><li>Do you have a passion for everything management entails, not just the promotion?</li></ul><p>During my final year as a programmer in the IDF’s Meitav unit, I asked my superior officer to task me with the additional duties of company sergeant major (CSM), in charge of administration, shifts, and equipment. When I first came to the unit, the acting CSM simply didn’t care about the soldiers he was supposed to represent, and I wanted to prove that it could be done differently.</p><p>I got the job and it was the best year of my service. The satisfaction I felt while providing support to the division’s soldiers, and the deep appreciation they expressed, was incomparable to anything I had experienced before.</p><p>I realized that helping improve the environment, processes, and communication people encounter <em>while </em>working, in addition to the work itself, was something I was very excited about.</p><h3>2. Understand your company’s formal career track and milestones</h3><ul><li>Get clarity on the milestones that lead to becoming a manager.</li><li>Companies that encourage <em>all </em>their employees to develop, provide both managerial and professional trajectories.</li></ul><p>Even before I joined ZipRecruiter, during the first interview with Ran, VP of Engineering and the hiring manager at the time, he asked me which career path I saw myself advancing on — professional or management. Without a moment’s hesitation, I answered: “management.”</p><p>The management track at ZipRecruiter is as follows: you start off managing a small team in trial mode, without formally receiving the title and promotion. During this period, which generally lasts three months, you assume full responsibility for ongoing management of the team. It is an opportunity to experience the role, before deciding if you are ready to take it on full-time. In essence, you are both being tested and testing the position yourself.</p><p>Upon successful completion of the trial stage, one can officially be promoted to engineering team manager. And if you decide the position isn’t right for you, shifting back to being an individual contributor (IC) on the professional track is easy.</p><h3>3. Align expectations with your manager early on and make a plan</h3><ul><li>Coordinating expectations is the foundation for a “course of action” that will ultimately enable you to smoothly transition to becoming a manager.</li><li>It is extremely important that you assume an active role in the expectation-setting and planning process. Don’t wait for the opportunity to arise; challenge your managers and ask them what you should do to advance towards — and achieve — your goal.</li></ul><p>During my first few months as a software engineer, Ran and I made a point of discussing my goal of becoming a manager at length. What skills I had to develop, the resources I needed to succeed, what this required of each of us, and how we could ensure we stayed on track.</p><p>At ZipRecruiter, like most software companies, the manager of a technical team must have the technical knowledge to guide team members and pitch in when it’s crunch time. Taking the time to develop those skills, alongside management skills, is imperative.</p><p>The plan we devised outlined how I would develop the spectrum of skills that a leading developer at ZipRecruiter, who is also a manager, must possess. Ran promised to challenge me at every available opportunity, and his constant feedback on my performance kept me motivated to succeed.</p><h3>4. Gradually develop the management skills you need to advance</h3><ul><li>Together with your manager, find as many growth opportunities as possible. Training and mentoring new employees, leading complex projects, collaborating, and pitching to Product, will all help you develop along your desired trajectory.</li><li>Don’t underestimate the learning process. Gradually(!) take on more responsibility while making sure you have all the support you need to succeed.</li></ul><p>After only 3 months at ZipRecruiter, Ran asked me to mentor a new team member and bring him up to speed. Several months later I represented our team on an important transverse project. I took on both these opportunities without a moment’s hesitation, knowing that they would enrich my experience and serve as stepping stones to “the real thing.”</p><p>Then, a big opportunity came my way. An unknown issue in our integration with Google Jobs was causing us to lose inbound traffic from Google. Ran didn’t sugar coat it: “solving this will be huge,” he told me, fueling my motivation to tackle the task.</p><p>He wanted me to lead the project, and assigned two talented teammates to work under my direction as tech lead, while Ran mentored me in the background. With all this responsibility placed on my shoulders I felt challenged and emboldened. I was eager to steer this project to success.</p><p>First, we investigated the problem. It turned out that we were sending Google multiple instances of the same job description, with only minor differences, and every update to the position sent out multiple change tasks. Google’s system didn’t like it and was reducing our priority. We backed this up with data, and spent a month planning the solution. I then wrote the Design Document and presented it to Product — another opportunity, another stepping stone. We now send out only one instance per job, and consolidate changes into one task. After implementing the update, traffic spiked by 3x within just a few days. Talk about impact.</p><p>The success filled me with pride and joy. Not just because of the final result, but mostly because of the path we took to get there. I led a very talented team, and together, we were able to develop, pitch, and implement a complete business and technical solution.</p><h3>5. Start small, if you can</h3><ul><li>It’s a lot easier to transition to management with a smaller team of 2–3 developers.</li><li>A smaller team will give you space and time to learn. You’ll be able to get to know each developer and what motivates them, receive guidance from your mentor, hone management skills, and keep up with your technical advancement.</li></ul><p>Eighteen months after joining ZipRecruiter, Ran was creating a new team to handle all of the Job Seeker Acquisition group’s micro-services and offered me the management position.</p><p>I embarked on this new journey with two team members — one in Israel and one in America — and a few open positions to fill. The goal was to build a team of 5–6 developers.</p><p>I immediately felt as though I’d jumped up the corporate ladder. One-on-one meetings, quarterly planning sessions, bi-annual evaluations, and more, filled up my schedule.</p><p>Two main challenges stood before me, both of which pertained to my team members’ personal development. The first regarded my American team member. He had been with the company for five years and spent most of his time maintaining and improving two critical micro-services that he had developed himself. He loved the work but didn’t like being a one-man show. It was clear that he wanted to be part of a team. The fact that he was eager to overcome the 10-hour time difference and never missed a video call, just goes to show how committed he was.</p><p>My second challenge was to help my Israeli employee develop and take on larger projects so that he could advance on a professional level.</p><h3>6. Accept change as part of the path to management</h3><ul><li>Changes and challenges are inevitable, many of which you have no control over. In fact, managing change and uncertainty is precisely what you are preparing for.</li><li>Adopt a flexible mindset, adapt to the reality at hand, and keep the goal in sight.</li><li>When things veer off course (and they will) don’t give up; coordinate with your mentor, adjust, and keep moving.</li></ul><p>In my case, the Covid-19 pandemic led to a change in plans. We temporarily paused recruiting, and the next stepping stone to a managerial role, a bigger team, was nowhere in sight.</p><p>I wasn’t discouraged, and continued to manage the micro-service team while focusing on the targets I had set. I began a significant project with the team member in America, and he was enjoying the new challenge, as well as the opportunity to work as part of a team. My Israeli employee continued to lead larger-scale projects and develop his skills en route to becoming a senior software engineer. I enjoyed guiding him and communicating exactly what was required, just like Ran had done for me.</p><p>Precisely when I was getting the hang of things, a re-org in the company forced me to move to a new team altogether. It wasn’t initially easy for me to accept, but after setting expectations with Ran, I understood that it was a good opportunity to practice being flexible as companies grow.</p><h3>7. Be a leader, even before you are promoted to management</h3><ul><li>Establish yourself as a leader, so that your eventual shift to a management role is smooth. Lead whenever you can, because that’s just who you are.</li><li>This requires delicate handling of your colleagues, emotional intelligence, and the support of your own manager.</li></ul><p>The team I joined was much larger and more mature, but it belonged to the same group I was already in, so I was familiar with its objectives. Ran and I defined what my main goals would be: quickly assimilate into the team’s processes, initiate and get involved with as many projects as possible, mentor a new employee, and slowly become the team’s natural leader.</p><p>Within six months I was promoted to official Team Manager. No one was surprised and the transition occurred seamlessly and without drama. Six developers were now under my management.</p><h3>8. Don’t be a superhero, learn to delegate</h3><ul><li>New managers should be aware of “superhero syndrome”; a situation whereby one repeatedly tries to do it all, instead of sharing the load and delegating.</li><li>Spend time getting to know each team member, mentoring, and teaching them. This will create the knowledge base and trust you’ll need to “let go.” It’s the best investment you can make.</li></ul><p>My new reality was extremely challenging; a nice-sized team with two new hires, and tons of responsibility related to data systems that support the company’s web services. I was scrambling. Then, just a few weeks after taking the reins, I stumbled upon an article about “superhero syndrome,” and it dawned on me that I was suffering from exactly that!</p><p>It wasn’t easy to overcome, especially with new hires on board, but what helped me the most was first acknowledging the problem. Once I internalized that my main objective was to promote the <em>entire </em>team’s success, I quickly shifted my focus. I helped my team members further develop their skills, which enabled me to delegate tasks to them and tackle broader, more strategic, tasks myself.</p><p>The transition to management is not always simple; in fact, it can be quite challenging. But once you’ve decided it’s right for you, the effort is worth it. Finding a company with a structured career path, and a manager that is delighted to groom and support you is essential. Then, by maintaining a flexible mindset, advancing adamantly, and learning every step of the way, success is all but guaranteed.</p><p>Good luck!</p><p><strong><em>This article shares some insight into the organizational culture within the ZipRecruiter Tech Team. If you’re interested in learning and growing in an environment like this, please </em></strong><a href="https://www.ziprecruiter.com/careers/engineering"><strong><em>visit our Careers page</em></strong></a><strong><em> to see open roles.</em></strong></p><p><em>* Source: Similar-web Market Intelligence Platform. The fastest growing online employment marketplace is defined by the number of total visitors. Results shown are from Feb 2021 — April 2021 compared to May 2021 — July 2021 for individual domains of ZipRecruiter.com, Monster.com, Glassdoor.com, CareerBuilder.com, Linkedin.com, and Indeed.com and not for parent companies, subsidiary sites, partner sites or sub-channels.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da7b060d4b63" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ziprecruiter-tech/8-steps-to-becoming-a-software-engineering-team-manager-da7b060d4b63">8 Steps to Becoming a Software Engineering Team Manager</a> was originally published in <a href="https://medium.com/ziprecruiter-tech">ZipRecruiter Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>