<?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 Miguel Duarte on Medium]]></title>
        <description><![CDATA[Stories by Miguel Duarte on Medium]]></description>
        <link>https://medium.com/@miguelduarte?source=rss-47d7d22b6f8e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2lgUPGWe9gBCj6wWfv610g.jpeg</url>
            <title>Stories by Miguel Duarte on Medium</title>
            <link>https://medium.com/@miguelduarte?source=rss-47d7d22b6f8e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 08:03:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@miguelduarte/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[Reduce your snowflake costs by accurately estimating the costs of each SQL statement.]]></title>
            <link>https://miguelduarte.medium.com/reduce-your-snowflake-costs-by-accurately-estimating-the-costs-of-each-sql-statement-b65f5143402f?source=rss-47d7d22b6f8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b65f5143402f</guid>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[snowflake-computing]]></category>
            <category><![CDATA[snowflake-cost-management]]></category>
            <dc:creator><![CDATA[Miguel Duarte]]></dc:creator>
            <pubDate>Mon, 04 Mar 2024 20:48:20 GMT</pubDate>
            <atom:updated>2024-03-04T22:28:36.425Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Abstract</strong>: An efficient way to accurately estimate the fair cost of snowflake SQL statements, using SQL only, leveraging SQL:2016match_recognizeto reconstruct warehouse activity periods from the query history table. This approach is also efficient, computing the cost at approximately 160.000 queries per second on an X-SMALL warehouse. The estimates can be used to focus on which SQL patterns need optimization.</p><p>Snowflake has become my go-to database for heavy analytics in the last two years due to its performance, advanced features and usability.</p><p>Unlike other databases, costs are driven mainly by <a href="https://docs.snowflake.com/en/user-guide/cost-understanding-compute">the time virtual warehouses are active</a>[1], so there is a strong incentive to keep your SQL nimble, right-sized warehouse clusters and optimal scaling policies.</p><p>Sadly, as of today, users are not provided with good information about how much each SQL statement contributes to the overall cost. In the admin console, users can see how much each warehouse costs, storage allocation and a list of the &quot;most expensive queries&quot;:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dsofk5tT1uEW09z617kUZQ.png" /><figcaption>Snowflake Cost Management dashboard</figcaption></figure><p>However, this view is misleading, as it only considers <strong>total execution time</strong> and<strong> warehouse size. </strong>This approach will both:</p><ul><li><strong>Overestimate costs</strong>: Snowflake warehouses can run multiple queries in parallel in each cluster. Therefore, a query&#39;s fair cost should split the warehouse activity cost by all the queries that ran in the same activity <em>window.</em></li><li><strong>Underestimate costs</strong>: A snowflake query that executes very quickly — say 1 ms -but is run every minute can keep a warehouse permanently busy, incurring costs even though most of the warehouse compute capacity is going to waste.</li></ul><p>What if we could reconstruct the warehouse activity using only the query history table? The query history table provides:</p><ul><li>Query start and end time</li><li>Warehouse name</li><li>Warehouse size</li><li>Cluster number</li></ul><p>This information can be used to reconstruct warehouse cluster activity windows alongside the queries that execute inside them. By applying snowflake billing rules, we can estimate the total cost of each activity window and split the cost for each query proportionally to its share of the full execution time.</p><h3>Preparation</h3><p>Before going into the computation details, we must prepare the database to analyse the query history table efficiently. It is not strictly necessary, but queries on a cloned table can be over ten times faster than the same query on the base snowflake.account_usage table:</p><pre>-- clone table<br>create or replace table query_history_backup as <br>select * <br>from snowflake.account_usage.query_history <br>limit 0;<br><br>-- copy the data incrementally<br>insert into query_history_backup<br>    select qh.* <br>    from snowflake.account_usage.query_history qh<br>    where qh.end_time &gt; (<br>        select coalesce(max(end_time), &#39;2000-01-01&#39;::timestamp_ntz) <br>        from query_history_backup<br>    )<br>    order by start_time;</pre><p>To account for warehouse suspend time we also need to obtain warehouse information.</p><pre>show warehouses;<br>create table warehouses as select * from table(result_scan(last_query_id()));</pre><p>Sadly, snowflake doesn&#39;t currently provide a way to programmatically fetch the warehouse suspend time for a specific time interval. So this means this approach assumes warehouse suspend times haven&#39;t changed in the current analysis.</p><p>To assert how close the estimated costs are to the real warehouse, it is also convenient to backup the warehouse metering history table:</p><pre>create or replace table warehouse_metering_history_backup as select * from snowflake.account_usage.warehouse_metering_history limit 0;<br><br>insert into warehouse_metering_history_backup<br>    select wmh.* <br>    from snowflake.account_usage.warehouse_metering_history wmh<br>    where wmh.end_time &gt; (<br>        select coalesce(max(end_time), &#39;2000-01-01&#39;::timestamp_ntz) <br>        from warehouse_metering_history_backup<br>    )<br>    order by start_time;</pre><h4>Efficiently estimating query costs:</h4><pre>create or replace table warehouse_costs_md as<br>with wh_etl as (<br>    select qhb.query_id,<br>           qhb.query_tag,<br>           qhb.user_name,<br>           qhb.role_name,<br>           qhb.start_time,<br>           qhb.end_time, <br>           min(qhb.start_time) over ( -- see explanation below<br>                partition by qhb.warehouse_name, qhb.warehouse_size, qhb.cluster_number <br>                order by end_time desc <br>                rows between unbounded preceding and current row<br>           ) as min_start,<br>           qhb.warehouse_name,<br>           qhb.warehouse_size,<br>           qhb.warehouse_type,<br>           qhb.cluster_number,<br>           qhb.total_elapsed_time,<br>           qhb.credits_used_cloud_services,<br>           qhb.query_parameterized_hash,<br>           w.&quot;auto_suspend&quot; as auto_suspend<br>    from query_history_backup qhb  <br>         inner join warehouses w     <br>         on (qhb.warehouse_name = w.&quot;name&quot;) <br>    where warehouse_size is not null -- if warehouse size is null compute costs are 0<br>),<br>queries as (<br>    select criteria,<br>            match_nr,<br>            warehouse_name,<br>            cluster_number,<br>            warehouse_size,<br>            warehouse_type<br>            query_id,<br>            query_parameterized_hash,<br>            query_tag,<br>            user_name,<br>            role_name,<br>            start_time,<br>            end_time,<br>            min_start,<br>            active_start,<br>            active_end,<br>            activity,<br>            total_activity,<br>            credits_used_cloud_services,<br>            total_elapsed_time,<br>            billable_time,<br>            case<br>                when warehouse_size is null then 0<br>                else (activity / total_activity) * billable_time end<br>            as execution_share,<br>            case when warehouse_type = &#39;STANDARD&#39; then 1<br>                 when warehouse_type = &#39;SNOWPARK-OPTIMIZED&#39; then 1.5<br>                 else null<br>            end as cost_multiplier,<br>            execution_share / 3600 *<br>            case<br>                when warehouse_size = &#39;X-Small&#39;  then 1<br>                when warehouse_size = &#39;Small&#39;    then 2<br>                when warehouse_size = &#39;Medium&#39;   then 4<br>                when warehouse_size = &#39;Large&#39;    then 8<br>                when warehouse_size = &#39;X-Large&#39;  then 16<br>                when warehouse_size = &#39;2X-Large&#39; then 32<br>                when warehouse_size = &#39;3X-Large&#39; then 64<br>                when warehouse_size = &#39;4X-Large&#39; then 128<br>                when warehouse_size = &#39;5X-Large&#39; then 256<br>                when warehouse_size = &#39;6X-Large&#39; then 512<br>            else<br>                null<br>            end * cost_multiplier as estimated_credits<br>    from wh_etl match_recognize (<br>        partition by warehouse_name,warehouse_size, cluster_number<br>        order by end_time desc<br>        measures<br>            final min(min_start) as active_start,<br>            final max(timestampadd(&#39;seconds&#39;, auto_suspend, end_time)) as active_end,<br>            total_elapsed_time as activity,<br>            final sum(total_elapsed_time) as total_activity,<br>            match_number() as match_nr,<br>            classifier as criteria<br>        all rows per match<br>        pattern (warehouse_end warehouse_continue*)<br>        define<br>            warehouse_end as true,<br>            warehouse_continue as end_time &gt;= timestampadd(second, -auto_suspend, lag(min_start) )<br>    ) as matchr, <br>    lateral (<br>        select timestampdiff(second, active_start, active_end) as diff,<br>               case when warehouse_size is null then 0<br>                    when diff &lt; 60 then 60<br>                    else diff end as billable_time<br>        )<br>)<br>select *<br>from queries<br>order by start_time;</pre><p>Let&#39;s unpack things from the query above:</p><pre>min(qhb.start_time) over (<br>    partition by qhb.warehouse_name, qhb.warehouse_size, qhb.cluster_number <br>    order by end_time desc <br>    rows between unbounded preceding and current row<br>) as min_start</pre><p>The snippet above adds the minimum start_time in all preceding queries inside the set of queries partitioned by warehouse_name , warehouse_size and cluster_number when in descending order by end_time.</p><pre>from wh_etl match_recognize (<br>        partition by warehouse_name,warehouse_size, cluster_number<br>        order by end_time desc<br>---(...)<br>        pattern (warehouse_end warehouse_continue*)<br>        define<br>            warehouse_end as true,<br>            warehouse_continue as <br>                end_time &gt;= timestampadd(second, <br>                                         -auto_suspend, <br>                                         lag(min_start) )<br>    ) as matchr,</pre><p>The snippet above is where the snowflake <em>magic</em> happens. The match_recognize statement identifies activity windows for each warehouse cluster number: a pattern starting from the end of the activity window warehouse_end and the last row that matches thewarehouse_continue predicate. To match the end_time the current row must be larger or equal to the min_start of the previous row subtracted by the current warehouse auto_suspend configuration.</p><pre>from wh_etl match_recognize (<br>  -- (...)<br>        measures<br>            final min(min_start) as active_start,<br>            final max(timestampadd(&#39;seconds&#39;, auto_suspend, end_time)) as active_end,<br>            total_elapsed_time as activity,<br>            final sum(total_elapsed_time) as total_activity,<br>            match_number() as match_nr,<br>            classifier as criteria<br>   --(...)</pre><p>For each activity window, we&#39;re computing</p><ul><li>When it started active_start</li><li>When it ended active_end . Considers warehouse suspend time.</li><li>How long this query used the current cluster activity</li><li>Total activity of all the queries in the current activity window total_activity</li><li>Used for debugging — match_nr and the predicate that matchedclassifier</li></ul><pre>lateral (<br>    select timestampdiff(second, active_start, active_end) as diff,<br>           case when warehouse_size is null then 0<br>                when diff &lt; 60 then 60<br>                else diff end as billable_time<br>    )</pre><p>The snippet above computes the total billable time for the activity window. Accounts for the minimum 1 minute of billable time.</p><pre>case<br>      when warehouse_size is null then 0<br>      else (activity / total_activity) * billable_time end<br>  as execution_share,<br>  case when warehouse_type = &#39;STANDARD&#39; then 1<br>       when warehouse_type = &#39;SNOWPARK-OPTIMIZED&#39; then 1.5<br>       else null<br>  end as cost_multiplier,<br>  execution_share / 3600 *<br>  case<br>      when warehouse_size = &#39;X-Small&#39;  then 1<br>      when warehouse_size = &#39;Small&#39;    then 2<br>      when warehouse_size = &#39;Medium&#39;   then 4<br>      when warehouse_size = &#39;Large&#39;    then 8<br>      when warehouse_size = &#39;X-Large&#39;  then 16<br>      when warehouse_size = &#39;2X-Large&#39; then 32<br>      when warehouse_size = &#39;3X-Large&#39; then 64<br>      when warehouse_size = &#39;4X-Large&#39; then 128<br>      when warehouse_size = &#39;5X-Large&#39; then 256<br>      when warehouse_size = &#39;6X-Large&#39; then 512<br>  else<br>      null<br>  end * cost_multiplier as estimated_credits</pre><p>The snippet above computes the <em>fair cost </em>of a single query, scaling the costs to the ratio between this query activity and the total activity of all queries in the activity window.</p><h3>How accurate is the estimate?</h3><p>The sum of all the individual query cost estimates should be close to the total compute costs reported in the warehouse metering table. The statement below can be used to verify the estimated monthly compute costs to the real ones. Results are sorted in descending order of estimated costs.</p><pre>with compare as (<br>select time, <br>    warehouse_name, <br>    sum(query_count) as query_count,<br>    round(sum(estimated_credits),2) as estimated, <br>    round(sum(credits_used_compute),2) as warehouse_metering,<br>    round(sum(estimated_credits) - sum(credits_used_compute),2)  as diff, <br>    case when sum(credits_used_compute) = 0 then null else <br>     round((sum(estimated_credits) - sum(credits_used_compute))  / sum(credits_used_compute),2) end<br>    as relative_diff<br>from (<br>select substring(end_time,1,7) as time, warehouse_name, <br>       1 as query_count, <br>       estimated_credits as estimated_credits, <br>       0 as credits_used_compute<br>from warehouse_costs_md<br>union all<br>select substring(end_time,1,7) as time, warehouse_name, 0, 0, credits_used_compute<br>from warehouse_metering_history_backup<br>where  end_time between <br>             (select min(end_time) from warehouse_costs_md) <br>             and <br>             (select max(end_time) from warehouse_costs_md)<br>)<br>group by 1,2<br>)<br>select *<br>from compare<br>order by 4 desc;</pre><p>Diff contains the difference in credits between the actual and estimate. The sum of the estimates is under 6% of the real value, which should be considered good to reason about query anti-patterns and wasteful warehouse usage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*85hpX0CytzdPfthc8yZwQA.png" /></figure><p>Now that we have estimated query costs, we can build a meaningful cost dashboard that highlights the top 100 queries by total costs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xWwGDW9YJxZGAidqHK03Ng.png" /></figure><p>SQL for top_100_expensive_patterns:</p><pre>with top_queries as (<br>select query_parameterized_hash, <br>       count(*) as cnt, <br>       sum(estimated_credits) as total_credits, <br>       round(sum(estimated_credits) /  (<br>        select sum(x.estimated_credits)  <br>        from warehouse_costs_md x <br>        where start_time &gt; &#39;2024-01-01&#39;)*100,2) as credits_share_pct<br>from warehouse_costs_md wc <br>where start_time &gt; &#39;2024-01-01&#39;<br>group by 1<br>order by 3 desc<br>limit 100<br>)<br>select <br>       max(cnt) as execution_count,<br>       max(total_credits) as total_credits,<br>       max(credits_share_pct) as credits_share_pct,<br>       max(query_text) as sql_sample<br>from top_queries tq inner join query_history_backup qh on (tq.query_parameterized_hash = qh.query_parameterized_hash)<br>where qh.start_time &gt; &#39;2024-01-01&#39;<br>group by tq.query_parameterized_hash<br>order by 2 desc;</pre><p>SQL for top_users:</p><pre>select substring(start_time, 1, 10) as day, user_name, sum(estimated_credits)<br>from warehouse_costs_md<br>where start_time &gt; &#39;2024-01-01&#39;<br>group by 1,2<br>order by 1 asc; </pre><p>[1] — <a href="https://docs.snowflake.com/en/user-guide/cost-understanding-compute">https://docs.snowflake.com/en/user-guide/cost-understanding-compute</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b65f5143402f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>