<?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[Hippo Engineering Blog - Medium]]></title>
        <description><![CDATA[Building the systems to help homeowners crush home ownership. - Medium]]></description>
        <link>https://medium.com/hippo-engineering-blog?source=rss----a3e32c500eb7---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Hippo Engineering Blog - Medium</title>
            <link>https://medium.com/hippo-engineering-blog?source=rss----a3e32c500eb7---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 15:06:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/hippo-engineering-blog" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[When two worlds collide — defect-oriented vs quality-oriented approach]]></title>
            <link>https://medium.com/hippo-engineering-blog/when-two-worlds-collide-defect-oriented-vs-quality-oriented-approach-7b11b1b0e3b9?source=rss----a3e32c500eb7---4</link>
            <guid isPermaLink="false">https://medium.com/p/7b11b1b0e3b9</guid>
            <category><![CDATA[qa]]></category>
            <category><![CDATA[test-management]]></category>
            <category><![CDATA[quality-assurance]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Grzegorz Niczyporuk]]></dc:creator>
            <pubDate>Thu, 03 Aug 2023 17:00:38 GMT</pubDate>
            <atom:updated>2023-08-03T17:00:38.728Z</atom:updated>
            <content:encoded><![CDATA[<h3>When two worlds collide — defect-oriented vs quality-oriented approach</h3><p>I remember my first day as a QA engineer, it was 12 years ago. I can still feel the amazement and excitement from that day. I was able to finally find the job that I’d been looking for. And of a sudden, I’ve started to hear that <strong>QAs are only pointing out others’ mistakes and focusing on what’s wrong</strong>. It was a shock for me. I’m a team player and I always wanted to contribute to all the efforts made to reach the goals. It took me a long time to understand… So who’s right and who’s wrong?</p><p>In 2012 I attended an ISTQB Foundation Level course led by Radoslaw Smilgin. During one of the coffee breaks, he started to explain how you can approach testing with a different mindset. He did something that I was surprised to get. He planted this seed in my head which has grown over the years in my head and watered this idea with a simple distinction between focusing on defects and focusing on quality. After almost 11 years from that moment, I’ve developed my own understanding of his words which I would like to share with you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SgK-grx2H8tp6-CNmuDi5Q.jpeg" /><figcaption>Image by <a href="https://pixabay.com/users/9866112-9866112/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=3821156">Родион Журавлёв</a> from <a href="https://pixabay.com//?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=3821156">Pixabay</a></figcaption></figure><h3>Back to the basics</h3><p>Before I even start to talk about different mindsets and approaches to testing, let’s pause for a moment to reflect on the most fundamental definition: <strong>the purpose of testing</strong>. It is often believed that testing is solely about finding defects, but it’s way more than that.<strong> If you take a look into ISTQB FL, you will discover that testing has multiple objectives beyond finding bugs.</strong> On top of that, testing also verifies requirements, validates user expectations, builds trust in the quality of the delivered product, minimizes risks, and provides the necessary information to stakeholders to help them in the decision-making process. That’s quite a lot under one word — “testing”.</p><h3>Defect-oriented vs quality-oriented approach</h3><p>The entire idea itself is easy to explain and understand. As Radek explained to me, a defect-oriented approach focuses on finding bugs, while a quality-oriented approach aims to establish a high-quality level build in your product. Simple, isn’t it? So where’s the entire fun? It always comes to how this will apply to your daily tasks.</p><p><strong>In a defect-oriented approach, you are focusing on breaking the app or product in all possible ways.</strong> You want to find bugs and prove that whatever you are testing is poor quality, right? Not necessarily! While the primary focus is on bugs, there’s a deeper context to consider. Sometimes companies simply want to identify the flaws in their app or product. It is so popular that it has become a model itself — pay-per-bug. Crowdsourcing and crowd-testing companies are often engaged to rapidly identify as many bugs as possible. Some companies even have open pay-per-bug programs allowing anyone to report an issue and get paid for it, this concept is known as bug bounty. Today it’s used by companies like Apple, Intel, Snapchat, and Facebook.</p><p>However, there is something to keep in mind with this approach. Yes, we’re focusing on finding bugs, it’s crucial to remember that it’s not about pointing fingers. <strong>Testing is never about assigning blame and shame.</strong> Despite being regarded as a potentially destructive activity, testing is always constructive. It uncovers what would otherwise remain hidden. Thus, with a defects-oriented approach, you can still bring a lot of positive value to the Software Development Life Cycle.</p><p><strong>The quality-oriented approach is about proving a high-quality level of our product or app and bugs are only a side effect of this process </strong>because<strong> </strong>bugs will happen anyway. <strong>As QA Specialists, our role is to cover what is important to fulfill the testing objectives mentioned earlier.</strong> It’s not just about covering only happy paths or brightest day scenarios but; it’s about thoroughly testing software without placing blame and driving towards reporting as many issues as possible, even if they are not necessarily an issue. Seems easy and positive, doesn’t it?</p><p>However, there is something that I must warn you about. The fact that you acknowledge the existence of the defects, and you know that they will occur, <strong>does not mean that we agree with or ignore them.</strong> Otherwise, you will sit in the middle of a burning house, sipping coffee out of your mug and telling “This is fine” to yourself (not literally, but you get the point).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zUtgio-TQIBphjqe" /><figcaption>Source: <a href="http://gunshowcomic.com/">http://gunshowcomic.com/</a></figcaption></figure><h3>Dark side and light side?</h3><p>So which approach is better? Which one should you take? I would say none and both at the same time. It all depends on situations, context, specific companies, products, planetary conjunction… There is no single solution or mindset which can be applied to every situation, project, or company. <strong>The most important thing is to know different approaches and know when and how to use them to bring value to what we do.</strong> This has grown in my mind from a simple sentence planted in my mind. Thank you, Radek!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b11b1b0e3b9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hippo-engineering-blog/when-two-worlds-collide-defect-oriented-vs-quality-oriented-approach-7b11b1b0e3b9">When two worlds collide — defect-oriented vs quality-oriented approach</a> was originally published in <a href="https://medium.com/hippo-engineering-blog">Hippo Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Case Study on Measuring Data Quality]]></title>
            <link>https://medium.com/hippo-engineering-blog/a-case-study-on-measuring-data-quality-96be0bf661ee?source=rss----a3e32c500eb7---4</link>
            <guid isPermaLink="false">https://medium.com/p/96be0bf661ee</guid>
            <category><![CDATA[datasets-review]]></category>
            <category><![CDATA[data-quality-innovation]]></category>
            <category><![CDATA[data-quality]]></category>
            <category><![CDATA[data-quality-management]]></category>
            <category><![CDATA[data-quality-metrics]]></category>
            <dc:creator><![CDATA[Aaditya Bansal]]></dc:creator>
            <pubDate>Wed, 30 Nov 2022 19:02:41 GMT</pubDate>
            <atom:updated>2022-11-30T19:02:41.845Z</atom:updated>
            <content:encoded><![CDATA[<p>Authored by <a href="https://www.linkedin.com/in/tarrung/"><strong>Tarrun Gunasekaran</strong></a> and <a href="https://www.linkedin.com/in/aaditya-bansal-a537456/"><strong>Aaditya Bansal</strong></a></p><h3>About Hippo</h3><p>Hippo is modernizing the $100 billion home insurance industry by putting customers at the center of everything we do, from the coverage we offer to the customer service we provide. If that wasn’t enough, it’s really just the beginning: Hippo’s true ambition lies in helping people prevent problems with their homes to begin with.</p><h4>What is Data Quality ?</h4><p>If you have ever worked with data, you would know that data quality is of paramount importance because it is important to have a trustworthy, accurate and consistent data for the company to analyze and make business decisions. Data Quality is not a one time project or initiative but an ongoing effort to continuously make the data better and more powerful to use.</p><p>Data Quality is an umbrella term that encompasses all of the factors that influence whether data can be relied upon for its intended use.</p><h4>What are different Data Quality Dimensions:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ljknmd4bkcGUO-tiSoAtqg.png" /></figure><h4>Why Data Quality Metric?</h4><p>We can give lip service to data quality but how do we actually measure it? At Hippo we came up with a measure or a score called <strong>data quality metric.</strong></p><p>It’s a measure that is calculated based upon several factors to assure ourselves that we have a high quality of trustworthy data that the business users can rely upon for their analytics, Machine Learning and Data Science projects.</p><h4>Our Current Data Quality Mechanisms:</h4><p>To achieve the above Data Quality Dimensions we have the following:</p><p><a href="https://docs.getdbt.com/docs/build/tests">DBT Tests</a></p><ul><li><a href="https://docs.getdbt.com/docs/build/tests#generic-tests">Generic Tests</a> — unique, not_null, accepted_values and relationships are the four generic tests that comes along with dbt package. We will be defining these tests in yml file that will get translated into sql taking the model name and corresponding column names into account. You can read more about them <a href="https://docs.getdbt.com/docs/build/tests#generic-tests">here</a>.</li><li><a href="https://docs.getdbt.com/docs/build/tests#singular-tests">Singular Tests</a> — Custom SQL written to check for business logic. E.g. To check if the policies are cancelled after certain date from its effective date.</li></ul><p><a href="https://www.montecarlodata.com/">Monte Carlo Monitors</a> — Tool we use for detecting deleted tables, schema changes, freshness anomalies, volume anomalies and field health anomalies.</p><h4>Our Journey for a Reliable Data Quality Metric</h4><p>Data Quality Metric is a continuously evolving process. We developed several iterations of our Data Quality Metric until we were confident that it actually reflected our data quality.</p><p><strong>Version 1.0</strong></p><p>As our first step, we wanted to identify the most used table and verify if we have sufficient tests being defined on that table. In order to do that we did two major steps in this version.</p><ol><li><strong><em>Get key assets from Monte Carlo</em></strong> — Monte Carlos assigns an<strong> <em>importance score </em></strong>for each table in the data warehouse based upon the number of times the table has been queried. We use this score to get the top 200 queried tables.</li><li><strong>Parse the DBT </strong><a href="https://docs.getdbt.com/reference/artifacts/other-artifacts#graphgpickle"><strong>graph.gpickle</strong></a> — The <a href="https://docs.getdbt.com/reference/artifacts/other-artifacts#graphgpickle"><strong>graph.gpickle</strong></a> file is a <a href="https://docs.getdbt.com/reference/artifacts/dbt-artifacts"><strong>DBT artifact</strong></a> that contains the metadata about all the models and all the tests defined for these models. We parse this file to collect the information on which columns the tests are defined for and what type of test are being defined for each column.</li></ol><p>After combining above two info together, we came up with a rough estimate of Data Quality Coverage Score for top 200 most queried tables in our Data Warehouse.</p><p><strong>Limitations of Version 1.0</strong></p><ul><li>Keys Assets from Monte Carlo show more than 100 tables with a score of 0.99. Without distinguishing tables from each other, it is hard to tell if one table is more important than the other.</li><li>Randomly defining a number for minimum tests required</li><li>Although we get a score, we are not able to see what the most important tables were and if they fulfilled the minimum tests criteria.</li><li>We just print out the score which isn’t visually appealing</li></ul><p><strong>Version 2.0</strong></p><ul><li>Instead of using Monte Carlo to define table importance we will use query logs from BigQuery to get table importance.</li><li>Use <strong>column coverage(</strong># of columns in a table<strong>) </strong>to define minimum number of tests.</li></ul><h4>Steps for Calculating Data coverage:</h4><p><strong><em>Step 1 : Get the important tables from Big Query Information schema</em></strong></p><ul><li>Get the top 100 tables that is being queried last 30 days from the information schema</li></ul><pre>WITH base AS<br>                (<br>            SELECT<br>                r.dataset_id, r.table_id, count(*) AS total<br>            FROM `region-us`.INFORMATION_SCHEMA.JOBS_BY_PROJECT<br>            CROSS JOIN UNNEST (referenced_tables) AS r<br>            WHERE<br>                creation_time BETWEEN TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 30 DAY)<br>                AND CURRENT_TIMESTAMP()<br>                AND split(user_email,&#39;@&#39;)[SAFE_OFFSET(1)] = &#39;&lt;company-email-domain&gt;&#39;<br>                AND lower(query) NOT LIKE &#39;%dbt%&#39;<br>                AND r.table_id NOT IN (&#39;audit_log&#39;, &#39;utils_dates&#39;)<br>                AND r.dataset_id IN (&#39;&lt;schema 1&gt;&#39;, &#39;&lt;schema 2&gt;&#39;,&#39;&lt;schema 3&gt;&#39;)<br>                GROUP BY 1,2<br>                ORDER BY 3 DESC<br>                limit 150<br>                )<br>            SELECT  b.dataset_id,<br>                    b.table_id as table_name,<br>                    b.total as query_count,<br>                    count(*) as column_count,<br>            FROM base b<br>            LEFT JOIN `region-us`.INFORMATION_SCHEMA.COLUMNS ic<br>            on ic.table_name = b.table_id and ic.table_schema = b.dataset_id<br>            GROUP BY 1,2,3<br>            ORDER BY 3 DESC</pre><p><strong><em>Step 2 : Define Number of Tests Based on the column</em></strong></p><ul><li>If number of columns &gt; 200 then, minimum number of test required is 20</li><li>If number of columns &lt; 200 then we require coverage on at least 10% of the columns. E.g. If there are 120 columns, then have a minimum of 12 tests defined for the table</li></ul><p><strong><em>Step 3 : Calculate Individual Table Coverage</em></strong></p><ul><li>If Number of Test &gt;= Number of Test Required → 100% Individual Table Coverage</li><li>If Number of Test &lt; Number of Test Required → Number of Test/Number of Test Required</li></ul><p><strong><em>Step 4: Calculate Total Quality Score</em></strong></p><ul><li>I<strong>ndividual Points Awarded for table</strong> = ( Individual Table Coverage ) * pct_total</li><li><strong>Quality Metric Score</strong> = Sum of Individual Table Points</li></ul><p>Below Illustration shows the above calculation for our top 10 used tables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FdUaqqFbSez4Zh_ZDLbP8Q.png" /></figure><h3>Our Next Steps</h3><p>This blogpost provides the information for test coverage strategy we have implemented for our most critical tables. In our next step, we will account for dbt test failures, data warehouse outages or delays, and other data quality alerts. This will provide us with Data Quality Metric on a daily basis and we will be able to measure how our Data Quality Score and Data Quality Coverage score trend over time. Along with that we are also looking to improve the following:</p><ul><li>Identify the tables [by user vs reports used by Tableau dashboard]</li><li>Post results to Big Query for further analysis</li><li>Getting a trendline in Grafana</li><li>Automate the process in Airflow</li><li>Better Visualization using Data Studio</li></ul><p>We already have started working on next steps and will publish another blogpost after releasing new version.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96be0bf661ee" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hippo-engineering-blog/a-case-study-on-measuring-data-quality-96be0bf661ee">A Case Study on Measuring Data Quality</a> was originally published in <a href="https://medium.com/hippo-engineering-blog">Hippo Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How we do Alerting and Escalation]]></title>
            <link>https://medium.com/hippo-engineering-blog/how-we-do-alerting-and-escalation-13ef3be5ece5?source=rss----a3e32c500eb7---4</link>
            <guid isPermaLink="false">https://medium.com/p/13ef3be5ece5</guid>
            <category><![CDATA[engineering-mangement]]></category>
            <category><![CDATA[sre]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[alerting]]></category>
            <dc:creator><![CDATA[Mike Gordon]]></dc:creator>
            <pubDate>Thu, 08 Sep 2022 01:53:18 GMT</pubDate>
            <atom:updated>2022-09-07T20:52:59.171Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aLBVsYO9pHW7Hg5G3w1DZA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@kirkthornton?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Kirk Thornton</a> on <a href="https://unsplash.com/s/photos/fire-engine?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>When I first joined Hippo in late 2019, if there was an outage from one of our systems then our engineering team would normally hear about it from our production support team. One of our agents would be using the app and it would stop working or they would discover a bug. This led to longer lead times to fix and less trust in our in-house developed systems.</p><p>Last year (2021) we were finally in a position to automate our outage detection in a way that would meaningfully benefit our business. We implemented a set of organization-wide alerts that could notify our engineering on-call through PagerDuty alerts to cell phones or through a Slack channel. We setup an alerts channel and defined a small number of P0 and P1 alerts to tell us if something was wrong before one of our users detected it.</p><p>It was imperative that we kept the number of alerts small, in order to build trust in alerts and monitoring and not have too much noise. We chose the number for organization-wide P0/P1 alerts to be 10 important alerts of each severity. Teams could still implement their own alerts for team-level alerts if they wanted to watch a service or system more closely.</p><p>Now we detect almost every technical problem our outage long before our business does. We often are able to adjust and take care of them quickly. This is the story of what we did and how we did it.</p><h3>Real-time Metrics</h3><p>In order to alert our team about problems that occur with our systems, we need some way to monitor them real-time. We had been using a log ingestion system for a while for our logs, but the purpose of logs and the purpose of real-time monitoring are different. Logs are there to provide us detailed information about problems. Some log management products also provide aggregation and alerting but as our system grew we outgrew the ability for the logging system alone to monitor our services.</p><p>We started to use Prometheus for real-time metrics. Prometheus provides a time-series database that makes it easy to query rates and trends. Most HTTP services expose an endpoint for Prometheus to scrape, collecting metrics using a “pull” method. Many Prometheus libraries and plugins provide default metrics for HTTP services. They also make it easy to create or instrument metrics for events.</p><p>For example, let’s say we want to capture an event every time a customer performs a certain action on our site, like getting a quote for insurance. We have a back end API that issues a quote. We could instrument that back end API to have a quoted event that’s recorded in real time through Prometheus. The pseudo-code would look something like:</p><pre>metrics.createEvent(&#39;quoted&#39;, typeOfProperty, priceRange);</pre><p>Notice that the example parameters are parameters that would generally be thought of as an enum. That’s not a mistake. Prometheus has a limit on cardinality of dimensions. We can record multiple dimensions within an event but each dimension should have a small number of possible values. If we’d use a wide range of values then Prometheus would run out of space in the underlying database. <a href="https://www.robustperception.io/cardinality-is-key/">Here</a> is a deeper discussion of that cardinality.</p><p>One more thing to note is that our real-time metrics system is not meant to store data forever. We set a certain amount of storage space to match roughly 14 or 30 day windows and when the system runs out of space, older events are deleted. Some organizations might require a longer window to retain metrics, so your retention window could vary.</p><p>Below is a simple summary of our monitoring and alerting systems. We have real time alerts as described above. We also use a system for business alerting, that allows us to alert us if business metrics change by using a query from our data warehouse. The two combined together let us watch both our distributed system and the health of the business at once:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5TJKjeBXg9xWTKPTUmSR7A.png" /><figcaption>A simplified summary of our monitoring and alerting at Hippo</figcaption></figure><h3>Defining and tuning alerts</h3><p>The first thing we needed to do was figure out what we wanted to monitor. Some of this was easy, since for every service we run — internal or external — we want to know:</p><ul><li><strong>Error Rate.</strong> What is the error rate? Do we see an error rate higher than our stated goal?</li><li><strong>Latency.</strong> What’s the latency of the median call to that service (also called 50p for 50th percentile)? What about the 95p call? Is the latency higher than we designed?</li><li><strong>Throughput.</strong> What’s the rate of requests to each service in our system? Do we see an unexpected jump or drop in that rate?</li></ul><p>Most scalable, well constructed APIs should have an error rate of 0.1% or less, depending on what kind of dependencies they have. I believe it’s OK to start with a rate much higher than that for alert thresholds and bring them down over time. For latency I like to use the guideline of no more than 1 second for 95p but latency can be much more variable than error rate, depending on what your service does.</p><p>Some more examples of metrics we might watch:</p><ul><li>Queue size for async systems. If queue size grows it could mean our system stopped processing items.</li><li>Dead letter queue size. Often indicates errors in async systems.</li><li>Memory/CPU. If a service could be memory or CPU bound.</li></ul><p>I’ll introduce a very simple example of tuning an error rate alert. Your service and error rate may vary. You also want to probably gather a longer history of data than I’m using for this example. Let’s say we have a service error rate graph over the last 12 hours that looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yPb8TcmntzqtzXtWj5-0Nw.png" /><figcaption>Sample service error rate graph</figcaption></figure><p>We can draw a few conclusions to tune an alert:</p><ul><li>Between 7:00am and 3:30pm the peak error rate is around 1.75%. That error rate lasts for less than 10 minutes.</li><li>There is a higher, short spike before 7am</li><li>The typical sustained error rate for this service hovers below 1%</li><li>I would start by configuring an alert to detect an error rate above 1% for a sustained 15 or 20 minutes</li></ul><p>We normally have this alert post to a Slack channel, then watch it for a few days. If it fires false alarms then we consider either fixing the underlying service or changing the alert threshold higher if that can’t be done.</p><p>If we’re not seeing it fire at all and we’re not satisfied with the service performance, we may adjust the thresholds of both rate and time down a little to detect outages more consistently.</p><p>Sometimes we have a service that usually has zero or very low error rate. If we see any spike in error rate it could indicate an outage. The example below has a short, high spike in error rate. Since it lasts only a few minutes, we probably want to ignore it as a blip or network hiccup and set the threshold longer than the spike:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TUaH6DJXh1_-kZtwk67B9A.png" /><figcaption>Another service error rate example, with a spike in errors</figcaption></figure><h3>Our escalation process</h3><p>When we have an automated alert fire we had to define an escalation process. The basic idea of an escalation process is to have a script that one of our engineers on call can follow to notify the right people of a problem and fix the problem as quickly as possible. Sometimes when an unfamiliar issue pops up with our system, it’s easy to panic and not know who to contact next for help. The escalation process removes that doubt and gives clarity to our on-call.</p><p>We setup a simple set of steps to escalate:</p><ol><li>Investigate the problem to classify as a real problem or false alarm. Every alert in our P0 and P1 alert list has a playbook that should describe what to do if that alarm shows up.</li><li>If the problem is a real problem, alert our user support team about the issue. If it can be fixed or mitigated quickly (within less than an hour), fix it.</li><li>If it can’t be fixed and the issue is P0, open a Slack channel and a Jira ticket describing the issue.</li><li>Add the right people to the channel to help fix.</li></ol><p>These simple steps give the on-call instructions on what to do when an alert shows up. They don’t need to know how to fix it, only what to do when they see it and how to contact someone to help fix it. Our team resolves most issues within a couple of hours.</p><p>We have other paths of escalation, such as user complaints about problems with the system, which get injected into this process in other ways but are probably beyond the scope of this short post.</p><h3>What can you do as a small organization?</h3><p>Not every organization has a 150-strong engineering team. Maybe you don’t even have 25. What can you do with a smaller team to achieve some of the same results?</p><p>Most log management systems have an alerting feature or function. With a small volume of traffic, it’s easy to setup alerts and thresholds all in one place. We use Loggly for processing logs, which has alerting functions that let you configure alerts to e-mail or Slack channels. That’s perfectly adequate for a 10 person team to set up some basic alerting. It’s also not that difficult to setup a Prometheus/Grafana combo and allow metric scraping from a running service. A good dev/devops team can prototype this in less than a day.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13ef3be5ece5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hippo-engineering-blog/how-we-do-alerting-and-escalation-13ef3be5ece5">How we do Alerting and Escalation</a> was originally published in <a href="https://medium.com/hippo-engineering-blog">Hippo Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Adapter Design Patterns To Migrate Legacy API Calls in FE]]></title>
            <link>https://medium.com/hippo-engineering-blog/using-adapter-design-patterns-to-migrate-legacy-api-calls-in-fe-419784f85be8?source=rss----a3e32c500eb7---4</link>
            <guid isPermaLink="false">https://medium.com/p/419784f85be8</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[adapter-design-pattern]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[bff]]></category>
            <dc:creator><![CDATA[TAN]]></dc:creator>
            <pubDate>Wed, 07 Sep 2022 18:39:47 GMT</pubDate>
            <atom:updated>2022-09-07T18:39:47.026Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wadqgW1q3j0G0MLewuZeFw.jpeg" /><figcaption>Credit to Call Me Fred <a href="https://unsplash.com/@callmefred">https://unsplash.com/@callmefred</a></figcaption></figure><p>In a fast-growing startup, its common to make tradeoffs between rapid growth, and future-proof architecture. While the early days of Hippo saw much of the former, the monolithic structure and lack of strong types in our main backend repository left much to be desired. Instead of fueling growth, it started to stunt it. As the company continues to scale and mature, we have shifted towards a micro-service architecture, making proper modeling of our insurance policy data a necessity. However, incorporating these new services into our existing applications comes with its own set of challenges.</p><h4>Customer Activation</h4><p>Our team manages the consumer-facing insurance signup flow: a multi-step single-page frontend application with variations on each step depending on the insurance product and the state the policy application is in. We’ll refer to each step in the flow as a “page.” This seemingly simple application is riddled with complexity at every layer.</p><p>Early in 2022, our team began migrating this React application to consume insurance policy data from a new Policy micro-service. Essentially, this changes the way we work with policy data from the backend. In the original implementation, the frontend called multiple legacy RESTful APIs directly to retrieve and update the data required to complete an insurance policy application. After our changes, the frontend will only call a public gateway — a backend-for-frontend (BFF) via GraphQL — to retrieve pre-composed and unified data.</p><blockquote><strong>Before:</strong> The frontend calls multiple RESTful APIs and stitches the responses together</blockquote><blockquote><strong>After:</strong> The frontend calls a BFF once to get composed and unified data, orchestrated across our various micro-services</blockquote><h4>Additonal Context</h4><p>Before this change, we had already established a BFF to serve non-policy data. Examples include, data describing which specific UI elements are shown on individual pages, how discounts should be described, and when modals are shown for a given insurance flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IbQznghIDZBCZKhGLWcq1A.png" /><figcaption>Current Architecture in FE</figcaption></figure><p>The goal of this project was to retrieve policy data from the BFF, already transformed and unified, alongside the UI data. Further, this allows us to retire the legacy RESTFul API calls in frontend.</p><h4>If at First you don’t Succeed…</h4><p>At first, we thought this was easy, as we could just start calling the new policy service from the BFF, and retire legacy API calls from the frontend at the same time. However, this turned out to be significantly more difficult than we thought.</p><p><strong><em>Problem 1: it was difficult to manage two different sets of responses in the frontend.</em></strong></p><p>At any given migration point, the frontend needed to manage two totally different sets of responses: legacy RESTFul policy data and new UI config with policy data mixed in. As you can probably guess, there is very little overlap between the format of these two data sets.</p><p>Since we were migrating page by page, there was a crucial point where a page being migrated needed to support and manage both responses. This makes our global application state extremely hard to manage. Because we were dealing with two incompatible data sets, it would fail when navigating between any migrated and non-migrated page. But, this was not the hardest part…</p><p><strong><em>Problem 2: it was almost impossible to do our desired canary-release to a subset of user sessions in an arbitrary page order for the migrations.</em></strong></p><p>I think it would be good to call out exactly how we want to do the canary-releases, i.e., rollout this work for a specific state or product at a time.</p><p>We have hundreds of products to support, and in order to mitigate risk we wanted to release a subset of these products on a page-by-page basis. This would mean thousands of release combinations to manually coordinate!</p><p>We also needed the flexibility to migrate arbitrary pages regardless of their order in the flow due to different priorities of the new policy micro-service. This became impossible as jumping between migrated and non-migrated pages was a nightmare (see problem 1).</p><p><strong><em>So, what should we do?</em></strong></p><p>I eventually found some inspiration in the adapter design pattern. Before I plot out my idea, here is a brief introduction of the pattern.</p><blockquote>Adapter pattern works as a bridge between two incompatible interfaces. This type of design pattern comes under structural pattern as this pattern combines the capability of two independent interfaces.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d5506flFQFEQgrN7Ji6AzA.png" /><figcaption>Adapter Design Pattern UML — from <a href="https://refactoring.guru/design-patterns/adapter">https://refactoring.guru/design-patterns/adapter</a></figcaption></figure><h4>A Policy Adapter in the BFF</h4><p>What if I put those two different systems in the BFF and normalize them so the upstream and downstream will not be affected. Here is my design:</p><p><strong>Have only one response for migrated pages in the frontend. We adapt the difference between legacy RESTFul API and the new policy micro-service in the BFF.</strong></p><p>In this case, the BFF is a standalone service, but has no database of its own. It simply acts as a sort of proxy to other services while normalizing and orchestrating their responses into a format the frontend understands. This way, the frontend doesn’t need to worry about different response types and making multiple RESTful API calls.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I8__7FWPmvkGA7M6zx34TQ.png" /><figcaption>Proposed Change for New Approach</figcaption></figure><p>This gives us quite a lot of benefits.</p><ul><li><strong><em>Pro 1: No more dramatically different response sets in the frontend.</em></strong> This means the migration work in the frontend could be much simpler! No need to handle legacy API calls, we can do a straight forward one-time migration per page.</li><li><strong><em>Pro 2: Easy canary-releasing and arbitrary page order migration.</em></strong> We can migrate any page in coordination with other teams working on that page, regardless of the page order in the flow. This gives the service team more flexibility to do their work in their own sequencing.</li></ul><p>This plan worked out. For our first major rollout, there were only one or two minor issues regarding data analytics and no issues with the actual policy application data interactions. Overall it worked as expected.</p><h4>A bit of Gratitude</h4><p>Here I’d like to take this opportunity to thank my manager Adi and my teammates David, Chris, Kyle and Maciek for the full support. Without you guys, this idea couldn’t be so successful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=419784f85be8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hippo-engineering-blog/using-adapter-design-patterns-to-migrate-legacy-api-calls-in-fe-419784f85be8">Using Adapter Design Patterns To Migrate Legacy API Calls in FE</a> was originally published in <a href="https://medium.com/hippo-engineering-blog">Hippo Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Server Side JS Patterns to Avoid]]></title>
            <link>https://medium.com/hippo-engineering-blog/server-side-js-patterns-to-avoid-c947cda08fd6?source=rss----a3e32c500eb7---4</link>
            <guid isPermaLink="false">https://medium.com/p/c947cda08fd6</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[code-review]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Mike Gordon]]></dc:creator>
            <pubDate>Wed, 17 Aug 2022 23:37:45 GMT</pubDate>
            <atom:updated>2022-08-24T20:00:56.274Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sm3vp7sIcbK6FuKnhPyRyg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@ballonandon?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Ben Allan</a> on <a href="https://unsplash.com/s/photos/construction?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Every organization has <em>legacy</em> code that was assembled a certain way for a certain reason but is now hard to read.</p><p>From time to time I look at some piece of code in our codebase and think “how could this have been done differently?”. At Hippo, we’ve since made the decision to optimize our code for readability vs. write-ability. We want those reading the code to be able to follow what’s happening, click to references easily in their IDE, and see the entire stack of function calls in a stack trace. In some parts of our legacy code, we attempted to optimize by re-using code and writing common functions. This optimization has often made the code harder to read.</p><p>This post highlights a few patterns to avoid, lists some reasons why to avoid them, and provides alternatives to the current code structure.</p><h3>Renaming Constants and Losing Context</h3><p>This is the simplest item in this post but the small amount of time it saves over hundreds or thousands of views adds up. Some of our code contains lines that will import or rename a constant to a regular variable.</p><p>Renaming the constant to a variable name requires the reader to jump to one more reference to figure out where the value came from:</p><p>const val = constModule.MY_CONST</p><p>or</p><p>const cookieNameFlags = require(&#39;../../constants&#39;).COOKIE_NAME_FLAGS;</p><p>The constant is more readable in its original ALL_CAPS format. If we want to use a constant with its original ALL_CAPS format, we do:</p><p>const { MY_CONST } = require(&#39;./const&#39;)</p><p>or:</p><pre>const constModule = require(&#39;...&#39;);<br>if (myVal === constModule.MY_CONST) {<br>  ...<br>};</pre><h3>Overusing the Plugin Pattern with Anonymous Functions</h3><p>The “plugin pattern” is a pattern when you want some common code to execute around a unique function. The Java sort <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html">comparator</a> is probably the simplest example of a plugin pattern implementation that I’ve found. A comparator is defined:</p><pre>class AgeComparator implements Comparator&lt;Person&gt; {<br>   @Override<br>   public int compare(Person a, Person b) {<br>     return a.age &lt; b.age ? -1 : a.age == b.age ? 0 : 1;<br>   }<br>}</pre><p>Then the sort is executed by plugging that comparator into the sort function:</p><p>Collections.sort(people, new AgeComparator());</p><p>In a simple case like a sort comparator, the plugin pattern can be obvious and useful. The following example of using the plugin pattern in Javascript attempts to be elegant by wrapping a logic function inside another function that’s meant to retrieve a lead. Instead of being elegant, it’s difficult to follow, read, and debug:</p><pre>app.get(&#39;/lead/:leadId&#39;,<br>        getProducerAndOrganization(),<br>        getCookieMetadata,<br>        getLead(leadRoutes.getLead));</pre><pre>app.get(&#39;/lead/:leadId/history&#39;, getLead(leadRoutes.lossHistory));</pre><p>The code attempts to wrap a controller-level business logic function in a getLead function. In the first case, it also specifies two functions to execute (Express executes middleware functions in order) before the business logic - one generates a function and one is a function. With so many patterns mixed together and the plugin of drastically different business logic functions, this becomes a nightmare to read. This is especially true when we’re already using Express middleware functions, which are essentially a plugin.</p><p>The contained function becomes anonymous and the stack trace is broken at runtime. This makes it hard to trace a problem to the lossHistory function, instead ending the stack trace at getLead</p><p>An easy-to-read alternative would be:</p><pre>const lossHistory = async function(req, res, next) {<br>  const lead = getLead(req, res);<br>  // Do some logic.<br>return history;<br>}</pre><p>Here the code can be traced and the stack trace will show both the lossHistory and getLead functions if execution is stopped in either.</p><h3>Unnecessary Promise Chains</h3><p>When Javascript introduced Promises it was a good way to manage async sequences. That has been replaced mostly with async/await which is easier to read. Instead of chaining promises together, it’s better to use async/await to wait for a response.</p><p>Instead of:</p><pre>.then(() =&gt; {<br>  return doSomethingAsync();<br> }).then(() =&gt; {<br>  return doSomethingElseAsync();<br> })</pre><p>Do this:</p><pre>await doSomethingAsync();<br>await doSomethingElseAsync();</pre><p>Which is easier to follow.</p><p>If there is a long block of code in one of the then blocks, sometimes it’s hard to pick out which function is the async function returning a promise. This is especially true if there are multiple functions called or there are multiple return statements due to conditionals.</p><h3>Mixing Express Routes and Business Logic</h3><p><a href="http://expressjs.com/">Express</a> is a popular NodeJS MVC framework. Applications built with express generally have 3 layers: routes, controllers, and models. Routes handle all of the marshaling HTTP requests and responses from the business logic embedded in the controller layer. When route and controller logic are mixed, it becomes hard to unit test business logic and hard to trace side effects when the reader of the code is looking at two layers instead of one.</p><p>Take this block of code:</p><pre>if (request.producer) {<br>  await verifyProducerAndOrgChainLicensesForState(<br>    request.producer, request.organization, lead.state);<br>}<br>if (lead.isBound()) {<br>  const leadUxData = await getBoundLeadData(lead);<br>  return response.status(responseCodes.SUCCESS).send(leadUxData);<br>}<br>const tpi =<br>  await lead.getTransactionData().enrichPolicyDataForLead();<br>const result = getUnboundLeadData(<br>  { tpi, lead, fullQuote: false, includeWorkflow: true }<br>);</pre><pre>updateLeadFlags(lead, request);<br>updateLeadCookies(lead, request);<br>result.leadMetadataFlags = _.get(<br>  lead, &#39;data.metadata.tracking.flags&#39;);</pre><pre>response.status(responseCodes.SUCCESS).send(result);<br>return lead.saveAll();</pre><p>It contains the following places where one could argue that “business logic” is being executed:</p><ul><li>Verifying the insurance agent license</li><li>Checking if the lead is bound (policy is sold) and sending a response if it is</li><li>Getting additional transaction data on the lead to send back to the client</li><li>Updating flags and cookies related to the client on the lead object</li></ul><p>The first item is business logic that should be handled in a controller layer. The second item seems like logic that belongs in the route, except for the fact that getBoundLeadData is implemented at the route layer and not the controller layer. The third item executes a database read on the model itself, skipping the controller layer. The fourth item is mutating the lead on an HTTP GET operation, which could be an unexpected side effect AND cause a race condition (see <a href="https://medium.com/p/ea6823ee2548">Race Conditions in a Distributed System</a> ).</p><p>Here’s some pseudocode that would refactor this to a more clean and testable set of interfaces:</p><pre>if (req.producer) {<br>  await controller.verifyProducerAndOrgChainLicensesForState( <br>    req.producer, req.organization, lead.state);<br>}<br>const leadUxData = controller.getBoundLead(lead);<br>if (leadUxData !== null) {<br>  return res.status(responseCodes.SUCCESS).send(leadUxData);<br>}</pre><pre>const unboundLeadData = controller.getUnboundLeadData(<br>  {lead: lead, fullQuote: false, includeWorkflow: true});<br>controller.updateLeadFlagsAndCookies(lead, req);<br>unboundLeadData.leadMetadataFlags = _.get(<br>  lead, &#39;data.metadata.tracking.flags&#39;);<br>res.status(responseCodes.SUCCESS).send(unboundLeadData);</pre><p>This update results in an easier-to-read route and all of the business logic pushed down to the controller. There’s possible further improvement in not sending the request to the controller in updateLeadFlagsAndCookies and possibly not relying on leadUxData to be null if not found. The separation of concerns between layers also makes it easier to write unit tests to cover most of the code in this route.</p><h3>Code Consistency: Factoring Middleware Out</h3><p>Keeping code organized and consistent for readability can be just as important as writing it well. Take this sequence of code:</p><pre>const leadRoutes = {<br>  successHandler: function (req, res, next) {<br>    res.render = function (data) {<br>      res.status(200).json({success: 1, data: data});<br>    };<br>    next();<br>  },<br>}<br>cloneextend.extend(leadRoutes, require(&#39;./lead&#39;));<br>app.use(leadRoutes.successHandler);</pre><p>A new object is defined with a function that has an Express middleware signature. This object is extended with an import from a file in the same directory and the middleware is then used in the app (also an Express concept).</p><p>Our code has a middleware directory. This directory contains other middleware implementations. Some of those are imported into the file in the require statement. Other functions extended onto leadRoutes are not middleware.</p><p>The lack of consistency, import in the middle of the file (which could have easily been imported at the beginning of the file), and the combinations of functions and middleware functions in the same import make this code hard to read, hard to follow, and hard to understand.</p><p>Instead, this would be simpler, keep directory structure consistency, and more explicitly self-documents what functions are being imported and executed:</p><pre>{ leadSuccessHander } = require(&#39;../middleware/lead&#39;);<br>{ leadHelper } = require(&#39;./lead&#39;);<br>if (condition === true) {<br>  leadHelper(leadData);<br>}</pre><pre>app.use(leadSuccessHandler);</pre><h3>Moving Forward</h3><p>As we move our monolith to smaller services, we still spot places in our legacy code base that could be improved. This article attempts to point a few of those out.</p><p>If you’d like to learn more about working in engineering at Hippo, go to <a href="https://www.hippo.com/careers">https://www.hippo.com/careers</a></p><p>Engineering Blog, Episode 5</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c947cda08fd6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hippo-engineering-blog/server-side-js-patterns-to-avoid-c947cda08fd6">Server Side JS Patterns to Avoid</a> was originally published in <a href="https://medium.com/hippo-engineering-blog">Hippo Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to overcome test flakiness with web UI tests?]]></title>
            <link>https://medium.com/hippo-engineering-blog/how-to-overcome-test-flakiness-with-web-ui-tests-9d866b399a60?source=rss----a3e32c500eb7---4</link>
            <guid isPermaLink="false">https://medium.com/p/9d866b399a60</guid>
            <category><![CDATA[web-automation]]></category>
            <category><![CDATA[cypress]]></category>
            <category><![CDATA[test-automation-framework]]></category>
            <category><![CDATA[quality]]></category>
            <dc:creator><![CDATA[Niranjani Manoharan]]></dc:creator>
            <pubDate>Tue, 09 Aug 2022 14:16:15 GMT</pubDate>
            <atom:updated>2022-08-09T14:16:15.257Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*lWzFyq97i2ndMx-hdVs9yg.png" /></figure><p><em>If you have been active in the testing space, one of the common concerns folks have around testing front-end applications is flakiness caused due to network latency or changes in backend APIs which prevents you from testing the front-end changes. A simple answer to this problem could be to mock back-end responses. But then, what if there are changes made to the backend APIs? That would still require human intervention to update the mocks. What if I told you that you could automatically generate these mocks to ensure that your tests consider the latest back-end changes?</em></p><p>At Hippo, when <a href="https://www.linkedin.com/in/susmitha-sethu-a7a20717/">Susmitha Sethu</a> from my team setup the <a href="https://www.browserstack.com/guide/cypress-framework-tutorial">Cypress</a> framework using mocks for adoption, one of the questions that came up from the team was — “<em>How are we going to handle the continuous changes made to the backend?</em>” Susmitha then worked on a proof of concept that involved leveraging the @graphql-tools/mock package to auto-generate these mocks which further made our test framework more extensible and robust.</p><p>Let’s do a quick walkthrough of what libraries we used and how we implemented the auto-generate mocks capability into our test framework.</p><h3><strong>Pre-requisites:</strong></h3><p>Our backend framework uses GraphQL. You can also use GraphQL on top of your existing infrastructure: REST, SOAP, existing databases, or any other tech stack.</p><h3><strong>Web Test Framework Architecture</strong></h3><p>Here’s an overview of our <strong><em>test framework architecture</em></strong> using Cypress and the graphql mock package:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*ldFEbIwCoWw4QFTr0LVdtQ.jpeg" /></figure><p>As Hippo is growing into a mature public company, we want to move faster but at the same time want to ensure we maintain a high-quality bar for the products we deliver. Speed and quality can be achieved only when we have a reliable automation framework which involves mocks.</p><p>Once a pull request is created, it triggers the sanity test suite which in turn uploads the <a href="https://www.browserstack.com/guide/cypress-framework-tutorial">Cypress</a> test suite image to <a href="https://www.browserstack.com/">BrowserStack</a> which is our 3rd party test lab to execute our tests. When the tests fail, pull requests are prevented from merging. This in turn ensures that the author of the pull request debugs, fixes the test failures and re-runs them. When the tests pass, the pull request is marked as ready to merge. We have implemented this process for a couple of projects and plan to expand it to other projects as well.</p><h3><em>Why do we resort to mock responses for test automation?</em></h3><p>Mocks are used in front-end applications for two key reasons:</p><ul><li>Develop features where backend is still in development</li><li>To isolate and test UI changes</li></ul><p>For both scenarios the mocks use the relevant data that is necessary for testing the component.</p><p>But for automation, we need a mock with all the required attributes to write E2E tests. As the product scales, managing and maintaining mocks manually becomes cumbersome.</p><p>Tools like @graphql-tools/mock package help auto-generate mocks and reduce the dependency on managing mocks manually.</p><h3>Why use the auto-generate mock approach?</h3><p>There are cases where the front-end doesn’t manage its own types and relies on auto generated types from back-end. In such cases, for any change in the back-end schema, failure to update mock schema will result in test failures as the front-end app is now interacting with stale mock response. This can be mitigated using auto-generate mocks which always returns data based on the updated back-end schema.</p><p><em>Example without auto-generated mock:</em></p><pre>export const mockPolicy: Policy = {</pre><pre>  id: ‘abcdstuuid’,</pre><pre>  policyNumber: ‘ABC-9999999’,</pre><pre>  effectiveDate: ‘2020–09–23T00:00:00.000Z’,</pre><pre>  bindDate: ‘2020–09–23T00:00:00.000Z’,</pre><pre>  status: PolicyStatus.Canceled,</pre><pre>  expirationDate: ‘2021–09–23T00:00:00.000Z’,</pre><pre>  documents: [],</pre><pre>  currentPaymentMethod: PaymentMethodType.CreditCard,</pre><pre>  paymentStatus: PaymentStatus.Pending,</pre><pre>  presentationPaymentStatus: PresentationPaymentStatus.AchPaid,</pre><pre>  termsAndConditions: {</pre><pre>    areTermsAccepted: true,</pre><pre>    acceptTermsLink: undefined,</pre><pre>  },</pre><pre>};</pre><p><em>Example with auto-generated mock:</em></p><pre>mockGraphQL({</pre><pre>  CreditCard: () =&gt; ({ expiryYear: 2030, expiryMonth: 6 }),</pre><pre>  Payment: () =&gt; ({ dueDate: ‘2021–06–09T00:00:00.000Z’, amount: 420}),</pre><pre>  Charge: () =&gt; ({ chargedAtISODateString: ‘2021–06–09T00:00:00.000Z’}),</pre><pre>  DateTime: () =&gt; ‘2021–06–09T00:00:00.000Z’,</pre><pre>  PolicyStatus: () =&gt; PolicyStatus.Pending,</pre><pre>  TermsAndConditions: () =&gt; ({ areTermsAccepted: true }),</pre><pre>  PaymentStatus: () =&gt; ‘Pending’,</pre><pre>  Policy: () =&gt; ({</pre><pre>    cancellation: null,</pre><pre>    currentPaymentMethod: ‘CreditCard’,</pre><pre>    expirationDate: ‘2023–06–09T00:00:00.000Z’,</pre><pre>    paymentFrequency: ‘Annually’,</pre><pre>    policyNumber: ‘2222222’,</pre><pre>  }),</pre><pre>  PresentationPaymentStatus: () =&gt;   PresentationPaymentStatus.CreditCardPaid,<br>});</pre><h3><strong>Customizing mocks</strong></h3><p>For specific needs, you can further customize the mocks to return user specified data by using mock object(mockData) as shown below:</p><pre>const schema = makeExecutableSchema({ typeDefs: schemaString });</pre><pre>export const schemaWithMocks = (mockData: IMocks&lt;any&gt;) =&gt; {</pre><pre>  return addMocksToSchema({</pre><pre>    schema, <strong>mocks: mockData</strong>, preserveResolvers: false,</pre><pre>  });</pre><pre>};</pre><pre>export const postAnyQuery = (mockedSchema) =&gt;</pre><pre>cy.intercept(‘POST’, customerPortalBFF, (req) =&gt; {</pre><pre>if (req.body.operationName === ‘IdentityVerificationHash’) {</pre><pre>  req.reply(identityVerificationResponse);</pre><pre>} else if (req.body.operationName === ‘RequestCustomerContact’) {</pre><pre>  req.reply(requestCustomerContactResponse);</pre><pre>} else if (req.body.query) {</pre><pre>  graphql({</pre><pre>    schema: mockedSchema,</pre><pre>    source: req.body.query,</pre><pre>    variableValues: {</pre><pre>      id: ‘1234’,</pre><pre>    },</pre><pre>  }).then((result) =&gt; req.reply(result));<br>}<br>}).as(‘postAnyQuery’);</pre><pre><strong>export const mockGraphQL = (mockData) =&gt; {</strong></pre><pre>  postFlagship();</pre><pre>  postEvents();</pre><pre>  postStripe();</pre><pre>  postIdentity();</pre><pre>  postAnyQuery(schemaWithMocks(mockData));</pre><pre>};</pre><p><strong><em>Auto-generated Mock Example:</em></strong></p><p>If we want to set a specific field e.g. <strong><em>claim contact</em></strong> in auto-generated mocks, then we just add it to mock object instead of mocking literally every attribute for every query.</p><pre>mockGraphQL({</pre><pre>  DateTime: () =&gt; new Date(‘2021–07–01’).toISOString(),</pre><pre>  TermsAndConditions: () =&gt; ({ areTermsAccepted: true }),</pre><pre>  PresentationPaymentStatus: () =&gt;   PresentationPaymentStatus.CreditCardPaid,</pre><pre><strong>  ClaimContact</strong>: () =&gt; ({</pre><pre>    firstName: ‘xxx’,</pre><pre>    lastName: ‘xxx’,</pre><pre>    phoneNumber: ‘xxxxxxx’,</pre><pre>    email: ‘<a href="/service/mailto:xxx@xxx.com">xxx@xxx.com</a>’,</pre><pre>    __typename: ‘ClaimContact’,</pre><pre> }),</pre><pre>   ClaimList:() =&gt; ({</pre><pre>    count: 0,</pre><pre>    items:[ {</pre><pre>    id:’0Zk6s000000CbZ4CAK’, claimNumber:’XXX- 0009894&#39;,status:ClaimStatusEnum.NewFnol,peril:ClaimTypeEnum.ServiceLine,</pre><pre> }],</pre><pre>}),</pre><p>Overall, we have achieved better efficiency, wherein we spent 1–2 hours each day debugging and fixing failing tests due to changes in back-end schema. By leveraging the auto-generated mock approach, we have optimized for that time spent debugging and increased reliability and confidence in these front-end tests.</p><p>I hope these insights from the Hippo Test Automation team have piqued your interest on improving stability and reliability of front-end automation!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d866b399a60" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hippo-engineering-blog/how-to-overcome-test-flakiness-with-web-ui-tests-9d866b399a60">How to overcome test flakiness with web UI tests?</a> was originally published in <a href="https://medium.com/hippo-engineering-blog">Hippo Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How We Created and Adopted an ELT Data Warehouse]]></title>
            <link>https://medium.com/hippo-engineering-blog/how-we-created-and-adopted-an-elt-data-warehouse-faef0e568382?source=rss----a3e32c500eb7---4</link>
            <guid isPermaLink="false">https://medium.com/p/faef0e568382</guid>
            <category><![CDATA[data-warehouse]]></category>
            <category><![CDATA[engineering-mangement]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Mike Gordon]]></dc:creator>
            <pubDate>Tue, 26 Jul 2022 14:45:51 GMT</pubDate>
            <atom:updated>2022-07-26T14:51:39.031Z</atom:updated>
            <content:encoded><![CDATA[<h3>History of Data at Hippo</h3><p>Initially, we had two data needs at Hippo — business analytics and reporting our policy and claims information to carriers. As a fronting carrier, Hippo has contracts with insurance companies to underwrite policies. To do so, we must report the status of our policy book and claims to these carriers so they can verify that our underwriting is being done according to their expectations. These reports must be sent electronically either daily, weekly, or monthly. Our business partners usually require that the reports be delivered in a specific format and delivery mechanism that they specify.</p><p>Prior to setting up a data warehouse, our team of analysts used a read replica of our production database to perform analysis and setup views of our data. That worked for a while but didn’t include the many external data sources we had, taxed our production systems, and didn’t include a process for verifying and cleaning our data.</p><h3>Data Requirements and Design</h3><p>Hippo’s business is a daily, weekly, and monthly business. Our business generally doesn’t make decisions in real time, with a few exceptions. Given this requirement we initially chose not to implement a real time solution to sync our production data into a data warehouse.</p><p>After evaluating a number of batch solutions and the possibility of a homegrown data sync, we chose <strong>Fivetran</strong> as our sync solution. Fivetran provides solid capability to sync from many data sources into a destination data warehouse. It has monitoring, logging, and recovery hooks. We reviewed a few other options, including:</p><ul><li>Building an in-house sync solution with Python</li><li>Using <strong>Stitch</strong>, a similar tool to Fivetran</li><li><a href="https://debezium.io/"><strong>Debezium</strong></a>, an open source alternative to SaaS sync tools</li></ul><p>Hippo does have a small number of real time requirements to understand certain sales targets throughout the day. To satisfy these requirements, we created materialized views on our production read replica database and use a dashboarding tool for displaying these numbers.</p><p>The final notable requirement is the need for our data warehouse to have a higher reliability than the typical data warehouse due to reporting requirements mentioned earlier. In most places, if the warehouse goes down or has issues, the analysts and a few business folks get annoyed and that’s the end of it. The service level objective (SLO) that we’re required to maintain is higher than that. An increasing number of organizations are treating their data warehouse as a “production” system and this requirement will become more typical over time.</p><h3>Implementation Details</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wfsLIKaYkWwKzUOFvECnyg.png" /><figcaption>Simple Data Flow diagram of our ELT data warehouse</figcaption></figure><p>Our data infrastructure consists of a number of parts. The source systems are our multiple production databases. At the time we started implementation of our data warehouse our primary production database was a monolithic db which stored our policy, customer, leads, claims, and property data. Since then we’ve been splitting that monolith into micro-services and updating our data ingestion along with the changes.</p><p>We decided to go with an Extract, Load, and Transform (ELT) paradigm for our data warehouse because it’s simple and well suited to dbt to copy data raw into a data lake and transform it from that raw data to more useful formats. We worked closely with an expert consulting firm, <a href="https://datacrt.com/"><strong>Data CRT</strong></a>, to help design and implement this system.</p><p>We use <strong>Google BigQuery</strong> for our data warehouse. We’ve found that BigQuery is a best in class data warehouse tool with a rich query language and significant scalability that meets our need in the foreseeable future.</p><p>Our sync tool is <strong>Fivetran</strong>. We also have a limited number of direct syncs from third party software systems that integrate well with BigQuery. A few of our other syncs are from flat files stored in AWS S3 or Google Drive. That data is usually reference data, such as insurance or commission tables.</p><p>We use <strong>dbt</strong> for our transform step. dbt provides query-first transformations and is able to mix SQL and code-like iteration together in a powerful processing language. dbt has allowed our teams to build a multi-step data validation and transformation. Because it’s based on SQL we’ve also been able to empower our analysts to help with ELT development. This has proven a great way for our analysts to learn how data engineering works without requiring them to write code. Since we were a small startup at the time we started this project, Hippo didn’t have the resources for a large specialized data engineering team. dbt allowed multiple team members of different skill levels to pitch in on developing our ELT and expanded our capacity of data warehouse developers to our analyst partners.</p><h3>Reports Framework</h3><p>Given Hippo’s significant reporting requirements, a way to auto-package and auto-deliver reports from our data warehouse is critical. Some reports are reviewed by people and others are machine-ingested. After a short debate and tool evaluation, we decided to write a home-grown Python framework for report delivery. Report preparation and delivery looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_bOQ5WYGQhBiw5YkGBmwKw.png" /><figcaption>Report delivery using a framework we developed in-house</figcaption></figure><p>Our in-house reports framework is written in Python and configurable to be able to schedule reports at any time and frequency to be delivered to a variety of destinations. Report metrics are sent to our observability infrastructure, allowing us to configure system-wide alerts if reports fail or are failed to be delivered to their destination.</p><p>Hippo has scheduled 150+ reports with this framework with various cadence and we’ve had few reporting failures. What once took a team of analysts days to compile is now completely automated by our reports infrastructure.</p><h3>Gaining Adoption</h3><p>When we first stood up our data warehouse, the organization had gotten used to having direct access to production data. With a number of systems, processes, and reports that were dependent on our production database it was a difficult climb to move over to the data warehouse.</p><p>The decision that aided our organizational adoption was to move most of our analyst team together with our data engineering team. By making them “one team” and putting them together to resolve issues with the data warehouse in real time, it built analyst trust in our systems. As our analysts became more comfortable with using the data warehouse as the source of truth for their reports and analytics, we began to remove views and access from our production read replica database.</p><p>This process took about six months of hard work, but ultimately resulted in the whole company transforming the way we worked. Instead of joining marketing or financial data in a spreadsheet exported from a production database, our analyst team could write queries in real time to join data from these sources. Once they realized the benefit of less manual work, they jumped onboard our data warehouse bandwagon.</p><h3>Our Future Plans</h3><p>As we’ve built a functioning and robust “v1” data warehouse, we’ve satisfied our business needs of getting data and dashboards in the hands of our users from any source. Our data warehouse normalizes/denormalizes this data and performs some basic data quality checks in the course of the ELT. The data is available at a frequency of more often than a day and we use BigQuery to run queries — which means users aren’t waiting very long for their queries to complete, no matter how complex their analysis.</p><p>By integrating readily available SaaS and cloud infrastructure, writing some custom code for functions specific to our business, and organizing our team to drive adoption of our data warehouse we were able to transform the way our data driven business uses that data. We did this with a relatively small team of fewer than 10 engineers and analysts and in a 6–8 month timeframe. This was quite an accomplishment for a small and capable team!</p><p>In our “v2” data warehouse, we’ll be looking at how we take a more modular and workflow-like approach to our ELT. We’ll also examine how we can build in powerful data quality checks and anomaly detection to our ELT, so that we can be sure the data is clean enough for building and running ML models. We’ve consolidated our PII and user data to special access tables where only authorized users can view PII. A reliable real time pipeline and event driven approach to real time is something else that we’re thinking about as we evolve our data infrastructure.</p><h3>What We Learned</h3><p><strong>Sometimes you have to organize the team in non-traditional ways to meet a goal.</strong> If our analyst team and engineering team weren’t combined, the pace of adoption to our new data warehouse would have been much slower.</p><p><strong>Data sync is a difficult but solved problem.</strong> We chose a sync system like Fivetran because we calculated the cost of maintaining our own would be far greater. It’s a nice idea to have an engineer write a data sync in an afternoon. It’s a much taller order to actually maintain one over years.</p><p><strong>The cost of data warehouse as a service isn’t prohibitive.</strong> Many organizations maintain their own Hadoop or Presto clusters to use as a query engine. Using a SaaS tool like BigQuery that has the user management, UI, and scalability built in isn’t as cheap as maintaining your own but costs can be managed.</p><p><strong>And building your own can be the right solution.</strong> We built our own reporting framework even though we knew we could probably find a commercial product to do it. We intended our framework to be a stop gap that lasted 6 months, but discovered it has a much longer shelf life than 6 months. Tools like Kubernetes cron and infrastructure-as-code now enable teams to stitch tested solutions together and build a good solution vs. buy one.</p><p><strong>Data warehouses are being treated more like production systems</strong>. Data warehouses, lakes, and processes are starting to come with the expectation of reliability and timeliness. In this day and age so many businesses run on data. The more up to date and correct that data is, the easier it is to make effective and quick business decisions. Cycle time is being reduced as new technologies are harnessed to deliver data to business decision makers.</p><h3>References</h3><p><a href="https://fivetran.com/">Fivetran</a></p><p><a href="https://cloud.google.com/bigquery/">Google BigQuery</a></p><p><a href="https://pypi.org/project/dbt/">dbt data transformation tool</a></p><p><a href="https://datacrt.com/">Data CRT</a></p><p>Thanks to our data engineering team, data analytics team, and the team at Data CRT for helping to provide detail and review this post. If you’d like to learn more about working in data engineering at Hippo, go to <a href="https://www.hippo.com/careers">https://www.hippo.com/careers</a></p><p>Engineering Blog, Episode 3</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=faef0e568382" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hippo-engineering-blog/how-we-created-and-adopted-an-elt-data-warehouse-faef0e568382">How We Created and Adopted an ELT Data Warehouse</a> was originally published in <a href="https://medium.com/hippo-engineering-blog">Hippo Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Service Acceptance is Important to Hippo]]></title>
            <link>https://medium.com/hippo-engineering-blog/why-service-acceptance-is-important-to-hippo-c5ad6fa9513?source=rss----a3e32c500eb7---4</link>
            <guid isPermaLink="false">https://medium.com/p/c5ad6fa9513</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Mike Gordon]]></dc:creator>
            <pubDate>Thu, 07 Jul 2022 17:00:36 GMT</pubDate>
            <atom:updated>2022-07-07T20:21:56.061Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q3mZiQ7GBMpqMbr4cr7bjA.jpeg" /><figcaption>Photo by Dominik Lückmann URL <a href="https://unsplash.com/s/photos/ships-in-harbor?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">link</a></figcaption></figure><p>Many engineers like to write software but when it comes time to operate that software, it’s often pushed aside or not thought about until the last minute.</p><p>At Hippo Insurance, our engineering team has decided to move to a service oriented architecture. Some will call them “microservices” but we aim to not write too many services in order to keep our platform manageable. We do build other services for other purposes but the majority of our business logic resides in a small number of core services.</p><p>When we build and deploy a service at Hippo, we want to be assured that we can successfully operate that service. We want to know how it performs, be able to monitor it, and be able to fix issues quickly. We’d like to deploy the highest quality services that take the least amount of effort to maintain. This article describes how we established service acceptance criteria and how we think about operating the service from inception to shutdown. It describes different tools, techniques, and principles we use to successfully run our distributed system.</p><p>I like to use the term MOPS for service acceptance. A service should be Measurable, Operable, Predictable, and Scalable to be able to be accepted into our production environment. Here’s a quick explanation as to what each of these mean:</p><h3><strong>Measurable</strong></h3><p>We should be able to measure low-level health (e.g. CPU utilization, heartbeat), high-level health (does listing an entity returned by the service return a non-empty set?, what is the success rate of HTTP requests to that service?), and application metrics (e.g. how many times a new implementation of a feature is executed). Examples of metrics that could be included in a “measurable” requirement:</p><ul><li>Inbound HTTP request rate</li><li>Inbound HTTP request error rate</li><li>Inbound HTTP 50p/95p latency</li><li>CPU and memory utilization average for each replica of a service</li><li>Database CPU utilization, memory, available space for a service</li><li>Queue size and dead letter queue size for a system that relies on a queue to process requests</li></ul><p>I like to setup a dashboard for each service in our dashboard system of choice, <a href="https://grafana.com/">Grafana</a>, with a tile for each of these items, drawn from metrics from our real time monitoring system (we use <a href="https://prometheus.io/docs/prometheus/latest/getting_started/">Prometheus</a>).</p><h3>Operable</h3><p>We should be able to operate a service or system successfully. Operation requires an operator’s manual or run-book. For example, when we expose an HTTP interface to kick off a bulk process, the run-book should include an example request, link to an OpenAPI spec, and description of parameters and behavior. It’s also a really good idea to have a Postman or equivalent setup for all of the different endpoints that the service can handle, to be able to test instantly with the click of a button.</p><h3>Predictable</h3><p>A service/system should be predictable and reliable. We shouldn’t see large spikes in HTTP requests, queues, or CPU that are unexpected. When measured for reliability, our goal for service level objective (SLO) on services is 99.8%. Most tech companies who operate back end infrastructure shoot for reliability in the range of 99% to 99.99%, depending on their business and need to invest in a certain level of reliability.</p><p>A batch or bulk system should have a predictable ramp up, maximum rate of processing data, and predictable ramp down.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aKrRYeeIHWoSqq8sTO_KIg.png" /><figcaption>An example graph of traffic on a predictable system</figcaption></figure><p>Here is an example of a system that is less predictable. It has a huge spike of requests initially, then a long tail of unpredictable activity. It’s difficult to determine when the process will be finished and why our system hasn’t been processing the maximum throughput to make it finish more quickly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*1n6fxj4jPVGQBDvKxmy4JQ.png" /><figcaption>An unpredictable service, number of items processed</figcaption></figure><p>And here’s an example of a system that has a more predictable behavior pattern:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*-MYdpAIPfO1sHYFcIKWe0g.png" /><figcaption>A predictable service, number of items processed</figcaption></figure><p><strong>Reliable</strong></p><p>A sub-category of “Predictable”, reliable means that we can define a specific rate of unexpected or system errors that we expect from our system. The simplest way to get an error rate is to load test and simulate the level of requests that we expect in production. Sometimes test versions of our systems can’t replicate the behavior of our production systems. It’s also possible to measure reliability of a system by running a canary in production before release.</p><h3>Scalable</h3><p>A service/system should be able to scale appropriately for business needs. If we expect a bulk process to finish in 10 minutes but the maximum scaling will only meet a 2 hour time frame then the scaling is not correct for the business requirements.</p><p>Below is an example of a service that has predictable scaling, but doesn’t scale quickly enough to meet the needs of the business. Let’s assume we have a Node JS service running in production that has some basic requirements:</p><ul><li>It relays data in real time from our system to third party analytics solution</li><li>It will have traffic in bursts and will need to scale quickly</li></ul><p>We have a minimum of 2 replicas configured for this service in Kubernetes:</p><pre>replicas: 2</pre><p>But the auto-scaling settings use CPU and memory-based scaling and is limited to the 2 replicas. Since this service is handling simple HTTP requests and is single-threaded Node JS, it is unlikely to ever reach these CPU or memory limits to scale up:</p><pre>resources:<br>  limits:<br>    cpu: &quot;2&quot;<br>    memory: 2Gi<br>  requests:<br>    cpu: &quot;1&quot;<br>    memory: 1000Mi</pre><p>In this case, the service will only support the throughput handled by 2 parallel instances. We know the downstream system where we send analytics data can handle much higher throughput. The service will run much more slowly than we would need because its scaling settings aren’t set to fit the situation. This is an example where scaling for the sake of scale isn’t necessary —<strong> it’s scaling in the right way to meet the needs of the system that’s important</strong>.</p><h3>Acceptance Checklist</h3><p>To accept a service into our production environment, we have a simple checklist to cover. In addition to the MOPS guidelines we also want to make sure we agree that the service should exist, that it’s not duplicating another service, and that it doesn’t introduce new infrastructure that we’re not capable of operating. With those guidelines our checklist is:</p><ul><li>For new services, it must have an approval from our architecture review process</li><li>If new infrastructure is required for a service, it must have a design document and that document previously been reviewed by our Cloud Platform team. We don’t want to introduce MongoDB into our system if we’re already using a NoSQL database or don’t have a need for one.</li><li>If a service is adding a new external API dependency or significantly changing an existing one, it must also have an approval through our architecture review process.</li><li>Services and external (third-party) API dependencies must have metrics/monitoring in place in accordance with the measurable section of this doc.</li><li>Each new service or subsystem should have an operator’s manual/playbook upon release. That operator’s manual should describe how to investigate issues, what to do to fix problems, and who to call if a problem can’t be fixed.</li><li>Each service and subsystem should have appropriate inbound and outbound (dependency) request timeouts set. Those should be addressed in a design document and review. This helps make a service predictable.</li><li>All services, workers, and subsystems must be capable of being deployed to <strong>all</strong> environments managed by Hippo.</li><li>Each new service will have a go-live review before the staging environment release. This will be a 30 minute live meeting for our Ops/Infra teams to review this list.</li></ul><h3>Wrap it With a Bow</h3><p>Even if your organization doesn’t want to be so strict as to have a service acceptance process, writing down what you think make the right acceptance criteria can help guide an engineering team to successfully operate services. A list of requirements influences the culture of an organization to reach that goal. We spent a long time at Hippo with this list as just a suggestion, but teams started taking it seriously and were already doing these things before we decided to actually accept services to run in production.</p><p>I believe an organization can define its own service acceptance requirements, which will benefit the development of those services. There are few worse problems for an engineering org than building a service, then finding out that you can’t successfully operate it in production. Or it doesn’t meet the reliability that your organization needs. Using some of these principles can help you decide what your services need to do in production.</p><p>To try out our reliable production systems, go to <a href="https://www.hippo.com/">hippo.com</a> to get a quote for insurance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5ad6fa9513" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hippo-engineering-blog/why-service-acceptance-is-important-to-hippo-c5ad6fa9513">Why Service Acceptance is Important to Hippo</a> was originally published in <a href="https://medium.com/hippo-engineering-blog">Hippo Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Race Conditions in a Distributed System]]></title>
            <link>https://medium.com/hippo-engineering-blog/race-conditions-in-a-distributed-system-ea6823ee2548?source=rss----a3e32c500eb7---4</link>
            <guid isPermaLink="false">https://medium.com/p/ea6823ee2548</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[insurtech]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Mike Gordon]]></dc:creator>
            <pubDate>Thu, 07 Jul 2022 01:36:23 GMT</pubDate>
            <atom:updated>2022-06-23T02:13:21.574Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EWqEwFk_ISkEn3mF8mjW0Q.jpeg" /><figcaption>Photo credit: Chris Peeters</figcaption></figure><p>Imagine the following use case: A Hippo insurance customer purchased an insurance policy. After a year that policy term expires and is due for renewal. Once we inform the customer we automatically will renew a policy if the customer takes no action as a convenience to the customer. After notifying a customer 30–60 days in advance we must maintain a process to schedule and execute those automatic renewals.</p><p>At Hippo, we’ve built a distributed system and are working to refactor our monolith out to smaller services. Many of our processes still write to the same database that stores our policy data. This is the story about a race condition we encountered with our renewal process, which iterates through renewals one by one and executes the renewal. Before it saves the updated policy with the renewal, it publishes a renewal event so that other processes related to the renewal can pick up the event and act on it. One of those processes is our running Smart Home process, which updates the smart home device status for our customer for devices (“kits”) that are attached to the policy.</p><p>You’ll see some references to the database, SNS, and SQS. We use AWS RDS Postgres for our databases, SNS for pub/sub, and SQS for reliable queues. We simultaneously have a number of async processes running in our system and also have some older batch processes, such as the renewal process described here.</p><p>Our monitoring recently detected a problem with the renewals in our renewal process. About a third of our automated renewals had been failing due to a version mismatch error. This error is a protection in our policy database that stops a write from overriding a previous write to the table. It uses a version field on the record to check whether the record has changed before writing — aka “optimistic locking”. To read about optimistic vs. pessimistic locking, here’s a <a href="https://stackoverflow.com/questions/129329/optimistic-vs-pessimistic-locking">StackOverflow Article</a>.</p><p>When we see this error this means that a process has tried to write to the policy database but failed because another process wrote to the same row before the first process had a chance to save. This is usually due to a concurrency condition. In this specific case, the Smart Home process was writing a field to a policy with an ID for a renewal that hadn’t yet been created. When it wrote that field (and created the policy record), the renewal process renewal creation failed.</p><p>This possibly occurred because of a recent enhancement to our renewal process. One of our other teams recently improved the performance of the renewal process by adding indexing that made the queries for policies to renew much faster. This cut up to 2 hours of processing time off of this daily job. A renewal task that was running at 8am now may run at 6am . It’s possible that network latency is much better at 6am and the SNS publish and SQS queue + Smart Home is faster than the database save from the renewal process. An illustration is below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SXRbFEewmbeD6x_Y92iusw.png" /><figcaption>Illustration of the race condition between our renewal process and Smart Home process</figcaption></figure><p><strong>What can we do about this?</strong></p><p>Race conditions are generally hard to diagnose and solve, but if a process is failing some percentage of the time it’s often a good indicator that the cause is a race condition. There are a few ways to prevent a race condition like this:</p><ul><li><strong>Set a delay on the queue that’s receiving the message</strong> — this is a good short term fix to make the process work. Even a 1 or 2 second delay will probably provide enough buffer for the renewal to save. Long term this could be problematic because it (a) can mask other problems and (b) we may want the async part of our system to perform at a certain rate or latency. This slows it down and makes it hard to figure out why it’s slow.</li><li><strong>Have the Smart Home process check whether the policy exists before updating it</strong> — this would help prevent this case because the Smart Home process wouldn’t update the policy unless it existed. This is a relatively simple way to prevent this but doesn’t prevent this problem with updates to a policy, which does happen often.</li><li><strong>Check the current version of the policy before writing</strong> — Our SNS message has a field for version so that the subscriber has a version for optimistic locking. Doing this version check again before attempting to write to the policy would also prevent this (and cover the update case). Our billing subsystem does this when generating invoices in an async manner. The downside of this is that we put more load on the db with the extra reads.</li><li><strong>Implement the outbox pattern</strong> — The outbox pattern stores a record of the attempt to publish in a db and guarantees that the publish attempt completes. It’s more work, effort, and cost to implement. See: <a href="https://microservices.io/patterns/data/transactional-outbox.html">https://microservices.io/patterns/data/transactional-outbox.html</a></li><li><strong>Move the Smart Home save to an unrelated database</strong> — In a micro-service architecture, the Smart Home database could store the link between the policy and the Smart Home kit status. Because these transactions are in different databases, though refer to the same policy, there is no chance of collision. There are other issues like a risk of out-of-sync data but those also could be engineered out of the system. That is beyond the scope of this discussion.</li><li><strong>Publish the events after the renewal saves</strong> — this could be an option but we have many cases where it’s worse that the events aren’t published than the save failing.</li></ul><p>This is a good practical example of engineering reliability into a distributed system. We sometimes like to talk about “how many nines” our system can support and the fact that making a system 99.99% reliable is significantly more expensive than making it 99.9% reliable. By adding some of these checks we spend more time and effort to engineer our system but ultimately make it more reliable. When we talk about engineering reliability into a system, the conversations and options considered often match the list presented earlier.</p><p>Resolving this problem was a true team effort that involved a few of our software engineers. We have an on-call who is the first to be notified of failures like this. Our on-call brought in one of our more senior engineers who understands the policy renewal process. The team traced the issue to the race condition and decided to add a delay temporarily while they patched our system for one of the more permanent fixes.</p><p>If you’d like to learn more about engineering at Hippo, go to <a href="https://www.hippo.com/careers">https://www.hippo.com/careers</a></p><p>Engineering Blog, Episode 1</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea6823ee2548" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hippo-engineering-blog/race-conditions-in-a-distributed-system-ea6823ee2548">Race Conditions in a Distributed System</a> was originally published in <a href="https://medium.com/hippo-engineering-blog">Hippo Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>