<?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 Nastain on Medium]]></title>
        <description><![CDATA[Stories by Nastain on Medium]]></description>
        <link>https://medium.com/@niatsan?source=rss-4fea037fa01f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*7d7clyv_SPLn8rsf</url>
            <title>Stories by Nastain on Medium</title>
            <link>https://medium.com/@niatsan?source=rss-4fea037fa01f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 19:07:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@niatsan/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[50%+ cost reduction by changing how we get table’s partition in dbt]]></title>
            <link>https://niatsan.medium.com/50-cost-reduction-by-changing-how-we-get-tables-partition-in-dbt-c7201aa36763?source=rss-4fea037fa01f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7201aa36763</guid>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[cloud-cost-optimization]]></category>
            <category><![CDATA[data-warehouse]]></category>
            <category><![CDATA[dbt-labs]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Nastain]]></dc:creator>
            <pubDate>Thu, 17 Jul 2025 10:19:34 GMT</pubDate>
            <atom:updated>2025-07-17T10:35:12.849Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NFDjlUbqZHbOP2xXh074vw.png" /></figure><h4>Small improvement for dbt + BigQuery’s cost-saving measures.</h4><p>So, first thing first. In <a href="https://medium.com/inadigital-edu/how-we-cut-95-cost-for-analytics-reporting-and-what-we-have-learned-b52640aa8412">my previous story</a> on cutting ~95% infra cost for analytics reporting, we use dbt + BigQuery as our tech stack, with BigQuery using on-demand pricing model as opposed to flat rate, so every query call will incur cost.</p><blockquote>You might have different stack / models but perhaps part of this story can be applied as well, for example, it could fasten your pipeline because number of query calls are reduced (oops, a little bit of spoiler here).</blockquote><p>I believe many or most data warehouse tables are partitioned to reduce query’s table scan, leading to faster execution time and lower cost. Sometimes we cannot use static partition for filtering in query like yesterday or last week’s data because of data lagging. Hence, we need to filter partition in query by dynamically using latest partition.</p><p><a href="https://medium.com/inadigital-edu/how-we-cut-95-cost-for-analytics-reporting-and-what-we-have-learned-b52640aa8412#:~:text=Scan%20the%20whole%20table%20to%20get%20the%20latest%20partition">This section</a> of my previous story explains how we retrieve it initially, and <a href="https://medium.com/inadigital-edu/how-we-cut-95-cost-for-analytics-reporting-and-what-we-have-learned-b52640aa8412#:~:text=Querying%20latest%20partition%20multiple%20times">further step to improved it</a>.</p><h4>What I’ve done</h4><p>I’ll just summarize the code snippet here for easier explanation. This is dbt macro / function, get_latest_part_date(), to get latest partition from <a href="https://cloud.google.com/bigquery/docs/information-schema-partitions?hl=en">PARTITIONS view</a>.</p><pre>&lt;some_macro_file.sql&gt;<br>-----------------------------------------------------------------------------<br><br>{% macro get_latest_part_date(relation) %}<br><br>{% set relation_query %}<br>  ## Get latest date from metadata<br>  SELECT<br>    MAX(SAFE.PARSE_DATE(&#39;%Y%m%d&#39;, partition_id))<br>  FROM<br>    {{ relation.database }}.{{ relation.schema }}.INFORMATION_SCHEMA.PARTITIONS<br>  WHERE<br>    table_name = &#39;{{ relation.identifier }}&#39;<br>{% endset %}<br><br>{% set results = run_query(relation_query) %}<br><br>{% if execute %}<br>  {% if results.columns[0][0] != None %}<br>  ## Latest partition not null (found)<br>  {% set results_list = results.columns[0][0] %}<br>  {% else %}<br>  ## Default value<br>  {% set results_list = &#39;2021–01–01&#39; %}<br>{% endif %}<br><br>{{ return(results_list) }}<br><br>{% endmacro %}</pre><p>Let’s say the table’s partition column is event_date_gmt7, initially we call get_latest_part_date() multiple times in a model.</p><pre>&lt;some_model_file.sql&gt;<br>-----------------------------------------------------------------------------<br><br>...<br>WITH<br>t1 AS (<br>  SELECT<br>    f.*<br>  FROM<br>    {{ ref(&#39;table_name_1&#39;) }} f<br>  WHERE<br>    event_date_gmt7 &gt; &#39;{{ get_latest_part_date(this) }}&#39;<br>    AND event_date_gmt7 &lt;= &#39;&lt;yesterday_date&gt;&#39;<br>)<br>, t2 AS (<br>  SELECT<br>    g.*<br>  FROM<br>    {{ ref(&#39;table_name_1&#39;) }} g<br>  WHERE<br>    event_date_gmt7 &gt; &#39;{{ get_latest_part_date(this) }}&#39;<br>    AND event_date_gmt7 &lt;= &#39;&lt;yesterday_date&gt;&#39;<br>)<br>...</pre><p>Turns out, dbt will call each macros separately. So, in this example, we send query twice, incurring 20MB of cost just to get the same result.</p><p>Hence we tweak it to only call the macro once, put the result in CTE, and join it to the rest of model.</p><pre>&lt;some_model_file.sql&gt;<br>-----------------------------------------------------------------------------<br><br>...<br>WITH<br>vars AS (<br>  -- Get latest partition of this table<br>  SELECT<br>    DATE(&quot;{{ get_latest_part_date(this) }}&quot;) AS latest_partition<br>)<br>, t1 AS (<br>  SELECT<br>    f.*<br>  FROM<br>    {{ ref(&#39;&lt;table_name_1&gt;&#39;) }} f,<br>    vars<br>  WHERE<br>    event_date_gmt7 &gt; latest_partition<br>    AND event_date_gmt7 &lt;= &#39;&lt;yesterday_date&gt;&#39;<br>)<br>, t2 AS (<br>  SELECT<br>    g.*<br>  FROM<br>    {{ ref(&#39;&lt;table_name_1&gt;&#39;) }} g,<br>    vars<br>  WHERE<br>    event_date_gmt7 &gt; latest_partition<br>    AND event_date_gmt7 &lt;= &#39;&lt;yesterday_date&gt;&#39;<br>)<br>...</pre><p>Now we only incur 10MB of cost compared to 20MB previously. 50% reduction. Bigger if this model initially called more than 2 times, let’s say 4 times. Then it would be 75% reduction, from 40MB to 10MB.</p><h4>What I do now</h4><p>I realize that this saving method works only in the same model. If we have multiple model using same partition tables, it will still running same macro with same result for each models.</p><blockquote>So I wonder, can I call the macro <strong>only onc<em>e</em></strong> for the whole run, store the result somewhere, and all models will refer to it?</blockquote><p>Apparently, yes. Thank you Gemini!</p><p><strong>First</strong>, tweak get_latest_part_date() to basically retrieve all latest partitions needed from all models.</p><pre>&lt;some_macro_file.sql&gt;<br>-----------------------------------------------------------------------------<br><br>{% macro get_latest_part_date() %}<br><br>{# A list of datasets to query #}<br>  {% set datasets = [<br>      &#39;&lt;dataset_a&gt;&#39;,<br>      &#39;&lt;dataset_b&gt;&#39;,<br>      ...<br>    ]<br>  %}<br><br>  {% set partition_query %}<br>  SELECT<br>    table_schema,<br>    table_name,<br>    -- Format the timestamp directly in SQL to avoid Jinja manipulation<br>    FORMAT_TIMESTAMP(&#39;%Y-%m-%d&#39;, MAX(SAFE.PARSE_TIMESTAMP(&#39;%Y%m%d&#39;, partition_id))) AS max_partition<br>  FROM (<br>    {% for dataset in datasets %}<br>      SELECT table_schema, table_name, partition_id<br>      FROM `&lt;project_id&gt;.{{ dataset }}.INFORMATION_SCHEMA.PARTITIONS`<br>      WHERE partition_id IS NOT NULL AND partition_id != &#39;__NULL__&#39;<br>      {% if not loop.last %}UNION ALL{% endif %}<br>    {% endfor %}<br>  )<br>  GROUP BY ALL<br>  {% endset %}<br><br>  {# Execute the query and store the results in the `graph` variable #}<br>  {% if execute %}<br>    {% set results = run_query(partition_query) %}<br>    {% set partition_map = {} %} {# Initialize an empty dictionary #}<br><br>    {% for row in results.rows %}<br>      {# Access columns by name for clarity #}<br>      {% set table_schema = row.table_schema | lower | trim %}<br>      {% set table_name = row.table_name | lower | trim %}<br>      {% set max_partition = row.max_partition %}<br><br>      {# Build the nested dictionary #}<br>      {% if table_schema not in partition_map %}<br>        {% do partition_map.update({table_schema: {}}) %}<br>      {% endif %}<br>      {% do partition_map[table_schema].update({table_name: max_partition}) %}<br>    {% endfor %}<br><br>    {# Store the structured data in the global `graph` context variable #}<br>    {% do graph.update({&quot;raw_latest_partition&quot;: partition_map}) %}<br><br>    {{ log(&quot;Raw latest partition map stored in `graph.raw_latest_partition`.&quot;, info=True) }}<br>    {{ log(graph.raw_latest_partition | tojson(2), info=True) }} {# Pretty print the JSON structure #}<br>  {% else %}<br>    {{ log(&quot;Skipping raw latest partition setup during parsing.&quot;, info=True) }}<br>  {% endif %}<br><br>{% endmacro %}</pre><p>We build partition_query by listing all datasets used in all models, because PARTITION views are split for each dataset, then store the result in &#39;global variable’ <a href="https://docs.getdbt.com/reference/dbt-jinja-functions/graph">graph function</a>, as raw_latest_partition. log helps us to debug and inspect the value, and looks like this :</p><pre>&lt;log_in_terminal&gt;<br>----------------------------------------------------------------------------<br><br>{<br>  &quot;&lt;dataset_a&gt;&quot;: {<br>    &quot;&lt;table_1&gt;&quot;: &quot;2025–07–02&quot;,<br>    &quot;&lt;table_2&gt;&quot;: &quot;2025–07–02&quot;<br>  },<br>  &quot;&lt;dataset_b&gt;&quot;: {<br>    &quot;&lt;table_3&gt;&quot;: &quot;2025–07–03&quot;,<br>    &quot;&lt;table_4&gt;&quot;: &quot;2025–07–04&quot;<br>  }<br>  ...<br>}</pre><p><strong>Second</strong>, update dbt_project.yml to call get_latest_part_date() when running dbt, using on-run-start config.</p><pre>&lt;dbt_project.yml&gt;<br>-----------------------------------------------------------------------------<br><br>...<br>on-run-start:<br>  - &#39;{{ get_latest_part_date() }}&#39;</pre><p>or you can add condition when you don’t always want to run it e.g. when compiling or run in dev / staging env. Can use var or other method.</p><pre>&lt;dbt_project.yml&gt;<br>-----------------------------------------------------------------------------<br><br>...<br>on-run-start:<br>  - &#39;{{ get_latest_part_date() if var(&quot;run_part_macro&quot;, false) }}&#39;</pre><p><strong>Third</strong>, update models to retrieve raw_latest_partition.</p><pre>&lt;some_model_file.sql&gt;<br>-----------------------------------------------------------------------------<br>{%- set partition_date = graph.get(&#39;raw_latest_partition&#39;, {}).get(&#39;dataset_a&#39;, {}).get(&#39;table_1&#39;) -%}<br><br>{{<br>  config(<br>    &lt;fafifuwasweswos&gt;<br>  )<br>}}<br><br>...<br>WITH<br>t1 AS (<br>  SELECT<br>    f.*<br>  FROM<br>    {{ ref(&#39;table_name_1&#39;) }} f<br>  WHERE<br>    event_date_gmt7 &gt; &#39;{{ partition_date }}&#39;<br>    AND event_date_gmt7 &lt;= &#39;&lt;yesterday_date&gt;&#39;<br>)<br>, t2 AS (<br>  SELECT<br>    g.*<br>  FROM<br>    {{ ref(&#39;table_name_1&#39;) }} g<br>  WHERE<br>    event_date_gmt7 &gt; &#39;{{ partition_date }}&#39;<br>    AND event_date_gmt7 &lt;= &#39;&lt;yesterday_date&gt;&#39;<br>)<br>...</pre><p>We can also adjust our model by adding fallback to avoid error when raw_latest_partition is empty. For example, by using yesterday’s date.</p><pre>&lt;some_model_file.sql&gt;<br>-----------------------------------------------------------------------------<br>{%- set default_timezone = var(&#39;timezone&#39;, &#39;Asia/Singapore&#39;) -%}<br>{%- set tz = modules.pytz.timezone(default_timezone) -%}<br><br>{%- set yesterday = (modules.datetime.datetime.now(tz) - modules.datetime.timedelta(days=1)).strftime(&#39;%Y-%m-%d&#39;) -%}<br><br>{%- set partition_date = graph.get(&#39;raw_latest_partition&#39;, {}).get(&#39;dataset_a&#39;, {}).get(&#39;table_1&#39;) -%}<br><br>{{<br>  config(<br>    &lt;fafifuwasweswos&gt;<br>  )<br>}}<br><br>...<br>WITH<br>t1 AS (<br>  SELECT<br>    f.*<br>  FROM<br>    {{ ref(&#39;table_name_1&#39;) }} f<br>  WHERE<br>    event_date_gmt7 &gt; &#39;{{ partition_date if partition_date else yesterday }}&#39;<br>    AND event_date_gmt7 &lt;= &#39;&lt;yesterday_date&gt;&#39;<br>)<br>, t2 AS (<br>  SELECT<br>    g.*<br>  FROM<br>    {{ ref(&#39;table_name_1&#39;) }} g<br>  WHERE<br>    event_date_gmt7 &gt; &#39;{{ partition_date if partition_date else yesterday }}&#39;<br>    AND event_date_gmt7 &lt;= &#39;&lt;yesterday_date&gt;&#39;<br>)<br>...<br></pre><p>This way, we can use graph.get(...) in all models.</p><p>Another point to note, BigQuery PARTITION view stored separately for each datasets, so if you have let’s say 3 dataset which you need, then get_latest_part_date() call will cost at least 30MB. Two dataset will cost at least 20MB, and so on. One view’s minimum cost is 10MB, can be higher if size is bigger, but in normal cases it shouldn’t exceed 10MB per view.</p><p>50% is the minimum achievable cost reduction, as it will reduce multiple macro calls (minimum 2) to only once; from 20MB to 10MB.</p><p>Hmm wait, if one has 3 tables in 2 dataset, macro calls reduced from 3 to 1, then from 30MB it would reduced 20MB, which is 33.3% reduction. Turns out it can be less than 50%, but anyway.</p><blockquote>In my case, I need latest partition for 28 tables across 4 datasets, so that is 280MB to 40MB → <strong>85.7%</strong> reduction.</blockquote><p>As dbt runs more frequently, and with ever-increasing cost of cloud platform, I believe this small improvement might come in handy.</p><p><em>*apart from the code, this post does not powered by AI. Need to hone that human writing skill.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7201aa36763" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How we cut ~95% cost for analytics reporting and what we have learned]]></title>
            <link>https://medium.com/inadigital-edu/how-we-cut-95-cost-for-analytics-reporting-and-what-we-have-learned-b52640aa8412?source=rss-4fea037fa01f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b52640aa8412</guid>
            <category><![CDATA[ina-digital-edu]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[cost-optimization]]></category>
            <dc:creator><![CDATA[Nastain]]></dc:creator>
            <pubDate>Thu, 02 Feb 2023 04:22:31 GMT</pubDate>
            <atom:updated>2025-07-16T02:28:35.716Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IQrP9SftaudS_U94Gh20ow.png" /></figure><p>One of INA Digital Edu’s focuses is developing digital products (known as: apps) for The Ministry of Primary and Secondary Education (MPSE) such as <a href="https://play.google.com/store/apps/details?id=id.belajar.app&amp;gl=id&amp;pli=1">Ruang GTK</a> for teachers and <a href="https://play.google.com/store/apps/details?id=com.kemendikdasmen.rumahpendidikan&amp;gl=id">Rumah Pendidikan</a>. These apps generate enormous amounts of data that we could utilize further for analytical and modeling purposes to help MPSE take action, improving the digital products and the programs themselves. Given the important role of produced data, we may see the app-generated data as a product in and of itself. To optimize the data utilization later downstream, we build data pipelines that are, in a simplified term, like your normal one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xskSBuoGOdeGPBeY" /><figcaption>Figure 1. Data Pipeline in General</figcaption></figure><p>We employ Google BigQuery to store data, <em>dbt </em>for our data processing platform, and Google Looker Studio as our data visualization platform.</p><p>To support our pipelines in serving dashboards and daily reports — let’s use the term ‘reports’ from now onwards — we <a href="https://medium.com/govtech-edu/data-quality-measurement-and-monitoring-for-successful-product-development-and-product-iteration-8dd25775ddf3">monitor data quality</a> and infrastructure cost for processing data. We also set a daily quota limit for query processing. We treat this cost monitoring and limit as a high priority, as we must be as thoughtful as possible in getting the best value for our data without compromising the total cost.</p><h3>How do we diagnose and analyze our cost?</h3><p>As the users’ adoption of our platforms exponentially grows, our data processing cost has consistently grown more than 4 times over the first 3 months (Figure 2). It caused the daily quota limits to be hit more frequently. Some ETLs (or ELTs) have stopped running, and numbers (or business metrics) are not shown in reports. Since these reports are needed by internal and external stakeholders such as product managers, heads of departments, and even the stakeholder at the ministry, our data analysts and scientists helped us by manually rerunning it. Such manual effort, however, is not scalable and does not bring any best values from our talents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yWSd0_SzV8Px__Kq" /><figcaption>Figure 2. BigQuery Cost Growth in 3 Months</figcaption></figure><p>To respond to such challenges, we assessed the costliest BigQuery jobs by destination table from <a href="https://cloud.google.com/bigquery/docs/reference/auditlogs/#data_access_data_access">BigQuery Audit Log — Data Access</a>. We did this by creating a cost-monitoring dashboard through 3 steps :</p><ol><li>Categorize jobs by looking at patterns; executor’s email, job name, source, destination table, etc. Some of the categories are <em>dbt</em> job (ELT), BigQuery console, Python, and Google Spreadsheet</li><li>Create <em>dbt </em>job to calculate BigQuery jobs’ cost on a daily basis and store it in a table</li><li>Using this table as the source, we make a dashboard that includes multiple visualizations to be analyzed</li></ol><p>We found that <em>dbt</em> job is one of the highest categories in terms of cost.</p><p>Then, from these <em>dbt </em>jobs, we choose which ones need to be tackled based on these criteria consecutively :</p><ol><li>Those with the highest cost during the time span</li><li>Looking at the cost trend using a simple line chart<br>Jobs in an inclining trend will be ranked higher, and declining ones will be ranked lower</li><li>Those with the highest average cost per job running, because once those jobs need to be run more frequently, the cost will significantly rise</li><li>Those with the highest number of jobs running</li></ol><h3>Cost-wise inefficiencies and its solving</h3><p>After analyzing problematic <em>dbt </em>jobs, updating its queries, and validating results (numbers stay the same + cost reduced), we learned that these inefficiencies could be found when processing data in BigQuery.</p><h4>Process all time data when it can be updated on a daily basis</h4><p>Imagine you work for an e-commerce app, and your job is to provide daily summaries of transactions and revenue. You do this by querying the raw order table and storing the result in the summary table. Pretty straightforward. Then you create this query to be run daily.</p><pre>SELECT<br>  order_date,<br>  SUM(1) AS transactions,<br>  SUM(total_amount) AS revenue<br>FROM<br>  `raw.order`<br>GROUP BY<br>  order_date<br>ORDER BY<br>  order_date</pre><p>Usually, ELT is run on D-1 data, meaning you wait until day 2 to let day 1 data be fully gathered before processing it. Hence, at date 2 run, this is your result.</p><pre>╔════════════╦══════════════╦═══════════╗<br>║ order_date ║ transactions ║  revenue  ║<br>╠════════════╬══════════════╬═══════════╣<br>║ 2022-01-01 ║        1,124 ║ 3,567,300 ║<br>╚════════════╩══════════════╩═══════════╝</pre><p>Assume 1 row represents 1 transaction. It means you process 1,124 rows on January 1st, 2022, data.</p><p>On to the next day.</p><pre>╔════════════╦══════════════╦═══════════╗<br>║ order_date ║ transactions ║  revenue  ║<br>╠════════════╬══════════════╬═══════════╣<br>║ 2022-01-01 ║        1,124 ║ 3,567,300 ║<br>║ 2022-01-02 ║        1,549 ║ 4,938,100 ║<br>╚════════════╩══════════════╩═══════════╝</pre><p>On January 3rd, 2022, you processed a total of 2,673 rows. <em>This is where it gets interesting</em>. If you look once again, you already ran January 1st data twice. However, the result of ‘transactions’ and ‘revenue’ stays at 1,124 and 3,567,300, respectively. It means that <em>you are recalculating 1,124 rows of data to have the same result</em>. Sounds a bit wasteful, eh?</p><p>Imagine running this process up to January 6th, 2022.</p><pre>╔════════════╦══════════════╦═══════════╗<br>║ order_date ║ transactions ║  revenue  ║<br>╠════════════╬══════════════╬═══════════╣<br>║ 2022-01-01 ║        1,124 ║ 3,567,300 ║<br>║ 2022-01-02 ║        1,549 ║ 4,938,100 ║<br>║ 2022-01-03 ║        1,374 ║ 4,538,900 ║<br>║ 2022-01-04 ║          862 ║ 2,551,600 ║<br>║ 2022-01-05 ║          938 ║ 3,498,500 ║<br>╚════════════╩══════════════╩═══════════╝</pre><p>Now, you are processing 5,847 rows, and have already recalculated</p><ul><li>4 times of January 1st data,</li><li>3 times of January 2nd data,</li><li>2 times of January 3rd data, and</li><li>1 time of January 4th data.</li></ul><p>And this number will keep increasing as days go on. This is how the processed data will look, and in line with that, the cost.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*J9BzGZuroasmZCuX" /></figure><p>So how do we solve this issue? The solution is to <em>run the query only on new data</em> (those which haven’t been calculated before) and <em>append the result</em> to the result table <em>as opposed to a full rewrite</em>. In other words :</p><ol><li>at date 2, run only January 1st data, then append the result on the summary table</li><li>at date 3, run only January 2nd data, then append the result like point #1</li><li>and so on.</li></ol><p>The processed data will look like this. It is much smaller — which leads to faster processes — and more efficient, isn’t it?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5TuBhm7f3Rh9R7F7" /></figure><blockquote>We can reduce the cost by running the calculation on daily data instead of all time. The bigger our daily data, the more significant this method will save us money.</blockquote><p>In BigQuery, this concept called <a href="https://cloud.google.com/bigquery/docs/partitioned-tables">partitioning</a> splits tables into “mini-tables” based on a table’s field. In a query, we can <em>retrieve</em> those partitions instead of one whole table, then <em>store</em> the result as a new partition (or overwrite) in the destination table. So, for partitioning to be fully utilized, both source and destination need to enable this concept.</p><ul><li>Mainly for source table(s) because it determines a query’s cost in BigQuery, and</li><li>for the destination table because it might become a source table for other queries.</li></ul><p>We modify our query to retrieve sources’ partitions and also store it as a partition. Here is the snippet of our <em>dbt </em>script to configure the destination partition.</p><pre>{{ config(<br>     materialized = &#39;incremental&#39;,<br>     partition_by = {<br>       &quot;field&quot;: &quot;event_date_gmt7&quot;,<br>       &quot;data_type&quot;: &quot;date&quot;,<br>       &quot;granularity&quot;: &quot;day&quot;<br>     }<br>)}}</pre><p>Generally, this snippet tells <em>dbt </em>to partition our destination table by `event_date_gmt7` field.</p><p>Meanwhile, this is the snippet of our source one.</p><pre>FROM<br>  {{ ref(&#39;&lt;fact_table_name&gt;&#39;) }}<br>WHERE<br>  event_date_gmt7 &gt; &#39;&lt;latest_date_partition_of_destination_table&gt;&#39;<br>  AND event_date_gmt7 &lt;= DATE_SUB(CURRENT_DATE(&#39;+07:00&#39;), INTERVAL 1 DAY)</pre><p>By using `event_date_gmt7` in the WHERE clause, which is the partition field of this source table, we already tell <em>dbt </em>to only retrieve part(s) of the source table instead of the whole. Pretty simple and straightforward!</p><p>BigQuery also has another concept of splitting tables called <a href="https://cloud.google.com/bigquery/docs/clustered-tables">clustering</a>. In short, clustering is like a partition, but instead of being based on one field, it is based on a combination of fields. So, when querying, BigQuery will filter both partitioned and clustered field(s) before scanning table source(s). Here is an example snippet of enabling clusters in a table.</p><pre>{{ config(<br>     materialized = &#39;incremental&#39;,<br>     partition_by = {<br>       &quot;field&quot;: &quot;event_date_gmt7&quot;,<br>       &quot;data_type&quot;: &quot;date&quot;,<br>       &quot;granularity&quot;: &quot;day&quot;<br>     },<br>   cluster_by = [<br>      &#39;user_interface&#39;,<br>      &#39;&lt;column_b&gt;&#39;,<br>      &#39;&lt;column_c&gt;&#39;,<br>      &#39;…&#39;<br>   ]<br>)}}</pre><p>This is the snippet of using it.</p><pre>FROM<br>  {{ ref(&#39;&lt;fact_table_name&gt;&#39;) }}<br>WHERE<br>  event_date_gmt7 &gt; &#39;&lt;latest_date_partition_of_destination_table&gt;&#39;<br>  AND event_date_gmt7 &lt;= DATE_SUB(CURRENT_DATE(&#39;+07:00&#39;), INTERVAL 1 DAY)<br>  AND user_interface = &#39;Android&#39;</pre><p>Yes, it was the same as using partitioning. You only need to declare the filter in the WHERE clause. Again, pretty simple and straightforward!</p><p>Actually, you could use clustering without using partitioning. But if you combine both, you could optimize your cost even further. You could learn about partitioning and clustering <a href="https://codelabs.developers.google.com/codelabs/gcp-bq-partitioning-and-clustering/">in this short lab provided by Google</a>.</p><h4>Scan the whole table to get the latest partition</h4><p>Looking at the previous code snippet of the source partition, we retrieve the latest destination’s date partition. The purpose is to only run unprocessed data from the source table. So how do we get it?</p><p>In most cases, we will use this query.</p><pre>SELECT<br>  MAX(&lt;partition_field&gt;)<br>FROM<br>  `&lt;source_table&gt;`</pre><p>However, if the source table contains millions of rows, we will run through all those rows and incur more costs. Imagine a table that has 100 partitions that contain 1,000,000 rows each. By using the actual table, we query 100 x 1,000,000 = 100,000,000 rows. Is there a better way to get the latest partition?</p><p>Yes, definitely, by using a metadata table. In BigQuery, metadata is stored in <a href="https://cloud.google.com/bigquery/docs/information-schema-intro">INFORMATION_SCHEMA</a> views, which contains all information about our BigQuery objects, including a list of partitions from a table stored in <a href="https://cloud.google.com/bigquery/docs/information-schema-partitions">PARTITIONS</a> view. One row in this view contains information about one partition, such as its table dataset/schema, table name, partition ID, total rows, and last updated time. Here is the SQL snippet for querying metadata.</p><pre>SELECT<br>  MAX(SAFE.PARSE_DATE(&#39;%Y%m%d&#39;, partition_id))<br>FROM<br>  `&lt;project_name&gt;.&lt;dataset_name&gt;.INFORMATION_SCHEMA.PARTITIONS`<br>WHERE<br>  table_name = &#39;&lt;table_name&gt;&#39;</pre><p>So, by using the previous example, <em>we only query 100 rows</em> using metadata instead of 100,000,000 rows. Much faster and much cheaper.</p><p>In <em>dbt</em>, we put this query in <a href="https://docs.getdbt.com/docs/build/jinja-macros#macros">macros</a> so we can reuse it across our ELTs. The macro code will look something like this</p><pre>{% macro get_latest_part_date(column_name, relation) %}<br><br>{% set relation_query %}<br>  ## Get latest date from metadata<br>  ## If &#39;column_name&#39; is null, return D-1<br>  SELECT<br>    MAX(SAFE.PARSE_DATE(&#39;%Y%m%d&#39;, partition_id))<br>  FROM<br>    {{ relation.database }}.{{ relation.schema }}.INFORMATION_SCHEMA.PARTITIONS<br>  WHERE<br>    table_name = &#39;{{ relation.identifier }}&#39;<br>{% endset %}<br><br>{% set results = run_query(relation_query) %}<br><br>{% if execute %}<br>  {% if results.columns[0][0] != None %}<br>  ## Latest partition not null (found)<br>  {% set results_list = results.columns[0][0] %}<br>  {% else %}<br>  ## Default value<br>  {% set results_list = &#39;2021–01–01&#39; %}<br>{% endif %}<br><br>{{ return(results_list) }}<br><br>{% endmacro %}</pre><p>and the query will look like this.</p><pre>FROM<br>  {{ ref(&#39;&lt;fact_table_name&gt;&#39;) }}<br>WHERE<br>  event_date_gmt7 &gt; &#39;{{ get_latest_part_date(&#39;event_date_gmt7&#39;, this) }}&#39;<br>  AND event_date_gmt7 &lt;= DATE_SUB(CURRENT_DATE(&#39;+07:00&#39;), INTERVAL 1 DAY)</pre><h4>Querying latest partition multiple times</h4><p>Another point related to previous learning about not using the metadata table, this one came in parallel with it. We often use more than one source table in our ELT to produce one new result table. This initially makes us call the macro for each source.</p><p>However, after several days, we realized our cost was rising again to the initial level. We discovered that each time the macro is called, it sends a query job to BigQuery to retrieve the result. So if we got 10 source tables that use this macro, there would be 10 query jobs to BigQuery <em>to return the same result</em>. Amplified by the fact that we still use the actual table at that time, imagine having 10 queries scanning the whole table containing tens of millions of rows.</p><p>We fix the issue by calling this macro just once, putting it as CTE (the table in WITH clause), then joining the table in each source tables’ FROM clause.</p><pre>WITH<br>vars AS (<br>  -- Get latest partition of this table<br>  SELECT<br>    DATE(&quot;{{ get_latest_part_date(&#39;event_date_gmt7&#39;, this) }}&quot;) AS latest_partition<br>)<br>, t1 AS (<br>  SELECT<br>    f.*<br>  FROM<br>    {{ ref(&#39;&lt;fact_table_name_1&gt;&#39;) }} f,<br>    vars<br>  WHERE<br>    event_date_gmt7 &gt; latest_partition<br>    AND event_date_gmt7 &lt;= &#39;&lt;yesterday_date&gt;&#39;<br>)<br>, t2 AS (<br>  SELECT<br>    g.*<br>  FROM<br>    {{ ref(&#39;&lt;fact_table_name_1&gt;&#39;) }} g,<br>    vars<br>  WHERE<br>    event_date_gmt7 &gt; latest_partition<br>    AND event_date_gmt7 &lt;= &#39;&lt;yesterday_date&gt;&#39;<br>)<br>...</pre><h3>Result</h3><p>Combining those learnings to update some of our costliest <em>dbt </em>jobs, we reduced our cost by ~95.91%. We also tweaked our Looker Studio data sources and reduced costs by ~98.97%.</p><h3>Takeaways</h3><ol><li>Take advantage of partitioning and clustering. Or whatever chunking mechanism is provided in your database.</li><li>To get the latest partition, use metadata instead of the actual table. Except your table is not partitioned.</li><li>You might be using macros not only to run queries for getting the latest partition but since it will trigger a job for each macros calling, be aware and make it as ‘parameter’.</li><li>Do not hesitate to look at the documentation (e.g. ETL/ELT platform like <em>dbt</em>). It might look intimidating at first, but I’m sure we will learn one or two things about the platform (whatever that be) that might be useful for our problems or optimize our current scripts even before a problem arises. You could also learn tutorials or conferences from YouTube.</li><li>It’s okay to improve step-by-step. These learnings, I also found out week after week, not all at once. Strive for progress instead of perfection</li><li>Last but not least, if you are migrating/changing your table instead of creating a new one, ensure your table has the same result as the previous model for seamless changes. We do not want to compromise our report’s accuracy just for the sake of cost efficiency.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b52640aa8412" width="1" height="1" alt=""><hr><p><a href="https://medium.com/inadigital-edu/how-we-cut-95-cost-for-analytics-reporting-and-what-we-have-learned-b52640aa8412">How we cut ~95% cost for analytics reporting and what we have learned</a> was originally published in <a href="https://medium.com/inadigital-edu">INA Digital Edu</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>