<?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[dataxu.technology - Medium]]></title>
        <description><![CDATA[Notes and ideas from dataxu’s technology team - Medium]]></description>
        <link>https://medium.com/dataxutech?source=rss----e2bf46625e2b---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>dataxu.technology - Medium</title>
            <link>https://medium.com/dataxutech?source=rss----e2bf46625e2b---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 23:01:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/dataxutech" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[A/B testing (a.k.a. split-run testing) in Ad Tech— why, when & what?]]></title>
            <link>https://medium.com/dataxutech/a-b-testing-a-k-a-split-run-testing-in-ad-tech-why-when-what-8337f2c1a80d?source=rss----e2bf46625e2b---4</link>
            <guid isPermaLink="false">https://medium.com/p/8337f2c1a80d</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ab-testing]]></category>
            <category><![CDATA[advertising]]></category>
            <category><![CDATA[adtech]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[Charith Peris]]></dc:creator>
            <pubDate>Tue, 14 May 2019 13:00:45 GMT</pubDate>
            <atom:updated>2019-05-31T19:48:36.540Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Why is A/B testing important?</strong></h3><p>Advertising is money. Optimizing the spend of advertising dollars towards improving the relevant metrics is top priority for every advertiser. While programmatic advertising enables automatic optimization of a campaign toward the best possible inventory, there are still quite a few variables that the user needs to tune in order to achieve the ultimate performance.</p><p>A/B testing is the typical first-choice method when it comes to optimizing an ad campaign setup [1]. It enables users to utilize a more scientific choice when optimizing their ad spend instead of relying on guess-work. The following is a quick and easy read for a non-expert to familiarize themselves with A/B testing in the ad tech space, and an introduction on how to start testing at <a href="http://www.dataxu.com/">dataxu</a>.</p><h4><strong>How is A/B testing different to incrementality testing?</strong></h4><p>Incrementality testing is a specific flavor of A/B testing that focuses on the lift¹ of key purchase indicators as measured by the conversion rate². In general, it is a methodology used to measure the lift provided to a brand by some channel of digital advertising, versus not using that channel. It is an important tool for advertisers who need to compare the performance of their campaigns on targeted user populations against groups where their ads are not served. While the typical methodology in the industry for such a test is treatment vs. Public Service Announcement (PSA), at dataxu we offer a range of choices including a <a href="https://medium.com/dataxutech/predicted-ghost-ads-an-accurate-and-cost-effective-method-for-advertisers-to-measure-ad0068b4da1">version of Predicted Ghost Ads</a> [2] and a version of the Intent-to-Treat method that we call Audience Holdout. While incrementality testing is in itself an interesting subject, the rest of this blog post will be focused on <strong><em>general A/B testing</em></strong> or simply A/B testing for short.</p><h3><strong>When should A/B testing be used?</strong></h3><p>A/B testing is used when required to measure the performance boost that can be achieved by changing one variable in an ad campaign setup. If the first version is the one currently used (commonly referred to as control), the new version is usually modified in one aspect (commonly referred to as treatment).</p><p>The following lists several variables that are commonly used in the advertising space:</p><ul><li><a href="https://www.mbaskool.com/business-concepts/marketing-and-strategy-terms/13385-creatives.html">Creatives</a></li><li><a href="https://www.digitaland.tv/blog/what-is-tracking-pixel-ht/">Pixels</a> (or landing pages)</li><li>Algorithms (optimizing strategies)</li><li>Audiences</li><li>DMAs/regions/locations</li></ul><h3><strong>What is A/B testing?</strong></h3><p>A/B testing is a method used to measure the effectiveness of one version of a given variable against another. At dataxu, we typically run A/B tests at the flight-level. In the world of ad tech, a flight can be defined as a collection of creatives that belong to a campaign for a specific advertiser. Typically, most targeting and delivery rules are set at the flight-level. These rules include budget, impression goals, active day parts, tracking methods, dates to run, etc [3]. In order to run an A/B test, typically a copy of a test flight is created which differs only in the “single” variable that needs to be measured. As listed above, common test variables are creatives, pixels or landing pages, algorithms, audiences and regions. Once these two flights have completed their course over a specific period of time, a pre-chosen KPI is analyzed to study the performance of the variable in test (see Figure 1 for an example case). The time period chosen to run the test should be enough to obtain a significant result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1LolzmKOC-DHXM6JMSX1vw.png" /><figcaption><strong>Figure 1:</strong> This figure illustrates a simple A/B test. In order to test a new variation of a creative (in blue) vs. the original creative (in red), an A/B test is run. The available audience is split into two equivalent parts and each portion is exposed to one of the two creatives. In this toy-example, one out of four people (25% of the audience) that sees the original creative convert, while two out of four people (50% of the audience) that sees the new creative converts. This suggests that the new creative might be a better option to move forward with since it received a higher conversion rate (50%).</figcaption></figure><h4><strong>What to do before an A/B test…</strong></h4><p>One fundamental requirement of an A/B test is to ensure your two test flights are both targeting unbiased audiences. If the audience-splitting process is biased your A/B test could yield invalid results.</p><p>dataxu’s A/B testing framework enables audience splitting on a range of identifiers. With our OneView™ and graph technologies, we are able to split audiences on:</p><ul><li><strong>Households</strong> <em>(which should be the default choice for all Connected TV inventory)</em></li><li><strong>Cookies</strong></li><li><strong>Devices — </strong><a href="https://searchbusinessanalytics.techtarget.com/definition/Google-Advertising-ID">Google_ad_ids</a>; <a href="https://www.techopedia.com/definition/29032/identifier-for-advertisers-ifa-ifda">IDFAs</a>; <a href="https://www.techopedia.com/definition/29032/identifier-for-advertisers-ifa-ifda">Generic_IFAs</a></li><li><strong>People</strong> —<strong> </strong><a href="https://liveramp.com/discover-identitylink/identitylink-features/identity-graph/">LiveRamp_IDLs</a></li></ul><p>dataxu’s framework uses a hashing function applied on a selected identifier (one of the above) to separate incoming bids into treatment and control groups. This hashing function is applied in<strong><em> real-time</em></strong> on bids arriving from exchange enabling us to do real-time audience-splitting. The hashing mechanism also ensures that the identifiers that arrive in our bid-stream, and are assigned to either treatment or control, stay within the assigned group for the duration of the test. This ensures no overlap in groups and thus a fair test.</p><p><strong><em>Here is an example setup:</em></strong></p><p>Let’s say you have a new creative and wanted to test how well it would perform in comparison with an existing creative. The summary steps to execute are as follows:</p><ol><li>Create a copy of the existing flight with the exact same settings.</li><li>Setup the new flight with the new creative that you want to test.</li><li>Launch the flights to two audiences which are split using the hashing method described above.</li></ol><p>However, there are a few things to check off before you begin this test:</p><p><strong>1. Identify test variable</strong></p><ul><li>Each flight contains many variables that can be tested. Identify which one you would like to test.</li><li>An A/B test should only test one variable at a time.</li><li>In the example above, the variable is the creative.</li></ul><p><strong>2. Identify KPI</strong></p><ul><li>Identify which KPI you would like to measure ahead of setting the test. In our test involving the two creatives, we can consider using action-through-rate (ATR) as the KPI. ATR is the number of converters divided by the number of impressions served. It can reveal which creative is driving more conversions, therefore, is a good KPI to measure.</li></ul><p><strong>3. Setup a control and a treatment flight</strong></p><ul><li>All settings in both flights should be equal except for the variable you would like to test.</li></ul><p><strong>4. Determine your budget (sample size)</strong></p><ul><li>In advertising, your budget determines the number of impressions you receive and thus your sample size for the A/B test. It is important that your budget is of sufficient size to allow detection of an actual difference in the KPI between the A and B flights.</li><li>The time taken to complete the test would depend on the time taken to spend this budget.</li><li>This time can be estimated by using features such as impression-pacing and spend-forecasting, available on the platform.</li><li>In order to avoid bias due to the effects of seasonality, spend can be further regulated so that the time span would be a whole number of cycles (typically a week or multiple weeks).</li></ul><p><strong>5. Decide the split proportions and how significant your results need to be</strong></p><ul><li>First, decide how much of a change you need to see.</li><li>Next, decide the level of significance that needs to be achieved in order to consider the results valid.</li><li>For our creative example above, let’s assume that any change less than a 10% difference between treatment and control ATRs is not of use to us. Let’s also assume that you need to be 95% positive that one creative is working better than the other creative. In this case, the test should be set up with the expectation of seeing at least a 10% improvement, at 95% significance (<a href="https://www.statsdirect.com/help/basics/p_values.htm">p-value</a> &lt; 0.05). At dataxu, we provide a handy tool which enables you to tune your budget and split it in order to increase your probability to see the desired result, given the usual KPI you expect to see.</li></ul><p><strong>6. Make sure that only one test is running at a given time on any campaign</strong></p><ul><li>Tests can easily yield inaccurate results if there are multiple variables being changed. Make sure you are only running one test at a time</li></ul><p>Now we have all the information that is needed to setup and run the A/B test!</p><h4><strong>What to do after an A/B test…</strong></h4><p>Once the test is complete, you need to collect and analyze your results. In the case of dataxu, the use of a reproducible deterministic hash on the identifier to panel to A/B makes it easy to split the results for analysis. Recall the KPI that you chose prior to the test and measure its difference across the two groups. Measure the significance of your result by calculating a <a href="https://www.statsdirect.com/help/basics/p_values.htm">p-value</a> [4] for the test.<strong> </strong>Finally, if the results of the test are significant, the most important step is to <strong>make a choice. </strong>Now that you are armed with results based on an A/B test, you can make a scientific choice on how to optimize the variable you are testing. And don’t stop there. Pick the next variable you want to optimize and continue to test!</p><h4><strong>Multivariate testing</strong></h4><p>You can also set up multivariate testing which allows for many tests to run at the same time. However, please note that this will significantly lower the potential of achieving statistical significance and might not always help with the decision-making process. Even when there is a need to test multiple changes, we recommend testing a single change at a time.</p><p><em>For more information on A/B testing at dataxu, reach out to your dataxu representative.</em></p><p><strong>References:</strong></p><p><strong>[1] </strong><a href="https://en.wikipedia.org/wiki/A/B_testing"><strong>https://en.wikipedia.org/wiki/A/B_testing</strong></a></p><p><strong>[2] </strong><a href="https://medium.com/dataxutech/predicted-ghost-ads-an-accurate-and-cost-effective-method-for-advertisers-to-measure-ad0068b4da1"><strong>https://medium.com/dataxutech/predicted-ghost-ads-an-accurate-and-cost-effective-method-for-advertisers-to-measure-ad0068b4da1</strong></a></p><p><strong>[3 ] </strong><a href="https://dev.adzerk.com/docs/flights"><strong>https://dev.adzerk.com/docs/flights</strong></a></p><p><strong>[4] </strong><a href="https://www.statsdirect.com/help/basics/p_values.htm"><strong>https://www.statsdirect.com/help/basics/p_values.htm</strong></a></p><p>¹<em>Lift represents an increase in sales in response advertising.</em></p><p><em>²Conversion rate in this context means the ratio of outcomes to investment, such as product purchases per ad impression, or the number of units of an awareness increase metric (for example views or clicks) per ad impression etc.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8337f2c1a80d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dataxutech/a-b-testing-a-k-a-split-run-testing-in-ad-tech-why-when-what-8337f2c1a80d">A/B testing (a.k.a. split-run testing) in Ad Tech— why, when &amp; what?</a> was originally published in <a href="https://medium.com/dataxutech">dataxu.technology</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Predicted Ghost Ads: An accurate and cost-effective method for advertisers to measure…]]></title>
            <link>https://medium.com/dataxutech/predicted-ghost-ads-an-accurate-and-cost-effective-method-for-advertisers-to-measure-ad0068b4da1?source=rss----e2bf46625e2b---4</link>
            <guid isPermaLink="false">https://medium.com/p/ad0068b4da1</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[ab-testing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[advertising]]></category>
            <dc:creator><![CDATA[Charith Peris]]></dc:creator>
            <pubDate>Thu, 06 Dec 2018 19:26:24 GMT</pubDate>
            <atom:updated>2018-12-08T17:06:15.291Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Predicted Ghost Ads: An accurate and cost-effective method for measuring incrementality</strong></h3><p>Incrementality testing measures the impact of advertising spend on the conversion rate¹ of a test campaign. When measuring incrementality, advertisers need to compare the performance of their campaigns on targeted user populations, against control groups where their ads are not served. In a typical setting, the campaign serves actual ads to users in treatment while PSAs (Public Service Announcements) are substituted for the control group. However, there are several issues that arise with this method. To learn more about these issues as well as a new method for measuring incrementality for advertisers, read more below.</p><h3>Uncovering issues with PSA-based incrementality testing</h3><p>There are many issues with the traditional method for incrementality testing which advertisers should keep in mind. First, in order to achieve statistical significance, the advertiser needs a significantly large control group. Since advertisers are paying for both the ads served in their campaign as well as the PSA ads served to the control group, this can be added cost which advertisers are unwilling to take on. Second, PSA-based incrementality testing becomes inaccurate when advertisers use performance-optimizing computer algorithms to deliver ads. This is because the algorithms will target the PSA ads in control to people who are more likely to interact with the PSA ad. This population is most likely not the same population who is interested in the ads launched by the test campaign.</p><h3>Predicted Ghost Ads: Why is it better?</h3><p>There is another method advertisers should consider when executing incrementality testing: Predicted Ghost Ads. Predicted Ghost Ads [1] offers a couple of major advantages that are attractive and beneficial to advertisers:</p><ul><li><strong><em>Entire budget is available for advertiser’s ads:</em></strong> The Predicted Ghost Ads method doesn’t serve ads to the control set at all, meaning that there is no cost to measure control responses. Once a would-be-bid in the control set is recorded, an alternate ad can be served in place of the campaign in test, thus not losing the bidding opportunity.</li><li><strong><em>Works on performance-optimized campaigns: </em></strong>In campaigns which optimize towards a certain audience, PSAs might fail due to the targeting algorithm being biased toward a different audience profile. Predicted Ghost Ads would be immune to this issue.</li></ul><h3>Predicted Ghost Ads: How does it work?</h3><p>The Predicted Ghost Ads method doesn’t serve ads to the control group at all; it simply records all bids which would have been served. One of the core functions of this methodology is choosing a set of bids as “would-be-impressions”, from the recorded control group bids. This is achieved using a simulated auction (see Section 4 in [1]). At <a href="https://www.dataxu.com/">dataxu</a>,<strong> </strong>this simulated auction is implemented by training a recall-optimized machine-learning model on the bid and impression data from the treatment group. A recall-optimized model focuses on making sure that a majority of the impressions are predicted correctly rather than purely the accuracy with which it predicts the impressions and non-impressions. By “recalling” most impressions in this way, it helps the test capture more conversions within the relevant population in treatment and control, and in turn helps achieve significance.</p><p><strong>Figure 1</strong> shows a flow chart of the predicted ghost ads process. <strong>(1) </strong>As bid opportunities arrive from exchanges, the flights in the test campaign bid on the dataxu internal auction according to recommendations based on the dataxu bidding engine. If the flight wins, the ID relevant to the bid opportunity (either at cookie level or household level) is marked as falling in either the treatment or control group by leveraging a hashing function. The hashing function ensures that an ID which reappears will always be marked to the same group. <strong>(2)</strong> If in treatment, the ad is served. Both bids and actual impressions are recorded. If in control, the bid is recorded but the ad is not served. <strong>(3)</strong> A machine-learning model is then created using the treatment bid and impression data to predict impressions with high recall. <strong>(4)</strong> This model is run on the recorded bids from both treatment and control in order to obtain predicted impressions in both sets. Any small errors in the model will be shared by both groups and thus a fair comparison is achieved. <strong>(5)</strong> Actual conversion events within the predicted treatment and control impressions is calculated. <strong>(6)</strong> The lift is calculated across these conversion events. It is then scaled by the probability that a predicted impression is an actual impression, which is calculated using the treatment data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ot6pqETHdcU8RdU7umET8w.png" /><figcaption><strong>Figure 1: Predicted ghost ads as implemented at dataxu</strong></figcaption></figure><h3><strong>Results</strong></h3><p><strong>Table 1</strong> shows preliminary results for a campaign in test. We use a two-proportion z-test to compare the conversion rates in treatment and control. A small <a href="https://www.statsdirect.com/help/basics/p_values.htm">p-value</a> (typically p &lt; 0.05) indicates strong evidence against the null hypothesis, which in this case is the conversion rates being equal.</p><p>The results show Tactic 2 to be performing well in treatment while a significant lift is not observed in Tactic 1 (see <strong>Figure 2</strong>). This suggests that Tactic 1 should be tuned up and retested or its budget could be diverted to the more successful Tactic 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VCf657yqf9BoZ3YdMfX0kw.png" /><figcaption><strong>Table 1:</strong> Predicted Ghost Ads preliminary results for a campaign in test</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kC5H0K9EXTq4ol8UBU7SeQ.png" /><figcaption><strong>Figure 2:</strong> Difference in Conversion Rates in Treatment and Control for each tactic</figcaption></figure><p>Overall, using the Predicted Ghost Ads methodology over the traditional PSA-based incrementality test allows the advertiser to measure incrementality for their campaigns in a more accurate and cost-effective manner. The implementation of this tool expands the state-of-the-art in the dataxu A/B testing framework and, as always, enables more accurate and data-driven decision-making for advertisers using the platform. If you’re interested in learning more about this methodology, reach out to your dataxu representative.</p><h4><strong>References</strong></h4><p>[1]<a href="https://courses.cit.cornell.edu/jl2545/adpapers/Randall%20Lewis.pdf"> Johnson et al. 2015</a></p><p>¹<em>Conversion rate in this context means the ratio of outcomes to investment, such as product purchases per ad impression, or the number of units of an awareness increase metric (for example views or clicks) per ad impression etc.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad0068b4da1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dataxutech/predicted-ghost-ads-an-accurate-and-cost-effective-method-for-advertisers-to-measure-ad0068b4da1">Predicted Ghost Ads: An accurate and cost-effective method for advertisers to measure…</a> was originally published in <a href="https://medium.com/dataxutech">dataxu.technology</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Synchronizing Data Pipelines]]></title>
            <link>https://medium.com/dataxutech/synchronizing-data-pipelines-93443b501a4a?source=rss----e2bf46625e2b---4</link>
            <guid isPermaLink="false">https://medium.com/p/93443b501a4a</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-pipeline]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[big-data]]></category>
            <dc:creator><![CDATA[Javier Buquet]]></dc:creator>
            <pubDate>Wed, 13 Jun 2018 13:37:49 GMT</pubDate>
            <atom:updated>2018-06-13T13:37:49.106Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*NjHaL5EtJDIHY7SF7mewlw.png" /></figure><p>Are you finding it hard to synchronize processes that read and write data on a data lake?</p><p>Are your solutions overly complex?</p><p><strong>If you answered yes to these questions, there is a simple pattern we use at </strong><a href="https://www.dataxu.com/"><strong>dataxu</strong></a><strong> that can help. It gets the work done with minimal overhead.</strong></p><p>The Data Science Engineering team at dataxu spends most of its’ day designing, developing, and maintaining a wide range of data pipelines that support our AI-based bidding system.</p><p><strong>A pipeline is a set of stages (or sub-processes) that process input data producing an output, in which the output of each stage serves as the input for the subsequent stage</strong>; thus creating a chain of stages that modify a given input to produce a desired output. In particular, a data pipeline can be defined as the process or pipeline of processes that move, join, format, and process data in a system. And a good data pipeline should do so in an automated and reliable way, with minimum — or, ideally, no — human intervention.</p><p>In the case of systems with the scale and complexity of dataxu’s platform, TouchPoint, it’s common to have many different data pipelines — each having a particular goal or role in the whole system — that need to interact. Let’s say we have a dataset with all the ads we’ve shown to different users and another dataset with all the clicks the users have made. We want to have two pipelines that “clean” both datasets independently, and then use the output of those pipelines to study which ads were effective.</p><p>Given all these interactions, it’s very important that we have a robust mechanism, or protocol, for synchronizing the data between the different pipelines. I.e. making sure we provide the correct input to each pipeline based on the output of its predecessors.</p><h3>Defining a synchronization protocol</h3><p>An acceptable first approach to this problem could be to run each of the predecessors for a given pipeline on each run keeping the results in the program’s memory, and therefore have all the necessary data available right away. Of course, this method is immediately hindered by a number of drawbacks such as:</p><ul><li>Not being able to reuse an intermediate result in case we need to re-run a pipeline (which usually makes things a lot more difficult to debug too)</li><li>Doing duplicate work when different pipelines have shared predecessors</li><li>Not being able to fully de-couple a given pipeline from its predecessors (for example, implementing them using different languages or technologies).</li></ul><p>Another approach could be to implement every pipeline independently of its predecessors and agree on a location in which each pipeline will drop its final results (so that they can be picked up by any other pipeline).</p><p>For example, let’s say we agree that <em>Pipeline A</em> will drop its results in <em>Location A</em>, so that <em>Pipeline B</em> knows that it should look for its input in such location. Each time <em>Pipeline A</em> runs, it must make sure it cleans its drop location (remove any previous results) and then store the new results in the same place.</p><p>This is, in many ways, better than our previous approach, but still not ideal as we don’t keep a history of the various pipelines’ results (which might be useful in some other moment or for some other pipeline). Nor does a pipeline have a way to differentiate complete results from partial results. Imagine the case in which <em>Pipeline B</em> starts running before <em>Pipeline A </em>has finished storing its results.</p><blockquote>By the way, this is a simple example of what we call <a href="https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-170-laboratory-in-software-engineering-fall-2005/lecture-notes/lec18.pdf">“the blackboard” architectural pattern</a>. The main idea is that<strong> we define “a blackboard” in which each “producer” (in this case a predecessor pipeline) writes down its results so that any “consumer” can pick it up at any given time that it needs to.</strong> In our case, we usually use <a href="https://aws.amazon.com/s3/">Amazon S3</a> as “the blackboard” and each pipeline defines a specific location for its results within the service, which is then shared with pipelines that need its output as input.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HFg_GCVNPTOkbXf5Vw3Duw.png" /></figure><p>So, how can we define a synchronization protocol in which we address or mitigate each of the drawbacks of the two approaches mentioned above?</p><h3>The File Feed</h3><p>We developed our own synchronization protocol for data pipelines, and named it the <strong>“File Feed”.</strong> This protocol is no more than a set of conventions that make it possible for a data pipeline to store its results in a way that any other pipeline can synchronize with it — i.e. use its output (and the correct output at any given moment in time) as input.</p><p>In order to comply with this protocol, a data pipeline must:</p><ul><li>Define a location for the feed</li><li>Upload results following the “new update convention”</li><li>Add an “update manifest” when the uploading of results is complete</li></ul><h4>Feed Location</h4><p><strong>To comply with the File Feed protocol, a data pipeline first declares a location in which it will store its results</strong>. An example of this location when using Amazon S3 as the blackboard could be <em>s3://my-bucket/my-prefix/</em>. A data pipeline also normally declares a current version, which, if available, will be used as the suffix for the location, resulting in something like <em>s3://my-bucket/my-prefix/v2.1/</em> as the full path to a feed. <strong>This is where the data pipeline should store its results, so that another pipeline can retrieve them and use them as input.</strong></p><h4>New Update Convention</h4><p><strong>Each time a data pipeline creates a new update in the feed — i.e. uploads a new set of results — the timestamp of creation of the update is recorded and used as the prefix for the path in which the result files are stored.</strong></p><p>For example, if we were to create a new update on May 16th 2018 at midday in a feed with location <em>s3://my-bucket/my-prefix/v2.1/</em>, then the results should be uploaded to <em>s3://my-bucket/my-prefix/v2.1/20180516.120000/</em>. This way we can keep a history of updates (or data pipeline run outputs) and still have a way to distinguish which is the latest, and to what specific moment in time those results belong to.</p><h4>Update Manifest</h4><p>Lastly, a <strong>data pipeline complying with the File Feed protocol should mark the created updates as complete when the upload of results is done</strong>. This is done by creating a file with name <em>_SUCCESS,</em> which should have as its content the number of files uploaded in the update — e.g. if we create an update and upload three files containing the results to it, then the <em>_SUCCESS</em> file’s content should be just <em>“3”</em> — and helps to distinguish those updates that are complete from those that are still being uploaded.</p><blockquote><strong>Note:</strong></blockquote><blockquote>If our “blackboard” is an <a href="https://en.wikipedia.org/wiki/Eventual_consistency">“eventually consistent”</a> data store — such as Amazon S3 — it is important that we include the number of files in the update as there is a chance that a consumer will only see a subset of the uploaded results even if the update is marked as complete by the producer.</blockquote><blockquote>If you don’t know what eventual consistency means, I would suggest you also take a look to the <a href="https://en.wikipedia.org/wiki/CAP_theorem">CAP theorem</a> to see why a distributed data store would make this tradeoff.</blockquote><p>This mechanism also comes in handy when there is the need to “invalidate” an update. One can either remove the <em>_SUCCESS</em> file or add an empty file to the update, and that would cause the update to fail to be considered as valid when being consumed.</p><h3>How To Use It</h3><p>Let’s say we want to use the File Feed to synchronize the three pipelines in the example described at the beginning of this post, the pipeline that cleans the ads shown to users, the one that cleans the ads clicked by users, and the one that uses the results’ from both to calculate the effectiveness of ads shown.</p><h4>Defining A Pipeline</h4><p>First, we need to define each pipeline and define a location for each pipeline’s result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LCaa90INn82l_s1eYoRWKw.png" /></figure><h4>Storing New Results</h4><p>Each time a pipeline needs to store new results, it should:</p><ol><li><strong>Create a new prefix inside the pipeline’s defined location with the current timestamp as name</strong> — i.e. in the case of the “Clean Ads Shown To Users” pipeline, if we were to store results for the ads shown to users on date <em>2018–05–20</em> and we were creating this update at <em>2018–05–21 16:00:00</em> we should create a new prefix <em>s3://my-bucket/ads-shown-to-users/v1.0/2018–05–20/20180521.160000/</em> in which we will store our results.</li><li><strong>Upload the results to the created prefix — </strong>i.e. If we had our results split into 3 partial csv files, we would upload them to <em>s3://my-bucket/ads-shown-to-users/v1.0/2018–05–20/20180521.160000/part-1.csv, </em><em>s3://my-bucket/ads-shown-to-users/v1.0/2018–05–20/20180521.160000/part-2.csv, </em><em>s3://my-bucket/ads-shown-to-users/v1.0/2018–05–20/20180521.160000/part-3.csv</em></li><li><strong>Upload the update manifest to the created prefix — </strong>i.e. In this case we should upload a new file with name <em>_SUCCESS</em> and content “3” to <em>s3://my-bucket/ads-shown-to-users/v1.0/2018–05–20/20180521.160000/_SUCCESS</em></li></ol><h4>Retrieving Results</h4><p>When a pipeline <em>A</em> needs to retrieve results from some other pipeline <em>B</em>, it should:</p><ol><li><strong>Get all the existing prefixes in pipeline <em>B</em>’s location — i.e.</strong> We should list all the prefixes in <em>s3://my-bucket/ads-shown-to-users/v1.0/2018–05–20/</em></li><li><strong>Sort these prefixes by their name,</strong> which is actually the timestamp in which they were created, in descending order</li><li><strong>Check whether the latest update can be considered valid</strong> by making sure the content of the <em>_SUCCESS</em> file matches the actual number of files in the update</li><li>Download all files in the latest valid update found</li></ol><h3>Simple data pipeline synchronization</h3><p>By implementing this protocol, it makes it very easy to synchronize data pipelines, and has proven to be very effective for our use case.</p><p>The fact that no additional components are required for tracking the outputs, or state, of different pipelines — such as a database containing the path to the latest results produced by a pipeline or a hive metastore — makes this solution a lot simpler than other approaches. And at the same time it is much easier to perform tests or human exploration of the data.</p><p>Versioning the feeds, even though not an enforced item in the protocol declaration (and instead is just part of the feed location definition), has also proven to be very effective in our case by protecting dependent pipelines from changes in the data definition contract of some of its predecessors until the pipeline is appropriately adapted.</p><p><em>Let us know if you found this post interesting and helpful, and if you use a different approach to deal with this same problem!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93443b501a4a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dataxutech/synchronizing-data-pipelines-93443b501a4a">Synchronizing Data Pipelines</a> was originally published in <a href="https://medium.com/dataxutech">dataxu.technology</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 write a custom Spark Classifier: Categorical Naive Bayes]]></title>
            <link>https://medium.com/dataxutech/how-to-write-a-custom-spark-classifier-categorical-naive-bayes-60f27843b4ad?source=rss----e2bf46625e2b---4</link>
            <guid isPermaLink="false">https://medium.com/p/60f27843b4ad</guid>
            <category><![CDATA[naive-bayes]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Máximo Gurméndez]]></dc:creator>
            <pubDate>Mon, 23 Apr 2018 20:12:38 GMT</pubDate>
            <atom:updated>2018-04-23T20:12:37.963Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*W9plQwqU2uScm2iggvi9Og.png" /></figure><p>Last week, <a href="https://medium.com/dataxutech/why-write-your-own-spark-classifier-27363960dc88">we took a look at a few reasons why you would want to write your own Spark Classifier/Estimator</a>. And now that you’ve decided to move forward, <strong>let’s take a look at how to write your own Spark Classifier</strong> by going over the implementation of a flavor of <a href="https://en.wikipedia.org/wiki/Naive_Bayes_classifier">Naive Bayes</a> for binary classification over categorical features. As opposed to the standard Spark <a href="https://spark.apache.org/docs/2.2.0/mllib-naive-bayes.html">implementation</a>, this version does not need additional stages for feature encoding into numerical vectors, making it much faster to train.</p><p><a href="http://dataxu.com/">dataxu</a> bids on ads in <a href="https://en.wikipedia.org/wiki/Real-time_bidding">real-time</a> on behalf of its customers, and trains on past bids to optimize for future bids. <strong>Our system trains thousands of advertiser-specific models and has multi-terabyte datasets.</strong> Hence, we need to consider both model performance and cost of training. We always choose the model with the highest performance, but for a given performance level, we need to pick the classifier that minimizes training time (and prediction time, but that’s a topic for another blog post).</p><p>For our case, the custom implementation we’ll describe, which we’ll call <strong>Categorical Naive Bayes</strong>, has similar model performance (using <a href="https://en.wikipedia.org/wiki/Receiver_operating_characteristic">ROC AUC</a> as metric) to the standard Naive Bayes implementation that comes with Spark. However, to achieve that parity, <strong>we had to add some additional stages of feature engineering to Spark’s Naive Bayes, such as numerical encoding from categorical features, and attribute selection. </strong>This slows down the trainer as it implies several more passes through the dataset.</p><p><em>Full disclosure, we didn’t end up using this new implementation in production, and chose mostly tree-based algorithms due to model performance reasons. That said, </em><strong><em>Categorical Naive Bayes is 3X faster than Spark Naive Bayes and 10X faster than Spark Random Forest Bayes</em></strong><em> for our real time bidding training data, in which most features are categorical.</em></p><blockquote>Recap on Spark Pipeline Concepts:</blockquote><blockquote>A Spark ML <a href="https://spark.apache.org/docs/2.2.0/ml-pipeline.html">pipeline</a> consists of a series of stages. Each stage can be a Transformer or an Estimator. Transformers apply a well defined transformation on a dataset while Estimators have the added capability of producing Models by traversing the dataset. NaiveBayes and StringIndexer are example of Estimators while VectorAssembler and OneHotEncoder are examples of Transformers. Models in turn are transformers because they can provide predictions for all elements in a dataset as a transformation.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/0*dgxAS87ieixTH-Vd." /></figure><h3>Comparing Spark Naive Bayes to Categorical Naive Bayes</h3><p>Spark Naive Bayes assumes a feature layout mostly used in<a href="https://nlp.stanford.edu/IR-book/pdf/12lmodel.pdf"> language models</a> (e.g. multiple Bernoulli or Multinomial models) where the<strong> value of a feature indicates the presence or strength of that term (column) within the document (row)</strong>. Hence, one needs to use techniques such as one-hot-encoding to run a Naive Bayes algorithm on top of categorical features, and some sort of feature selection to avoid having too many features. A typical pipeline would be:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac1c57297a9a2558d2be17fe1066b380/href">https://medium.com/media/ac1c57297a9a2558d2be17fe1066b380/href</a></iframe><p>Note that we have two string indexers in this sample pipeline. At the time of this writing, Spark is not smart enough to realize that those two stages could be parallelized and, thus, we pay the cost of traversing the data twice before we submit it to the classifier. In order to avoid this, <strong>our implementation computes the conditional probabilities for all categories in a single pass. These conditional probabilities are sufficient to make predictions on a dataset.</strong></p><p>For each categorical value of a feature, we need to compute the conditional probability by counting the number of positive and negative instances. As you can imagine, <strong>features with extremely high cardinality might blow up the memory of the executors.</strong> For this reason we use the <a href="https://github.com/addthis/stream-lib">stream-lib</a> library which calculates the top-k elements and their frequency on a stream of data, following the ideas from Metwally, Agrawal, and Amr Abbadi (<a href="http://link.springer.com/chapter/10.1007/978-3-540-30570-5_27">Efficient computation of frequent and top-k elements in data streams</a>).</p><h3>A typical usage of CategoricalNaiveBayes is:</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/33f36dd4354a6e7f0d0cf593d6482a8c/href">https://medium.com/media/33f36dd4354a6e7f0d0cf593d6482a8c/href</a></iframe><p>Note that it just needs the feature names as input as well as the max number of category values that we can keep in memory for every feature. All is done with a single stage.</p><blockquote>Using top-k here might be a good or bad idea depending on how the features are distributed on your dataset. We found that it typically works great, but users should do the proper feature exploration before applying it. For example, if instances with positive labels occur across a long tail of infrequent values (larger than k), it’s possible the performance of the classifier is degraded.</blockquote><h3>Implementation of Categorical Naive Bayes</h3><p>To implement an Estimator in Spark, you need to <strong>extend the Estimator trait and implement the fit() function to return a Model</strong>. This model should have as data structures everything that is needed to calculate predictions on a dataset (in our case, the conditional probabilities).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab2c1dcd4035b679146c27b3dca2836a/href">https://medium.com/media/ab2c1dcd4035b679146c27b3dca2836a/href</a></iframe><p>To implement the fit() function, we traverse the dataset once and use Spark <a href="https://spark.apache.org/docs/2.1.0/api/java/org/apache/spark/util/AccumulatorV2.html">Accumulators</a> to compute the conditional probabilities for each category value. These accumulators have a <a href="https://github.com/addthis/stream-lib/blob/master/src/main/java/com/clearspring/analytics/stream/StreamSummary.java">StreamSummary</a> as underlying data structure that counts the frequencies of the top-k elements on a stream. The fit function returns a Categorical Naive Bayes Model which we initialize by providing the smoothed conditional probabilities using the simplest Laplace smoothing.</p><p>To implement the Categorical Naive Bayes Model we can extend Spark’s class <a href="https://github.com/apache/spark/blob/master/mllib/src/main/scala/org/apache/spark/ml/classification/ProbabilisticClassifier.scala">ProbabilisticClassificationModel</a> which implements all the necessary methods, including the transform() method. You need to specify how to compute predictions given one row of data. We do this by overriding the methods predictRaw(Seq[String]) and raw2probabilityInPlace(Vector). This first method is responsible for computing a raw score for a row of data. Basically, it returns the unnormalized probability using the standard Naive Bayes calculation and the log-sum-exp trick. The second method, raw2probabilityInPlace, just normalizes the probabilities.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ecd2f47729faf23cced6f7373b64e343/href">https://medium.com/media/ecd2f47729faf23cced6f7373b64e343/href</a></iframe><h3>How to use the Categorical Naive Bayes</h3><p>We provide the source code for Categorical Naive Bayes on our dataxu github <a href="https://github.com/dataxu/spark-ext">repository</a>. <strong>To use it on your application, you can just build the jar, attach it to your Spark application, and import the class.</strong> To build the Categorical Naive Bayes from source, you can clone the repository on your computer:</p><p><a href="https://github.com/dataxu/spark-ext">https://github.com/dataxu/spark-ext</a></p><p>Then build the sources with Apache Maven by running the console command:</p><p><em>mvn clean install</em></p><p>This creates a jar file in the spark-ext/target directory called spark-ext-0.0.1.jar (or similar).</p><p>To get started, you can use the Spark Shell to run a toy example. First download this sample trainer.scala file from gist</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/984f484f584667854a4afa2986527e85/href">https://medium.com/media/984f484f584667854a4afa2986527e85/href</a></iframe><p>This trainer file will create a dataset on-the-fly, train a model, and show the predictions. To invoke it, run the spark-shell by providing the location of the jar file and the trainer.scala script file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ac25616d34c30e6708ad803e52b5f58/href">https://medium.com/media/4ac25616d34c30e6708ad803e52b5f58/href</a></iframe><h3>Writing your own Spark classifier</h3><p>It’s fairly simple to write your own Spark Classifier if you know your way around the Spark ML classes and scala’s type system. Naive Bayes is one of the simplest algorithms to implement and we provide such code for exploration, fixes, and enhancements. Also, those interested in using it for categorical features might find it handy. Writing your own Spark classifier may be useful for when you have a very specific algorithm or when you can relax some constraints of a generic algorithm to make it more performant by some criteria.</p><p>Want to learn more about why you might want to write your own Spark Classifier? Check out the first blog in this series <a href="https://medium.com/dataxutech/why-write-your-own-spark-classifier-27363960dc88">here</a>.</p><p><em>Please post your feedback in the comments — have you written a custom Spark estimator? What was your method? If you found this post useful, please feel free to “applause” and share!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60f27843b4ad" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dataxutech/how-to-write-a-custom-spark-classifier-categorical-naive-bayes-60f27843b4ad">How to write a custom Spark Classifier: Categorical Naive Bayes</a> was originally published in <a href="https://medium.com/dataxutech">dataxu.technology</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why write your own Spark Classifier?]]></title>
            <link>https://medium.com/dataxutech/why-write-your-own-spark-classifier-27363960dc88?source=rss----e2bf46625e2b---4</link>
            <guid isPermaLink="false">https://medium.com/p/27363960dc88</guid>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Máximo Gurméndez]]></dc:creator>
            <pubDate>Mon, 16 Apr 2018 17:25:38 GMT</pubDate>
            <atom:updated>2018-04-30T16:50:07.608Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*t-kDBFwySYoyBftko31Qow.png" /></figure><p>You may be asking yourself, why write your own <a href="https://spark.apache.org/">Spark</a> Classifier? The most obvious reason is <strong>to craft your own <em>secret-sauce</em> model outside of Spark </strong>and integrate it into a Spark pipeline. However, nowadays, with the array of available algorithms and feature engineering tools, this is rarely a necessity.</p><p>Other cases exist for which you’d want to consider writing your own Classifier, such as <strong>when you need a very efficient, simple, or relaxed algorithm and the nature of your dataset does not merit a more powerful machine learning Classifier</strong>. (The next blog post in this series “How to write a custom Spark Classifier: Categorical Naive Bayes” for a case will cover this very scenario.)</p><p>To illustrate the fact that there are certain situations for which your simplest or relaxed algorithm can work just as well as a more complex one, we created a synthetic dataset generator capable of customizing a dataset in different ways (number of features, cardinality, label imbalance, etc). With the synthetic dataset, we varied the average cardinality of features and recorded the different values of ROC AUC for CategoricalNaiveBayes and Spark’s RandomForest in the graph below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/0*FHnW7srwAIiAS8lL." /></figure><p>Note how, for the lower cardinality values, both algorithms perform just as well. RandomForest seems more robust to increased cardinality.</p><p>We also considered varying the frequency with which we witness a positive label. See in the chart below how, beyond a certain threshold, the performance of Naive Bayes and Random Forests are similar. However, for datasets with greater imbalance, the performance of Naive Bayes drops dramatically (as expected).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/0*A7vzSpOMXzd7VwvE." /></figure><p>A similar occurrence happens when increasing the number of features in the dataset, as can be seen in the plot below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/0*Y3sbVB7Mk5wCgggU." /></figure><p>We varied some other properties of the dataset and made similar experiments. Completing such an exercise is useful to determine the return on investment (ROI) for the algorithm. In our example, Random Forests are particularly slow, and hence expensive, for categorical values — as the underlying decision trees have an explosive number of binary split candidates. If under a specific scenario, both algorithms have similar predictive power, we might as well pick the algorithm that is most efficient in terms of training time, or even the simplest to understand.</p><h3>So when should you choose to write your own Spark Classifier?</h3><p>Writing your own Spark classifier may be useful for when you have a very specific algorithm or when you can relax some constraints of a generic algorithm to make it more performant by some criteria without necessarily affecting the predictive power. Such is the rationale for implementing a Categorical Naive Bayes, which we will cover extensively in the second post of this series.</p><p>Considering this return on investment for Classifiers becomes very relevant when one needs to train thousands of models across many terabytes, like <a href="http://dataxu.com/">dataxu</a> does on a daily basis. If you’ve determined that writing your own Spark Classifier is the path for you, check back next week to learn <a href="https://medium.com/dataxutech/how-to-write-a-custom-spark-classifier-categorical-naive-bayes-60f27843b4ad">how you can write a custom Spark Classifier using Categorical Naive Bayes</a>.</p><p><em>Please post your feedback in the comments — Do you frequently consider the ROI of the Classifier when working with Big Data? If you found this post useful, please feel free to “applause” and share!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27363960dc88" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dataxutech/why-write-your-own-spark-classifier-27363960dc88">Why write your own Spark Classifier?</a> was originally published in <a href="https://medium.com/dataxutech">dataxu.technology</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Separation of metadata and data: Building a cloud native warehouse, Part 3]]></title>
            <link>https://medium.com/dataxutech/separation-of-metadata-and-data-building-a-cloud-native-warehouse-part-3-72680d1d97f2?source=rss----e2bf46625e2b---4</link>
            <guid isPermaLink="false">https://medium.com/p/72680d1d97f2</guid>
            <category><![CDATA[metadata]]></category>
            <category><![CDATA[warehouse]]></category>
            <category><![CDATA[cloud-native]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[big-data]]></category>
            <dc:creator><![CDATA[Dong Jiang]]></dc:creator>
            <pubDate>Fri, 16 Mar 2018 18:17:47 GMT</pubDate>
            <atom:updated>2018-03-16T18:17:46.654Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*4LMX7zgn09lXFFXI_F3X3w.png" /></figure><p><em>This is part 3 of a series of blogs on </em><a href="https://www.dataxu.com/"><em>dataxu</em></a><em>’s efforts to build out a cloud-native data warehouse and our learnings in that process. You can find part 1 </em><a href="https://medium.com/dataxutech/dataxus-journey-from-an-enterprise-mpp-database-to-a-cloud-native-data-warehouse-part-1-e36952d87a1f"><em>here</em></a><em> and part 2 </em><a href="https://medium.com/dataxutech/dataxus-journey-from-an-enterprise-mpp-database-to-a-cloud-native-data-warehouse-part-2-8f2a807feb0b"><em>here</em></a><em>.</em></p><p>There have been many discussions in the industry on the <a href="https://www.qubole.com/blog/advantage-decoupling/">separation of compute and storage</a>. In this post, we will do an in-depth exploration on the less discussed separation of metadata and data.</p><p>Here at <a href="https://www.dataxu.com/">dataxu</a>, to say we handle a lot of data is an understatement. But in our daily dealings with data and its metadata, we began to explore the topic, and potential advantages, of separating metadata from data.</p><p>Below, we will review how metadata is handled in a traditional database vs <a href="https://www.dataxu.com/">dataxu</a>’s cloud warehouse, discuss design patterns and high-level implementation, and take an in-depth look at the benefits of decoupled metadata. <strong>But before we dig in, let’s start at the beginning — what exactly is metadata?</strong></p><h3>What is metadata?</h3><p>In the most basic sense, <a href="https://en.wikipedia.org/wiki/Metadata">metadata</a> describes the structure of the data, like name for table/column/partition, datatype, and ordering.</p><p><strong>In almost all traditional databases, the metadata exists as a catalog.</strong> In Oracle, there are <a href="https://docs.oracle.com/cd/E11882_01/nav/catalog_views.htm">catalog views</a>, such as USER, ALL, and DBA views. In Postgres, there are <a href="https://www.postgresql.org/docs/current/static/information-schema.html">information_schema</a> and <a href="https://www.postgresql.org/docs/current/static/catalogs.html">pg_catalog</a>. With such catalogs, it is always possible to find answers to the following questions:</p><ul><li>What are the schemas in the database?</li><li>What are the tables and views in each individual schema?</li><li>What are the columns in each individual table, (like data_type, ordinal_position, nullability, etc.)?</li><li>What are the constraints declared in the table?</li><li>What are the partitions in tables?</li><li>What are the <a href="https://en.wikipedia.org/wiki/User-defined_function">UDFs</a> in the database?</li></ul><p>In a cloud-based warehouse, like our’s here at <a href="https://www.dataxu.com/">dataxu</a>, <a href="https://cwiki.apache.org/confluence/display/Hive/AdminManual+MetastoreAdmin">Hive Metastore</a> provides similar functionality. Either installed as a hive component backed by an aurora database or as a Glue Data Catalog, we can manipulate the catalog via <a href="https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DDL">Hive DDL</a>. Beyond the obvious similarities and limitations (for example, Glue Data Catalog does not support views or UDFs yet), there is a significant distinction.</p><p>In traditional databases, the metadata and data is tightly coupled. <strong>You cannot have data without metadata.</strong> The pattern is “create-validate-insert”. Consider a typical database development process:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/69ad532b5a70d53bc7b5a3afe5100a25/href">https://medium.com/media/69ad532b5a70d53bc7b5a3afe5100a25/href</a></iframe><p>However, in the cloud warehouse, the metadata and data are separated. <strong>Data can exist independently on the S3.</strong> This means:</p><ul><li><strong>It is possible to have data but no metadata</strong>, i.e., no associated table definition in a data catalog. You might not think this is a very interesting use case. If you don’t have definition, how can you query? However, this point proves to be useful in cases of data corruption handling. We will explore this use case more in depth below.</li><li><strong>It is possible to have data associated with one or more tables.</strong> This is interesting. A data set can be defined as a table while at the same time be incorporated as a partition in another table. It all depends on the use case.</li><li>More commonly, we can have data generated first, validated, and then make it available in a data catalog to support additional processing.</li></ul><p>Why is this separation of metadata and data crucial? Let’s take a look at two critical and interlinked issues, <strong>transaction and data validation</strong>.</p><h3>ACID and transaction are difficult</h3><p>Database theories would emphasize <a href="https://en.wikipedia.org/wiki/ACID#Atomicity">ACID</a> — atomicity, consistency, isolation, and durability — properties:</p><p><strong>Atomicity: </strong>requires that each transaction be “all or nothing”, either at single statement level or multi-statement level.</p><p><strong>Consistency:</strong> ensures that any transaction will bring the database from one valid state to another, the data must satisfy all declared database level constraints.</p><p><strong>Isolation:</strong> ensures that the concurrent execution of transactions results in a system state that would be obtained if transactions were executed sequentially, most common level is read committed.</p><p><strong>Durability:</strong> ensures that once a transaction has been committed, it will remain so.</p><p>Fortunately, or sadly, depending on your perspective, <strong>Consistency</strong> is the first ACID property to relax for warehousing and <a href="https://en.wikipedia.org/wiki/Extract,_transform,_load">ETL</a> — extract, transform, load — in the name of performance. It is a long established ETL approach to validate constraints in an application, rather than rely on declared database constraints. And in the cloud environment, the remaining AID properties are significantly altered as well.</p><p>The traditional approach of locking, or <a href="https://en.wikipedia.org/wiki/Multiversion_concurrency_control">MVCC</a> — Multiversion concurrency control, is hard to implement in a distributed environment. With <strong>Atomicity</strong>, Hive has so far only supported single statement transaction, i.e., only auto-commit, no support for multi-statement transaction by BEGIN, COMMIT and ROLLBACK.</p><p>Similarly for Spark, transaction is left to the application to manage. Consider an ETL application to ensure read committed <strong>Isolation</strong>, when a writer process is manipulating table T by updating/deleting old records and inserting new records. Not only is an intermediate result immediately available to query users with potential inconsistent data, but it is also hard to clean up if there is an error.</p><p>Even <strong>Durability</strong> is challenging. S3 eventual consistency is very different from a file system, where an OS level flush would be an efficient way to guarantee the data persistence. If a request to put or delete a large amount of data is attempted, S3 may even throttle and throw the dreaded 503 Slow Down response.</p><p>In essence, all ACID properties are intrinsically linked to transaction management. Yet transaction is left to the application to manage in a cloud warehouse. Thus, we rely on separation of metadata and data to manage the transaction. <strong>The main idea is that while data is written to S3, it is not “committed” until it is made available in a data catalog.</strong></p><p>There are 3 common cases where this can occur</p><ul><li><strong>Unpartitioned tables, typically including small dimension tables or fully refreshed aggregate tables.</strong> In such tables, we can use the following syntax to set the location.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a77769a6732a5987703f5e38609cee27/href">https://medium.com/media/a77769a6732a5987703f5e38609cee27/href</a></iframe><p>What does this mean? Suppose we have the current copy of data available for a user to query at location s3url1. We can create a new copy of the data with required modifications to s3url2, make sure the data is valid and then issue the above statement to make the new copy available to the query user, achieving both atomicity and isolation.</p><ul><li><strong>Append-only partitioned table, meaning every batch processing only inserts new partitions to the table, with new unique values for partition keys. </strong>This is applicable if each ETL batch has a unique identifier and the batch_id forms part of the partition key. Multiple partitions can be added in a single DDL statement, the syntax is:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dcc6e5c62d5a7b4df39bcc05828d367d/href">https://medium.com/media/dcc6e5c62d5a7b4df39bcc05828d367d/href</a></iframe><ul><li><strong>In case no unique ID is available in the partition key, we need to alter the existing partition and add a new partition at the same time.</strong> We implemented a simple “merge partition”, similar to <a href="https://en.wikipedia.org/wiki/Merge_(SQL)">merge DML</a>. If the partition doesn’t exist, use the above syntax to insert new partitions and if the partition does exist, use the following syntax to alter existing partition:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2439f90c3a853b346727b082c0ded587/href">https://medium.com/media/2439f90c3a853b346727b082c0ded587/href</a></iframe><p>For a multi-statement transaction where multiple tables need to be manipulated, in an all-or-nothing fashion, we can generate a data set for all tables, and then issue all hive DDLs at the end in succession. If any operations failed before issuance of the first hive DDL, the EMR step would fail, and the data location will not be made to Data Catalog. This means, <strong>cluster failure is transaction rollback</strong>. From the query user perspective, the potentially corrupted S3 data does not exist and will be cleaned up by S3 lifecycle policies, no need for manual intervention.</p><p>There is a chance that the series of DDL could fail in the middle. But, in reality, we rarely experienced such issues in both Aurora backed metastore or Glue Data Catalog. Should we encounter such an error, it is still much easier to recover from, compared to the messy S3 cleanup. Just <strong>identify the affected table or partition and revert to previous s3 location before the first Hive DDL.</strong></p><h3>Schema-on-read, Pattern: Validate-Insert-Create</h3><p>Traditional databases follow the pattern of “create-validate-insert”, where tables have to be created first, with all the proper validation, before any data can be inserted. We could follow the same pattern, as shown below, but there could be some surprises</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa884f6b988b8c6dacdc98d4fe98d88b/href">https://medium.com/media/fa884f6b988b8c6dacdc98d4fe98d88b/href</a></iframe><p>Given the above surprises in our Spark based ETL, we don’t want to follow the typical database “create-validate-insert” pattern. There are two connected issues that are outlined in this example:</p><ol><li>Without transaction guarantee, we could get partial and corrupt data upon DML failures.</li><li>As the underlying storage is S3, with eventual consistency mechanism, the cleanup on partially corrupt data is hard to guarantee in a timely fashion.</li></ol><p>Instead of using the typical pattern, at <a href="https://www.dataxu.com/">dataxu</a> we have adopted a “validate-insert-create” pattern. The steps to implementing this pattern include:</p><ul><li><strong>Create a spark temporary view matching the target external table schema.</strong> We created a helper class for this purpose, which ensures the temporary view has exactly the same number of columns, data types and ordering as the target external table.</li><li><strong>The validated data will be collected in the above temp view and write to S3 directly</strong>, without using INSERT INTO, like the following</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qn5_79Fo7aSpxWO9." /></figure><ul><li><strong>Then create/alter either an external table or partition depending on the use case</strong>, to point the location to the s3Path referenced above. This step is only executed when the above validation and write passed.</li></ul><p>An alternate popular option is Hive’s <a href="https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DDL#LanguageManualDDL-DynamicPartitions">dynamic partitioning</a> feature, where you can set a root location, and have Hive generate the data and metadata dynamically.</p><p>We did not adopt this approach for two reasons:</p><ol><li><strong>With the Hive partitioning scheme, the generated S3 prefixes are all relative to the root location. </strong>This means, all the data will have the same prefix. This is in conflict with <a href="http://docs.aws.amazon.com/AmazonS3/latest/dev/request-rate-perf-considerations.html">S3 best practice for performance</a>. The S3 guidance is to append a random alphanumeric prefix to the location to ensure best GET request throughput. For data warehousing, the predominant use case is querying, thus we optimize for GET over PUT.</li><li>Current version of Spark, (actually, Hadoop), treats S3 as a file system. In write operation, Spark creates _temporporay prefix, and then moves them to the final location. If this fails in the middle of the move, we could have partial and corrupt S3 data that is difficult to clean up.</li></ol><p>At <a href="https://www.dataxu.com/">dataxu</a>, we use Spark to write partitioned data and then add partitions manually. Pseudo-code for partitioned write:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*491l3UOHvsrH8Xfg." /></figure><p>With this approach, each batch can have a random prefix to ensure the best possible query performance.</p><h3>DDL is the new DML</h3><p>In a traditional database, we are comfortable with INSERT, UPDATE, and DELETE to perform data modification operations. The UPDATE and DELETE statements are typically harder to write, compared to INSERT and SELECT, and perform much worse. The common cause is, most databases have to maintain before and after images in UPDATE and DELETE, resulting in much larger overhead than INSERT.</p><p>One common approach, even in the traditional database realm, is to create a separate table on the side, recreate the data set with INSERT/SELECT, SELECT records to keep and INSERT records to update, and then swap with the current table. I compare this approach to a common technique, <a href="https://en.wikipedia.org/wiki/Multiple_buffering#Double_buffering_in_computer_graphics">double buffering in UI</a>. <strong>With the separation of metadata and data, this technique is very easy to achieve without the complexity of managing a second table</strong> and it becomes the predominant pattern in ETL chains at <a href="https://www.dataxu.com/">dataxu</a>. DDL contains much smaller data volume to manipulate — usually it just involves the table name, partition key/value, and location — the hive metastore API call is efficient compared to the time it would require to generate a large amount of data. The impact to the query user is minimal.</p><p><strong>A key concept is that the operation unit is now a table or partition.</strong> If we were to update or delete, it must be at an entire table or partition level. If we are to update 5 rows out of 100 million row dataset, we would alter the location of an entire table or partition to the new location for the updated result. In this sense, designing a proper partition key is critical. For example, for an append-only partitioned table, we assign a unique batch ID and ensure the batch ID is part of the partition keys.</p><p>Some readers may question the performance on partitioned tables. But there is no need to worry. Hive DDL supports multi-level partitions, and Glue Data Catalog supports 20,000 partitions per table by default and can be raised higher. We had no problem with tables of 5,000 partitions.</p><h3>Temporary View vs External Table</h3><p>Another area to consider for metadata is what kind of objects to use to support ETL and querying in the cloud warehouse. In Spark SQL, there are three basic types of “tables”:</p><ul><li><strong>Temporary view:</strong> The object only exists in Spark session and Spark catalog. Once the spark session is terminated, the metadata object disappears.</li><li><strong>External table:</strong> The table can be persisted into hive metastore. When the external table is deleted from hive metastore, only the table definition is deleted, not the data on S3.</li><li><strong>Managed table:</strong> The table is managed by Spark. If the table is deleted, both the table definition (metadata) and data are deleted.</li></ul><p>At <a href="https://www.dataxu.com/">dataxu</a>, we do not use managed tables. We only have temporary view and external tables in ETL processing. In MPP database, we created many staging tables, or temporary tables, to support ETL, such objects are accessible to query users and can be very confusing. With Spark ETL, such objects are created as temporary views, thus they don’t persist in metastore and query users are completely unaware of their existence. We are able keep a very clean schema, significantly reducing the number of persistent tables in the catalog.</p><p>For external tables, we configure Spark connection to Glue catalog with the following two simple EMR configurations.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6b0177b6aec48b6ec922524faa8cc73/href">https://medium.com/media/d6b0177b6aec48b6ec922524faa8cc73/href</a></iframe><p>As Athena uses the same Glue Data Catalog, the metadata updates from Spark ETL are immediately available to Athena query users, tying up both ETL process and querying activities. Worth mentioning, <strong>leveraging Glue service yields significant cost savings</strong>, <a href="https://www.dataxu.com/">dataxu</a><em> </em>spend on Glue Data catalog is less than 2% of the spend when metadata is hosted on Aurora RDS.</p><h3>Schema Evolution</h3><p><strong>Schema evolution refers to modifications to the table definitions over time</strong>. We may need to add new columns, drop old columns, update existing columns for datatype, name, etc. to tables and partitions. Schema evolution in traditional databases typically involves reorganization of the data, leading to locking or performance penalty on a heavily loaded system. In a cloud warehouse, we present two primary ways for schema evolution, to be compatible with separation of metadata and data, as well as query engine behavior, with none of the downsides that exist in traditional databases.</p><p>Consider upgrading schema from version 1 to version 2:</p><ul><li>For unpartitioned table, if it is acceptable for query users to experience a short period of outage, we can create the new dataset conforming to version 2, then drop the version 1 table and recreate version 2.</li></ul><p>However, this option may not always be acceptable, as there is a brief period of time, usually within a second, that the version 1 is dropped and version 2 has not been created in catalog, resulting query failures. Most of the time, users do not want an interruption in service, i.e., when a table suddenly disappears before reappearing. Which brings us to option two:</p><ul><li>Append new columns only in evolution. <strong>Never drop old columns,</strong> instead, use alter column data type as an example, create a new column with the new data type and keep the old column.</li></ul><p>One of the major concerns with dropping a column is that it would require a re-processing of existing data, to remove the column from the actual data on S3. It is a relatively small effort for dimension tables, but for fact tables with billions of records, this could be a task that is next to impossible. With append-only schema evolution, version 1 data is still compatible with version 2 schema.</p><p>As a concrete example, suppose version 1 has column c1 to c100, where c59 is a bigint column. We want version 2 to change the data type to decimal(10, 8). We can alter the table, add c59_v2 of decimal(10, 8). Query engines like Spark, Hive, Presto, Athena can generate null values for c59_v2 with data generated for version 1 and able to project data from both version1 and version 2 in version 2 schema. We can then use coalesce in SQL query to consolidate the two columns:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/866852e22fc8ae731289100060c9fc0f/href">https://medium.com/media/866852e22fc8ae731289100060c9fc0f/href</a></iframe><p>As of this point, we have discussed the common patterns of separating metadata and data. Now let’s dive into the significant benefits and interesting use cases that are possible with this method.</p><h3>Removal of DDL or DML locks and data fragmentation</h3><p>In databases with a locking approach for transactions, writers would block readers. With MVCC, generally readers don’t block writers and writers don’t block readers. Regardless, writers always block writers on the same table. This means, DML operations to a single table is serialized, leading to slow performance. <strong>With separation of metadata and data in a cloud warehouse, writers don’t block writers either.</strong> It can be huge advantage if managed properly.</p><p>Generally, if we ensure write to a table is idempotent, like a unique-id partition for each batch or merge partition, then we can have many writers manipulating the same table at the same time. An interesting use case is when ETL is significantly behind, either due to application bugs or outage from upstream system or AWS, we can launch as many EMR clusters as number of batches in the backlog for concurrent execution and quick catch up. <strong>If we have 10 batches, we can be 10x faster than MPP database.</strong></p><p>Not only DML can acquire locks, DDL will also acquire locks in a database, leading to slow performance. And similarly, there is no DDL locking in a cloud warehouse, further removing performance bottlenecks.</p><p>A common reason for DDL locks is vacuuming. Data can get fragmented in a database, not only for data, but also metadata in the catalog. Different databases have different tools to manage the fragmentation, typically requiring DML and DDL locks in the defragmentation process. Catalog vacuuming could be particularly problematic, typically requiring database outage to query users. <strong>In our Spark ETL, we won’t have data fragmentation, as we always recreate the new data set for DML, there is no need for such defragmentation and DML/DDL locks.</strong></p><h3>Test with real production data</h3><p>In traditional databases, testing with real production data is always a struggle for performance testing. You can create a second set of equivalent hardware and restore the full database for performance testing, but that’s usually cost-prohibitive and time consuming. Even if you can afford a second set of hardware, developers usually have to make reservations to access such an environment. Alternatively, you can compromise by testing a small percentage of the data, risking unexpected problems in production with insufficient testing coverage.</p><p>With the separation of metadata and data, it is easy to test at the full scale of production data, with no compromise. With the production data on S3, all we need to do is make a copy of the metadata catalog and suddenly the same data is available for QA or dev proposes.</p><p>Our practice at <a href="https://www.dataxu.com/">dataxu</a> is to organize production objects in Hive <a href="https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DDL#LanguageManualDDL-Create/Drop/Alter/UseDatabase">database</a>, typically, named as “default”. We created a custom process to export all objects, including tables, columns, and partitions of the default database from Glue Data Catalog as JSON, and then restore to a database in the dev environment. The catalog JSON export is a few megabytes and restore takes less than 5 minutes. Every developer can afford to have their own production-sized database or as many as databases to fit their needs in the dev environment. In essence, each database just holds pointers to the massive production S3 data set and we do not need to make a full copy of the S3 data.</p><p>Consider this interesting use case: we have an application bug or performance issue, and we would like to test a few potential fixes, in different “what-if” scenarios. We can create several dev databases by restoring the production catalog, try each possible fix at full scale and validate the data correctness or performance improvement before deployment to production.</p><p>Another interesting use case is point-in-time recovery. We store the Glue Data Catalog JSON export at an hourly interval. That’s minimal cost on S3, yet, <strong>we can restore to any point of time within the past 1 month for testing purposes or disaster recovery, all within 5 minutes.</strong></p><h3>Boosting performance by separating metadata and data</h3><p>Traditional databases have metadata and data tightly coupled, leading to problems like performance degradation from catalog locking and data loss due to catalog corruption. With <a href="https://www.dataxu.com/">dataxu</a>’s cloud warehouse implementation, we leveraged AWS Glue, specifically, Data Catalog, as the metadata service. In addition to addressing the common problems in traditional databases, we reaped the benefits of development agility as well as full functional and performance testing.</p><p><em>Please post your feedback in the comments — do you have an interesting approach in exploiting separation of metadata and data? In the next post, we will discuss Spark SQL optimization techniques</em></p><p><em>If you found this post useful, please feel free to “applause” and share!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72680d1d97f2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dataxutech/separation-of-metadata-and-data-building-a-cloud-native-warehouse-part-3-72680d1d97f2">Separation of metadata and data: Building a cloud native warehouse, Part 3</a> was originally published in <a href="https://medium.com/dataxutech">dataxu.technology</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 implement Singletons in Scala at dataxu]]></title>
            <link>https://medium.com/dataxutech/how-we-implement-singletons-in-scala-at-dataxu-8ccba9e6dd59?source=rss----e2bf46625e2b---4</link>
            <guid isPermaLink="false">https://medium.com/p/8ccba9e6dd59</guid>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[software-design-patterns]]></category>
            <category><![CDATA[software-design]]></category>
            <category><![CDATA[singleton]]></category>
            <dc:creator><![CDATA[Javier Buquet]]></dc:creator>
            <pubDate>Mon, 15 Jan 2018 14:04:17 GMT</pubDate>
            <atom:updated>2018-01-15T14:04:17.010Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*6m-iOEM0-f6jP-yPsyUmXg.png" /></figure><p>At dataxu, we have been using <a href="https://www.scala-lang.org/"><em>Scala</em></a> for a while now, and in our journey we have perfected our best practices. Among these best practices, we have refined our implementation of the <em>Singleton design pattern</em> in Scala. In implementing this pattern there are some aspects that require significant attention to detail to increase its ease of use, especially when testing.</p><p>The <strong>Singleton design pattern,</strong> according to <a href="https://en.wikipedia.org/wiki/Singleton_pattern">Wikipedia</a>, <em>is a software design pattern that restricts the instantiation of a class to one object</em>. This means that this pattern promises to be handy when dealing with a class that we want to instantiate once, and only once, across a system (or, more generally, a subsystem), and have that same instance shared by every potential user of the class. For example, think about a <em>DatabaseConnection</em> class that handles the connection between the system and its database, it is reasonable to have only one instance of the class and make any database client use that same connection.</p><p>But the question is, <strong>how do we implement this Singleton design pattern in Scala</strong>?</p><h3>Implementing the Singleton design pattern in Scala</h3><p>If you have already given Scala a try, you are probably familiar with Scala’s <a href="https://docs.scala-lang.org/tour/singleton-objects.html"><em>Singleton Objects</em></a>. These are Scala’s approach to the <em>static</em> keyword in <em>Java</em>. Any function or variable defined in a <em>Scala Object</em> can be used statically, as there is one and only one instance of an object, which is not instantiated by any consumer, but just exists.</p><p><strong>Our first hunch when implementing the Singleton design pattern in Scala was to make use of the Singleton Objects.</strong></p><p>Let’s say we actually want to implement the DatabaseConnection class we mentioned above following the Singleton design pattern. This will allow different consumers to share the same DatabaseConnection instance for running commands on our application’s database. Using Scala’s Singleton Objects we can achieve this by doing:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/75af9d112f93ffe8a7e9dec345c33b83/href">https://medium.com/media/75af9d112f93ffe8a7e9dec345c33b83/href</a></iframe><p>And that’s all. We can now support different consumers running commands on a shared DatabaseConnection instance implementing the Singleton design pattern. For example, we could have a function somewhere else that retrieves all the <em>Users</em> in the database, as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1feb30cc5c7230744038dbed45a4c756/href">https://medium.com/media/1feb30cc5c7230744038dbed45a4c756/href</a></iframe><p>As you can see, there’s no need to instantiate a new DatabaseConnection nor to somehow keep a reference to it — we have direct access to the one and only DatabaseConnection instance just as if it was a static call in Java.</p><p>As we started using this approach in our code, we found it had some limitations that were important to note:</p><ul><li><strong>There’s no way one can easily swap the implementation being used.</strong> The fact that the user does not control the creation of this singleton instance — as it exists naturally in the program — makes it impossible to easily swap the implementation being used. It is common for us at dataxu to need a different implementation of our DatabaseConnection class when running our unit tests so that we don’t connect to the actual database but instead use an in-memory implementation of the class which is faster and cheaper. Using the Singleton Object does not allow us to swap the implementation of DatabaseConnection we want to instantiate as the singleton, but instead we would need to modify each and every consumer of the class to point to a different Object.</li><li><strong>Can’t be instantiated lazily.</strong> It might be the case that we need our singleton instance to be created lazily — only instantiate it once it has been requested for the first time by a consumer, not before. Again, as we don’t control the creation of this singleton instance, there’s no way we can do so lazily — it will be instantiated upon program execution.</li></ul><p>These limitations are a consequence of the fact that these Scala Singleton Objects are not meant to be used this way. These Objects are not a built-in implementation of the Singleton design pattern, but instead are Scala’s approach to Java’s static. Hence, we should not include in these Objects code that is intended to be used as non-static code accessed through a singleton instance, but instead we should only include static code.</p><h4>Perfecting our implementation of the Singleton design pattern</h4><p>Given the limitations of our first approach, we came up with a different strategy that could effectively implement the Singleton design pattern without sacrificing the ease to test and use, while still being clean and elegant.</p><p>We knew that we shouldn’t use a Scala Object, as it proved to not fit our needs. Instead, we should use a regular Scala Class and have some infrastructure for holding a single instance of it and making sure we only allow that one instance to be used.</p><p>By the way, this is similar to how we implement the Singleton design pattern in Java — we define a <em>class</em> and its functionality, and add static infrastructure for handling the singleton instance. In this case, Scala helps to make our code cleaner by more explicitly encapsulating the static code in a Scala Object.</p><p>Our code now looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5099f1b844c12771d254a156c86ca85/href">https://medium.com/media/e5099f1b844c12771d254a156c86ca85/href</a></iframe><p>And we can use the singleton instance this way:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb2a43ecd3a769675983c6d3db849abe/href">https://medium.com/media/eb2a43ecd3a769675983c6d3db849abe/href</a></iframe><p>And <em>voilà</em> — we can now easily change the implementation of DatabaseConnection we want to instantiate as the singleton instance by just modifying the instantiation of the <em>val instance</em> in our <em>object </em>DatabaseConnection, as well as instantiating the singleton instance lazily just by adding the <em>lazy</em> keyword before the <em>val</em> for the <em>instance</em>.</p><p>This infrastructure can easily (and we think it should) be extended to allow programmatic swapping of the singleton instance being held. This means adding support for overriding the implementation being used, using a single line of code, which comes in very handy for solving the case mentioned above where we want to use a different implementation of the DatabaseConnection class when testing.</p><p>We decided to add this infrastructure to new functions to make our lives easier when testing:</p><ul><li>A <strong>force(…)</strong> function that receives an instance of DatabaseConnection and forces the singleton instance to be the one received.</li><li>A <strong>reset()</strong> function that puts the singleton instance back to its default (not-forced) one.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d49240afb60e0a311bd5502ddbea4a3b/href">https://medium.com/media/d49240afb60e0a311bd5502ddbea4a3b/href</a></iframe><h4>Generalizing our solution</h4><p>Once we were happy with our solution, and proved that it was an effective implementation of the Singleton design pattern in Scala, we tried to generalize our solution to make it as simple as possible for other classes using this infrastructure. We came up with a simple utility that any developer who needs to implement a Singleton class in Scala can simply extend and start using.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4839c4bbf742896e11cf7b7c8dad226b/href">https://medium.com/media/4839c4bbf742896e11cf7b7c8dad226b/href</a></iframe><p>And can be simply used as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01cd2e0db396144a709c86d0c206ae34/href">https://medium.com/media/01cd2e0db396144a709c86d0c206ae34/href</a></iframe><p>We also created a test base for our solution so that those who are using it can very easily have their <em>Singleton Instance Providers</em> thoroughly tested, just by extending this <em>trait</em> in their test classes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ddc37ffff07959731ad8019e0b36e9d/href">https://medium.com/media/4ddc37ffff07959731ad8019e0b36e9d/href</a></iframe><p><strong><em>What do you think of our solution? </em></strong><em>Do you think others would find it useful if we published this simple utility? How do you handle implementing Singletons in Scala? Please let us know! If you found this post useful, please feel free to “applause” and share!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ccba9e6dd59" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dataxutech/how-we-implement-singletons-in-scala-at-dataxu-8ccba9e6dd59">How we implement Singletons in Scala at dataxu</a> was originally published in <a href="https://medium.com/dataxutech">dataxu.technology</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[dataxu’s journey from an Enterprise MPP database to a cloud-native data warehouse, Part 2]]></title>
            <link>https://medium.com/dataxutech/dataxus-journey-from-an-enterprise-mpp-database-to-a-cloud-native-data-warehouse-part-2-8f2a807feb0b?source=rss----e2bf46625e2b---4</link>
            <guid isPermaLink="false">https://medium.com/p/8f2a807feb0b</guid>
            <category><![CDATA[athena]]></category>
            <category><![CDATA[data-lake]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Dong Jiang]]></dc:creator>
            <pubDate>Thu, 21 Dec 2017 17:40:30 GMT</pubDate>
            <atom:updated>2017-12-21T21:07:21.916Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*dMM7olKLrTkNKhBPrsFWXw.png" /></figure><p><em>This is part 2 of a series of blogs on dataxu’s efforts to build out a cloud-native data warehouse and our learnings in that process. See part 1 </em><a href="https://medium.com/dataxutech/dataxus-journey-from-an-enterprise-mpp-database-to-a-cloud-native-data-warehouse-part-1-e36952d87a1f"><em>here</em></a><em>.</em></p><p>Once we determined the architecture of the cloud-native data warehouse as discussed in <a href="https://medium.com/dataxutech/dataxus-journey-from-an-enterprise-mpp-database-to-a-cloud-native-data-warehouse-part-1-e36952d87a1f">part 1 of this series</a>, we set out to select a query engine.</p><p><a href="https://www.dataxu.com/"><em>dataxu</em></a> was an early participant in the preview of the Amazon <a href="https://aws.amazon.com/athena/">Athena</a> Service, and once the service went GA, we became an early adopter. With Athena, our analytical users are able to run complex and interactive SQL queries over the data stored on S3 with excellent performance and cost efficiency, without the necessity of managing a cluster. After months of testing, Athena has been incorporated as our default query engine in the cloud-native warehouse.</p><p>As with any SQL engine, it is critical to learn a few things about the engine in order to write performant SQL. AWS published an excellent blog <a href="https://aws.amazon.com/blogs/big-data/top-10-performance-tuning-tips-for-amazon-athena/">Top 10 Performance Tuning Tips for Amazon Athena</a> that discusses this topic. But to make things easier, here at dataxu, we distilled these tips down to 3 key recommendations:</p><ol><li><strong>Select only the columns you need</strong>, particularly if the underlying data is in columnar format like Parquet or ORC. Never write “ <em>select * </em>”.</li><li><strong>Always include a filter on the partition column in the where clause</strong>. A partitioned table is almost certainly a large table, without a filter on the partition column it will result in a full scan of the data.</li><li><strong>Mind the join order.</strong> On multi-table joins, start with the table that has the most rows to the least, from left to right.</li></ol><p>We would also like to share a SQL rewrite technique that would significantly improve the query performance and is most applicable to <a href="https://en.wikipedia.org/wiki/Star_schema">Star schema</a>, a common approach to data organization.</p><p>Let’s start with a typical schema in ad tech, where we have a fact table of impressions and a few dimension tables, like campaigns, creatives, algorithms, etc. A sample schema looks like the example below*:</p><p><em>Note the impressions records each individual event, well over hundreds of billions records annually.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b86fd6bc4f8a6a734661dac5388bc65/href">https://medium.com/media/3b86fd6bc4f8a6a734661dac5388bc65/href</a></iframe><p>One query asks for a break down of the number of impressions and spend during the second half of 2017 by month, creative_type, algorithm_type and advertiser_name.</p><p>Most of us would write SQL like the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b08e6c974922caef9d055289c7aa99a/href">https://medium.com/media/7b08e6c974922caef9d055289c7aa99a/href</a></iframe><p>The query above only selected the columns needed, has a filter on the partition column <em>created_date,</em> and ordered the tables in the number of rows. This is all well and good, however, with the amount of data in the impressions table, the query timed out on Athena, even after we raised the timeout setting from 30 minutes to 1 hour.</p><p>If you look at the query, it is a massive table with three adjoining small dimension tables. Due the sheer amount of data in impressions, the join is extremely expensive. <strong>I call this type of SQL “Join-GroupBy” approach. </strong>However, if we rewrite the query, first run a groupBy just on the fact table “impressions” for the join keys and then join with dimensions, followed by another groupBy if necessary, the data size involved in the join would be significantly reduced. I call this rewritten approach “GroupBy-Join-GroupBy”.</p><p>The rewrite query looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d52a93880a937f0d98a2f2e1b7b9ca7/href">https://medium.com/media/3d52a93880a937f0d98a2f2e1b7b9ca7/href</a></iframe><p>This query finished on Athena in 15 minutes, a vast improvement from the 1 hour timeout we encountered with the first SQL approach.</p><p>Why the drastic difference? Simple. GroupBy first significantly compresses the joined columns. In our specific example, the total number of rows in impressions vs. total number of rows after GroupBy is at a ratio of 3000:1. This means that the join is much more efficient and Athena is able to complete it much faster.</p><p><strong>Is GroupBy-Join-GroupBy always better than Join-GroupBy?</strong> Not necessarily.</p><p>GroupBy-Join-GroupBy involves an extra GroupBy compared to Join-GroupBy, so there must be a significant reduction of the dataset after the first GroupBy to offset the cost. Obviously, you may have a huge variance due to the types of data and organization, yet as a rule of thumb, if the compression ratio is at least 1 order of magnitude, the extra GroupBy is usually worthwhile. It is particularly worthwhile if there is complex logic on the dimension columns, i.e., case statement or regular expression on creative_type, algorithm_type as in the above example. The compression on the fact table will reduce the invocations on case statement and regular expression as well.</p><p>We have had similar experiences on PostgreSQL, so it could also be applicable to other SQL engines and believe it may be worthwhile to try.</p><p>Next time, we will do a deep-dive on separation of metadata and data.</p><p><em>Please post your feedback in the comments — how do you handle complex SQL queries and what are you techniques to improve performance? If you found this post useful, please feel free to “applause” and share!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f2a807feb0b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dataxutech/dataxus-journey-from-an-enterprise-mpp-database-to-a-cloud-native-data-warehouse-part-2-8f2a807feb0b">dataxu’s journey from an Enterprise MPP database to a cloud-native data warehouse, Part 2</a> was originally published in <a href="https://medium.com/dataxutech">dataxu.technology</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[dataxu’s journey from an Enterprise MPP database to a cloud-native data warehouse, Part 1]]></title>
            <link>https://medium.com/dataxutech/dataxus-journey-from-an-enterprise-mpp-database-to-a-cloud-native-data-warehouse-part-1-e36952d87a1f?source=rss----e2bf46625e2b---4</link>
            <guid isPermaLink="false">https://medium.com/p/e36952d87a1f</guid>
            <category><![CDATA[data-warehouse]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[data-lake]]></category>
            <category><![CDATA[spark]]></category>
            <dc:creator><![CDATA[Dong Jiang]]></dc:creator>
            <pubDate>Wed, 13 Dec 2017 19:47:42 GMT</pubDate>
            <atom:updated>2017-12-13T19:47:41.788Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This is part 1 of a series of blogs on dataxu’s efforts to build out a cloud-native data warehouse and our learnings in that process.</em></p><p>At <a href="https://www.dataxu.com/">dataxu</a>, we deal with data collection, storage, processing, analysis, and consumption at massive scale. For this reason, we were an early adopter of the Hadoop framework. We quickly discovered that Hadoop and Hive alone were not sufficient for the growing needs of interactive analysis and querying. And so, about five years ago, we incorporated an <a href="https://en.wikipedia.org/wiki/Massively_parallel">MPP</a> database as our warehouse solution.</p><p>The on-premise solution served us well as the cluster size expanded 16 fold over the course of five years. However, even with the addition of an MPP, we started to run into significant operational challenges:</p><ul><li><strong>While it is possible to expand the MPP database, it takes months of planning and execution.</strong> The capacity planning is particularly tricky. If the business experienced unexpected growth, it would be difficult to bring additional capacity online in a timely fashion. If the business growth slowed, we could be stuck with an over-sized cluster for a number of months, before the volume eventually caught up.</li><li><strong>The database requires constant maintenance</strong>, both in terms of hardware (like replacing failed disks) and software (like vacuuming catalog). Moreover, the database constantly experienced failed processes, which requires DBA to perform recovery operations.</li><li><strong>Ad-hoc query users constantly compete with production ETL loads for the fixed capacity</strong>, leading to unpredictable load times and SLA misses.</li></ul><p>The MPP solution was clearly not a sustainable option for serving dataxu’s business needs. As such, we started to look for an AWS cloud-native solution. After reviewing several competing solutions, we settled on <a href="http://docs.aws.amazon.com/emr/latest/ReleaseGuide/emr-spark.html">Apache Spark on EMR</a> as our primary ETL solution and <a href="https://aws.amazon.com/athena/">AWS Athena</a> as primary query solution.</p><p>In this blog, we will discuss the comparison of a cloud-native warehouse vs. MPP, with some focus on Spark as an ETL solution.</p><h3>Cloud-native warehouse vs. MPP</h3><p>First and foremost, the primary reason to choose Spark is not for performance. As it currently stands, even if a Spark cluster is configured with an equivalent amount of CPU, RAM, and disk capacity, it is unlikely to beat the query performance of the MPP solution. There are many reasons why an MPP database will “beat” Apache Spark on paper:</p><ul><li>EMR clusters run on VMs, while MPP on-prem runs on highly tuned bare metal servers.</li><li>EMR clusters run in VPC, while MPP on-prem has a dedicated network switch and 100Gbit throughput.</li><li>EMR clusters use S3 as storage, while MPP on-prem has superior I/O performance with direct attached disks on RAID10.</li><li>MPP database has years of query optimization expertise, while Spark has a lot to catch up on.</li><li>MPP databases allow for data locality. That means the data can be split into shards by a key — so each fixed node “owns” a shard. A well chosen distribution key cuts down on so-called broadcasts (data movements over network across the nodes).</li></ul><h3>Reasons for choosing Spark</h3><p>While an MPP may look like the better option on the surface, there are a number of reasons why here at dataxu we chose to implement Spark as our primary ETL solution.</p><ol><li><strong>Separation of Compute and Storage. </strong>The Storage tier is S3, with all the durability, infinite scalability, and recoverability built-in. The Compute is EMR with a wide range of possible instance families to match CPU and RAM needs. We also use transient and dedicated EMR clusters for ETL loads, where there is no sharing of workloads. <strong>A single cluster is dedicated for only one load</strong>, which enables a predictable execution time and guarantees SLA. We never have to worry about having the right balance of storage and compute. We never have to worry about running out of storage or having enough compute.</li><li><strong>Separation of Metadata and Data.</strong> Hive metastore has evolved as the de facto open source standard for managing schema objects, supporting tables, view, partitions, and UDFs. We no longer need to vacuum data catalog which also removes a common locking condition on MPP databases.</li><li><strong>Dynamic Elasticity</strong>. The ability to scale the computing resources to dynamically match the business and technical requirements. In addition, with EMR auto-scaling features, a cluster can be scaled up and down even when active queries are executing and newly provisioned capacity can be put to in-flight query instantly.</li><li><strong>Reduction of Maintenance</strong>. There is no longer a physical database to manage. No more backups, no more disk failures and replacement, and no more shutting down databases for hardware/network maintenance.</li><li><strong>Resilience and Fault Tolerance</strong>. Any tiny issues in MPP will cause a query to fail, while Spark will re-try multiple times. This leads to significantly increased resilience, particularly in the hostile cloud environment.</li><li><strong>Cost Efficiency</strong>. Spot pricing and Instance Fleets yield significant savings over a fixed-cost, on-prem solution.</li><li><strong>Open Source</strong>. As the most active Big Data open source project, the amount of contributions for <a href="https://github.com/apache/spark/graphs/contributors">Spark</a> hugely dwarfs that for any other MPP solutions out there.</li></ol><h3>Electrical wiring: A visual analogy</h3><p>For simplicity’s sake, we can compare MPP vs. the cloud-native warehouse to different methods of electrical wiring:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*k1CK7esxcAqqGXU5." /></figure><p>The left side is a serial circuit with no switches. The capacity is fixed, has to size for peak capacity and is always on. Bringing in a new workload meaning less throughput to all existing workloads, such is the case with an MPP solution.</p><p>On the other hand, the right side is a parallel circuit with switches. The capacity is elastic — you can use and pay when needed. Bringing on a new workload does not diminish or interfere with any existing workload, such is the case with our cloud-native warehouse.</p><h3>Cloud-native warehouse: Endless possibilities</h3><p>With cloud-native warehouse, there is no longer a monolithic database stack. The database is decomposed into</p><ul><li><strong>Storage</strong> (open file formats on S3). File formats are open, like Parquet or ORC, no longer locked into proprietary formats, support queries via many different platforms and query engines.</li><li><strong>Compute</strong> (EMR, Athena, Redshift-Spectrum), with pluggable query engines like Spark or Presto, also platforms like <a href="http://www.qubole.com/">Qubole</a>.</li><li><strong>Metadata</strong> (schema) layer, can be hosted on RDS-Aurora or the AWS Glue-Data catalog.</li></ul><p>Each of the component layers has many options that allow you to piece together different systems with different characteristics, suitable for a variety of use cases.</p><h3>dataxu’s Cloud-native warehouse:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yl71Fj64H4XHtHtn." /></figure><h3>Performance is better with Spark</h3><p>And finally, let’s take a look at the performance benefits Spark brings to the table:</p><ol><li>As we iterate over versions of Spark, from 1.6, to 2.0 and 2.2, the common thread is a <strong>significant performance improvement with each release</strong>, see discussions <a href="https://databricks.com/blog/2016/05/23/apache-spark-as-a-compiler-joining-a-billion-rows-per-second-on-a-laptop.html">here</a> and <a href="https://databricks.com/blog/2017/08/31/cost-based-optimizer-in-apache-spark-2-2.html">here</a>. With this background, we are confident that the Spark project will continue on this trajectory.</li><li><strong>The separation of compute and storage is huge</strong>. Running a single query as the sole workload will perform better on MPP over Spark on EMR, yet, in reality, the MPP database is almost always shared among a variety of competing workloads, resulting in much slower performance than a dedicated EMR cluster or Athena.</li><li>And last but not least, <strong>with dynamic elasticity, the option to scale out to meet SLA/performance requirements is always available</strong> at your fingertips.</li></ol><p>Keep an eye out for the second post in this series, where we will take a deeper dive into how we “rewired the house” at dataxu.</p><p><em>Please post your feedback in the comments — what kind of solutions do you employ? If you found this post useful, please feel free to “applause” and share!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e36952d87a1f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dataxutech/dataxus-journey-from-an-enterprise-mpp-database-to-a-cloud-native-data-warehouse-part-1-e36952d87a1f">dataxu’s journey from an Enterprise MPP database to a cloud-native data warehouse, Part 1</a> was originally published in <a href="https://medium.com/dataxutech">dataxu.technology</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>