<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ankit Prakash Gupta on Medium]]></title>
        <description><![CDATA[Stories by Ankit Prakash Gupta on Medium]]></description>
        <link>https://medium.com/@info.ankitp?source=rss-d774cabc71ee------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*c6h21bcEPh7ym2SFL49CRg.jpeg</url>
            <title>Stories by Ankit Prakash Gupta on Medium</title>
            <link>https://medium.com/@info.ankitp?source=rss-d774cabc71ee------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 18:04:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@info.ankitp/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Ingestion to Insight: AI-Orchestrated Data Platform]]></title>
            <link>https://medium.com/@info.ankitp/ingestion-to-insight-ai-orchestrated-data-platform-15e0dd944ccf?source=rss-d774cabc71ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/15e0dd944ccf</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-platforms]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Ankit Prakash Gupta]]></dc:creator>
            <pubDate>Sat, 09 May 2026 04:53:34 GMT</pubDate>
            <atom:updated>2026-05-09T04:53:34.339Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>This captures the vision for Future of Data Platforms as well as a quick design reference, using AI as the mechanism to build up and power the platform and automate the mundane processes of creation of new metrics, doing RCAs for the failures and fixing them or to even search/build for any metric at a specific grain, taking sprints to actually serving the new analysis.</p><h3>Pre-Requisites</h3><ul><li>A <strong>Data Cataloging layer</strong>, powered with MCP Server, so that AI Agents can communicate and polished and vetted metadata.</li><li>Standardised <strong>Config Driven Ingestion System.</strong></li><li>Standardised<strong> Config Driven ETL/Reverse ETL System</strong> which can help in creating Processing Workflows.</li><li>Common semantic layer centralising the definition of metrics.</li><li><strong>Out of Scope Things :</strong> Storage/Data Lakes and Governance.</li></ul><h3>High Level Design</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pyZco0l2_6NKWt9MzpGq2Q.png" /><figcaption>AI Driven Data Platform</figcaption></figure><h3>Pre-Requisites</h3><ul><li>A single Data Cataloging layer, powered with MCP Server, so that AI Agents can communicate and fetch polished and vetted metadata.</li><li>Automated Config Driven Ingestion Facilitation System.</li><li>Automated Config Driven ETL/Reverse ETL System which can help in creating Processing Workflows.</li></ul><h3>Flow-Diagrams</h3><h3>1. Find out RCA for the failure of the Job</h3><p>A lot of productive time of developers is actually spent on keeping the systems alive as of now and finding out the reasons of failures of the system. If we automate the RCA for Jobs Failures/Data Quality Issues, the same time can actually be spent on more innovative things.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3if9CdYDMF6BF06uDfeVlQ.png" /><figcaption>Flow for RCA of Failures</figcaption></figure><h3>2. To serve X metric on Y Grain</h3><p>Serving a new metric either for taking business decisions or for training models or for populating feature stores, with current development cycles easily take weeks, what if some part of the development cycle is taken by AI Agents, from identifying the sources for a metric to writing logic, which is eventually vetted by humans having more business context and better knowledge of the existing metrics, again leading to more productive work at the end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hsk-8dbPDetviihlVsfwtA.png" /><figcaption>Flow for new Metric Creation</figcaption></figure><h3>3. Create an Ingestion Pipeline</h3><p>Ingestion Pipelines are usually standardised, since we have to onboard data from other operational systems to Platform, and the possible sources are finite, so standardising this framework itself would save a lot of time, rest if we can train an AI Agent to configure this system as well, it would mean reducing the development time of Ingestion pipeline to minutes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rhrGd5FNKDbLFxlf2sBVCQ.png" /><figcaption>Flow for new Ingestion Pipeline Creation</figcaption></figure><h3>4. Create an ETL Pipeline</h3><p>ETL Pipelines is the most tricky part, since transformations will depend on business use case and should be correct and efficient, else in this Big Data world it might cost a lot for fixing the problems in the code and reprocessing the data or for processing the data at the first time with inefficient code you might end up paying a very good amount. This layer is mostly going to be dependent on the Human Developers, but AI Agents can still help out in bringing the first draft of the ETL Pipeline and then eventually developers can build over/fix the generated code, which will again save good amount of time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D7daTc7T6mYDBVlDIiZSuA.png" /><figcaption>Flow for new ETL Pipeline Creation</figcaption></figure><h3>Summary</h3><p>Data teams today spend more time maintaining systems than building value. Failed pipelines, manual metric definitions, and reactive data quality fixes consume engineering capacity that should be focused on innovation.</p><p>The next generation of data platforms changes this by embedding AI agents at the core — not as an add-on, but as active participants in how data is managed and served. Pipelines that fail diagnose themselves. Metrics are created through conversation, not code sprints. Data quality issues are detected, root-caused, and resolved automatically before the business feels the impact.</p><p>The most fascinating part is, the technology needed to build this exists today, and we have also started taking a dig at it but in parts and fragments. Good way to look at it would be to make sure we remove fragments and silos and start moving towards a <strong>One-Stop Shop Data Platforms.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15e0dd944ccf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cost Optimization of Spark on Kubernetes Batch Workloads on Public Clouds]]></title>
            <link>https://medium.com/data-science-collective/cost-optimization-of-spark-on-kubernetes-batch-workloads-on-public-clouds-aa23585b4b45?source=rss-d774cabc71ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa23585b4b45</guid>
            <category><![CDATA[cloud-finops]]></category>
            <category><![CDATA[distributed-computing]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[public-cloud]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Ankit Prakash Gupta]]></dc:creator>
            <pubDate>Fri, 24 Apr 2026 08:02:07 GMT</pubDate>
            <atom:updated>2026-04-25T17:53:36.394Z</atom:updated>
            <content:encoded><![CDATA[<p>These small cost optimizations techniques eventually led to <strong>~2 Million US$</strong> for the organization.</p><p>We all know public clouds in many cases are black boxes for all of us and have an <strong>extremely absurd pricing model. </strong>Specially in the case of Big Data Processing Workloads, since the quantity used is extremely high directly proportional to the 4Vs of data. Below is one such instance that actually costed US$ 10k for a BQ query running for 22 seconds only.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yr8uh6gx8C0Q_IvPsUxWIA.png" /><figcaption>Public Cloud costing US$10,000 for a 22 seconds query</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PSsHRaYe7IT6KfaZOw0G9w.png" /><figcaption>Public Cloud Pricing already mentions the details</figcaption></figure><p>Now, before delving into the cost optimization techniques worked with, let me set the scale at which we have been using Spark Jobs, we are running ~25k Spark Jobs on GKE cluster using Spark on Kubernetes, ~150k executor pods on a daily basis.</p><h3><strong>How Public Cloud Costing Works for Spark jobs</strong></h3><p>We use Kubernetes (K8s) resource manager integration available inside open-source Spark to submit the jobs on K8s cluster directly, which scales out the cluster up by adding new nodes when there is demand and scales down in case resources are free, (<strong>pay-as-you-go</strong>)</p><p>The Key cost drivers for the Spark Jobs</p><ul><li>Compute Resources (RAM / vCPUs)</li><li>Network Transfer out (Zonal / Regional)</li><li>Persistent Disk Storage</li></ul><h3><strong>Types of Cost Optimizations in scope</strong></h3><ul><li><strong>Network Cost Optimization</strong></li><li><strong>Hardware Cost Optimization</strong></li></ul><h3><strong>Network Cost Optimization</strong></h3><p><strong>Network Inter Zone/Region Data Transfer Out Cost </strong>is the cost which is incurred when the data is transferred from one zone to another zone or from one region to another region.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*JA9K7uD7IF_0UPt8pnOoLg.png" /><figcaption>Inter-zone Data Transfer Out Charges on GCP</figcaption></figure><p>How spark jobs incurs this costing, whenever a particular executor shuffles data to another executor running in another zone, the data transferred eventually incurs cost when this data is being transferred.</p><p>The inter region data transfer out cost ~ 10 x inter zone data transfer out cost.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*5aXTc64rrfcjwUtlTTQbDQ.png" /><figcaption>Spark Data Shuffle in case of Spark Executors running in multiple zones</figcaption></figure><p>You must be thinking about, why we could not just resort to a single-zone cluster, it will lead to below two problems</p><ol><li><strong>Unavailability of Resources in a Zone<br></strong>Zonal GKE Cluster -&gt; No Scalability<br>Regional GKE cluster -&gt; <strong><em>Better Scalability/Availability</em></strong></li><li><strong>Reduced Fault Tolerance<br></strong>Zonal GKE Cluster -&gt; No Fault Tolerance<br>Regional GKE cluster -&gt; <strong><em>Better Fault Tolerance</em></strong></li></ol><p>Now the main part how did we actually reduced the network cost, what we needed to do was to colocate all the executors in the same zone, and to ensure we can still use resources from multiple zones atleast, in order to have better availability as well as scalability for the system.</p><p>To achieve the above we did the following two things</p><ul><li>Collocate executors in the same zone as the driver.</li><li>Allocation of driver in any random zone/region.</li></ul><p>We needed to attach a hard affinity for the executor pods to run all the executor pods in the same zone as the driver, below is what we could attach to the executor pod, but we needed the dynamic spark app id which is populated at runtime.</p><pre>affinity:<br>  podAffinity:<br>    requiredDuringSchedulingIgnoredDuringExecution:<br>    - labelSelector:<br>        matchExpressions:<br>        - key: spark-app-selector<br>          operator: In<br>          values:<br>          - &lt;UNIQUE_APPLICATION_NAME&gt;<br>      topologyKey: topology.kubernetes.io/zone</pre><p>Now to ensure we can dynamically attach this pod affinity, we developed the following pod feature step, since we can get the application id dynamically in the feature steps.</p><p>Feature steps are the functions that are applied at the runtime while creating the pod specifications for driver as well as executor in Spark Jobs, so we used these feature steps to customize and attach the pod affinity at runtime to the executor pods.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/de711bae6521b0a0a27f0ddeac9a85cc/href">https://medium.com/media/de711bae6521b0a0a27f0ddeac9a85cc/href</a></iframe><h4><strong>Results</strong></h4><ul><li><strong>Cost reduction from day one</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*XIUMdWnmnjdEk5CO24BvOQ.png" /><figcaption>Cost reduction from 500 US$ to less than 10 US$ per day for inter zone data transfer</figcaption></figure><ul><li><strong>Performance Improvements</strong>: Since all the data shuffle will be inside a DC, there won’t be any network delays, resulting in performance improvements.</li><li><strong>Increased Reliability</strong>: We will be resilient to any zonal incidents happening in a single zone, hence increasing the reliability and customer satisfaction</li><li><strong>Better Availability </strong>: Since, we are not using reservations on cloud, if there is resource shortage on Cloud in any region, we will be automatically moved to other zone.</li></ul><h3>Hardware Cost Optimization</h3><p><strong>What are Spot VMs?</strong></p><p>Spot Virtual machine (VM) instances that are excess Compute Engine capacity on already occupied node.</p><ul><li>Spot VMs have significant discounts, but Compute Engine might <strong>preemptively stop or delete (preempt) Spot VMs</strong> to reclaim the capacity at any time.</li><li><strong>60–90%</strong> cheaper than regular VMs</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZXFlysISlqKoCYbAHcnGEQ.gif" /><figcaption>Spot VMs in Action</figcaption></figure><p><strong>Motivation for Shifting the Spark Executors to Spot VMs</strong></p><ul><li>Spark’s backbone is RDDs, which is immutable and fault-tolerant collection of elements, which makes spark fault-tolerant as well.</li><li><strong>Fault–tolerant -&gt; cater preemption of VMs</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*utwGwWHOgF4qL2jxVMpuLQ.png" /><figcaption>Motivation for moving to Spot VMs for Batch Workloads</figcaption></figure><p><strong>Gotchas</strong></p><ul><li>But using Spot VMs does not come without challenges, what if there are no Spot VMs available, our jobs SLAs would take a hit, so we needed to ensure that only if the Spot VMs are available, we should use them but if Spot VMs are unavailable in that case we should continue using the normal VMs, so we basically needed a soft affinity.</li><li>Since the driver pods were also running on the same K8s cluster, we needed to ensure that driver pods should not run on the Spot Nodes, otherwise on preemption of Spot Node resulting to preemption of Driver pod would have led to loss of complete job progress. For this we eventually added taints onto the Spot Nodes and ensured that only the executor pods run on them since they were the only ones to have tolerations.</li><li>•For <strong>high priority jobs </strong>and <strong>long running jobs</strong>, we should use non-preemptible VMs and their SLA is not hampered</li></ul><p>To ensure both of the above points we attached the affinity to pod like below:</p><pre>affinity:<br>  nodeAffinity:      <br>    preferredDuringSchedulingIgnoredDuringExecution:<br>    - weight: 100<br>      preference:<br>        matchExpressions:<br>        - key: cloud.google.com/gke-spot<br>          operator: In<br>          values:<br>          - &quot;true”<br>tolerations:<br>- key: cloud.google.com/gke-spot<br>  operator: Equal<br>  value: &quot;true&quot;<br>  effect: NoSchedule</pre><p>We again developed a feature step for doing this and ensured that it is extremely easily configurable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c53d0a069c1dd6887f83418f232bdec7/href">https://medium.com/media/c53d0a069c1dd6887f83418f232bdec7/href</a></iframe><h4>Results</h4><ul><li>Lowered monthly hardware costing by ~90k US$</li><li>Total Spark Jobs compute cost was down by ~45%.</li></ul><h3>Conclusion</h3><p>Public Clouds can be extremely costly if we do not pay attention to the smaller pricing details of the resources as well as do not design the system well to take care of such nitty details.</p><p>In summary, cost optimization for Spark on Kubernetes batch workloads on public clouds hinges on leveraging Spot Instances for executors, colocating the executors in a single zone, dynamic resource allocation, and auto scaling to achieve up to 50% savings while maintaining resiliency as well as availability.</p><h3><strong>References</strong></h3><ul><li><a href="https://dev.to/__354f265b41dafa0d901b/bigquerys-ridiculous-pricing-model-cost-us-10000-in-just-22-seconds-4c43">https://dev.to/__354f265b41dafa0d901b/bigquerys-ridiculous-pricing-model-cost-us-10000-in-just-22-seconds-4c43</a></li><li><a href="https://spark.apache.org/docs/latest/running-on-kubernetes.html">https://spark.apache.org/docs/latest/running-on-kubernetes.html</a></li><li><a href="https://www.naukri.com/code360/library/introduction-to-apache-spark">https://www.naukri.com/code360/library/introduction-to-apache-spark</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa23585b4b45" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science-collective/cost-optimization-of-spark-on-kubernetes-batch-workloads-on-public-clouds-aa23585b4b45">Cost Optimization of Spark on Kubernetes Batch Workloads on Public Clouds</a> was originally published in <a href="https://medium.com/data-science-collective">Data Science Collective</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Efficient Cardinality Estimation using HLL with Spark and Postgres]]></title>
            <link>https://medium.com/data-science/efficient-cardinality-estimation-using-hll-with-spark-and-postgres-dcf1cd66ede9?source=rss-d774cabc71ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/dcf1cd66ede9</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[hyperloglog]]></category>
            <category><![CDATA[postgres]]></category>
            <dc:creator><![CDATA[Ankit Prakash Gupta]]></dc:creator>
            <pubDate>Sat, 12 Jun 2021 18:10:43 GMT</pubDate>
            <atom:updated>2021-06-14T03:53:31.920Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A complete guide that assists you to do end-to-end efficient cardinality estimation using HyperLogLog Algorithm.</em></p><h3><strong>Problem Statement</strong></h3><p>The cardinality estimation problem is the problem of finding the number of distinct elements in a chunk of data with the same elements being repeated multiple times. The problem is very generic and has a lot of applications in the real world like active-unique users of a website, unique live sessions and many more.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b928a93d2d3f02f40d8a9dc5afa97b87/href">https://medium.com/media/b928a93d2d3f02f40d8a9dc5afa97b87/href</a></iframe><p>The problem seems to be child’s play, but we have to keep all the values in a set to keep a track of what all values we have already taken into consideration and this will eventually be a problem when we talk of Millions or Billions of Users/ Sessions. We surely cannot keep and process sets having such big cardinalities in memory.</p><h3><strong>Possible Solutions</strong></h3><p>We can use any of the following approaches for doing the cardinality estimation:</p><ol><li>Distinct Counting</li><li>Linear Counting</li><li>LogLog Algorithm</li><li>HyperLogLog Algorithm</li></ol><p><strong>Distinct Counting</strong></p><p>Brute-force approach of finding the cardinality, what we discussed above about keeping all unique elements in a set and finding out the cardinality. It is linear O(n) in terms of time and space complexities, storing all objects as is.</p><p><strong>Linear Counting</strong></p><p>This technique uses a hash table with capacity B bits, all bits initialised to 0. As soon as an entry arrives we hash it and that bit’s value is changed to 1. Deduplication is being taken care of by hashing the inputs. This algorithm is also linear in terms of time and space complexities but takes much less space as we are only saving bits and not the exact values. Now, let’s compare the size of the hash table with the size of Unique Elements we can have. Suppose, N unique entries can come in your set:</p><ol><li>When N &lt;&lt; B, then hash collisions would be less and the count of 1 bit in the hash table would be a good estimate of the cardinality.</li><li>When N ≈ B, then a significant number of hash collisions would surely occur. But we can estimate the number of collisions by checking how full the hash table is. Using this estimation of the number of collisions we can extrapolate to the approximate cardinality of the set.</li><li>When N &gt;&gt; B, then every bit in the hash table would be set to 1 and it won’t be possible to calculate the true cardinality.</li></ol><p>This approach seems to be a good fit when we have knowledge about the maximum possible unique elements we can have priori.</p><p><strong>LogLog Algorithm</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y8cj7Pz4tyKfOcgaT6ZY7Q.png" /></figure><p>This algorithm is also based on hashing, it keeps a track of the maximum number of zeroes appearing in the binary representation of the hashed values. Let’s assume that the maximum number of zeroes appearing is k, then the estimated count would be 2^k.</p><p>It is based on the idea that one-half of the values would start with 1 and one-fourth with 01 and one-eighth with 001 and so on, the probability of getting the k leading zeroes would be 1/2^(k+1). Now, this estimation would be very unstable and would have a very high variance as we can have the very first hashed value having 5 leading zeroes also.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*7K6O22q1jzCSJtfuwmW5MQ.png" /></figure><p>To make it more stable we take average (arithmetic mean) values of the estimates given by multiple hash functions. Bringing us to another computationally expensive process, hashing. Now, to cater for this issue, LogLog converts the value attained from the already hashed value into 2 values, taking the first m bits, which points to a specific bucket of values and then the rest of the bits as the value to get the maximum number of zeroes.</p><p>So, if we assume that our hash function returned 32 bits, and we took the first 14 bits to decide the bucket to which it points, so we will have 2^14 buckets to average the value of k from.</p><p>Suppose in each bucket we wanted to store N elements then we will have to store only a single number which is of log(N) magnitude and to store that we need only log(log(N)) number of bits, which gives it its name.</p><p>Taking as an example, if we take 5 bits register for each bucket to store the max-value of k for that bucket and 2^14 buckets, which will allow us to have values for each bucket from 0–31, which means that we might have 2^31 elements in each bucket (Using the above probability), which implies that we can approximately keep 2^(31+14) distinct elements at max, by using space (214 * 5) = 81920 bits (10 KBs) only.</p><p>It defines the estimated count as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*aCWkUnuDp6ha0kn7lp2tlQ.png" /></figure><blockquote>where, α → estimation factor (constant value) <br> registers(i) → value of the max-leading-zero count for the ith bucket</blockquote><h4>HyperLogLog Algorithm</h4><p>This is an improvement algorithm on LogLog Algorithm. It uses Harmonic mean in place of arithmetic mean when combining the results of multiple buckets, which caters unusually high values of max-leading-zero counts. Additionally, it provides corrections for two extreme cases when not all of the buckets are occupied and when a hash collision causes underestimation.</p><h3>HyperLogLog Implementation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nHy_Ze40g6-Vc_TA5fG5Fw.png" /></figure><p>Different libraries are implementing the HLL algorithm, we chose to use Aggregate Knowledge’s HLL implementation, because of the following factors:</p><ul><li>Has an inter-operable library with Postgres DB (<a href="https://github.com/citusdata/postgresql-hll">postgresql-hll</a>) as well as same has been used by Swoop’s <a href="https://github.com/swoop-inc/spark-alchemy">Spark-Alchemy</a>.</li><li>Has an ability to union two HLLs.</li><li>Easy to use APIs.</li></ul><h3>Implementation</h3><p>To try out the <a href="https://github.com/citusdata/postgresql-hll">postgresql-hll</a> extension on Mac Systems, Please use the following steps:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e42c82f7e07581691490d124caf4c68b/href">https://medium.com/media/e42c82f7e07581691490d124caf4c68b/href</a></iframe><p>So, the extension is installed in Postgres. Now, we need to run the following query to activate the extension in a particular DB.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fbf6ada4f9cda666b637ae2c7845a88b/href">https://medium.com/media/fbf6ada4f9cda666b637ae2c7845a88b/href</a></iframe><p>To test the above example, Create a table and inserted some data with the following queries:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/295da4cf674e7ce325d7385984d220b4/href">https://medium.com/media/295da4cf674e7ce325d7385984d220b4/href</a></iframe><p>Then tried the interoperability of the HLLs in Postgres with Java APIs. Created another table using the following query</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db8d6f44ba8616c07cb2fa09809ed485/href">https://medium.com/media/db8d6f44ba8616c07cb2fa09809ed485/href</a></iframe><p>Then used a Java Program to Create HLLs using a range of numbers from 0 to n, so that we know how many unique entries are there in it, pushed them to Postgres and then aggregated and did a count on them. Since we know the unique entries this way, we can calculate the error percentages for user_id and session_id.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b1cfe361b5a3f5809adb7d372b8834e/href">https://medium.com/media/5b1cfe361b5a3f5809adb7d372b8834e/href</a></iframe><p>A few things to note here are:</p><ul><li>If we want to union two HLLs or merge two HLLs, then we should always hash them with the same seed, or else the same value will also give two different hashed value and will be counted as two.</li><li>Standard Error for the HLLs can be given by the following formula and the calculated values are expected to be within the σ, 2σ, 3σ of the actual count for 65%, 95%, 99% of the cases respectively.<br>σ = (1.04)/√(number of buckets)</li></ul><h3>Spark UDFs</h3><p>We used the Java APIs to write the UDFs</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f7411e55b244060e2be2ee32576ebd6/href">https://medium.com/media/6f7411e55b244060e2be2ee32576ebd6/href</a></iframe><h3>Aggregate Knowledge’s Storage Specifications</h3><p>Let’s visit the types of the HLLs AgKn has come up with to increase the accuracy of Cardinality Estimation.</p><h4>Types</h4><ul><li><strong>Empty</strong><br>A constant value denotes the empty set.</li><li><strong>Explicit</strong><br>An explicit, unique, sorted list of hashed integers in the set, which is maintained up to a fixed cardinality [If using the Auto expthresh (-1) that number can be defined by (regwidth * 2^log2m)/64 )]. This is done to increase accuracy at low cardinalities, as we can directly keep the explicit set of hashed inputs as a sorted list of 64-bit integers. We can also tweak the expthresh, to keep more numbers or fewer numbers according to our use-case, but the auto mode supports optimal memory usage.</li><li><strong>Sparse</strong><br>Its idea is based on Sparse Arrays, in which we keep the values of indexes that have only non-zero values. Similarly, it is a map-based implementation of HLL, which stores only the indices values of non-zero registers in a map, until the number of non-zero registers exceeds a fixed cardinality. So, it actually keeps the registers value of only those buckets whose register is having at least 1 non-0 bit.</li><li><strong>Full</strong><br>A fully materialised, list-based implementation of HLL. Explicitly stores the values of every register in a list ordered by register index.</li></ul><p>Not, visiting the Schema Layout and how data is arranged in the byte array format, it can be visited <a href="https://github.com/aggregateknowledge/hll-storage-spec/blob/master/STORAGE.md#storage">here</a>.</p><h3>Aggregate Knowledge’s Parameter Definition and Tuning</h3><h4>1. Log2m</h4><p>This value decides the number of buckets or registers, m is the actual number of registers here, and we can calculate the number of registers by 2(Log2m). Also, this value decides the accuracy of the HLLs. The following expression gives the standard error estimate. Also, one important thing to note is the calculated values are expected to be within the σ, 2σ, 3σ of the actual count for 65%, 95%, 99% of the cases respectively.<br>σ = (1.04)/√(m)</p><h4>2. RegWidth</h4><p>This is the width of the Register/Bucket or the number of bits to be used per register in the HLL Algorithm. Must be at least 1 and at most 8. This parameter, in conjunction with log2m, tunes the maximum cardinality of the set whose cardinality can be estimated. Please refer to the <a href="https://github.com/citusdata/postgresql-hll#regwidth">table</a> for the clarification of the HLL sizes and Maximum Cardinalities.</p><p><strong>3. ExpThresh</strong></p><p>Tunes when the EXPLICIT to SPARSE promotion occurs, based on the set’s cardinality.</p><pre>If the `EXPLICIT` representation is turned off, the `EMPTY` set is promoted directly to `SPARSE`. Must be -1 {Promote at whatever cutoff makes sense for optimal memory usage. (&#39;auto&#39; mode)}, 0 {Skip EXPLICIT representation in hierarchy. (Promotes directly to Sparse.)}, or 1-18 inclusive {Promote at 2^expthresh - 1 cardinality}.</pre><p>You can choose the EXPLICIT cutoff such that it will end up taking more memory than a FULL hll representation. This is allowed for those cases where perfect precision and accuracy are required up through some pre-set cardinality range, after which estimates of the cardinality are sufficient.</p><p><strong>4. SparseOn</strong></p><p>Enables or disables the SPARSE representation. If both the EXPLICIT and SPARSE representations are disabled, an EMPTY set will be promoted directly to a FULL set. If SPARSE is enabled, the promotion from SPARSE to FULL will occur when the internal SPARSE representation’s memory footprint would exceed that of the FULL version. Must be either true or false. True means enabled and false means disabled.</p><h3>Conclusion</h3><p>HyperLogLog Algorithm helps solve the cardinality estimation problem up to a certain threshold without overburdening the storage space to keep all the elements.</p><p>Additionally, Aggregate knowledge provides great Support for HLL Algorithms. Other libraries which can be tried are <a href="https://datasketches.apache.org/docs/HLL/HLL.html">Datasketch</a>, <a href="https://github.com/google/zetasketch">Zetasketch</a>.</p><h3>References</h3><ul><li><a href="https://mungingdata.com/apache-spark/hyperloglog-count-distinct/">https://mungingdata.com/apache-spark/hyperloglog-count-distinct/</a></li><li><a href="https://github.com/swoop-inc/spark-alchemy/wiki/Spark-HyperLogLog-Functions">https://github.com/swoop-inc/spark-alchemy/wiki/Spark-HyperLogLog-Functions</a></li><li><a href="https://databricks.com/session_eu19/high-performance-advanced-analytics-with-spark-alchemy">https://databricks.com/session_eu19/high-performance-advanced-analytics-with-spark-alchemy</a></li><li><a href="https://github.com/aggregateknowledge/java-hll">https://github.com/aggregateknowledge/java-hll</a></li><li><a href="https://www.moderndescartes.com/essays/hyperloglog/index.html">https://www.moderndescartes.com/essays/hyperloglog/index.html</a></li><li><a href="https://highlyscalable.wordpress.com/2012/05/01/probabilistic-structures-web-analytics-data-mining/">https://highlyscalable.wordpress.com/2012/05/01/probabilistic-structures-web-analytics-data-mining/</a></li><li><a href="https://github.com/citusdata/postgresql-hll#explanation-of-parameters-and-tuning">https://github.com/citusdata/postgresql-hll#explanation-of-parameters-and-tuning</a></li><li><a href="https://github.com/aggregateknowledge/hll-storage-spec/blob/master/STORAGE.md">https://github.com/aggregateknowledge/hll-storage-spec/blob/master/STORAGE.md</a></li><li><a href="https://banner2.cleanpng.com/20190623/uxe/kisspng-logo-java-development-kit-portable-network-graphic-5d0f25d6871765.6875406615612738145533.jpg">https://banner2.cleanpng.com/20190623/uxe/kisspng-logo-java-development-kit-portable-network-graphic-5d0f25d6871765.6875406615612738145533.jpg</a></li><li><a href="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f3/Apache_Spark_logo.svg/1200px-Apache_Spark_logo.svg.png">https://upload.wikimedia.org/wikipedia/commons/thumb/f/f3/Apache_Spark_logo.svg/1200px-Apache_Spark_logo.svg.png</a></li><li><a href="https://cpl.thalesgroup.com/sites/default/files/content/paragraphs/intro/2020-03/postgresql-logo.png">https://cpl.thalesgroup.com/sites/default/files/content/paragraphs/intro/2020-03/postgresql-logo.png</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dcf1cd66ede9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/efficient-cardinality-estimation-using-hll-with-spark-and-postgres-dcf1cd66ede9">Efficient Cardinality Estimation using HLL with Spark and Postgres</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apache Hive Optimization Techniques — 2]]></title>
            <link>https://medium.com/data-science/apache-hive-optimization-techniques-2-e60b6200eeca?source=rss-d774cabc71ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/e60b6200eeca</guid>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[apache-hive]]></category>
            <category><![CDATA[best-practices]]></category>
            <dc:creator><![CDATA[Ankit Prakash Gupta]]></dc:creator>
            <pubDate>Tue, 13 Aug 2019 10:06:34 GMT</pubDate>
            <atom:updated>2019-08-14T00:26:56.341Z</atom:updated>
            <content:encoded><![CDATA[<h3>Apache Hive Optimization Techniques — 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*phURc4rNRM7wmCts_MJJ4g.png" /></figure><p>In the <a href="https://towardsdatascience.com/apache-hive-optimization-techniques-1-ce55331dbf5e">earlier article</a>, we covered how appropriate data modeling using partitioning and bucketing, choosing Tez as execution engine as well as compression could prove to be very big cost-saving factors. Let us now delve into the other factors which can be very fruitful optimizations.</p><h3>Using ORC Format</h3><p>Choosing the correct file format can be another thing which can optimize the processing job to a great extent. Hive supports a big family of file-formats:</p><ul><li>Text File</li><li>SequenceFile</li><li>RCFiles</li><li>Avro Files</li><li>ORC Files</li><li>Parquet</li><li>Custom INPUTFORMAT and OUTPUTFORMAT</li></ul><p>Before, any of these columnar-format most of the data was stored in the form of delimited text files. In these files, even if we have to read only one column we have to read and parse the whole record for each row. ORC files enable numerous optimizations in Hive like the following:</p><ul><li>Achieves higher level of compression, the compression algorithm can be changed using <strong>orc.compress </strong>setting in the hive. By default, it uses Zlib Compression.</li><li>It has the ability to skip scanning an entire range of rows within a block, if irrelevant to the query, using the light-weight indexes stored within the file.</li><li>It has the ability to skip decompression of rows within a block, if irrelevant to the query.</li><li>Single file as the output of each task, reducing the load on the name node.</li><li>It supports multiple streams to read the file simultaneously.</li><li>It keeps the metadata stored in the file using Protocol Buffers, used for serializing structured data.</li></ul><p>The ORC storage strategy is both column-oriented and row-oriented. An ORC format file consists of tabular data that is written in “stripes” of a convenient size to process in a single mapper (256 MB and 512 MB are common sizes.) Stripes may or may not be processed by separate tasks, and a single ORC file can contain many stripes, each of which is independent. In stripes, the columns are compressed separately, only the columns that are in the projection for a query need be decompressed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*Y8Urvk1yFoo0jmYf8XBvgQ.png" /></figure><p>Within a stripe the data is divided into 3 Groups:</p><ol><li>The <strong>stripe footer</strong> contains a directory of stream locations.</li><li><strong>Row data</strong> is used in table scans, by default contains 10,000 rows.</li><li><strong>Index data</strong> include min and max values for each column and row positions within each column. <strong>Row index</strong> entries provide offsets that enable seeking to the right compression block and byte within a decompressed block. Note that ORC indexes are used only for the selection of stripes and row groups and not for answering queries.</li></ol><p>Just using ORC format, gives rise to the following optimizations:</p><ul><li>Push-down Predicates</li><li>Bloom Filters</li><li>ORC Compression</li><li>Vectorization</li></ul><h4>Push-down Predicates</h4><p>The ORC reader uses the information present in the Index data of the stripes, to make sure whether the data in the stripe is relevant to the query or not. So, essentially the where conditions of the query are passed to the ORC Reader, before bothering to unpack the relevant columns from the row data block. For instance, if the value from the where condition is not within the min/max range for a block, the entire block can be skipped.</p><h4>Bloom Filters</h4><p>Bloom Filters is a probabilistic data structure that tells us whether an element is present in a set or not by using a minimal amount of memory. A catchy thing about bloom filters is that they will occasionally incorrectly answer that an element is present when it is not. Their saving grace, however, is that they will never tell you that an element is not present if it is.</p><p>Bloom Filters again helps in the push-down predicates for ORC File formats. If a Bloom filter is specified for a column, even if the min/max values in a row-group’s index say that a given column value is within the range for the row group, the Bloom filter can answer specifically whether the value is actually present. If there is a significant probability that values in a where clause will not be present, this can save a lot of pointless data manipulation.</p><p>We can set the bloom filter columns and bloom filter’s false positive probability using the following table properties:</p><ul><li><strong>orc.bloom.filter.columns: </strong>comma-separated list of column names for which bloom filter should be created</li><li><strong>orc.bloom.filter.fpp: </strong>false positive probability for bloom filter.</li></ul><h4>ORC Compression</h4><p>ORC format not only compresses the values of the columns but also compresses the stripes as a whole. It also provides choices for the overall compression algorithm. It allows the following compression algorithm to be used :</p><ul><li><strong>Zlib: </strong>Higher Compression. Uses more CPU and saves space.</li><li><strong>Snappy : </strong>Compresses less. Uses less CPU and more space.</li><li><strong>None: </strong>No compression at all.</li></ul><p>If the CPU is tight, you might want to use Snappy. Rarely will you want to use none, which is used primarily for diagnostic purposes. Also, the Hive’s writer is intelligent if it does not foresee any marginal gain, it will not compress the data.</p><h4>Vectorization</h4><p>Query Operations like scanning, filtering, aggregations, and joins can be optimized to a great extent using the vectorized query execution. A standard query execution processes one row at a time and goes through a long code path as well as significant metadata interpretation.</p><p>Vectorization optimizes the query execution by processing a block of 1024 rows at a time, inside which each row is saved as a vector. On vectors, simple arithmetic and comparison operations are done very quickly. Execution is speeded up because within a large block of data of the same type, the compiler can generate code to execute identical functions in a tight loop without going through the long code path that would be required for independent function calls. This SIMD-like behavior gives rise to a host of low-level efficiencies: fewer instructions executed, superior caching behavior, improved pipelining, more favorable TLB behavior, etc.</p><p>Not every data type and operation can benefit from vectorization, but most simple operations do, and the net is usually a significant speedup.</p><p>To use vectorized query execution, you must store your data in ORC format, and set the following variable as shown in Hive SQL:</p><blockquote><strong>set hive.vectorized.execution.enabled = true;</strong></blockquote><blockquote><strong>set hive.vectorized.execution.reduce.enabled=true</strong></blockquote><blockquote><strong>set hive.vectorized.execution.reduce.groupby.enabled=true</strong></blockquote><p>We can check if the query is being executed in a vectorized manner using the Explain Command. In the output of the Explain Command, you will probably see the following in different stages:</p><p><strong>Execution mode:</strong> vectorized</p><h3>Join Optimizations</h3><p>So, before delving into the join optimizations, let’s understand how a common join query is actually executed using MapReduce.</p><ul><li>Mappers do the parallel sort of the tables on the join keys, which are then passed on to reducers.</li><li>All of the tuples with the same key is given to the same reducer. A reducer may get tuples for more than one key. Key for tuple will also include table id, thus sorted output from two different tables with the same key can be recognized. Reducers will merge the sorted stream to get join output.</li></ul><p>One thing to keep in mind while writing the join query is the table which is mentioned last is streamed through the reducers, rest all are buffered in the memory in the reducers. So, we should always keep in mind that the large table is mentioned in the last which will lessen the memory needed by the reducer, or we can use the STREAMTABLE hint.</p><blockquote><em>SELECT /*+ STREAMTABLE(a) */ a.val, b.val, c.val FROM a JOIN b ON (a.key = b.key1) JOIN c ON (c.key = b.key1)</em></blockquote><p>Another thing to pay attention to when where clause is used with a join, then join part is executed first and then the results are filtered using the where clauses. Like, in the below query:</p><blockquote>SELECT a.val, b.val FROM a LEFT OUTER JOIN b ON (a.key=b.key) WHERE a.ds=’2009–07–07&#39; AND b.ds=’2009–07–07&#39;</blockquote><p>While the same filtering of the records could have been executed along when joining the tables. This can be done by including the filtering conditions along with the join conditions.</p><blockquote>SELECT a.val, b.val FROM a LEFT OUTER JOIN b<br>ON (a.key=b.key AND b.ds=’2009–07–07&#39; AND a.ds=’2009–07–07&#39;)</blockquote><p>This join includes a shuffle phase in which outputs of the mappers is sorted and shuffled with the join keys, which takes a big cost to be executed in terms of processing, I/O and data transfer cost. So, to reduce the above-mentioned costs, a lot of join algorithms have been worked on, like:</p><ul><li>Multi-way Join</li><li>Map Join</li><li>Bucket Map Join</li><li>SMB Join</li><li>Skew Join</li></ul><h4>Multi-way Join</h4><p>If multiple joins share the same driving side join key then all of those joins can be done in a single task.<br>Example: (R1 PR1.x=R2.a — R2) PR1.x=R3.b — R3) PR1.x=R4.c — R4<br>All of the joins can be done in the same reducer since R1 will already be sorted based on join key x.<br>Hence, Reducing the number of reducers by doing all reducing task in just one reducer. Hive does this optimization itself and manages it internally. Like in the below query:</p><blockquote>SELECT a.val, b.val, c.val FROM a JOIN b ON (a.key = b.key1) JOIN c ON (c.key = b.key1)</blockquote><h4>Map Join (Broadcast Join or Broadcast-Hash Join)</h4><p>Useful for star schema joins, this joining algorithm keeps all of the small tables (dimension tables) in memory in all of the mappers and big table (fact table) is streamed over it in the mapper. This avoids shuffling cost that is inherent in Common-Join. For each of the small table (dimension table), a hash table would be created using join key as the hash table key and when merging the data in the Mapper Function, data will be matched with the mapping hash value.</p><p>But the constraint is, all but one of the tables being joined are small, the join can be performed as a map only job.</p><p>Hive can optimize join into the Map-Side join, if we allow it to optimize the joins by doing the following setting:</p><blockquote><strong>set hive.auto.convert.join=true;</strong></blockquote><blockquote><strong>set hive.auto.convert.join.noconditionaltask = true;</strong></blockquote><blockquote><strong>set hive.auto.convert.join.noconditionaltask.size = 10000000;</strong></blockquote><p>The first two settings will allow hive to optimize the joins and third setting will give hive an idea about the memory available in the mapper function to keep the hash table of the small tables.</p><p>Or else, we can also use MAPJOIN hint in the query, such as:</p><blockquote><strong>SELECT /*+ MAPJOIN(b) */ a.key, a.value</strong></blockquote><blockquote><strong>FROM a JOIN b ON a.key = b.key</strong></blockquote><p>But the restriction is, full outer join AND right outer join cannot be performed for the table b.</p><h4>Bucket Map Join</h4><p>Let’s assume that the size of the tables bigger to fit in the memory of the Mapper. But when chunked into buckets can fit in the memory, the tables being joined are bucketized on the join columns, and the number of buckets in one table is a multiple of the number of buckets in the other table, the buckets can be joined with each other by creating a hash table of the smaller table’s bucket in the memory and streaming the other table’s content in the mapper. Assuming, If table A and B have 4 buckets each, the following join can be done on the mapper only.</p><blockquote>SELECT /*+ MAPJOIN(b) */ a.key, a.value<br>FROM a JOIN b ON a.key = b.key</blockquote><p>Instead of fetching B completely for each mapper of A, only the required buckets are fetched. For the query above, the mapper processing bucket 1 for A will only fetch bucket 1 of B. It is not the default behavior, and is governed by the following parameter.</p><blockquote><strong>set hive.optimize.bucketmapjoin = true</strong></blockquote><h4>Sort-Merge-Bucket Join</h4><p>This is an optimization on Bucket Map Join; if data to be joined is already sorted on joining keys then hash table creation is avoided and instead a sort-merge join algorithm is used. This join can be used using the following settings:</p><blockquote><strong>set hive.input.format= org.apache.hadoop.hive.ql.io.BucketizedHiveInputFormat;<br>set hive.optimize.bucketmapjoin = true;<br>set hive.optimize.bucketmapjoin.sortedmerge = true;</strong></blockquote><p>The query would be the same as the above query, and the hive would form its execution strategy.</p><blockquote>SELECT /*+ MAPJOIN(b) */ a.key, a.value<br>FROM a JOIN b ON a.key = b.key</blockquote><h4>Skew Join</h4><p>If the distribution of data is skewed for some specific values, then join performance may suffer since some of the instances of join operators (reducers in the map-reduce world) may get overloaded and others may get underutilized. On user hint, hive would rewrite a join query around skew value as union of joins. So, it would execute one query to implement join of the skewed key and other for the rest of the join keys, and would further merge the outputs of both the queries.</p><p>Example R1 PR1.x=R2.a — R2 with most data distributed around x=1 then this join may be rewritten as (R1 PR1.x=R2.a and PR1.x=1 — R2) union all (R1 PR1.x=R2.a and PR1.x&lt;&gt;1 — R2)</p><blockquote><strong>set hive.optimize.skewjoin = true;<br>set hive.skewjoin.key=500000;</strong></blockquote><h3>Cost-based Optimizations</h3><p>So, we all will agree to the saying that there could be multiple solutions to one problem and until the rise of the cost-based optimizer, hive used the hard-coded query plans to execute a single query. The CBO lets hive optimize the query plan based on the metadata gathered. CBO provides two types of optimizations: logical and physical.</p><p><strong>Logical Optimizations:</strong></p><ul><li>Projection Pruning</li><li>Deducing Transitive Predicates</li><li>Predicate Pushdown</li><li>Merging of Select-Select, Filter-Filter into a single operator</li><li>Multi-way Join</li><li>Query Rewrite to accommodate for Join skew on some column values</li></ul><p><strong>Physical Optimizations:</strong></p><ul><li>Partition Pruning</li><li>Scan pruning based on partitions and bucketing</li><li>Scan pruning if a query is based on sampling</li><li>Apply Group By on the map side in some cases</li><li>Optimize Union so that union can be performed on map side only</li><li>Decide which table to stream last, based on user hint, in a multiway join</li><li>Remove unnecessary reduce sink operators</li><li>For queries with limit clause, reduce the number of files that needs to be scanned for the table.</li></ul><p>Turning on CBO will typically halve the execution time for a query, and may do much better than that.<strong> </strong>Along with these optimizations, CBO will also transform join queries into the best possible join using the statistics of the table saved in the metastore.</p><p>CBO can be turned on using the following setting in the hive-site.xml file :</p><blockquote><strong>hive.cbo.enable=true</strong></blockquote><p>The statistics of the table is auto gathered by hive, if <em>hive.stats.autogather</em> is set to True else could be calculated using the ANALYZE command.</p><p>I hope this and the <a href="https://towardsdatascience.com/apache-hive-optimization-techniques-1-ce55331dbf5e">earlier article</a> might have given you a complete overview of how Hive Queries can be optimized and how hive’s key features work in the background using MapReduce.</p><p>I hope you find this article informative and easy to learn if you have any queries feel free to reach me at <a href="/service/mailto:info.ankitp@gmail.com">info.ankitp@gmail.com</a> and connect with me on <a href="https://www.linkedin.com/in/infoankitp/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e60b6200eeca" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/apache-hive-optimization-techniques-2-e60b6200eeca">Apache Hive Optimization Techniques — 2</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apache Hive Optimization Techniques — 1]]></title>
            <link>https://medium.com/data-science/apache-hive-optimization-techniques-1-ce55331dbf5e?source=rss-d774cabc71ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce55331dbf5e</guid>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[hive]]></category>
            <category><![CDATA[hadoop]]></category>
            <category><![CDATA[tez]]></category>
            <dc:creator><![CDATA[Ankit Prakash Gupta]]></dc:creator>
            <pubDate>Fri, 09 Aug 2019 16:41:41 GMT</pubDate>
            <atom:updated>2019-08-13T10:07:59.640Z</atom:updated>
            <content:encoded><![CDATA[<h3>Apache Hive Optimization Techniques — 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nd79weIivnt7f43-mlP-DQ.png" /></figure><p>Apache Hive is a query and analysis engine which is built on top of Apache Hadoop and uses MapReduce Programming Model. It provides an abstraction layer to query big-data using the SQL syntax by implementing traditional SQL queries using the Java API. The main components of the Hive are as follows:</p><ul><li>Metastore</li><li>Driver</li><li>Compiler</li><li>Optimizer</li><li>Executor</li><li>Client</li></ul><p>While Hadoop/hive can process nearly any amount of data, but optimizations can lead to big savings, proportional to the amount of data, in terms of processing time and cost. There are a whole lot of optimizations that can be applied in the hive. Let us look into the optimization techniques we are going to cover:</p><ol><li>Partitioning</li><li>Bucketing</li><li>Using Tez as Execution Engine</li><li>Using Compression</li><li>Using ORC Format</li><li>Join Optimizations</li><li>Cost-based Optimizer</li></ol><h3><strong>Partitioning</strong></h3><p>Partitioning divides the table into parts based on the values of particular columns. A table can have multiple partition columns to identify a particular partition. Using partition it is easy to do queries on slices of the data. The data of the partition columns are not saved in the files. On checking the file structure you would notice that it creates folders on the basis of partition column values. This makes sure that only relevant data is read for the execution of a particular job, decreasing the I/O time required by the query. Thus, increasing the query performance.</p><p>When we query data on a partitioned table, it will only scan the relevant partitions to be queried and skips irrelevant partitions. Now, assume that even on partitioning, the data in a partition was quite big, to further divide it into more manageable chunks we can use Bucketing.</p><blockquote><em>CREATE TABLE table_name (column1 data_type, column2 data_type, …) PARTITIONED BY (partition1 data_type, partition2 data_type,….);</em></blockquote><ul><li>Partition Columns are not defined in the Column List of the table.</li><li>In insert queries, partitions are mentioned in the start and their column values are also given along with the values of the other columns but at the end.</li></ul><blockquote><strong><em>INSERT INTO TABLE table_name PARTITION (partition1 = ‘partition1_val’, partition2 = ‘partition2_val’, …) VALUES (col1_val, col2_val, …, partition1_val, partition2_val, …);</em></strong></blockquote><ul><li>Partitioning is basically of two types: <strong>Static</strong> and <strong>Dynamic</strong>. Well, names are very much self-explanatory.</li><li><strong>Static Partitioning<br></strong>This is practiced when we have knowledge about the partitions of data we are going to load. It should be preferred when loading data in a table from large files. It is performed in strict mode:</li></ul><blockquote><strong><em>set hive.mapred.mode = strict;</em></strong></blockquote><ul><li><strong>Dynamic Partitioning<br></strong>It is used when we do not have knowledge about the partitions of the data. It takes more time to load data in the table. Usually, we load data in the table using another table having non-partitioned data. <br>To enable dynamic partitioning in the hive:</li></ul><blockquote><strong><em>SET hive.exec.dynamic.partition = true;</em></strong></blockquote><p>There are two modes of <strong>dynamic partitioning:</strong><br><strong>Strict: </strong>This needs at least one column to be static while loading the data.<br><strong>Non-strict: </strong>This allows us to have dynamic values of all the partition columns.</p><blockquote><strong>SET hive.exec.dynamic.partition.mode = nonstrict;</strong></blockquote><p>Some other things are to be configured when using dynamic partitioning, like</p><blockquote><strong>Hive.exec.max.dynamic.partitions.pernode: </strong>Maximum number of partitions to be created in each mapper/reducer node</blockquote><blockquote><strong>Hive.exec.max.dynamic.partitions: </strong>Maximum number of dynamic partitions allowed to be created in total</blockquote><blockquote><strong>Hive.exec.max.created.files: </strong>Maximum number of HDFS files created by all mappers/reducers in a MapReduce job</blockquote><blockquote><strong>Hive.error.on.empty.partition: </strong>Whether to throw an exception if the dynamic partition insert generates empty results</blockquote><h3>Bucketing</h3><p>Bucketing provides flexibility to further segregate the data into more manageable sections called buckets or clusters. Bucketing is based on the hash function, which depends on the type of the bucketing column. Records which are bucketed by the same column value will always be saved in the same bucket. <strong>CLUSTERED BY</strong> clause is used to divide the table into buckets. It works well for the columns having high cardinality.</p><blockquote>CREATE TABLE table_name (column1 data_type, column2 data_type, …) PARTITIONED BY (partition1 data_type, partition2 data_type,….) CLUSTERED BY (clus_col1) SORTED BY (sort_col2) INTO n BUCKETS;</blockquote><p>In Hive Partition, each <strong>partition</strong> will be created as a <strong>directory</strong>. But in Hive Buckets, each <strong>bucket</strong> will be created as a <strong>file</strong>.</p><blockquote><strong>set hive.enforce.bucketing = true;</strong></blockquote><p>Using Bucketing we can also sort the data using one or more columns. Since the data files are equal-sized parts, map-side joins will be faster on the bucketed tables.</p><p>Bucketing also has its own benefit when used with ORC files and used as the joining column. We will further discuss these benefits.</p><h3>Using Tez as Execution Engine</h3><p>Apache Tez is a client-side library which operates like an execution engine, an alternative to traditional MapReduce Engine, under Hive and Pig which allows faster processing of jobs using the DAG formation.</p><p>To look into how Tez helps in optimizing the jobs, we will first look into the stereotyped processing sequence of a MapReduce Job:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/1*mRPF-3T7q50jsTtaJSWMEQ.png" /></figure><ul><li>The Mapper function reads data from the file system, processes it into Key-Value Pairs which is further stored temporarily on the local disk. These Key-value pairs, grouped on the key values, are sent to the reducers over the network.</li><li>On nodes where Reducers are to be run, the data is received and is saved on the local disk and waits for the data from all the mappers to arrive. Then, the entire set of values for a key is read into a single reducer, processed and further writes the output which is then further replicated based on the configuration.</li><li>As you can notice a whole lot of unnecessary read/write overhead is involved in a single MapReduce job. Multiple MapReduce jobs are run to accomplish a single Hive query and all outputs of the MapReduce Jobs are first written in the DFS and then transferred to nodes, and the cycle is repeated since there is no coordination between two MapReduce jobs.</li></ul><p>Apache Tez optimizes it by not breaking a Hive-query in multiple MapReduce Jobs. Since, Tez is a client-side library, to orchestrate the processing of MapReduce Jobs. Tez optimizes the jobs using the steps like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*sHCF1sPMTb2rKiipqzsQkQ.png" /></figure><ul><li>Skipping the DFS write by the reducers and piping the output of a reducer directly in the subsequent Mapper as input.</li><li>Cascading a series of Reducers without intervening Mapper steps.</li><li>Re-use of containers for successive phases of processing.</li><li>Optimal Resource usage using Pre-warmed containers.</li><li>Cost-based Optimizations.</li><li>Vectorized Query Processing.</li></ul><p>We can set the execution engine using the following query, or by setting it in the hive-site.xml.</p><blockquote><strong>set hive.execution.engine=tez/mr</strong></blockquote><h3>Using Compression</h3><p>As you might have noticed that hive queries involve a lot of Disks I/O or Network I/O operations, which can be easily reduced by reducing the size of the data which is done by compression. Most of the data formats in Hive are the text-based formats which are very compressible and can lead to big savings. But, there is a trade-off involved when we take compression into consideration, the CPU cost of compression and decompression.</p><p>Following are the main situations where I/O operations are performed and compression can save cost:</p><ul><li>Reading data from a local DFS directory</li><li>Reading data from a non-local DFS directory</li><li>Moving data from reducers to the Next stage Mappers/Reducers</li><li>Moving the final output back to the DFS.</li></ul><p>Also, DFS replicates the data as well to be fault-tolerant, there are more I/O operations involved when we are replicating data.</p><p>You can import text files compressed with Gzip or Bzip2 directly into a table stored as TextFile. Compressed data can directly be loaded in Hive, using the LOAD statement or by creating table over compressed data location. The compression will be detected automatically and the file will be decompressed on-the-fly during query execution. However, in this case, Hadoop will not be able to split your file into chunks/blocks and run multiple maps in parallel. But, zipped sequence files can be split into multiple.</p><p>The above optimizations will save a whole lot of execution cost and will lead to pretty quicker execution of jobs. In the <a href="https://medium.com/@info.ankitp/apache-hive-optimization-techniques-2-e60b6200eeca">next article</a>, we will discuss the remaining techniques: optimizations using ORC files, optimizations in Join queries as well as the Cost Based Optimizer.</p><p>I hope you find this article informative and easy to learn if you have any queries feel free to reach me at <a href="/service/mailto:info.ankitp@gmail.com">info.ankitp@gmail.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce55331dbf5e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/apache-hive-optimization-techniques-1-ce55331dbf5e">Apache Hive Optimization Techniques — 1</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The characteristics of Big Data platforms and their importance for data exploration]]></title>
            <link>https://medium.com/data-science/the-characteristics-of-big-data-platforms-and-their-importance-for-data-exploration-650ec45cec14?source=rss-d774cabc71ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/650ec45cec14</guid>
            <dc:creator><![CDATA[Ankit Prakash Gupta]]></dc:creator>
            <pubDate>Tue, 28 May 2019 02:31:28 GMT</pubDate>
            <atom:updated>2019-05-29T12:27:46.829Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nAi01GeQyQCwGO7XX1OEgQ.png" /></figure><p><strong>Introduction: </strong>The exponentially increasing data has been the key to knowledge in the last decade. Traditional Systems couldn’t do the timely processing of such volumes of data. Big data Technologies and Platforms have made it possible to generate not just information but also meaningful insights timely. It is not just the volume of the data, but the variety, structured or unstructured, and velocity of the increment of the data which makes traditional systems incapable of processing the humongous data. On the basis of the velocity of the ingestion, preprocessing and processing, the processing of the data can be of different kinds: Batch, Real-time, Stream, and Interactive. The increasing demand to process the enormous data led to the rise of many Big Data Platforms like Cloudera’s Distribution for Hadoop (CDH), Hortonworks Data Platform (HDP), AWS Elastic Map-Reduce(AWS-EMR) and many more. Each of these distributions of open source technologies like Apache Hadoop, Hive, HBase, Sqoop, etc. is a unified product on which users don’t have to spend time on assembling these elements into a single functional component. This essay will further discuss the architectures of the CDH, HDP, and AWS-EMR and compare them and also discusses how those are important for data exploration and intuition generation.</p><p><strong>Architectures of Different Big Data Platforms :</strong></p><ol><li><strong>Hortonworks Data Platform (HDP): </strong>HDP is a combination of open source technologies aimed to simplify the adoption of Big Data Technologies. HDP’s latest version 3.1 supports batch processing services, stream processing services, real-time processing services as well as Machine Learning and Deep Learning Frameworks. It uses Apache Ranger, Apache Knox and Apache Atlas for consistent and secure access to the data as well as management of the metadata and Apache Ambari for orchestrating the provisioning, managing, and monitoring of a cluster. Yarn does all the resource negotiation for the Cluster. HDP is now a Hybrid Data Platform, i.e., analysis scripts can be run on Cloud Storages (AWS S3, Azure ADLS) along with the HDFS Storage System. HDP also supports Distributed Tensorflow using which Deep learning scripts can be run on a distributed cluster. HDP also supports third-party applications in Docker containers or native Yarn Containers.</li><li><strong>2.2. Cloudera’s Distribution for Hadoop (CDH): </strong>CDH’s vision has been to bring analytical queries and real-time queries to Hadoop and Big Data, which pushed them to work on projects like Impala, Kudu which were later donated to Apache Software Foundation. Cloudera has come up with different solutions based on the usage of the data, namely: Data Warehouse, Data Science, Data Engineering, Operational Database and Hybrid Cloud Deployment which are provided in different combinations as per need of the customer. CDH is also a Hybrid Data Platform. Just like HDP, CDH also does not support Jupyter IPython Notebooks. CDH also supports Apache Kite which provides high-level APIs and tools to store data in a Hadoop Cluster.</li><li><strong>Amazon Web Service — Elastic Map-Reduce (AWS-EMR): </strong>Amazon Web Services has been a complete solution for an enterprise, they offer complete cloud solutions (Infrastructure, Platform, Software). They offer Big Data analytics with EMR. EMR is not a Hybrid Data Platform but is closely knitted with S3 for analytics. EMR offers great cost-savings as we can specifically configure to launch a cluster for a job and shut it down as soon as the job ends or run a cluster continuously as per our own choice. We can also scale a cluster dynamically while a job is running. AWS EMR clusters also support TensorFlow and MxNet Deep Learning Frameworks.</li></ol><p><strong>Data Exploration with different Big Data Platforms</strong>: Big Data Exploration basically follows either of the two famous architectures, either Lambda or Kappa. Lambda includes the Batch Processing Layer, Stream Processing layer and Service Layer, while in Kappa Architecture batch processing layer is skipped and both real-time and continuous processing is done in a single stream. Each big data platforms uses different tools for different processing types. So, to compare the three big data platform, we shall compare them in the processing scenarios:</p><ol><li><strong>Batch Processing: </strong>All three platforms support a wide variety of Batch Processing Tools, such as Apache Hadoop, Hive, Pig, Spark; which can be used for both batch as well as stream processing. HDP and CDH do not support Flink which is another Hybrid Processing Tool just like Spark, Flink and Presto are available with AWS-EMR and CDH support Impala as a batch processing tool which provides very quick throughput.</li><li><strong>Stream Processing: </strong>For Stream Processing Spark and Kafka is supported by all three platforms additionally, AWS-EMR supports Apache Flink and HDP supports Apache Storm. Storm is the first true Stream Processing Engine while Flink in its core is another true Stream Processing Engine and supports almost all advanced features for stream processing like event time processing, watermarks, etc and also provides low latency with high throughput.</li><li><strong>Service Layer or Real-time Processing: </strong>Hbase is a common tool in all the platforms, which can be used for servicing the data while CDH supports Kudu. Druid is supported by HDP along with Phoenix and Accumulo and AWS provides Hbase and Phoenix for quick-accessing and querying data.</li></ol><p><strong>Conclusion:</strong> The universe of data on analysis enlighten patterns which could succor humans in every realm of life. Big data technologies like Hadoop, Spark, etc. made such analysis possible. Big data platforms facilitated the easier implementation of big data processing architectures: Lambda and Kappa by provisioning of big data technologies together. On comparing the architectures of AWS-EMR, CDH, and HDP, we noticed that all the platforms brings up different amalgamation of technologies, have started facilitating the distributed Deep Learning frameworks and are independently complete platforms to perform any type of processing of the data.</p><p><strong>References:<br></strong>1. <a href="https://www.ibm.com/downloads/cas/DKWR4KZB">Hortonworks Data Platform</a><br>2. <a href="https://www.researchgate.net/profile/Allae_Erraissi/publication/322686669_Digging_into_Hadoop-based_Big_Data_Architectures/links/5a68e1cea6fdcccd01a1943f/Digging-into-Hadoop-based%20-Big-Data-Architectures.pdf">Digging into Hadoop-based Big Data Architectures</a><br>3. <a href="https://hortonworks.com/products/data-platforms/hdp/">Hortonworks Data Platform</a><br>4. <a href="https://www.cloudera.com/documentation/enterprise/6/6.1/topics/introduction.html">Cloudera Enterprise Architecture</a><br>5. <a href="https://aws.amazon.com/emr/">Amazon EMR Architecture</a><br>6. <a href="http://druid.io/docs/latest/comparisons/druid-vs-kudu.html">Druid vs Kudu</a><br>7. <a href="https://cs.uwaterloo.ca/~jimmylin/publications/Lin_IEEE2017b.pdf">The Lambda and the Kappa</a><br>8. <a href="https://medium.com/@chandanbaranwal/spark-streaming-vs-flink-vs-storm-vs-kafka-streams-vs%20-samza-choose-your-stream-processing-91ea3f04675b">Spark Streaming vs Flink vs Storm vs Kafka Streams vs Samza: Choose Your Stream Processing Framework</a></p><p>I hope you find this article informative and easy to learn, if you have any queries feel free to reach me at <a href="/service/mailto:info.ankitp@gmail.com">info.ankitp@gmail.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=650ec45cec14" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/the-characteristics-of-big-data-platforms-and-their-importance-for-data-exploration-650ec45cec14">The characteristics of Big Data platforms and their importance for data exploration</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Going Serverless with AWS Lambda Functions — 2]]></title>
            <link>https://medium.com/geekculture/going-serverless-with-aws-lambda-functions-2-51a1bd786547?source=rss-d774cabc71ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/51a1bd786547</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <dc:creator><![CDATA[Ankit Prakash Gupta]]></dc:creator>
            <pubDate>Sun, 13 Jan 2019 14:57:08 GMT</pubDate>
            <atom:updated>2021-06-13T11:31:53.165Z</atom:updated>
            <content:encoded><![CDATA[<h3>Going Serverless with AWS Lambda Functions — 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*OzF8lZeoDGxAJ4HzrHbp1w.png" /></figure><p>As discussed earlier, <a href="https://medium.com/@info.ankitp/going-serverless-with-aws-lambda-functions-1-edec330c2bce">in the previous article</a>, Lambda Functions can be written to perform complex operations as well which might require multiple libraries or modules. For example — Extracting face from images using MXNET, downloading images using links. For these use cases, we will need multiple libraries packed in the execution environment, as coding it from the scratch will be very complex. So, to deploy those we will have to provide the required libraries to the lambda instances since, lambda instances only have specific libraries to work with.</p><p>One more thing to notice is AWS Lambda Instances are actually Amazon Linux based instances, which are different from Ubuntu environments and might have different codes for different modules. Due to this reason, a lot of people have faced import issue of PIL library with python while using it in Lambda Functions.</p><p>To overcome this issue, I would suggest using docker to build runtime environments for scripts and installing libraries and testing it on the same environment. I would brief you about the usage of docker in downloading modules for Amazon Linux instances. Post that, we will see how to form Custom Layers and configure layers for AWS Lambda Functions along with creating a lambda function triggered using Object Creation on S3 Bucket and downloading images using data in the files.</p><p>Starting off with using docker to download modules for Amazon Linux Instances. Docker facilitates containerization or operating-system-level virtualization. We first need to install docker.</p><p>To install docker on Ubuntu (Xenial or Bionic) and to know more about basics of Docker, please refer to <a href="https://medium.com/@info.ankitp/virtualizing-cuda-environment-using-nvidia-docker-and-deploying-apis-on-those-environments-508e0171d4a6">Virtualizing Cuda Environment Using Nvidia-Docker and Deploying APIs</a> :</p><p>After installing docker, we will have to run a docker’s container of AWS Lambda Instance and run its shell. <br>sudo docker run [ --rm] -it -v &lt;code_dir&gt;:/code lambci/lambda:&lt;runtime&gt; sh<br>Let us discuss more about the available Lambda Function Runtime here :<br><strong>lambci/lambda:&lt;runtime&gt; : </strong>Image of Lambda Instance, we don’t need to worry about the image being locally available or not, we just need an active internet connection and the docker image will automatically be installed. We can choose from the following list of the Lambda Instances runtime options.</p><ul><li>build-nodejs8.10</li><li>build-nodejs4.3</li><li>build-nodejs6.10</li><li>build-python2.7</li><li>build-python3.6</li><li>build-python3.7</li><li>build-ruby2.5</li><li>build-go1.x</li><li>build-java8</li><li>build-dotnetcore2.0</li><li>build-dotnetcore2.1</li></ul><p>For python3.6 runtime environment , I will run the following command.</p><pre>sudo docker run — rm -it -v /path/to/code/:/code/ lambci/lambda:build-python3.6 sh</pre><p>4. Now after running into the interactive shell, we would use pip3 to download the modules needed. To download the PIL and requests module we would run the following command in the Lambda’s shell.<br>pip3 install pillow<br>pip3 install requests</p><p>Now, since we have already installed the requirements, we will have to locate the required modules and copy those into the /code/ directory. By default, most of the downloaded packages are downloaded in /var/lang/lib/python3.6/site-packages/ directory.</p><p>We will copy the PIL and requests module along with their dependencies in the /code/ folder using the following commands which we can also access after closing the docker container using ubuntu from /path/to/code/ directory.</p><pre>cp -r /var/lang/lib/python3.6/site-packages/PIL /code/<br>cp -r /var/lang/lib/python3.6/site-packages/Pillow-5.3.0.dist-info /code/<br>cp -r /var/lang/lib/python3.6/site-packages/requests /code/<br>cp -r /var/lang/lib/python3.6/site-packages/urllib3 /code/<br>cp -r /var/lang/lib/python3.6/site-packages/urllib3–1.24.1.dist-info/ /code/<br>cp -r /var/lang/lib/python3.6/site-packages/chardet /code/<br>cp -r /var/lang/lib/python3.6/site-packages/chardet-3.0.4.dist-info/ /code/<br>cp -r /var/lang/lib/python3.6/site-packages/idna /code/<br>cp -r /var/lang/lib/python3.6/site-packages/idna-2.7.dist-info/ /code/<br>cp -r /var/lang/lib/python3.6/site-packages/certifi /code/<br>cp -r /var/lang/lib/python3.6/site-packages/certifi-2018.11.29.dist-info/ /code/</pre><p>Now, after having the required modules in a defined directory, we have correctly downloaded the required libraries. Now, we will focus on forming Custom Layers on AWS.</p><p>After logging into AWS Console and opening the Lambda Dashboard. Open the Layers Dashboard and click on “Create Layer”.</p><p>Subsequently, we will be on the following screen and as you can see, we need to fill in the name of the Layer, description of the layer then select compatible runtimes and upload a zipped file having the modules. But, the modules or the libraries need to be in a specific structure. Let us go through that as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o2WtRxNQhdH5kpPOhPuXGQ.png" /><figcaption>Layer Creation Screen</figcaption></figure><p>To include libraries in a layer, place them in one of the folders supported by your runtime mentioned below :</p><ul><li><strong>Node.js</strong> : nodejs/node_modules, nodejs/node8/node_modules (NODE_PATH)</li><li><strong>Python</strong> : python, python/lib/python3.7/site-packages (site directories)</li><li><strong>Java</strong> — java/lib (classpath)</li><li><strong>Ruby</strong> — ruby/gems/2.5.0 (GEM_PATH), ruby/lib (RUBY_LIB)</li><li><strong>All</strong> — bin (PATH), lib (LD_LIBRARY_PATH)</li></ul><p>We will create a directory in the above mentioned format. Firstly, we will have to change the read-write permissions of the /path/to/code/ folder using the following command as we were using docker with sudo permissions. So, either we will have to change the permissions of the folder or switch to a user with sudo (superuser do) permissions. <br>sudo chmod 777 -R /path/to/code/<br>Post which, we will create a folder inside the /path/to/code/ named python.<br>mkdir /path/to/code/python<br>Move all the folders in the python directory, except the python directory itself</p><pre>cd /path/to/code<br>mv !(python) -t ./python/</pre><p>After pushing all these libraries in the above directories, zip the folder and upload it on the AWS Layer Creation Screen. We can use the following command to do that.</p><ol><li>Download zip in Ubuntu. <br>sudo apt-get install zip</li><li>Run the following commands to zip the folder</li></ol><pre>cd /path/to/code<br>zip -r ~/lambda-layer_1.zip python</pre><p>Now, Click on the Upload button on the Create Layer Screen, Browse and select the lambda-layer_1.zip file and then click on Create.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ts-v1szbGlJ1a0IrqHnTQg.png" /></figure><p>We have created the layer successfully. We can also create versions of single layer and can also download the package of the layer created.</p><p>Now, Carrying forward with creating a Lambda Function which downloads images provided a list of Youtube’s Channel Ids and their profile picture link as a file on S3 and uploads the images in a compressed file on S3. For that let us create a role for lambda functions, which allows lambda function to create Cloudwatch Logs and gives full access of S3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ED4HxPfzQjyhbM7RXDCG8Q.png" /><figcaption>Role Creation Screen</figcaption></figure><p>Open IAM service from AWS Console and select Roles. Click on Create Role and choose Lambda as the service which will use this role and click on Next:Permissions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PKhIEalOjfJ-CkDrYhK2Ug.png" /><figcaption>Role Review Screen</figcaption></figure><p>Now, select the required policies for Full Access to S3 (AmazonS3FullAccess) and Lambda Cloudwatch Logs Creation Policy (AWSLambdaBasicExecutionRole). And click on Next:Tags and can provide Key-Value Pairs, we will skip tags for now and would click on Next:Review. Eventually, Providing name and description about the Role and checking the Policies in the Role, we will click on the Create Role Button to complete the Role Creation Process.</p><p>Now we will create a Lambda Function, using the above created role and the layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B3vUtmgj5Q590OvpAid0OQ.png" /></figure><p>After clicking, Create Function button select S3 Trigger and select Object Creation Event and give the Prefix Path at which you are going to upload the input file and click Add.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p2u0hKllZIRxV5Qim2we1A.png" /><figcaption>S3 Trigger Configuration</figcaption></figure><p>Now, we will configure Layer to the Lambda Function, Click on the Layers on the Lambda Designer and then click on Add a layer. Select the relevant layer and its version and click Add.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2uBoJUxCj_7mEqAFr0H-lg.png" /><figcaption>Configuring Layer to a Lambda Function</figcaption></figure><p>Eventually, change the code in the inline editor. Use the following code to download the images in a zipped format, change the Timeout and CPU Memory Settings and save the lambda function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d54f274c8bad03dc7489744fd2d82f24/href">https://medium.com/media/d54f274c8bad03dc7489744fd2d82f24/href</a></iframe><p>Now, to test the Lambda Function Upload a file on Target S3 Bucket having json dumped in every line. I have manually copied links of profile pictures of several people and have dumped them in this file.</p><pre>1546760133<br>{&quot;thumbnail&quot;:&quot;https:\/\/yt3.ggpht.com\/a-\/AN66SAwK4vgc4xY4WEkqBN-L5PAMxMk78S7N9FjL_Q=s800-mo-c-c0xffffffff-rj-k-no&quot;,&quot;num&quot;:&quot;1&quot;}<br>{&quot;thumbnail&quot;:&quot;https:\/\/yt3.ggpht.com\/a-\/AN66SAyXDERjWHJoIOMzk3oGIb9AW4epd59EIZoV3w=s800-mo-c-c0xffffffff-rj-k-no&quot;,&quot;num&quot;:&quot;2&quot;}<br>{&quot;thumbnail&quot;:&quot;https:\/\/yt3.ggpht.com\/a-\/AN66SAxTMaIX7mBvmGmHAdYhZe1C9UuqmH6TWG5nxQ=s800-mo-c-c0xffffffff-rj-k-no&quot;,&quot;num&quot;:&quot;3&quot;}<br>{&quot;thumbnail&quot;:&quot;https:\/\/yt3.ggpht.com\/a-\/AN66SAwaRnCUkcxfZW1LkRPQNqnrNmaTGWWuSyEvSA=s800-mo-c-c0xffffffff-rj-k-no&quot;,&quot;num&quot;:&quot;4&quot;}<br>{&quot;thumbnail&quot;:&quot;https:\/\/yt3.ggpht.com\/a-\/AN66SAwgXwU1xHh7-WauvK-4OY7InqChVF-nKSOB0A=s800-mo-c-c0xffffffff-rj-k-no&quot;,&quot;num&quot;:&quot;5&quot;}<br>{&quot;thumbnail&quot;:&quot;https:\/\/yt3.ggpht.com\/a-\/AN66SAxtsoYVvKUkLEokTKHi9KznmpeXRlWIzXyhBQ=s800-mo-c-c0xffffffff-rj-k-no&quot;,&quot;num&quot;:&quot;6&quot;}</pre><p>Post uploading, we will see a new directory “output_files” created in the lambda_test directory, where the zipped images and error files will be uploaded on S3.</p><p>I hope this might have given you a complete overview of how AWS Lambda Function works and how you can easily develop Lambda Functions having different libraries and solve your use cases easily.</p><p>I hope you find this article informative and easy to learn, if you have any queries feel free to reach me at <a href="/service/mailto:info.ankitp@gmail.com">info.ankitp@gmail.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51a1bd786547" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/going-serverless-with-aws-lambda-functions-2-51a1bd786547">Going Serverless with AWS Lambda Functions — 2</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Going Serverless with AWS Lambda Functions — 1]]></title>
            <link>https://medium.com/geekculture/going-serverless-with-aws-lambda-functions-1-edec330c2bce?source=rss-d774cabc71ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/edec330c2bce</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[aws-api-gateway]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[serverless-architecture]]></category>
            <dc:creator><![CDATA[Ankit Prakash Gupta]]></dc:creator>
            <pubDate>Sun, 06 Jan 2019 07:07:28 GMT</pubDate>
            <atom:updated>2021-06-13T11:31:55.582Z</atom:updated>
            <content:encoded><![CDATA[<h3>Going Serverless with AWS Lambda Functions — 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*nKIc1WANH4xdkcs2U2tfMw.png" /></figure><p>Few years back, traditional physical servers were replaced by Cloud Servers and now, serverless is the new cool. In serverless execution, the servers are there but we don’t need to manage those servers anymore. All that is taken care by Service Provider. Along with this, no cost is levied as there is no instance of server running until unless the trigger is fired, which ends up as soon as the execution ends. AWS Lambda Functions, facilitating the serverless execution by providing compute resources on need without provisioning or managing servers, can be triggered in different ways: an HTTP request, a new document upload to S3, a scheduled Job, an AWS Kinesis data stream, or a notification from AWS Simple Notification Service (SNS).</p><p>AWS Lambda Functions might appear as the ubiquitous solution, but there are a few limitations in working with them. A single lambda function comes with a limited storage of 512 MBs, limited size of 50 MBs in the zipped form for deployment package and is short-lived maximum for 15 minutes. All the above mentioned demerits can be managed in one way or another. Along with this, there is one more significant issue with AWS Lambda Functions, cold start. It takes some time for the Lambda function to handle a first request, because Lambda has to start a new instance of the function. The cold start can be a real problem for your function, if at any time you expect a fast response and there are no active instances of your function.</p><p>Here, I will brief you through the simple and complex Lambda Function Creation along with creating and configuring AWS Lambda Layers using AWS CLI to be used with AWS Lambda Functions, which lets us surpass the limitation of having a deployment package of 50 MBs maximum, by allowing us to have a maximum of 5 layers having different libraries and having a total unzipped size of libraries upto 250 MBs.</p><p>Here, We will go through the steps of creating a simple Lambda Function triggered using an API :</p><ol><li>First, Login into AWS Account.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XeQjFU2iITuekWXUKRXEWw.png" /><figcaption>AWS Login Screen</figcaption></figure><p>2. Go to the Lambda Dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hM3iqrS4QaczgW64hKQmYQ.png" /><figcaption>AWS Service Dashboard</figcaption></figure><p>3. On the Lambda Dashboard, click on Create Function option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GGTBYZfQgg09qeFg7VJxPA.png" /><figcaption>AWS Lambda Dashboard</figcaption></figure><p>4. On the Create Function Screen, type in the name of the Lambda Function, choose the Runtime Environment and choose Create a Custom Role in the Role selection Area which will direct you to the Role Creation Screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r2R58SjXWHCqH6ydQm6eSg.png" /><figcaption>Create Lambda Function Screen</figcaption></figure><p><strong>Lambda Roles : </strong>Each Lambda function has an IAM role (execution role) associated with it. You specify the IAM role when you create your Lambda function. Permissions you grant to this role determine what AWS Lambda can do when it assumes the role.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZIssEYwAQRE3kGO-wXVgKw.png" /><figcaption>Role Creation Screen</figcaption></figure><p>5. For now, we will select the lambda_basic_execution Role which will grant permissions only for the Amazon CloudWatch Logs actions to write logs. We will use this policy as our Lambda function is a basic function and will not access any other AWS resources except writing logs.</p><p>Post this, click on Allow which will take you back on the Create Function Screen and an existing lambda_basic_execution role will be selected. After this, click on Create Function</p><p>6. We will be at Lambda Configuration Screen, using which we can change all the settings of the Lambda Function. Mainly, Add/Remove Trigger, change the lambda Function, change its role, memory allocation, set environment variables, set the timeout period, select Virtual Private Cloud (VPC) as well as set error handling mechanism.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JPq_iSlS-HNLwOdM_lOr6A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ElFrqyV2WB2OoNMiVSiLmA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uRlLFWVk4EVXk7mlxbZ0BQ.png" /><figcaption>Lambda Configuration Screen</figcaption></figure><p>We should always make changes to the required settings before activating the Lambda Function. For now, the main settings are :</p><ol><li>Trigger</li><li>Lambda Function’s Code and lambda handler function.</li><li>Timeout</li><li>Allocated Memory</li><li>Role and Permissions</li></ol><p>7. Now, we will set the Trigger (Trigger is actually the event when the lambda function should be called and executed) for our function. For now, we will use an API hit on the AWS API Gateway as the triggering event and will choose API Gateway on the Add Triggers Panel on the Configuration Tab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hHsKtQlm26RqOAMqivnNKQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aWyxpEmgwWZ0aQOujTqLlA.png" /><figcaption>API Trigger Configuration</figcaption></figure><p>We choose to create a new API and in the security tab we choose to create an open API with API Key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wbX_Q8LZ4OPBc5WpHw6Heg.png" /></figure><p>Type in the name of the API and click on Add button.</p><p>After this, we will click on the first_lambda button over Layers button and edit the code and use the following mentioned code for our first Lambda Function which will use passed name in the returned expression.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/170cc228d766e88007c8cc549f350e86/href">https://medium.com/media/170cc228d766e88007c8cc549f350e86/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gXruw3pYtyn5Q6oBK1CqyQ.png" /><figcaption>Inline Code Editor</figcaption></figure><p>We can use the inline editor to write the code or can also upload a zipped file having the code inside it. In both cases, we will have to set the Handler as the &lt;file_name&gt;.&lt;function_name&gt;. In the above case we have set it to be lambda_function.lambda_handler as the file name is lambda_function and function’s name is lambda_handler.</p><p>Also, note that event and context two variables are passed to lambda_handler function which provides us information about the triggering event.</p><p>Post this, click on Save button to save the changes in the Lambda Function.</p><p>8. We have successfully created our First Lambda Function triggered using API. Post which, on clicking on the highlighted API Gateway Button, we will see the API endpoint and API Key to be used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R0LgVyty-xZmo5pgkLeP4w.png" /><figcaption>Successful Creation of Lambda</figcaption></figure><p>We could try the lambda Function using Postman and hitting a request on the API endpoint along with API Key in the header with the header key as ‘x-api-key’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QDyQ1_6HXXhiq3UNKQNs5A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K95MH52lQ36wLq81D9hWxw.png" /><figcaption>API Hit using Postman</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2cqhfKatqLn5KH7n1nNdsg.png" /><figcaption>AWS Lambda Monitoring Screen</figcaption></figure><p>9. We can also check the invocations and errors occured in the lambda executions using the Monitoring Tab of the Lambda Dashboard.<br>We can also check the logs of Lambda Executions using Cloud Watch, since we provided permission to create CloudWatch Log Streams.</p><p>Not all lambda functions will have such small code and might need multiple modules to carry out the functionality feasibly. One such use case can be downloading images using AWS Lambda Functions. If, we are developing using python, we will need PIL and requests module along with their dependencies.</p><p>In the <a href="https://medium.com/@info.ankitp/going-serverless-with-aws-lambda-functions-2-51a1bd786547">next article</a>, we will cover creating custom layers, downloading libraries or modules for AWS Lambda instances using Docker and will create a lambda triggered using AWS S3’s Object Creation which will use a custom created layer.</p><p>I hope you find this article informative and easy to learn, if you have any queries feel free to reach me at <a href="/service/mailto:info.ankitp@gmail.com">info.ankitp@gmail.com</a></p><p>EDIT : <a href="https://medium.com/@info.ankitp/going-serverless-with-aws-lambda-functions-2-51a1bd786547">Going Serverless with AWS Lambda Functions — 2</a> has been published.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=edec330c2bce" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/going-serverless-with-aws-lambda-functions-1-edec330c2bce">Going Serverless with AWS Lambda Functions — 1</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Virtualizing Cuda Environment Using Nvidia-Docker and Deploying APIs on those environments]]></title>
            <link>https://medium.com/@info.ankitp/virtualizing-cuda-environment-using-nvidia-docker-and-deploying-apis-on-those-environments-508e0171d4a6?source=rss-d774cabc71ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/508e0171d4a6</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[apache]]></category>
            <category><![CDATA[cuda]]></category>
            <category><![CDATA[nvidia-docker]]></category>
            <dc:creator><![CDATA[Ankit Prakash Gupta]]></dc:creator>
            <pubDate>Tue, 01 Jan 2019 07:10:03 GMT</pubDate>
            <atom:updated>2019-01-22T10:54:07.523Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Virtualizing Cuda Environment Using Nvidia-Docker and Deploying APIs</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iKfo6oLp8aiTKhu3CKhpGg.png" /></figure><p>In this quickly evolving domain of Artificial Intelligence and Deep-Learning, advancements are so quick that nobody is able to quickly scale to the latest ones. Many algorithms are there which run on specific versions of Cuda and switching from one version to another is a complete hassle. An easy workaround is to use nvidia-docker to launch compatible container’s which will not only save time, but will also let you use different configurations simultaneously and deploy different micro-services on different environments concurrently.</p><p>Prerequisite of using nvidia-docker2 is</p><ul><li>docker-ce</li><li>Remove if already installed :nvidia-docker (Version 1)</li></ul><p>For Installing Docker-ce version :</p><ol><li>Make sure you don’t have any earlier versions. If you have those uninstall using the following command : <br>sudo apt-get remove docker docker-engine docker.io</li><li>Install the Docker Community Edition, using the following command. <br>sudo apt-get update<br>sudo apt-get install docker-ce</li></ol><p>Subsequently, we will install nvidia-docker2</p><ol><li>First, we make sure that we do not have nvidia-docker (Version 1) installed by running these commands. <br>docker volume ls -q -f driver=nvidia-docker | xargs -r -I{} -n1 \<br>docker ps -q -a -f volume={} | xargs -r docker rm -f <br>sudo apt-get purge nvidia-docker</li><li>Secondly, we add the package repositeries<br>curl -s -L <a href="https://nvidia.github.io/nvidia-docker/gpgkey">https://nvidia.github.io/nvidia-docker/gpgkey</a> | \<br>sudo apt-key add -<br>distribution=$(. /etc/os-release;echo $ID$VERSION_ID)<br>curl -s -L <a href="https://nvidia.github.io/nvidia-docker/$distribution/nvidia-docker.list">https://nvidia.github.io/nvidia-docker/$distribution/nvidia-docker.list</a> | \<br>sudo tee /etc/apt/sources.list.d/nvidia-docker.list<br>sudo apt-get update</li><li>Next, we install nvidia-docker2 and would reload the docker daemon configuration<br>sudo apt-get install nvidia-docker2<br>sudo pkill -SIGHUP dockerd</li><li>Try the nvidia-Docker to check if it is running fine <br>docker run --runtime=nvidia --rm nvidia/cuda:9.0-base nvidia-smi</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*f7bto6TSkZS36EuavFH1YQ.png" /><figcaption>nvidia-smi Command’s Output from docker container</figcaption></figure><p>Carrying forward, Let us learn how to deploy a hello-world API using apache on this docker container and how to bind it using the IP of host system.</p><p>We open a docker container binding port 82 of host system to port 80 of the docker container.</p><pre>sudo docker run -v &lt;code_dir&gt;:/code/ -p 82:80 \<br>--name=cuda8_cnn7_image_docker -it --runtime=nvidia [ --rm] \<br>&lt;cuda_env&gt; /bin/sh</pre><p>Lets visit the options of the docker run command for our reference.</p><ul><li><strong>--rm</strong> : By default a conatainer’s file system persist even after the container exits. To automatically clean up the container and remove the file system when the container exits, we use the — rm flag.</li><li><strong>-v or --volume : </strong>We can add -v or — volume flag to bind mount a volume in the following format. <br>-v or --volume=[host-src:]container-dest[:&lt;options&gt;]<br>Where options can be comma-separated settings for binding a volume</li><li><strong>--name : </strong>Provide the name of the container, so that you can attach to the same container easily later. <br>BTW, to detach from a container and letting it run in the background, Press and hold &lt;Ctrl&gt;Key and then press P and Q keys and to attach to the same container again. Type in the below command <br>sudo docker attach &lt;container’s name&gt;</li><li><strong>-p : </strong>Publish a container᾿s port or a range of ports to the host<br>format: ip:hostPort:containerPort | ip::containerPort | hostPort:containerPort | containerPort<br>Both hostPort and containerPort can be specified as a range of ports.</li><li><strong>&lt;cuda_env&gt; : </strong>A complete list of available cuda environment can be found on the below mentioned link : <br> <a href="https://gitlab.com/nvidia/cuda">https://gitlab.com/nvidia/cuda</a></li><li><strong>sh : </strong>It is the command that we want to run on the Docker’s container when we load it. We would like to open the shell when we open the container. So that we can install the modules we want to.</li><li><strong>-it : </strong>Here we have combined two flags, which is used with docker when we want to use interactive shell on docker container. <br> <strong>-i : </strong>Keeps standard input open<br> <strong>-t : </strong>Allocates a pseudo-tty.</li></ul><p>You can use the below mentioned command as an example for yourself.</p><pre>sudo docker run -v “/path/to/code/”:/code/ -p 82:80 --name=cuda8_cnn7_image_docker -it --runtime=nvidia --rm nvidia/cuda:8.0-cudnn7-runtime-ubuntu16.04 /bin/sh</pre><p>After completion of this downloading and loading of container. <br>Install the necessary things on the container, but first update the existing packages. <br>apt-get update</p><ol><li>Vim : apt-get install -y vim</li><li>Python : apt-get install -y python3-pip</li><li>Apache 2: apt-get install -y apache2</li><li>WSGI : apt-get install -y libapache2-mod-wsgi-py3<br>Enable WSGI Module<br>a2enmod wsgi</li><li>Flask : pip3 install flask</li></ol><p>Add the following files in the /path/to/code/ directory</p><ol><li>app.py : This will create a Flask application having endpoints and returning different replies to different endpoints.</li></ol><pre>from flask import Flask<br>app = Flask(__name__)<br>@app.route(“/”)<br>def hello():<br>    return “Hello World!”<br>if __name__ == “__main__”:<br>    app.run()</pre><p>2. app.wsgi : The <strong>Web Server Gateway Interface</strong> (<strong>WSGI</strong>) is a simple calling convention for web servers to forward requests to web applications or frameworks written in the Python programming language. Here we just import the app variable which we created in the app.py file.</p><pre>import sys <br>sys.path.append(“/code/”) <br>‘’’We either need to add this directory in path here or while editing 000-default.conf. ‘’’ <br>from app import app as application</pre><p>Now edit the 000-default.conf configuration file of Apache2 in the container. By default it is in /etc/apache2/sites-enabled/000-default.conf path and add the following lines in the VirtualHost *:80 which actually binds the port 80 of the docker container to the flask application that we are running in the above file using WSGI as the middleware.</p><pre>WSGIDaemonProcess docker_test python-path=/usr/local/lib/python3.5/dist-packages/<br>WSGIScriptAlias /nvidia-docker/test /code/app.wsgi<br>WSGIScriptReloading On<br>ServerAdmin abc@xyz.com<br>DocumentRoot /code/<br>&lt;Directory /code/&gt;<br> WSGIProcessGroup docker_test<br> WSGIApplicationGroup %{GLOBAL}<br> Require all granted<br>&lt;/Directory&gt;</pre><p>Restart the server now using the following command:<br>service apache2 restart</p><p>Try hitting on the URL using the Host system : Remove if already installed<br><a href="http://localhost:82/nvidia-docker/test/">http://localhost:82/nvidia-docker/test/</a><br>OR <br>http://&lt;private-ip&gt;:82/nvidia-docker/test/</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*eAqlF7GLs9wH194zuK6oMg.png" /></figure><p>I hope you find this article informative and easy to learn, if you have any queries feel free to reach me at <a href="/service/mailto:info.ankitp@gmail.com">info.ankitp@gmail.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=508e0171d4a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>