<?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 Prabodh Agarwal on Medium]]></title>
        <description><![CDATA[Stories by Prabodh Agarwal on Medium]]></description>
        <link>https://medium.com/@pbd_94?source=rss-9856a06a88a6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*7Fxm3KQ5vsAzRtutLNQMpg.png</url>
            <title>Stories by Prabodh Agarwal on Medium</title>
            <link>https://medium.com/@pbd_94?source=rss-9856a06a88a6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 17:11:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pbd_94/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[A lakehouse by the kafka stream]]></title>
            <link>https://medium.com/@pbd_94/a-lakehouse-by-the-kafka-stream-338928ff5115?source=rss-9856a06a88a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/338928ff5115</guid>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[apache-hudi]]></category>
            <dc:creator><![CDATA[Prabodh Agarwal]]></dc:creator>
            <pubDate>Thu, 04 Jul 2024 13:17:56 GMT</pubDate>
            <atom:updated>2024-07-04T13:17:56.576Z</atom:updated>
            <content:encoded><![CDATA[<p>We are onboarding Apache Hudi + Apache Spark + Apache Kafka into our data stack &amp; can’t wait to talk more about it.</p><p>Head over to <a href="https://pbd1194.substack.com/p/kafka-lakehouse-1">https://pbd1194.substack.com/p/kafka-lakehouse-1</a> to follow along.</p><p>We’ll be releasing more articles there as we get along.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=338928ff5115" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Project Nessie and the auth swamp]]></title>
            <link>https://towardsdev.com/project-nessie-and-the-authentication-swamp-4d1e3efe208a?source=rss-9856a06a88a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d1e3efe208a</guid>
            <category><![CDATA[apache-iceberg]]></category>
            <category><![CDATA[project-nessie]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-lakehouse]]></category>
            <dc:creator><![CDATA[Prabodh Agarwal]]></dc:creator>
            <pubDate>Sun, 07 Apr 2024 16:10:39 GMT</pubDate>
            <atom:updated>2024-05-21T09:17:48.758Z</atom:updated>
            <content:encoded><![CDATA[<h4>Auth and Iceberg Catalog</h4><h4>Challenges with configuring auth on Project Nessie while setting up Apache Iceberg on AWS.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2DOf4fjVhtpBK9iI" /><figcaption>Photo by <a href="https://unsplash.com/@ramon_vloon?utm_source=medium&amp;utm_medium=referral">Ramon Vloon</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Project Nessie serves as a catalog option for Apache Iceberg, providing an open-source solution that can be self-hosted. Developed primarily by Dremio, it also offers a managed service known as the Arctic Catalog.</p><p>Project Nessie offers a REST based interface. Mind you, it is different from Iceberg’s default Rest Catalog. Project Nessie is a Quarkus based web service and can be hosted like any other web application.</p><p>I come from a Snowflake background. Snowflake DWH defines authn &amp; authz at multiple levels. We leverage authz to control resource access for different team members. It is important for us regulate what team can access what data. Also, since snowflake warehouses are expensive, we regulate a team’s warehouse access as well by enforcing Authz.</p><p>Similarly, we want to configure AuthN &amp; AuthZ in our Lakehouse setup as well. Like any other web service, Project Nessie needs to fronted with auth so that read/write/deletes and multiple other table &amp; DB ops can be segregated safely. However, the HTTP service &amp; the S3 storage are two different services and hence require different auth setup.</p><h3><strong>Auth Architecture</strong></h3><p>Let’s look at a possible architecture for auth setup in Apache Iceberg.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*NbC3c5hYnuB4CYLJvgO4GA.png" /><figcaption>Iceberg auth architecture</figcaption></figure><h3><strong>Basic Setup</strong></h3><ol><li>Iceberg is storing data in S3.</li><li>Project Nessie is hosted on either of EC2/EKS/ECS and has an accessible HTTP endpoint.</li><li>Clients are using Spark to access the data. Client can be setup<br>a) either on a local dev machine<br>b) or can be on a Spark cluster say EC2/EMR, etc.</li></ol><p><strong>Auth architecture</strong></p><ol><li>Client hits Nessie endpoints with authentication<br>a) either via authorization_code flow on the browser.<br>b) or via client_credentials flow for service account access</li><li>Auth setup will enforce read/write/delete access on the table.</li><li>Hence relevant Spark jobs will behave as per their accesses.</li></ol><p>However; configuring auth on Nessie won’t stop you from tampering with the data files on S3. A driver can independently point itself to a relevant metadata file bypassing the catalog and use that to modify the data.</p><p>Such an action can jeopardise the state of our data.</p><p>To save ourselves from such data corruption, we can easily define fine grain IAM policies on the S3 bucket for individual users &amp; AWS services.</p><p>There are multiple challenges to this setup now.</p><ol><li>We have to define the set of users in <em>both</em> an Authorization Server as well as in IAM.</li><li>The semantics of auth will vary between the two services, hence we’ll need to do Auth modeling accordingly.<br>a) we’ll need to define user scopes in the authorization server<br>b) we’ll need to define IAM policies for different users in IAM</li></ol><p>Maintaining two auth systems is hence inherently error prone in a bare bones setup 👼.</p><p>If you are looking to setup Apache Iceberg for your team like I am and want to evaluate your options, Project Nessie looks like a promising candidate, but I see auth to be a challenge.</p><p>Considering we want to avoid having a significant <em>DBA</em> setup 😅, I would prefer choosing a no-brainer auth setup, and Project Nessie is yet to evolve in that direction.</p><p>With this out of the way, what will I go with?</p><p>🥁🥁🥁🥁🥁🥁🥁🥁 AWS Glue Data Catalog 🥁🥁🥁🥁🥁🥁🥁🥁.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d1e3efe208a" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/project-nessie-and-the-authentication-swamp-4d1e3efe208a">Project Nessie and the auth swamp</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OIDC with Google & Quarkus]]></title>
            <link>https://itnext.io/oidc-with-google-quarkus-13003a1354ae?source=rss-9856a06a88a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/13003a1354ae</guid>
            <category><![CDATA[auth0]]></category>
            <category><![CDATA[quarkus]]></category>
            <category><![CDATA[google-oauth]]></category>
            <category><![CDATA[oidc]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Prabodh Agarwal]]></dc:creator>
            <pubDate>Fri, 29 Mar 2024 17:34:27 GMT</pubDate>
            <atom:updated>2024-04-13T08:03:47.563Z</atom:updated>
            <content:encoded><![CDATA[<h4>OAuth in Quarkus</h4><h4>How to configure Quarkus OIDC with Google Cloud credentials?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FUji4F_3Z-_rT2e7" /><figcaption>Photo by <a href="https://unsplash.com/@hermeus?utm_source=medium&amp;utm_medium=referral">Hermeus</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This article is a massive segue from my research on the lakehouse architecture. But this is much needed for the GPT world. If you Google/GPT/Gemini how to setup Quarkus OIDC with Google Cloud, none of the tutorials can be copy-pasted, so I aim to fill in that gap with this article 😄.</p><p>I have been researching &amp; learning how to setup Project Nessie for my <a href="https://iceberg.apache.org/">Apache Iceberg</a> lake house architecture. I have started exploring and published my <a href="https://medium.com/@pbd_94/skiing-with-snowflake-b196e8f7e2e6">first article</a> regarding the same. Apache Iceberg practitioners know that the catalog is a critical component of the architecture (<em>newbies please take note of the same</em> 😉).</p><p>One important catalog in this category is <a href="https://projectnessie.org/">Project Nessie</a> 🌊 by <a href="http://dremio.com/">Dremio</a>. I have been exploring this catalog and one important detail that stood out is the fact that it is written in 🥁🥁🥁 <a href="https://quarkus.io/">Quarkus</a>.</p><p><em>Quarkus is a pretty exciting framework. I am yet to find opportunities to work on a production grade Quarkus applications, so I decided to jump into the Nessie codebase to gain more exposure to the same.</em></p><p>I have done <em>hello-world</em> setup with Project Nessie as per their guide. Now, the next thing to understand is how to setup auth. We currently use Snowflake for a bunch of production use cases and have setup Google SSO for auth purpose. I want to setup a similar experience with Project Nessie as well. While scrolling around the auth setup doc, I noticed that we can use the native auth provided by Quarkus OIDC as well. So I decided to take a segue 🚲 and explore how to create a <em>Hello World</em> of OIDC in Quarkus 😃.</p><p>Now, I spent some time to setup a <a href="https://quarkus.io/get-started/">basic Quarkus application</a> and taught myself basics of OAuth &amp; OIDC <a href="https://www.youtube.com/watch?v=996OiexHze0&amp;ab_channel=OktaDev"><em>thanks to Okta dev</em></a>. I could perform a setup in Google Cloud and test it out on a OIDC debugger. Next, I wanted to setup the same in Quarkus as well.</p><p>There are a bunch of docs &amp; tutorials from Quarkus &amp; Okta that explain how to setup OIDC using Keycloak &amp; Okta Auth, but these tutorials have a slight hiccup when it comes Google OAuth 😅. So I decided to redo the tutorial and publish a straightforward guide on the same.</p><p>I have setup the tutorial in this <a href="https://github.com/prabodh1194/quarkus-google-oauth-security">github repo</a>. You can follow the link and stop reading this article! Otherwise, read on 😄.</p><h3>Howto</h3><ol><li><strong>Setup</strong></li></ol><p>I am using gradle build system with Kotlin DSL to create a starter Quarkus project as follows.</p><pre>mvn io.quarkus:quarkus-maven-plugin:create \<br>    -DprojectGroupId=dev.pbd \<br>    -DprojectId=quarkus-oidc-app \<br>    -DnoCode \<br>    -DbuildTool=gradle-kotlin-dsl \<br>    -DprojectArtifactId=security-openid-connect-quickstart</pre><p>This will create a directory called security-openid-connect-quickstart in<br>your $PWD.</p><p>2. <strong>Greeting resource</strong></p><p>Create a Greeting resource in Quarkus as follows. There are well known examples on the internet as well as on ChatGPT &amp; Gemini for the same.<br>Unfortunately, these examples suggest using javax.<br>Well, if you are on Java 11+ environment in 2024, you’ll know that javax has been long deprecated &amp; the namespace has been moved to jakarta 🤷‍♂.</p><p>So add the jakarta dependency to the quarkus application as follows.</p><pre>./gradlew addExtension --extensions=&#39;resteasy-jackson&#39;<br><br># or #<br><br>./gradlew addExtension --extensions=&#39;quarkus-rest&#39;</pre><pre>package dev.pbd;<br><br>import io.quarkus.oidc.IdToken;<br>import org.eclipse.microprofile.jwt.JsonWebToken;<br><br>import jakarta.inject.Inject;<br>import jakarta.ws.rs.GET;<br>import jakarta.ws.rs.Path;<br>import jakarta.ws.rs.Produces;<br>import jakarta.ws.rs.core.MediaType;<br><br>@Path(&quot;/&quot;)<br>public class GreetingResource {<br><br>    @Inject<br>    @IdToken<br>    JsonWebToken idToken;<br><br>    @GET<br>    @Produces(MediaType.TEXT_HTML)<br>    public String hello() {<br>        return<br>            &quot;&lt;html&gt;\n&quot; +<br>            &quot;    &lt;body&gt;\n&quot; +<br>            &quot;        &lt;h1&gt;Hello &quot; + idToken.getClaim(&quot;email&quot;) + &quot;&lt;/h1&gt;\n&quot; +<br>            &quot;    &lt;/body&gt;\n&quot;+<br>            &quot;&lt;/html&gt;\n&quot;;<br>    }<br>}</pre><p>3. <strong>Define the OIDC dependency</strong></p><pre>./gradlew addExtension --extensions=&#39;oidc&#39;</pre><p>OIDC dependency defines the goodness to do OIDC based auth in your quarkus application.</p><p>4. <strong>Run the application atleast once</strong></p><p>I am running this from intellij, so I can use the gradle plugin,<br>but you can do it from CLI as well like this.</p><pre>./gradlew quarkusDev</pre><p>You’ll see that your project deps are being pulled. You’ll also see some docker related activity in your application logs.</p><p>a) If your docker is not running, then you’ll see a failure!<br>b) If your docker is running, then you’ll see some images being pulled!</p><p>Any which ways, when OIDC client is installed, Quarkus by default<br>tries to use keycloak, and to do so tries to access docker. For now, you can just kill this instance cuz you can’t use it yet.</p><p>5. <strong>Lets refine our run</strong></p><p>We’ll define two application properties with the quarkus prefix.</p><p>a) http.port: The port on which your application will run. Defaults<br> to 8080. Can be overridden by the PORT environment variable.</p><p>b) oidc.auth-server-url: I’ll be using google cloud for oauth server.<br> This config tells quarkus to not depend on keycloak by default.</p><p>Run this command now:</p><pre>PORT=9000 ./gradlew quarkusDev</pre><p>You’ll see that your web application is now serving requests on port<br>9000. You can now try by switching off Docker as well! At this point, you won’t see much happening here as this auth-server is not real.</p><p>6. <strong>Throw in some auth</strong></p><ul><li>We’ll mark our GreetingResource as Authenticated now.</li><li>We’ll set the oidc provider to google because we want to use auth from GCloud.</li><li>We’ll obtain the client_id from GCloud.</li></ul><p>Quarkus provides an env variable to set the client ID as well (<a href="https://quarkus.io/guides/security-oidc-configuration-properties-reference"><em>full doc here</em></a>), but that is long in name, so we can define the CLIENTID env variable for convenience.</p><pre>quarkus.oidc.provider=google<br>quarkus.oidc.client-id=${CLIENTID:client_id}</pre><pre>@Path(&quot;/&quot;)<br>@Authenticated<br>public class GreetingResource</pre><p>Now when you re-run the application &amp; open the URL then your google auth will show up and give a redirect URI error. You can get around the redirect error by configuring the URL http://localhost:9000/ as your redirect URI.</p><pre>CLIENTID=xxx.apps.googleusercontent.com PORT=9000 ./gradlew quarkusDev</pre><p>After configuring the redirect URI as above you’ll get the next error asking you to configure a client secret.</p><p>OIDC config suggests multiple secret values. Which one do we<br>want to go for?</p><p>As of now it seems that we can use both the secret options:</p><p>a) quarkus.oidc.credentials.secret<br>b) quarkus.oidc.credentials.client-secret.value</p><p>For now I am proceeding with option a) . Now you can try accessing the endpoint localhost:9000 which will take you to the auth flow. Once you authenticate yourself, you will see an error in your Quarkus application!</p><p>This error is about inability to fetch the user info.</p><p><em>This error is the only reason why I am writing this article</em> 😅.</p><p>7. <strong>Verify User Token flow</strong></p><p>If you configure debug level logging you’ll notice that our application is able to access the relevant JWT token from the Google IdP but is unable to verify it because we have not given our application the right config. Let’s fix that.</p><pre>quarkus.oidc.authentication.user-info-required=true</pre><p>This config instructs our quarkus application to verify the JWT token and inject it into the application.</p><p>Voila! If you restart the application, it’ll work 💪 and show a screen with your email.</p><p><em>Happy coding!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13003a1354ae" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/oidc-with-google-quarkus-13003a1354ae">OIDC with Google &amp; Quarkus</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Skiing with Snowflake]]></title>
            <link>https://medium.com/toplyne-engineering/skiing-with-snowflake-b196e8f7e2e6?source=rss-9856a06a88a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/b196e8f7e2e6</guid>
            <category><![CDATA[snowflake-data-cloud]]></category>
            <category><![CDATA[aws-glue]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[apache-iceberg]]></category>
            <category><![CDATA[project-nessie]]></category>
            <dc:creator><![CDATA[Prabodh Agarwal]]></dc:creator>
            <pubDate>Mon, 18 Mar 2024 03:18:34 GMT</pubDate>
            <atom:updated>2024-04-13T08:02:53.910Z</atom:updated>
            <content:encoded><![CDATA[<h4>Apache Iceberg and Snowflake</h4><h4>Supercharge your compute strategy with Apache Iceberg, Snowflake, Apache Spark, AWS Glue &amp; Project Nessie</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Lpnx-J6BjC-Xfpuq" /><figcaption>Photo by <a href="https://unsplash.com/@sigmund?utm_source=medium&amp;utm_medium=referral">Sigmund</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this article, I will demonstrate how to formulate a lakehouse strategy that pairs well with Snowflake.</p><p>A few months ago, I began exploring opportunities to develop ETL pipelines in Ray. I had to perform my PoC on SnowflakeDB. Unfortunately, Ray Community Edition lacks APIs for reading data from Snowflake. So, I created my own Dataset API. This <a href="https://medium.com/toplyne-engineering/snorkeling-with-snowflake-6047af420541">article</a> details how to read data from SnowflakeDB in Ray.</p><p>To perform any compute in Ray, we need to do a SELECT * from the respective table to read that data into Ray. Snowflake charges us the standard WH rate for this query.</p><p>If you perform multiple experiments on Ray with Snowflake, be prepared to spend some big bucks. Additionally, there is latency associated with this ingest as the Ray application must wait for the SELECT * to complete before it can start operating on this data. This latency increases with the volume of data being operated on.</p><p><strong>What happens during a</strong>SELECT *<strong>?</strong></p><p>I have certain assumptions regarding what happens when you do SELECT * on Snowflake from a Python application. Here are a few:</p><ol><li>Snowflake stores data in a proprietary storage format. <a href="https://vinodhini-sd.medium.com/iceberg-tables-on-snowflake-design-considerations-and-life-of-an-insert-query-5026ea10bbea">Vino Duraisamy’s article</a> talks more about the workings of this proprietary format.</li><li>Upon reading, Snowflake converts data from its proprietary format to compressed Parquet file(s) and provides URLs of corresponding S3 endpoints.</li><li>The Python connector then starts hitting these S3 endpoints to load the data into memory as Apache Arrow tables.</li></ol><p>The assumptions regarding step 2 are based on my understanding of their <a href="https://github.com/snowflakedb/snowflake-connector-python/tree/main/src/snowflake/connector">Python-connector code</a> and the latency observations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/0*CP5cwFDytjfbAIip.png" /><figcaption>How select * works with Snowflake</figcaption></figure><p>Now, if our table contains a few hundred gigabytes of data, we&#39;ll be blocked waiting for steps 1 &amp; 2 to complete. While we can use larger warehouses to expedite step 2, step 3 can be executed in parallel. The <a href="https://docs.snowflake.com/en/developer-guide/python-connector/python-connector-api#fetch_arrow_batches">fetch_arrow_batches</a> API pings S3 URLs one-by-one. Although we can get <em>apparent</em> parallelism by multi-threading this invocation.</p><h3>Workaround</h3><p>Given the limitations of using SELECT *, engineers can infer the necessity of adopting an open data storage format. Open data storage formats, designed to be readable by various compute engines, alleviate limitations such as those presented by Snowflake&#39;s data format conversion.</p><p>Snowflake is doubling down on interoperability with Apache Iceberg. They have a bunch of content on this interoperability. I’ll <a href="https://medium.com/snowflake/an-overview-of-snowflake-apache-iceberg-tables-d5e85864ac99">refer</a> to the latest one that I could get my hands on.</p><p>This eliminates the need for a data warehouse and marginally reduces experimentation expenses. Users can now assume that Iceberg data is available and proceed with experiments, ushering us into the Lakehouse world.</p><p>Welcome to the Lakehouse world!</p><h3>The Lakehouse Strategy</h3><p>Apache Iceberg has great documentation and ample resources and I would leave it to the reader to familiarise themselves with the exact workings of this technology.</p><p>This definitive diagram speaks volumes about the possibilities of the Apache Iceberg format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*O5gj_OuFTwAERIFp.png" /><figcaption>Apache Iceberg Storage architecture</figcaption></figure><p>Since we are discussing using Apache Iceberg with the Snowflake <em>Cloud</em> Data Warehouse, selecting a cloud storage solution is the first and easiest step of our Lakehouse Strategy. Iceberg’s ACID transactions are centered around the operations of the Iceberg Catalog and this system will quite literally make or break our strategy.</p><p>Assuming we are using AWS S3 for storage, let’s understand how storage works at different layers of the architecture.</p><ol><li>The data layer lives in S3 ✅.</li><li>The metadata layer lives in S3 as well ✅.</li><li>Where does the catalog live 🤔?</li></ol><p>The Iceberg community offers various resources and options for selecting the catalog. We will explore the following catalogs, understand how to set them up, and evaluate associated tradeoffs:</p><ol><li>Snowflake Iceberg Catalog</li><li>AWS Glue Data Catalog</li><li>Project Nessie</li></ol><h3>Snowflake Iceberg Catalog</h3><p>Let’s understand the capabilities of the Snowflake + Apache Iceberg integration.</p><ol><li>Bring your storage: Snowflake writes to the chosen storage.</li><li>Snowflake will manage its <strong>own</strong> Iceberg catalog.</li><li>Spark can <strong>read</strong> data using the Snowflake catalog.</li><li>However, Spark <strong>can&#39;t write using this catalog</strong>.</li><li>Snowflake doesn’t charge you for that storage. Additionally, DDL &amp; DML ops from the snowflake connectors don’t discriminate in any manner.</li></ol><h3>Setup</h3><p>I have created a Terraform that can be applied to deploy Iceberg tables on Snowflake in <a href="https://gist.github.com/prabodh1194/74453c49b053521b0e112388d3a31148">this GitHub gist</a>. Here are the steps:</p><ol><li>Create a S3 bucket and an IAM role with RW access to this S3 bucket.</li><li>Configure an external volume in Snowflake. This external volume is configured with the AWS IAM role &amp; the S3 bucket from step 1.</li><li>Snowflake returns an IAM user &amp; session ID. Edit the trust policy of the role in step 1 to permit this IAM user &amp; session.</li></ol><p>Now that we have allowed Snowflake to write to the designated S3 location; writes can be channeled through the external volume. Creating iceberg table dumps the data into the above S3 bucket in our desired location in the Iceberg table format.</p><p><strong>How to use Iceberg tables?</strong></p><p>Create the iceberg table in Snowflake.</p><pre>CREATE ICEBERG TABLE -- magic words for creating the external iceberg table<br>my_sf_db.public.my_iceberg_table (<br>    boolean_col boolean,<br>    int_col int,<br>    string_col string,<br>    time_col timestamp_ltz<br>)<br>CATALOG = &#39;SNOWFLAKE&#39; -- this is the snowflake managed catalog<br>EXTERNAL_VOLUME = &#39;MY_ICEBERG&#39; -- same volume that we deployed earlier<br>BASE_LOCATION = &#39;my_db&#39;;<br><br>insert into my_iceberg_table values (true, 1, &#39;abc&#39;, sysdate()); -- insert a row<br><br>-- do a few more inserts to increase data volume exponentially ;-)<br><br>insert into my_iceberg_table select * from my_iceberg_table;<br>insert into my_iceberg_table select * from my_iceberg_table;<br>insert into my_iceberg_table select * from my_iceberg_table;<br>insert into my_iceberg_table select * from my_iceberg_table;</pre><p>View the data in S3.</p><pre># you can locate your files of data layer<br># in this folder hierarchy<br>aws s3 ls s3://my-iceberg</pre><p>Read it in Pyspark.</p><pre>import os<br>import re<br><br>from boto3 import Session<br>from pyspark.sql import SparkSession<br><br><br>session = Session()<br>credentials = session.get_credentials()<br>current_credentials = credentials.get_frozen_credentials()<br><br>os.environ[&quot;AWS_ACCESS_KEY_ID&quot;] = current_credentials.access_key<br>os.environ[&quot;AWS_SECRET_ACCESS_KEY&quot;] = current_credentials.secret_key<br>os.environ[&quot;AWS_SESSION_TOKEN&quot;] = current_credentials.token<br><br># Initialize Spark session with required packages<br>spark = (<br>    SparkSession.builder.appName(&quot;Iceberg and Snowflake Example&quot;)<br>    .config(<br>        &quot;spark.jars.packages&quot;,<br>        &quot;org.apache.iceberg:iceberg-spark-runtime-3.5_2.12:1.4.1,&quot;<br>        &quot;net.snowflake:snowflake-jdbc:3.14.2,&quot;<br>        &quot;software.amazon.awssdk:bundle:2.20.160,&quot;<br>        &quot;software.amazon.awssdk:url-connection-client:2.20.160,&quot;<br>        &quot;net.snowflake:spark-snowflake_2.12:2.12.0-spark_3.4&quot;,<br>    )<br>    .config(<br>        &quot;spark.sql.extensions&quot;,<br>        &quot;org.apache.iceberg.spark.extensions.IcebergSparkSessionExtensions&quot;,<br>    )<br>    .config(&quot;spark.sql.iceberg.vectorization.enabled&quot;, &quot;false&quot;)<br>    .getOrCreate()<br>)<br><br># Set Snowflake catalog<br>spark.conf.set(<br>    &quot;spark.sql.defaultCatalog&quot;,<br>    &quot;snowflake_catalog&quot;<br>)<br>spark.conf.set(<br>    &quot;spark.sql.catalog.snowflake_catalog&quot;,<br>    &quot;org.apache.iceberg.spark.SparkCatalog&quot;<br>)<br>spark.conf.set(<br>    &quot;spark.sql.catalog.snowflake_catalog.catalog-impl&quot;,<br>    &quot;org.apache.iceberg.snowflake.SnowflakeCatalog&quot;,<br>)<br>spark.conf.set(<br>    &quot;spark.sql.catalog.snowflake_catalog.uri&quot;,<br>    f&quot;jdbc:snowflake://{os.environ[&#39;SNOWFLAKE_ACCOUNT&#39;]}&quot;<br>     &quot;.snowflakecomputing.com&quot;,<br>)<br><br># Set Snowflake connection properties<br>spark.conf.set(<br>    &quot;spark.sql.catalog.snowflake_catalog.jdbc.user&quot;,<br>    os.environ[&quot;SNOWFLAKE_USER&quot;]<br>)<br>spark.conf.set(<br>    &quot;spark.sql.catalog.snowflake_catalog.jdbc.role&quot;,<br>    os.environ[&quot;SNOWFLAKE_ROLE&quot;]<br>)<br>spark.conf.set(<br>    &quot;spark.sql.catalog.snowflake_catalog.jdbc.private_key_file&quot;,<br>    os.environ[&quot;SNOWFLAKE_PRIVATE_KEY_FILE&quot;],<br>)<br>spark.conf.set(<br>    &quot;spark.sql.catalog.snowflake_catalog.io-impl&quot;,<br>    &quot;org.apache.iceberg.aws.s3.S3FileIO&quot;<br>)<br><br># configure s3 for the hadoop catalog. this is required cuz snowflake<br># seems to be configuring the hadoop catalog as well! you&#39;ll see the<br># infamous version-hint.txt file.<br>spark.conf.set(<br>    &quot;spark.hadoop.fs.s3a.impl&quot;,<br>    &quot;org.apache.hadoop.fs.s3a.S3AFileSystem&quot;<br>)<br>spark.conf.set(<br>    &quot;spark.hadoop.fs.s3a.aws.credentials.provider&quot;,<br>    &quot;org.apache.hadoop.fs.s3a.TemporaryAWSCredentialsProvider&quot;,<br>)<br>spark.conf.set(<br>    &quot;spark.hadoop.fs.s3a.endpoint&quot;, &quot;s3.amazonaws.com&quot;<br>)<br>spark.conf.set(<br>    &quot;spark.hadoop.fs.s3a.access.key&quot;, current_credentials.access_key<br>)<br>spark.conf.set(<br>    &quot;spark.hadoop.fs.s3a.secret.key&quot;, current_credentials.secret_key<br>)<br>spark.conf.set(<br>    &quot;spark.hadoop.fs.s3a.session.token&quot;, current_credentials.token<br>)<br>spark.conf.set(<br>    &quot;spark.hadoop.fs.s3a.endpoint.region&quot;, os.environ[&quot;AWS_REGION&quot;]<br>)<br><br>spark.sql(&quot;use my_sf_db.public&quot;).show()<br>spark.sql(&quot;SHOW TABLES&quot;).show()<br><br>tab = spark.table(&quot;my_sf_db.public.my_iceberg_table&quot;)<br>tab.show()<br><br>print(tab.count())<br>print(tab.schema)<br><br># this will throw an error cuz snowflake catalog doesn&#39;t<br># implement writes!<br>tab.writeTo(<br>    &quot;my_sf_db.public.my_iceberg_table&quot;<br>).using(&quot;iceberg&quot;).append()<br><br>spark.stop()</pre><p>If you have done some legendary ETL and want to write it back, you can’t it using the default Snowflake catalog. Refer to these two pieces of code in apache-iceberg:1.5.0 for yourself:</p><ol><li><a href="https://github.com/apache/iceberg/blob/apache-iceberg-1.5.0/snowflake/src/main/java/org/apache/iceberg/snowflake/SnowflakeTableOperations.java">Snowflake Metastore Ops</a></li><li><a href="https://github.com/apache/iceberg/blob/apache-iceberg-1.5.0/core/src/main/java/org/apache/iceberg/BaseMetastoreTableOperations.java#L145">Base Metastore Ops</a> — this is the base table of Snowflake Metastore ops.</li></ol><p>Although you can use the Spark &lt;&gt; Snowflake connector for writes, they may be inconvenient to implement and will pass through the Snowflake DWH, diluting the proposition of reducing dependency on Snowflake warehouse in the ETL phase.</p><h3>AWS Glue Data Catalog</h3><p>Let’s understand the capabilities of the AWS Glue Data Catalog + Apache Iceberg integration.</p><ol><li>Spark’s CREATE DATABASEAPI can create the <a href="https://docs.aws.amazon.com/glue/latest/dg/define-database.html">catalog</a> in AWS Glue.</li><li>Glue catalog’s table params point to the latest metadata location. This location is expressed as a S3 URI.</li><li>Snowflake can only read from this catalog. It can’t write to it 🤷‍♂.</li><li>Snowflake is very generous in its read operations. It can connect with the Glue data catalog directly.</li><li>Snowflake tables need to be refreshed to reflect any metadata changes.</li><li>If the snowflake iceberg table is directly connected to Glue, it’ll pull the metadata info internally &amp; update itself.</li><li>If you <em>don’t</em> want to connect it with Glue, you can manually obtain the metadata location from Glue &amp; pass it as a parameter to the Snowflake refresh.</li></ol><h3>Setup</h3><p>Configure the S3 bucket &amp; external volume for the Snowflake read access as in the previous demo.</p><p>AWS Glue Data Catalog itself doesn&#39;t entail any setup overhead, making it reliable &amp; easy to use. Writes will be done entirely by Pyspark. Reads can be done by anyone. Duh!</p><h3>How to use the Iceberg tables?</h3><p>Write Iceberg tables using Pyspark.</p><pre>import os<br><br>import boto3<br>from pyspark.sql import SparkSession<br><br>warehouse_path = &quot;s3://my-iceberg/&quot;<br><br><br>def create_spark_iceberg(catalog_nm: str) -&gt; SparkSession:<br>    # You can set this as a variable if required<br><br>    spark = (<br>        SparkSession.builder.config(<br>            &quot;spark.jars.packages&quot;,<br>            &quot;,&quot;.join(<br>                [<br>                    &quot;org.apache.iceberg:iceberg-spark-runtime-3.5_2.12:1.4.1&quot;,<br>                    &quot;software.amazon.awssdk:bundle:2.20.160&quot;,<br>                ]<br>            ),<br>        )<br>        .config(<br>            &quot;spark.sql.extensions&quot;,<br>            &quot;org.apache.iceberg.spark.extensions.IcebergSparkSessionExtensions&quot;,<br>        )<br>        .config(<br>            f&quot;spark.sql.catalog.{catalog_nm}&quot;, &quot;org.apache.iceberg.spark.SparkCatalog&quot;<br>        )<br>        .config(f&quot;spark.sql.catalog.{catalog_nm}.warehouse&quot;, warehouse_path)<br>        .config(<br>            f&quot;spark.sql.catalog.{catalog_nm}.catalog-impl&quot;,<br>            &quot;org.apache.iceberg.aws.glue.GlueCatalog&quot;,<br>        )<br>        .config(<br>            f&quot;spark.sql.catalog.{catalog_nm}.io-impl&quot;,<br>            &quot;org.apache.iceberg.aws.s3.S3FileIO&quot;,<br>        )<br>        .getOrCreate()<br>    )<br><br>    return spark<br><br><br>_catalog_nm = &quot;iceberg_catalog&quot;<br>spark = create_spark_iceberg(_catalog_nm)<br><br>table = f&quot;{_catalog_nm}.{os.environ[&#39;DATABASE_NAME&#39;]}.{os.environ[&#39;TABLE_NAME&#39;]}&quot;<br>table_path = f&quot;{warehouse_path}{os.environ[&#39;DATABASE_NAME&#39;]}/{os.environ[&#39;TABLE_NAME&#39;]}&quot;<br><br>glue_client = boto3.client(&quot;glue&quot;)<br><br># can also be done by spark sql as follows.<br># spark.sql(f&#39;create database {os.environ[&quot;DATABASE_NAME&quot;]}&#39;)<br><br>try:<br>    glue_client.create_database(<br>        DatabaseInput={<br>            &quot;Name&quot;: os.environ[&quot;DATABASE_NAME&quot;],<br>            &quot;Description&quot;: f&#39;{os.environ[&quot;DATABASE_NAME&quot;]} Iceberg Database&#39;,<br>        }<br>    )<br>except Exception:<br>    # cheap manner of handling already existing catalog!<br>    pass<br><br># based on your deployment strategy, you can choose to<br># provision catalogs separately say, as part of your IaC<br><br>df = spark.createDataFrame(<br>    [<br>        (&quot;2021-01-01&quot;, 1, &quot;A&quot;, &quot;X&quot;, &quot;2021-01-01&quot;),<br>        (&quot;2021-01-01&quot;, 2, &quot;B&quot;, &quot;Y&quot;, &quot;2021-01-01&quot;),<br>        (&quot;2021-01-01&quot;, 3, &quot;C&quot;, &quot;Z&quot;, &quot;2021-01-01&quot;),<br>    ],<br>    [&quot;col_1&quot;, &quot;col_2&quot;, &quot;col_3&quot;, &quot;col_4&quot;, &quot;col_5&quot;],<br>)<br><br>df.writeTo(table).using(&quot;iceberg&quot;).tableProperty(<br>    &quot;location&quot;, table_path<br>).tableProperty(<br>    &quot;write.format.default&quot;, &quot;parquet&quot;<br>).partitionedBy(df.col_5).append()<br><br>tab = glue_client.get_table(<br>    DatabaseName=os.environ[&quot;DATABASE_NAME&quot;], Name=os.environ[&quot;TABLE_NAME&quot;]<br>)<br><br># you can configure your iceberg table using this metadata location!<br># remember to strip the leading bucket name from the string.<br>print(&quot;new_metadata&quot;, tab[&quot;Table&quot;][&quot;Parameters&quot;][&quot;metadata_location&quot;])<br><br>spark.read.table(table).show()</pre><p>See the data in S3!</p><pre># you can locate your files of data layer<br># in this folder hierarchy<br>aws s3 ls s3://my-iceberg<br><br># get the latest metadata location from glue data catalog<br>aws glue get-table --database-name &lt;DATABASE_NAME&gt; --name &lt;TABLE_NAME&gt; | jq -r &quot;.Table.Parameters.metadata_location&quot;</pre><p>Read it in Snowflake. Mind it, we’ll be getting the metadata location from Glue.</p><pre>-- this means that metadata is on the external volume itself<br>CREATE OR REPLACE CATALOG INTEGRATION icebergCatalogExt<br>  CATALOG_SOURCE=OBJECT_STORE<br>  TABLE_FORMAT=ICEBERG<br>  ENABLED=TRUE;<br><br>-- use volume as configured. obtain metadata file path from the spark job.<br>CREATE ICEBERG TABLE read_iceberg_table_nessie<br>   EXTERNAL_VOLUME=&#39;MY_ICEBERG&#39;<br>   CATALOG = &#39;icebergCatalogExt&#39;<br>   METADATA_FILE_PATH=&#39;&lt;new_metadata&gt;&#39;</pre><p>Although Snowflake directly connects with Glue thereby doing away with the necessity of manually specifying the metadata_file_path param, I prefer the above method of not creating a Glue-specific integration. This <em>reduces</em><strong>vendor tie-in</strong> and makes the catalog integration on the Read end, i.e. Snowflake, thoroughly general purpose.</p><h3>Project Nessie</h3><p>Let’s understand the capabilities of the Project Nessie + Apache Iceberg integration.</p><p>One tradeoff with using AWS Glue Data Catalog is the vendor lock-in that comes with the catalog. If you are in a non-AWS environment, then the AWS glue data catalog becomes a no-go.</p><p>In this case, Project Nessie is a good <em>alternative</em> because it can be entirely self-hosted. Incorporating Project Nessie makes our system <strong>trulyvendor agnostic</strong> and makes it stand tall on the giant shoulders of the OSS community 💪.</p><ol><li>Setup Project Nessie. Spark’s CREATE DATABASEAPI can create the catalog in Nessie using its SQL extensions.</li><li>Just like Glue, the metadata location can be easily obtained from Nessie and this location is expressed as a S3 URI.</li><li>Snowflake can only read from this catalog. It can’t write to it. Similar to the previous AWS Glue catalog demo.</li></ol><p><strong>Setup</strong></p><ol><li>Configure the S3 bucket &amp; external volume for the Snowflake read access as in the previous demos.</li><li>Configure project Nessie deployment.<br>docker run -p 19120:19120 projectnessie/nessie:latest</li><li>Access the catalog info on you http://0.0.0.0:19120</li></ol><p>Project Nessie deployment seems a bit challenging as it is a fairly new technology. Convincing your team to take this up will require some massive effort! The remainder of the setup is quite similar to that of the AWS Glue Data Catalog.</p><p><strong>How to use the Iceberg tables?</strong></p><p>Create Iceberg tables using Pyspark. This implementation only differs from the previous demo in the choice of catalog. Everything else remains configurable.</p><pre>import os<br><br>from pyspark.sql import SparkSession<br><br>warehouse_path = &quot;s3://my-iceberg&quot;<br><br><br>def create_spark_iceberg(catalog_nm: str) -&gt; SparkSession:<br>    url = &quot;http://localhost:19120/api/v1&quot;<br>    ref = &quot;main&quot;<br>    spark = (<br>        SparkSession.builder.config(<br>            &quot;spark.jars.packages&quot;,<br>            &quot;,&quot;.join(<br>                [<br>                    &quot;org.apache.iceberg:iceberg-spark-runtime-3.5_2.12:1.4.1&quot;,<br>                    &quot;org.projectnessie.nessie-integrations:nessie-spark-extensions-3.5_2.12:0.79.0&quot;,<br>                    &quot;software.amazon.awssdk:bundle:2.20.160&quot;,<br>                ]<br>            ),<br>        )<br>        .config(<br>            &quot;spark.sql.extensions&quot;,<br>            &quot;,&quot;.join(<br>                [<br>                    &quot;org.apache.iceberg.spark.extensions.IcebergSparkSessionExtensions&quot;,<br>                    &quot;org.projectnessie.spark.extensions.NessieSparkSessionExtensions&quot;,<br>                ]<br>            ),<br>        )<br>        .config(&quot;spark.sql.execution.pyarrow.enabled&quot;, &quot;true&quot;)<br>        .config(<br>            f&quot;spark.sql.catalog.{catalog_nm}.io-impl&quot;,<br>            &quot;org.apache.iceberg.aws.s3.S3FileIO&quot;,<br>        )<br>        .config(<br>            f&quot;spark.sql.catalog.{catalog_nm}&quot;,<br>             &quot;org.apache.iceberg.spark.SparkCatalog&quot;<br>        )<br>        .config(<br>            f&quot;spark.sql.catalog.{catalog_nm}.catalog-impl&quot;,<br>            &quot;org.apache.iceberg.nessie.NessieCatalog&quot;,<br>        )<br>        .config(f&quot;spark.sql.catalog.{catalog_nm}.warehouse&quot;, warehouse_path)<br>        .config(f&quot;spark.sql.catalog.{catalog_nm}.uri&quot;, url)<br>        .config(f&quot;spark.sql.catalog.{catalog_nm}.ref&quot;, ref)<br>        .getOrCreate()<br>    )<br><br>    return spark<br><br><br>_catalog_nm = &quot;iceberg_catalog&quot;<br><br>spark = create_spark_iceberg(_catalog_nm)<br>table = f&quot;{_catalog_nm}.{os.environ[&#39;DATABASE_NAME&#39;]}.{os.environ[&#39;TABLE_NAME&#39;]}&quot;<br><br>spark.sql(f&quot;create namespace {_catalog_nm}.{os.environ[&#39;DATABASE_NAME&#39;]}&quot;)<br><br>df = spark.createDataFrame(<br>    [<br>        (&quot;2021-01-01&quot;, 1, &quot;A&quot;, &quot;X&quot;, &quot;2021-01-01&quot;),<br>        (&quot;2021-01-01&quot;, 2, &quot;B&quot;, &quot;Y&quot;, &quot;2021-01-01&quot;),<br>        (&quot;2021-01-01&quot;, 3, &quot;C&quot;, &quot;Z&quot;, &quot;2021-01-01&quot;),<br>    ],<br>    [&quot;col_1&quot;, &quot;col_2&quot;, &quot;col_3&quot;, &quot;col_4&quot;, &quot;col_5&quot;],<br>)<br><br>df.writeTo(table).using(&quot;iceberg&quot;).partitionedBy(df.col_5).createOrReplace()</pre><p>See the data in s3!</p><pre># you can locate your files of data layer<br># in this folder hierarchy<br>aws s3 ls s3://my-iceberg</pre><p>Fetch the metadata info from Nessie UI.</p><p>Nessie uses Git like semantics, so we can fetch metadata for any of the commits. This is very promising &amp; exciting!</p><p>Reading data into Snowflake is the same as we did for the AWS Glue Data Catalog.</p><p>Voila! We have understood three vastly different ways of using Apache Iceberg with Read-Write-Vendor tradeoffs.</p><p>If your data architecture is <strong>currently</strong> based entirely on Snowflake, then you would need a hybrid architecture. A good architecture would:</p><ol><li>🔼 Maximise the best of both Snowflake &amp; Apache Spark compute</li><li>🔽 Minimise infra costs significantly</li></ol><p>To begin with, converting the Snowflake table to Iceberg massively reduces the read costs. Engineers experienced in infra can also beat Snowflake’s storage pricing model with appropriate choice &amp; configuration in storage to extract that savings juice.</p><p>As far as compute is concerned, I have put Spark primarily for PoC purposes.</p><p>Data engineers have been using multiple compute technologies &amp; tools for a long time. Now they can bring their own tools to the party courtesy of Iceberg’s extensive integrations ecosystem.</p><h3>Next steps</h3><p>Readers will understand that the presentations of this blog are just the tip of the iceberg (<em>no pun intended</em>). Hardening such a system for production use cases requires analysis along multiple lines.</p><ol><li>Hybrid Architecture Design.<br>a) Choice of compute layer<br>b) Choice of storage layer<br>c) ID’ing a control plane</li><li>Updates to the relevant ETL algorithms.</li><li>Migration strategy.</li><li>Upskilling ourselves to understand the corresponding DevOps.</li></ol><p>I’ll be working on the next set of items here and publish follow-up articles that talk about the above items in the coming months. Meanwhile, HMU if you wish to go deeper into anything that I have written above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rUb8LU-YsyzR0RJu" /></figure><p><em>Readers, I have compiled this article after reading multiple tutorials, how to guides, blog posts, videos &amp; Stack Overflow posts, etc., and have then created the MVP for this post. Below are a few links for reference.</em></p><h3>References</h3><ol><li>Snowflake Iceberg setup:<br>a) <em>Document</em>: <a href="https://docs.snowflake.com/en/user-guide/tables-iceberg">https://docs.snowflake.com/en/user-guide/tables-iceberg</a><br>b) <em>Tutorial</em>: <a href="https://quickstarts.snowflake.com/guide/getting_started_iceberg_tables/index.html#0">https://quickstarts.snowflake.com/guide/getting_started_iceberg_tables/index.html#0</a><br>c) <em>Summary article</em>: <a href="https://www.snowflake.com/blog/unifying-iceberg-tables/">https://www.snowflake.com/blog/unifying-iceberg-tables/</a></li><li>Apache Iceberg resources:<br>a) <em>book</em>: <a href="https://hello.dremio.com/wp-apache-iceberg-the-definitive-guide-reg.html">https://hello.dremio.com/wp-apache-iceberg-the-definitive-guide-reg.html</a><br>b) <em>catalog summary by the same author</em>: <a href="https://www.linkedin.com/pulse/deep-dive-concept-world-apache-iceberg-catalogs-alex-merced-u0ucc/">https://www.linkedin.com/pulse/deep-dive-concept-world-apache-iceberg-catalogs-alex-merced-u0ucc/</a></li><li>AWS Glue as catalog:<br>a) <em>tutorial 1</em>: <a href="https://medium.com/@cesar.cordoba/how-to-work-with-iceberg-format-in-aws-glue-258bbcec52d7">https://medium.com/@cesar.cordoba/how-to-work-with-iceberg-format-in-aws-glue-258bbcec52d7</a><br>b) <em>tutorial 2</em>: <a href="https://medium.com/softwaresanders/aws-glue-apache-iceberg-d3790c0e91a4">https://medium.com/softwaresanders/aws-glue-apache-iceberg-d3790c0e91a4</a></li><li>Project Nessie as catalog:<br>a) <em>official tutorial</em>: <a href="https://github.com/projectnessie/nessie-demos/blob/main/notebooks/nessie-iceberg-demo-nba.ipynb">https://github.com/projectnessie/nessie-demos/blob/main/notebooks/nessie-iceberg-demo-nba.ipynb</a></li></ol><h3>Working at Toplyne</h3><p>We’re always looking for talented engineers to join our team. You can find and <a href="https://www.linkedin.com/jobs/view/3881191342/">apply for relevant roles here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b196e8f7e2e6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/toplyne-engineering/skiing-with-snowflake-b196e8f7e2e6">Skiing with Snowflake</a> was originally published in <a href="https://medium.com/toplyne-engineering">CMD-LYNE</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Snorkeling with Snowflake]]></title>
            <link>https://medium.com/toplyne-engineering/snorkeling-with-snowflake-6047af420541?source=rss-9856a06a88a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/6047af420541</guid>
            <category><![CDATA[anyscale]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[rays]]></category>
            <dc:creator><![CDATA[Prabodh Agarwal]]></dc:creator>
            <pubDate>Sat, 07 Oct 2023 09:38:32 GMT</pubDate>
            <atom:updated>2024-04-13T08:00:10.089Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<h4>Ray Dataset with snowflake</h4><h4>How to use Ray to execute massively parallel compute on a Snowflake dataset?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CNEZqnI4kI6KJe-7" /><figcaption>Photo by <a href="https://unsplash.com/@kiwihug?utm_source=medium&amp;utm_medium=referral">Kiwihug</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><a href="https://www.ray.io/">Ray</a> and its managed offering <a href="https://www.anyscale.com/">Anyscale</a> have been making waves now primarily because of how straightforward it makes for developers to leverage massively parallel compute with super simple idioms.</p><p>I have been using Snowflake at <a href="https://www.toplyne.io/">Toplyne</a> for a long time and looking for ways to leverage Ray with Snowflake to unlock next-level compute power.</p><p>The Snowflake Python connector offers a basic API that lets us pull data from Snowflake in a batched manner. To date, I have been using Python multi-threading to patch together basic Snowflake workflows. A basic workflow lets us boot up multiple threads wherein individual batches of Snowflake data can be mapped to different threads. This lets us get a seeming increase in throughput.</p><pre>from concurrent.futures import ThreadPoolExecutor<br><br>from snowflake.connector import connect<br><br>connect_args = {...}<br>query = &quot;select * from SNOWFLAKE_SAMPLE_DATA.TPCH_SF1.LINEITEM&quot;<br><br>def _compute(_sf_batch: ResultBatch):<br>    arrow_table = _sf_batch.to_arrow()<br>    # do more compute on this arrow table<br><br>with connect(**connect_args) as conn:<br>    with conn.cursor() as cur:<br>        cur.execute(query)<br>        batches = cur.get_result_batches()<br><br>with ThreadPoolExecutor() as _texec:<br>    for batch in batches:<br>        _texec.submit(_compute, batch)<br><br>_texec.shutdown()</pre><p>Multithreading is built into Python and for a lot of general-purpose tooling. It so happens that we can marry Snowflake’s APIs with multithreading and patch a workflow, but this approach has limited horizontal scalability capabilities.</p><p>Let’s see what this workflow will look like in Ray:</p><pre>import ray<br>import pyarrow as pa<br><br>from snowflake.connector import connect<br><br>connect_args = {...}<br>query = &quot;select * from SNOWFLAKE_SAMPLE_DATA.TPCH_SF1.LINEITEM&quot;<br><br>def _compute(arrow_table: pa.table):<br>    # do more compute on this arrow table<br>    pass<br><br>snowflake_datasource = SnowflakeDatasource(connect_args, query)<br>rds = ray.data.read_datasource(snowflake_datasource)<br>rds.map_batches(_compute, batch_format=&quot;pyarrow&quot;)</pre><p>This is what is so exciting about Ray. Simple idioms and maximum compute.</p><p>But wait, what is <em>SnowflakeDatasource</em>?</p><p>Ray’s <em>ray-data</em> library describes APIs to load data from different sources. The library implements a bunch of general-purpose APIs to read data from well-defined data sources. However, currently there are no APIs specifically for Snowflake.</p><p>Fortunately, implementing a data source for Snowflake is pretty straightforward.</p><p>How do we go about it though? We should collect some data points first:</p><ol><li>Ray has a <a href="https://docs.ray.io/en/latest/data/examples/custom-datasource.html">guide</a> wherein the implementation of a Mongo Datasource is described.</li><li>Anyscale’s GitHub repo has a <a href="https://github.com/anyscale/datasets-database/blob/master/python/ray/data/datasource/snowflake_datasource.py">fork</a> of Ray data which has an implementation of SnowflakeDataSource as well.</li><li>Additionally, Ray has documented the <a href="https://docs.ray.io/en/latest/data/data-internals.html">block API</a> which is fundamental to Ray’s internal data representation.</li></ol><p>One of Ray’s standout features is that we can easily map individual Snowflake result batches to Ray’s data blocks. Based on this information, we can start with our implementation.</p><p>We need to implement two Ray classes and follow these 3 methods to get the entire thing going:</p><ol><li><a href="https://docs.ray.io/en/latest/data/examples/custom-datasource.html">ray.data</a>.datasource.datasource.Datasource [<a href="https://docs.ray.io/en/latest/data/api/doc/ray.data.Datasource.html#ray.data.Datasource">source</a>]<br> a) create_reader [<a href="https://docs.ray.io/en/latest/data/api/doc/ray.data.Datasource.create_reader.html#ray.data.Datasource.create_reader">source</a>]</li><li><a href="https://docs.ray.io/en/latest/data/examples/custom-datasource.html">ray.data</a>.datasource.datasource.Reader [<a href="https://docs.ray.io/en/latest/data/api/doc/ray.data.datasource.Reader.html#ray.data.datasource.Reader">source</a>]<br> a) estimate_inmemory_data_size [<a href="https://docs.ray.io/en/latest/data/api/doc/ray.data.datasource.Reader.estimate_inmemory_data_size.html#ray.data.datasource.Reader.estimate_inmemory_data_size">source</a>]<br> b) get_read_tasks [<a href="https://docs.ray.io/en/latest/data/api/doc/ray.data.datasource.Reader.get_read_tasks.html#ray.data.datasource.Reader.get_read_tasks">source</a>]</li></ol><p>Now that we know <em>the</em> <em>which</em> of this Ray-data API, we can dive deeper into the what and why of the API:</p><ol><li>Reader.get_read_tasks:<br>a) Create a Snowflake connection.<br>b) Execute the query.<br>c) Fetch the snowflake ResultBatches.<br>d) Generate read tasks.</li></ol><p>These read tasks fetch the data batch from Snowflake. Since Ray’s APIs are lazy, the memory footprint of this execution step is minimal.</p><p>2. Reader.estimate_inmemory_data_size:<br>Get the total size of the table as of when it’ll be loaded into memory.</p><p>For our use, I’ll infer it to be the Pyarrow table size.</p><p>3. Datasource.create_reader:<br>Create an instance of a reader which has implemented the above two methods.</p><p>Now that we know <em>what</em> &amp; <em>why</em> to implement, let’s get into the <em>how</em>. I’ll be adding more descriptions in the documentation of this code.</p><pre>from ray.data.datasource import Reader<br>from ray.data.block import BlockMetadata<br>from ray.data import ReadTask<br><br>from snowflake.connector.result_batch import ResultBatch<br><br># The reader performs the heavy lifting<br>class _SnowflakeDatasourceReader(Reader):<br>    def __init__(self, connection_args: dict, query: str):<br>        # connection info like snowflake account name &amp; credentials.<br>        self._connection_args = connection_args<br> <br>        # the query to execute.<br>        self._query = query<br><br>    # this method will be reused in both creating the read_tasks<br>    # as well as calc<br>    @cached_property<br>    def _result_batches(self):<br>        # connect with snowflake<br>        with connect(**self._connection_args) as conn:<br>            # get the cursor<br>            with conn.cursor() as cur:<br>                cur.execute(self._query)<br>                # Get the result as batches.<br>                # This API has a minimal memory footprint because<br>                # the ResultBatch doesn&#39;t have any data. It only<br>                # tells us how to pull the data and what size/schema<br>                # to expect from this data once it lands.<br>                # The driver hence won&#39;t have any memory footprint<br>                # and can safely do the work of creating relevant<br>                # Block (s) for ray.<br>                batches = cur.get_result_batches()<br>        return batches<br><br>    def estimate_inmemory_data_size(self) -&gt; Optional[int]:<br>        sz = None<br><br>        for batch in self._result_batches:<br>            sz = (sz or 0) + (batch.uncompressed_size or 0)<br><br>        ray_data_logger.info(&quot;Estimating in-memory data size %s&quot;, sz)<br>        return sz<br><br>    def get_read_tasks(self, parallelism: int) -&gt; list[ReadTask]:<br>            read_tasks = []<br><br>            for batch in self._result_batches:<br>                # Map the batch metadata to the ray block metadata.<br>                metadata = BlockMetadata(<br>                    num_rows=batch.rowcount,<br>                    size_bytes=batch.uncompressed_size,<br>                    schema=pa.schema(<br>                        [<br>                            pa.field(<br>                                s.name,<br>                                FIELD_TYPE_TO_PA_TYPE[<br>                                    s.type_code<br>                                ]<br>                            )<br>                            for s in batch.schema<br>                        ]<br>                    ),<br>                    input_files=None,<br>                    exec_stats=None<br>                )<br><br>                # create a lazy handler that will load up the<br>                # ResultBatch in the worker and do the actual<br>                # pull from snowflake.<br>                _r_task = LazyReadTask(<br>                    arrow_batch=batch,<br>                    metadata=metadata<br>                )<br><br>                read_tasks.append(_r_task)<br><br>            return read_tasks<br><br><br># This read task is what executes in the worker(s) and pulls the data<br># from snowflake and returns an PyArrow table.<br>class LazyReadTask(ReadTask):<br>    def __init__(self, arrow_batch: ResultBatch, metadata: BlockMetadata):<br>        self._arrow_batch = arrow_batch<br>        self._metadata = metadata<br><br>    def _read_fn(self) -&gt; Iterable[pa.Table]:<br>        ray_data_logger.debug(<br>            &quot;Reading %s rows from Snowflake&quot;, self._metadata.num_rows<br>        )<br>        return [self._arrow_batch.to_arrow()]</pre><p>Woah 😅, that is <em>smooth</em>.</p><p>Now let’s <em>quickly</em> tidy over the data source, which will let us juice the Ray system.</p><pre>from ray.data.block import Block<br>from ray.data.datasource import Reader<br>from snowflake.connector import connect<br><br>class SnowflakeDatasource(Datasource):<br>    def __init__(self, connection_args: dict, query: str):<br>        self._connection_args = connection_args<br>        self._query = query<br><br>    def create_reader(self, **read_args) -&gt; Reader:<br>        # Yesss! This is the Reader you had just implemented.<br>        return _SnowflakeDatasourceReader(<br>            connection_args=self._connection_args,<br>            query=self._query<br>        )<br><br># This is it. You are not missing anything.<br># To reaffirm. This is it. You are not missing anything.</pre><p>That is all!</p><p>You have a Snowflake data source. The next time you want to use some Ray goodness on Snowflake, you won’t be left wanting for a fast-reading data source.</p><p>You already got it here.</p><p>Now please do the cool stuff and show it to me.</p><p>Appendix:</p><ol><li>The <a href="https://github.com/prabodh1194/ray_snowflake">GitHub repo</a> with my implementation.</li><li>The Anyscale blog that motivated me: <a href="https://github.com/prabodh1194/ray_snowflake">https://www.anyscale.com/blog/introducing-the-anyscale-snowflake-connector</a></li><li>The corresponding Anyscale fork: <a href="https://github.com/prabodh1194/ray_snowflake">https://github.com/anyscale/datasets-database/blob/master/python/ray/data/datasource/snowflake_datasource.py</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6047af420541" width="1" height="1" alt=""><hr><p><a href="https://medium.com/toplyne-engineering/snorkeling-with-snowflake-6047af420541">Snorkeling with Snowflake</a> was originally published in <a href="https://medium.com/toplyne-engineering">CMD-LYNE</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cooking with Snowflake]]></title>
            <link>https://medium.com/data-science/cooking-with-snowflake-833a1139ab01?source=rss-9856a06a88a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/833a1139ab01</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[airflow]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[etl]]></category>
            <dc:creator><![CDATA[Prabodh Agarwal]]></dc:creator>
            <pubDate>Wed, 17 May 2023 11:02:26 GMT</pubDate>
            <atom:updated>2024-04-13T07:57:45.931Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<h4>Snowflake optimisation</h4><h4>Simple recipes &amp; instant gratification on your Data Warehouse</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EKH4WeJLlLBbsla_tkuObA.png" /><figcaption>Generated using Midjourney (paid subscription)</figcaption></figure><p>The Snowflake community is rife with information dumps on how to optimize expensive queries. We know because we combed through a ton of them. What we present here are three tactical ways in which we’ve done this at <a href="https://www.toplyne.io/">Toplyne</a>.</p><p>Toplyne’s business involves extracting real-time insights from real-time data. This data is currently sourced from our customers’ Product Analytics, CRM, and payments system.</p><p>CRM and payment data volumes are mostly manageable. A product will have a limited set of paying customers and marginally more who are tracked in a CRM. However, product analytics data is much higher in volume.</p><p>Toplyne’s POC (proof-of-concept) and MVP (minimum viable product) were built on product analytics data. We knew right from the beginning we needed to use a Data Warehousing solution to handle the data. The solution had to pass two clear requirements:</p><ol><li>It should easily ingest a few 100 gigabytes of data.</li><li>It should offer a simple yet concise API to interact with this data.</li></ol><p>We compared 3 solutions: BigQuery, Redshift &amp; Snowflake.</p><p>Post-exploration, Snowflake was a clear choice. The simple reason is its SQL-based interface. SQL meant there was no cold start latency for our engineering ops. None of the engineers at Toplyne came from a DWH background, still, we found ourselves up to speed very quickly.</p><p>The process of interacting with customers’ product analytics data is simple as follows:</p><ol><li>The product analytics data lands into Snowflake via a connector. (There are a lot of over-the-counter as well as native connectors for the same).</li><li>Login to Snowflake and use the in-built worksheets to write SQL. 🎉</li></ol><p>This simple 2-step process means that we can get on top of the data that our customers share with us in no time.</p><p>In a short period, we cooked up two algorithms to transform the data we receive into a schema that can be trained by our data scientists. The first algorithm took care of transforming the product analytics events data. The second took care of identifying users’ profile data. Additional feature engineering algorithms are then written on top of this data.</p><p>SQL is a fourth-generation language (4GL) that is relatively easier to learn. Combined with a worksheet-based interface that just requires you to have a browser tab — Snowflake; a scrappy startup could do a lot of data-heavy lifting with minimal setup effort.</p><p>We wrote a few SQLs in the worksheet to transform the data and then our data scientists could just SELECT * the data and write their ML training programs.</p><p>Over time the entire above-mentioned process has scaled up significantly. The scaling up has happened in the following aspects:</p><ol><li>We have multiple customers, each of whom has their product analytics data in multiple platforms viz., Amplitude, Mixpanel, Segment, Clevertap, etc.</li><li>Our teams have written multiple algorithms to crunch the data along different axes.</li><li>We now integrate CRM as well as payment data. Further, these datasets have their own set of ETL algorithms.</li><li>We use Airflow to orchestrate enormous pipelines which have multiple stages.</li></ol><p>Sample architecture diagram of our ETL flow. Snowflake sits at the heart of this system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*8w49lWLMc_MGAr2c7rwJ2g.png" /><figcaption>Toplyne’s Data Pipeline architecture</figcaption></figure><ol><li>Sync source data into Snowflake.</li><li>Use Apache Airflow for ETL orchestration.</li><li>Land the transformed data into Snowflake.</li><li>DS/ML/Analysts/Product consumes data from Snowflake for their flows.</li></ol><p>Over the months, there have been multiple changes and major rewrites of different components of the system with Snowflake being the only constant.</p><p>As we have run and maintained a system, we would like to present a few ideas around query optimization in Snowflake. We have a super simple technique that has allowed us to extract a lot of performance from the system with minor tweaks in your existing queries.</p><h3><strong>Query optimization</strong></h3><p>We run a multi-tenant system wherein a single Snowflake instance is responsible for the ETL of a lot of customer data. ETL is orchestrated by Airflow.</p><p>We create a warehouse per customer and run all the ETL &amp; feature engineering on that warehouse. There are 100s of SQL queries that are fired against a warehouse in sequence and/or in parallel during the entire ETL run for the customer. One run can last for an hour and there can be multiple runs for the customer in a day.</p><p>Essentially, one warehouse size runs all expensive as well as cheap queries. So our objective is to keep warehouse size at a minimum. We define minimums by defining SLAs for different ETL runs. Then we modify the warehouse size so that ETL SLAs can be met at that size. Like any engineering org, we want to keep the warehouse size at a bare minimum given the SLA.</p><p>We have dashboards where we monitor query patterns of the most expensive queries. These dashboards are at different levels of granularity. We monitor these dashboards constantly and keep tweaking the queries. Over time we have identified a few patterns in expensive queries and have come up with a playbook on how to minimize the run time of these queries. We’ll present 3 case studies outlining the problem statement for the query, how it was originally written, what was the bottleneck in that query and what was the optimal solution for the same.</p><h3>Window queries</h3><h4>Scenario</h4><p>We track users’ profile information from product analytics data. Product Analytics systems save multiple data points about their users, e.g., location, device, subscription status, etc. Some data points change frequently while others do not so much. Given the nature of these data, the information is represented as an append-only log in a database.</p><p>One of our feature engineering requirements is to capture the users’ latest profile info as of the ETL run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JeI_H4jTLorKww90tpvvYg.png" /></figure><p>The above diagram gives a flowchart of the ETL.</p><p><strong>1</strong> is the raw_data from product analytics, <strong>2</strong> is the algorithm that we want to apply &amp; <strong>3</strong> is the final result of the ETL.</p><p>The SQL query that we have is this:</p><pre>select<br>    *<br>from<br>    tbl<br>qualify<br>    row_number() over (partition by id order by timestamp desc) = 1</pre><h4>Bottleneck</h4><p>This query is pretty simple to come up with and works great in Snowflake. However, the window function in this query is a bottleneck.</p><p>Here’s how the query works:</p><ol><li>create as many logical buckets as there are user_ids</li><li>sort data in every bucket in descending order</li><li>assign row_numbers to the arranged data</li><li>qualify the first entry in the bucket</li><li><em>discard</em> the remaining data.</li></ol><p>Based on the above explanation, we can see that as the data in the table increases, the number of buckets and the bucket sizes both will increase. Since we are dealing with an append-only dataset, we should be prepared for this eventuality. In Snowflake, you’ll notice the size increase trend as <strong>Byte Spillage</strong> in your query profiler.</p><p>Further, we need to understand that based on business requirements, it is expected for the number of buckets to increase, but as engineers, we can still keep the <strong>size of an individual bucket</strong> to a minimum.</p><h4>Optimal solution</h4><p>We’ll come up with a technique to keep the entries being bucketed to a minimum by using <strong>CTEs</strong> &amp; an <strong>aggregate function</strong>.</p><pre>with<br>prune_condition as (<br>    select id, max(timestamp) as prune_column from tbl group by id<br>),<br>pruned_data as (<br>    select * from tbl left join prune_condition using (id)<br>)<br>select<br>    * exclude prune_column<br>from<br>    pruned_data<br>where<br>    timestamp &gt;= prune_column<br>qualify<br>    row_number() over (partition by id order by timestamp desc) = 1</pre><p>We convert our descending sort expression in-the-window query clause to the max() function and then join that to our source data to obtain a filter. By using this filter, we ensure that the data that would have been <em>discarded</em> by the qualify clause anyways would never be bucketed in the first place. This reduces the work performed by the window query drastically. Also, the additional cost of using an aggregate function is massively offset by the reduction, so the overall query becomes performant.</p><h3>Pivot queries</h3><h4>Scenario</h4><p>We use a feature on event data that requires getting a per-user per-event count.</p><p>To obtain this data, we perform a group by query and then transpose this data to organize it into columns as shown in the image below.</p><p><strong>1</strong> is the raw data &amp; <strong>2</strong> is the output after the transformation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YE03wnT0qKI5WF-7fbSdWA.png" /></figure><p>The SQL query that we have is this:</p><pre>select * from (<br>    select id, id as users, data from tbl<br>) pivot(<br>    count(users)<br>    for data in (‘d1’, ‘d2’, ‘d3’)<br>)</pre><h4>Bottleneck</h4><p>Although the sample shows a pivot along 3 elements, our production use case generally functions on around a million users for approximately 1000 events.</p><p>The pivot function on this query is the slowest step of the query. So we want to replace this logic with a manual pivot query. We generate this query by using a combination of Group By clause &amp; Filter clause.</p><h4>Optimal solution 1</h4><pre>select <br>    id,<br>    sum(iff(data = ‘d1’, 1, 0)) as “‘d1’”,<br>    sum(iff(data = ‘d2’, 1, 0)) as “‘d2’”,<br>    sum(iff(data = ‘d3’, 1, 0)) as “‘d3’”<br>from<br>    tbl<br>group by id</pre><p>This query improved performance significantly.</p><p>We then <strong>reduced</strong> the warehouse size to see if the query remains equally performant. We observed that the query slowed down significantly and <strong>byte spillage</strong> was significant. However, an advantage of byte spillage is that we have more room for improvement in the reduced warehouse size.</p><h4>Optimal Solution 2</h4><p>We rewrote this query as per the <strong>Map-Reduce</strong> framework and observed a significant improvement in runtime.</p><p>The objective is to perform the above operation on a smaller set of events at a time and join all the data together in one go as follows:</p><pre>create temporary batch_1 as (<br>    select<br>        id,<br>        sum(iff(data = ‘d1’, 1, 0)) as “‘d1’”<br>    from<br>        tbl<br>    group by id<br>);<br><br>create temporary batch_2 as (<br>    select<br>        id,<br>        sum(iff(data = &#39;d2&#39;, 1, 0)) as &quot;&#39;d2&#39;&quot;,<br>        sum(iff(data = &#39;d3&#39;, 1, 0)) as &quot;&#39;d3&#39;&quot;<br>    from<br>        tbl<br>    group by id<br>);<br><br>create final_table as (<br>    select * from batch_1 full outer join batch_2 using(id)<br>);</pre><p>Our production system will break up <strong>1000 events</strong> into <strong>10 chunks</strong> of <strong>100 events</strong> each. This query speeds up significantly as it reduces byte spillage to near 0.</p><p>Also, this optimization is quite intuitive to derive once we replace the Pivot function with Optimal Solution 1.</p><p><em>Scroll to the bottom to find some accompaniment code for this article.</em></p><h3>Aggregate queries</h3><p>SQL spec defines a lot of aggregate functions and Snowflake does a great job at this. There is a massive repository of aggregate functions in Snowflake as well.</p><p>Different aggregate functions have varying runtimes and in our opinion, every aggregate function should be treated on its merit. A strategy for optimizing aggregate functions is to first identify aggregate functions to be a bottleneck and then motivate yourself that there <strong>might</strong> be an algorithmic solution to your problem statement.</p><p>We would like to share one case study with you where we identified a query in which a suboptimal aggregate function was chosen. We redid the algorithm for the solution using a simpler aggregate function thereby getting a far superior performance for the same result.</p><h4>Scenario</h4><p>We have a time series of events that are fired in the product analytics system. We need to answer 2 questions from this dataset for one of feature engineering.</p><p>Q1) Identify all data points that are mostly fired multiple times within a second</p><p>Q2) Identify data points that are mostly fired at least an hour apart</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nsJzv5VlKd3daqnQTYjmLA.png" /></figure><p>To answer these questions, we transform input data in tbl_1 to tbl_2 using a <strong>window query</strong> with the Snowflake <strong>lag function</strong>.</p><p>We then write the solution query using the <strong>median function</strong> as follows.</p><pre>-- Q1)<br><br>select<br>    data<br>from<br>    tbl_2<br>group by data<br>having median(sec_diff) = 0;<br><br>-- Q2)<br><br>select<br>    data<br>from<br>    tbl_2<br>where<br>    data &lt;&gt; lag_data<br>group by data<br>having median(hour_diff) &gt; 0;</pre><h4>Bottleneck</h4><p>The median function is super slow.</p><p>We asked ChatGPT to suggest an optimal solution. It did come up with a solution to use a <strong>Percentile</strong> function, but that was equally slow and seemed synonymous with the <strong>Median</strong> function itself.</p><p>However, ChatGPT did a good job of explaining why it came up with that solution. We then came up with a solution by iterating &amp; improving ChatGPT’s solution.</p><h4>Optimal solution</h4><p>We identified that for our requirement, we can just use count queries. For both <strong>Q1)</strong> &amp; <strong>Q2)</strong>, we want the majority of our events to have <strong>sec_diff</strong> &amp; <strong>hour_diff</strong> respectively equal to &amp; greater than 0.</p><pre>-- Q1) after optimisation<br><br>select<br>    data,<br>    count(iff(sec_diff = 0, 1, null)) / count(*) as seccount<br>from<br>    tbl_2<br>group by data<br>having seccount &gt;= 0.5<br><br>-- Q2) after optimisation<br><br>select<br>    data,<br>    count(iff(hour_diff &gt; 0, 1, null)) / count(*) as hourcount<br>from<br>    tbl_2<br>group by data<br>having hourcount &gt;= 0.5</pre><h3>Lessons learned</h3><p>We observe our systems constantly and then identify what optimizations require urgent analysis and what can be backlogged.</p><p>Snowflake provides multiple configuration parameters which can be tuned in conjunction to obtain performance. The Snowflake community regularly publishes tricks &amp; techniques.</p><p>Among all this information overload, we need to focus and build a playbook &amp; a repo of techniques that works for us and can be applied mindlessly.</p><p>These are the parameters that we use for our purpose:</p><ol><li>Inspect every node in the query profiler</li><li>Do an input v/s output ratio for the node<br> i) Try to bring down this ratio<br> ii) The output will remain constant given a problem statement<br>iii) Hence, try to reduce input to the aggregate node</li><li>Another way is to constantly measure the disk spillage. Reduce spillage whenever possible<br> i) Larger warehouses have low spillage but also cost higher<br>ii) You get optimization only if you can reduce spillage in the same warehouse</li></ol><p><strong><em>Reproducing this article as code: </em></strong>You can refer <a href="https://github.com/prabodh1194/sf-query-benchmarks">this github link</a> for code related to benchmarking of these queries.</p><h3>Conclusion</h3><p>The article provides three highly actionable optimization techniques that you can apply right away. You might have a suboptimal pattern in your codebase that is similar to the case we have presented here. Feel free to use the code examples to get an instant resolution. In any other scenario, put on the thinking hat and I’ll be excited to learn about your solutions.</p><p><a href="https://medium.com/@pbd_94">Follow me</a> for more articles on Snowflake, Data, and MLOps.</p><p>P.S. All the images unless noted otherwise are from the author</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=833a1139ab01" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/cooking-with-snowflake-833a1139ab01">Cooking with Snowflake</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>
    </channel>
</rss>