<?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 Oladayo on Medium]]></title>
        <description><![CDATA[Stories by Oladayo on Medium]]></description>
        <link>https://medium.com/@Oladayo?source=rss-93855656ee5f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*jxFE4teZIR4T8oWwrBIyAw.jpeg</url>
            <title>Stories by Oladayo on Medium</title>
            <link>https://medium.com/@Oladayo?source=rss-93855656ee5f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 21:16:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Oladayo/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[From Relational Models to Dimension Models: Architecting Oil & Gas Production Data]]></title>
            <link>https://medium.com/@Oladayo/from-relational-models-to-dimension-models-architecting-oil-gas-production-data-26a9c780e686?source=rss-93855656ee5f------2</link>
            <guid isPermaLink="false">https://medium.com/p/26a9c780e686</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-architecture]]></category>
            <category><![CDATA[dbt]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[dimensional-modeling]]></category>
            <dc:creator><![CDATA[Oladayo]]></dc:creator>
            <pubDate>Mon, 25 May 2026 22:02:07 GMT</pubDate>
            <atom:updated>2026-05-25T22:02:07.373Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m7wUklNN3i4t8rIWlpYgzw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@junscythe?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Jeanson Wong</a> on <a href="https://unsplash.com/photos/yellow-and-black-crane-near-body-of-water-during-daytime-QjdkpDmMSQA?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><a href="https://medium.com/data-engineer-things/from-flat-files-to-relational-models-architecting-oil-gas-production-data-8c9c1e684408">In my last post</a>, I wrote about how to move oil and gas production data from flat files to relational models. At the end of the post, I mentioned that relational models are not efficient for analytics because data is stored in rows and analytical queries involve joining multiple tables together.</p><p>To make the models ready for analytics, we have to apply dimensional modelling to them. But to do that, we need to get our relational models (tables) from the relational database to the data warehouse (examples are BigQuery in Google Cloud, Redshift in AWS). That’s the job of a data pipeline.</p><p>This post works on the assumption that a data pipeline has been built, and the tables from our relational database are now in the data warehouse.</p><p>Dimensional Modelling (by Kimball) follows a 4 step process:</p><h4>1. Select the business process</h4><blockquote>Business processes are the operational activities performed by an organization.</blockquote><p>In our case, the operational activity is the daily production of oil and gas from the wells.</p><h4>2. Declare the grain</h4><blockquote>The grain is what a single row in our fact table represents.</blockquote><p>In our case, the grain is the daily production of a single well.</p><h4>3. Identify the dimensions</h4><blockquote>Dimensions are attributes that provide context around the facts. They form the basis of analytical questions executives asks. For example, what’s the average production from a specific well over a given time period? or what’s the total production from this reservoir or a field since inception.</blockquote><p>In our case, the dimensions are the Well and the Date. The question here is why just the Well and date, what of the Reservoir, the Field. Dimensional modelling relies heavily on denormalization (consolidating related tables into a single table). That means all the descriptive information about our reservoir and our field will be flattened and stored directly inside the Well dimension table.</p><h4>4. Identify the facts</h4><blockquote>Facts are the numerical attributes (measurements or counting) generated by our business process.</blockquote><p>In our case, the facts are the daily oil production, daily gas production, daily water volumes.</p><h3>Building the Models with dbt</h3><p>Let’s get started with building our fact and dimension tables. I will be using Data Build Tool (dbt) for this transformation. dbt is common for transforming data using SQL (though it supports Python) because it adopts software engineering best practices like testing, versioning, and reusability.</p><h4>1. The Staging Layer</h4><p>In dbt, the first layer is the staging layer. This is the layer that connects to our raw relational tables that are already in the data warehouse. This is a 1:1 relationship with the source tables, meaning there is a staging model for each relational table.</p><pre>stg_wells.sql<br><br>select * from {{ source(&#39;oil_and_gas&#39;, &#39;Wells&#39;) }}</pre><pre>stg_reservoirs.sql<br><br>select * from {{ source(&#39;oil_and_gas&#39;, &#39;Reservoirs&#39;) }}</pre><pre>stg_fields.sql<br><br>select * from {{ source(&#39;oil_and_gas&#39;, &#39;Fields&#39;) }}</pre><pre>stg_production.sql<br><br>select * from {{ source(&#39;oil_and_gas&#39;, &#39;Production&#39;) }}</pre><p>In the code above, we have created 4 staging models (.sql files) for each of the 4 tables in the data warehouse. The ‘oil_and_gas’ string represents the name of the dataset in our BigQuery data warehouse where these raw tables currently live.</p><p>With the staging layers done, we can start building our dimension tables. These will sit in our mart layer.</p><h4>2. Building the Dimension Models</h4><pre>dim_date.sql<br><br>with date_spine as (<br>    {{ dbt_utils.date_spine(<br>        datepart=&quot;day&quot;,<br>        start_date=&quot;cast(&#39;2020-01-01&#39; as date)&quot;,<br>        end_date=&quot;dateadd(year, 1, current_date)&quot;<br>    ) }}<br>),<br><br>final as (<br>    select<br>        {{ dbt_utils.generate_surrogate_key([&#39;date_day&#39;]) }} as date_sk,<br>        cast(date_day as date) as date_day,<br>        extract(year from date_day) as date_year,<br>        extract(month from date_day) as date_month,<br>        extract(day from date_day) as day_of_month,<br>        &#39;Q&#39; || extract(quarter from date_day) as quarter_name<br>    from date_spine<br>)<br><br>select * from final;</pre><p>In the code above, we leveraged a dbt utility macro called date_spine to generate a continuous list of dates. We set the CTE to start on January 1, 2020, and automatically extend one year past the current date.</p><p>Business questions are not always about a specific day; executives often want to look at trends by year, month, or quarter. To handle this, we extracted those specific date parts out from the date_day column within our final CTE.</p><p>We also leveraged generate_surrogate_key macro to create a unique identifier (date_sk) for our table. You might wonder why we use this instead of a standard auto-incrementing ID (1, 2, 3…) or just using the raw date itself as the primary key.</p><ul><li><strong>Why not auto-incrementing IDs?</strong> Modern cloud data warehouses process data across many servers at the same time. This makes generating numbers sequentially very slow and difficult. (<a href="https://tomoharutsutsumi.medium.com/why-auto-increment-ids-are-challenging-for-scalability-bf51533e9632#:~:text=Why%20Auto%2DIncrement%20Fails,unsuitable%20for%20distributed%20databases.">source</a>)</li></ul><p>With dim_date done, the next model to build is dim_well</p><pre>dim_well.sql<br><br>with source_wells as (<br>    select * from {{ ref(&#39;stg_wells&#39;) }}<br>),<br><br>source_reservoirs as (<br>    select * from {{ ref(&#39;stg_reservoirs&#39;) }}<br>),<br><br>source_fields as (<br>    select * from {{ ref(&#39;stg_fields&#39;) }}<br>),<br><br>final as (<br>    select <br>        {{ dbt_utils.generate_surrogate_key([&#39;w.well_id&#39;]) }} as well_sk,<br>        w.well_id,         w.well_name, <br>        r.reservoir_name, <br>        f.field_name<br>    from source_wells w<br>    inner join source_reservoirs r<br>        on w.reservoir_id = r.reservoir_id<br>    inner join source_fields f<br>        on r.field_id = f.field_id<br>)<br><br>select * from final;</pre><p>In the code above, we referenced our staging models for the wells, reservoirs, and fields. We then joined them together to consolidate the information into a single table (denormalization). Just like before, we leveraged the generate_surrogate_key macro to create a unique identifier (well_sk) for our table.</p><p>With both dimension tables done, next model to build is the fact table fct_production</p><h4>3. Building the Fact Model</h4><p>In a fact table, the primary keys from the dimension tables are stored as foreign keys.</p><pre>fct_production.sql<br><br>with source_production as (<br>    select * from {{ ref(&#39;stg_production&#39;) }}<br>),<br><br>dim_well as (<br>    select * from {{ ref(&#39;dim_well&#39;) }}<br>),<br><br>dim_date as (<br>    select * from {{ ref(&#39;dim_date&#39;) }}<br>),<br><br>final as (<br>    select<br>        {{ dbt_utils.generate_surrogate_key([&#39;w.well_sk&#39;, &#39;d.date_sk&#39;]) }} as production_sk,<br>        d.date_sk, <br>        w.well_sk, <br>        p.oil_production, <br>        p.gas_production, <br>        p.water_production<br>    from source_production p<br>    inner join dim_well w<br>        on p.well_id = w.well_id<br>    inner join dim_date d<br>        on p.date = d.date_day<br>)<br><br>select * from final;</pre><p>In the code above, we referenced our production staging model, as well as our date and well dimension models. We then joined these models together.</p><p>To generate a unique identifier for each row in our fact table, we combined the dim_date and dim_well surrogate keys, once again leveraging the generate_surrogate_key macro.</p><p>Voila, our dimensional modelling is done! But how does this all work in practice?</p><p>When new daily production data for a well arrives in the data warehouse and the dbt scheduler runs, here is what happens:</p><p>First, the staging model (stg_production) is updated. It is then joined to both dimension tables to obtain the correct surrogate key from dim_well and the date surrogate key from dim_date for that specific day of production. Next, it generates a new unique identifier for that exact daily production record. Finally, the fct_production table is updated.</p><h4><strong>The dbt DAG (Directed Acyclic Graph)</strong></h4><p>When we run this project, dbt generates a DAG. A DAG is simply a visual map that shows exactly how our data flows from the raw tables to our final models.</p><p>For our pipeline, the flow looks like this:</p><ul><li>Our raw source tables connect directly to our staging layer (stg_wells, stg_reservoirs, stg_fields, and stg_production).</li><li>The well, reservoir, and field staging models merge to create dim_well.</li><li>Finally, stg_production, dim_well, and dim_date all flow together to build our final fct_production table.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YGQ_QY7RKgQA3sM_XXgZQA.png" /><figcaption><strong>Our dbt project’s data lineage, from raw staging to the final mart layer. Created with Mermaid.js.</strong></figcaption></figure><h4><strong>Why is this model better for analytics?</strong></h4><p>At the beginning of this post, I mentioned that relational models are not efficient for analytics because they require joining too many tables together just to answer a simple question.</p><p>By applying Kimball’s dimensional modelling, we solved this problem in three main ways:</p><ol><li><strong>Fewer Joins:</strong> Because we denormalized our data (packing all the reservoir and field details into a single dim_well table), the database doesn&#39;t have to work as hard. If an executive wants to see production by field, we only need one simple join between the fact table and the dimension table.</li><li><strong>Business-Friendly:</strong> We transformed raw dates into useful business categories (like quarters and years) inside our dim_date table, making it very easy to filter for specific time periods.</li><li><strong>Ready for BI Tools: </strong>With the fact table in the middle and the dimensions surrounding it, data analysts can connect to this warehouse and immediately start building dashboards.</li></ol><p>While this is a good start, there are attributes like well status (which change over time) that could have been captured in both the relational and dimensional models to improve our tracking. In dimensional modelling, this is handled using a Slowly Changing Dimension (SCD).</p><p>Additionally, the data ingestion pipeline that moves data from the source into the warehouse wasn’t discussed here. That is a critical part of the process, as decisions have to be made on whether the data ingestion will be full or incremental. Similarly, we also have to decide if our dbt transformations should run as full refreshes or incremental builds.</p><p>Thank you for reading.</p><p><strong>Reference:</strong> Kimball, R., &amp; Ross, M. (2013). <em>The Data Warehouse Toolkit: The Definitive Guide to Dimensional Modeling</em> (3rd ed.). Wiley.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26a9c780e686" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Infrastructure as Code (IaC) for Data Engineers: A Beginner’s Guide]]></title>
            <link>https://blog.dataengineerthings.org/infrastructure-as-code-iac-2039ad0e9a4f?source=rss-93855656ee5f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2039ad0e9a4f</guid>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <dc:creator><![CDATA[Oladayo]]></dc:creator>
            <pubDate>Tue, 07 Apr 2026 07:01:01 GMT</pubDate>
            <atom:updated>2026-04-18T21:44:15.493Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TpEsjqWhrI2zA6aO" /><figcaption>Photo by <a href="https://unsplash.com/@growtika?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Growtika</a> on <a href="https://unsplash.com/photos/a-robot-with-a-light-saber-wLknZfsKmxQ?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>In the modern data stack, a Data Engineer’s job goes far beyond just writing SQL or Python. You are responsible for the foundation those scripts run on. From deploying Cloud Functions for pipelines to setting up Cloud Storage staging areas and spinning up BigQuery data warehouses, you manage a lot of moving parts.</p><p>When you first learn to build these environments, you usually start with the cloud provider’s console. This graphical user interface (GUI) lets you click buttons (often called “ClickOps”) to create resources one by one.</p><p>The issue with this approach is that it leaves no trail of what was provisioned or by whom. It lacks reproducibility and is susceptible to human error. What if you could use configuration files to provision and manage these resources instead? This is what Infrastructure as Code (IaC) does.</p><p>The benefits of this approach become evident immediately. Using IaC makes team collaboration much easier because you can version-control your configuration files just like you version-control your Python scripts. I will highlight other advantages later in this post.</p><p>There are several IaC tools out there, but Terraform is arguably the most popular. According to the <a href="https://survey.stackoverflow.co/2024/technology#1-other-tools"><strong><em>2024 Stack Overflow Developer Survey</em></strong></a> and <a href="https://www.jetbrains.com/lp/devecosystem-2023/devops/#devops_infr_provisioning_devops"><strong><em>JetBrains’ State of Developer Ecosystem</em></strong></a>, TF is ranked as the most popular provisioning tool among DevOps professionals.</p><h3>Terraform: The Basics</h3><p>Terraform is an IaC tool created by HashiCorp. It uses HashiCorp Configuration Language (HCL) to provision cloud resources.</p><p>By “provision,” we simply mean managing the entire lifecycle of your infrastructure. Whether you need to create new resources, update existing ones, or delete them entirely, Terraform handles it all.</p><p>Before you start provisioning resources, there are three terms you should understand:</p><h4><strong>Terraform Core</strong></h4><p>This is the engine of the operation. It reads every configuration file (those with the .tf extension) in your folder and merges them into one single plan. Because the Core sees everything at once, it knows which resources can be built at the same time (parallelism), making it much faster than clicking through a console manually.</p><pre>        [ main.tf ]       [ variables.tf ]      [ providers.tf ]<br>              \                  |                  /<br>               \                 |                 /<br>                \---&gt;  [  TERRAFORM CORE  ]  &lt;--- /<br>                       (The Unified Plan)</pre><h4><strong>Provider</strong></h4><p>A configuration file written in HCL cannot talk to the cloud directly. That is where the <strong>Provider</strong> comes in. It is a plugin that translates your code into API calls that the cloud provider understands. There are providers for <a href="https://registry.terraform.io/browse/providers">AWS, Azure, Google Cloud, and many others.</a></p><pre>          [ main.tf ]       [ variables.tf ]      [ providers.tf ]<br>                \                  |                  /<br>                 \                 |                 /<br>                  \---&gt;  [  TERRAFORM CORE  ]  &lt;--- /<br>                         (The Unified Plan)<br>                                   |<br>                                   |<br>                         [ Provider Plugin ]<br>                                   |<br>                           ( Cloud API Call )</pre><p><strong>Resources</strong></p><p>Any cloud resource you want to create, like a BigQuery dataset, a Cloud Composer (Airflow) environment, or a Cloud Storage staging area, is called a <strong>Resource. </strong>In your configuration file, you define these using a specific “resource block.”</p><h3>Getting Started: A Simple Demo</h3><p>To get started with Terraform, you first need to download and install the application. In this demo, I will show you how to provision a Cloud Storage staging area. In a modern data pipeline, this is where raw data is stored before it gets ingested into a data warehouse.</p><p>First, create a project directory and a file named providers.tf:</p><pre>mkdir learn-terraform<br><br>cd learn-terraform<br><br>touch providers.tf</pre><p>In Terraform, code is organized into blocks. To set up our project, we need to understand three main types:</p><ol><li><strong>The Terraform Block:</strong> This is where you specify your “required providers,” including their source and version. You can list multiple providers here, which highlights another major advantage of Terraform: it allows you to provision resources across different cloud providers seamlessly for multi-cloud projects.</li><li><strong>The Provider Block:</strong> This is where you configure the specific provider. For example, you would specify your Project ID and your default region here.</li><li><strong>The Resource Block:</strong> This is where you define the actual “thing” you want to build (like our storage bucket).</li></ol><p>Here is what the providers.tf file looks like. I used the configuration found on the official <a href="https://registry.terraform.io/providers/hashicorp/google/latest/docs"><strong>Google Cloud Provider page</strong></a>:</p><pre>terraform {<br>  required_providers {<br>    google = {<br>      source = &quot;hashicorp/google&quot;<br>      version = &quot;7.26.0&quot;<br>    }<br>  }<br>}<br><br>provider &quot;google&quot; {<br> project = &quot;your-project-id&quot;<br> region  = &quot;us-central1&quot;<br>}</pre><h3>Initializing the Project</h3><p>Once the providers.tf has been been created, you need to initialize the project. We do this by running the following command in the terminal:</p><pre>terraform init</pre><p>This command does two things:</p><ol><li>It downloads the Google provider plugin into a hidden .terraform folder.</li><li>It creates a .terraform.lock.hcl file in the project directory.</li></ol><p>This lock file is crucial. For example, since we specified version 7.26.0 in our code, the lock file ensures Terraform will only use that exact version. Even if a newer update is released tomorrow, your project won&#39;t suddenly change or break.</p><p>However, there are instances where you might want to allow for minor updates to the plugin. You can do this by using the ~&gt; symbol (e.g., version = &quot;~&gt; 7.26.0&quot;). This tells Terraform it is safe to download minor updates (like version 7.99.9), but it will protect your project by never downloading a major, potentially breaking update (like version 8.0.0).</p><h3><strong>Authentication</strong></h3><p>Next, Terraform needs permission to build things in your Google Cloud account. To grant this permission securely, run this command:</p><pre>gcloud auth application-default login</pre><p>A browser window will open, asking you to log in. By doing this, you are verifying your identity and allowing Terraform to provision resources on your behalf.</p><p>Once that is done, it is important to make sure you are working in the right GCP project. You can run this command to see which project is currently active:</p><pre>gcloud config get-value project</pre><p>Running this will output your current project_id. If you realize you are in the wrong project, you can switch it by running:</p><pre>gcloud config set project [PROJECT_ID]</pre><h3>Provisioning Resources</h3><p>Next, we will provision our actual cloud resources: in this case, a simple storage bucket. To do this, I will create a new file called main.tf.</p><pre>touch main.tf</pre><p>The cool thing about creating resources using Terraform is that there is <a href="https://registry.terraform.io/providers/hashicorp/google/latest/docs">documentation</a> for every resource. You don’t have to memorize complex syntax. It is as easy as copying the code and customizing it for your specific use case.</p><p>The documentation to create a storage bucket can be found here. I am going to use the simple example provided under<a href="https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/storage_bucket#example-usage---enabling-public-access-prevention"> <strong>Example Usage — Enabling public access prevention</strong>.</a> I am going to add this block of code below to the main.tf file and save it.</p><pre>resource &quot;google_storage_bucket&quot; &quot;gcs-learn-terraform-bucket&quot; {<br>  name          = &quot;learn-terraform-bucket&quot;<br>  location      = &quot;US&quot;<br>  force_destroy = true<br><br>  public_access_prevention = &quot;enforced&quot;<br>}</pre><p>So, what does this code do?</p><p>The first line tells Terraform what we are building, and it is divided into two labels:</p><ol><li><strong>The Resource Type (</strong>&quot;google_storage_bucket&quot;<strong>):</strong> This is defined by Google. It tells Terraform what kind of object to build. You cannot change this.</li><li><strong>The Local Name (</strong>&quot;gcs-learn-terraform-bucket&quot;<strong>):</strong> This is just a name you give the resource so Terraform can identify it within your code. You can name this whatever you want.</li></ol><p>Inside the block, we define the argument references. These lines create a Google storage bucket named learn-terraform-bucket in the US location and enforce that the public cannot access it (basically making it a private bucket). The force_destroy = true line ensures that if you ever decide to delete the bucket, any objects (files) inside it will also be deleted.</p><p>Once the code has been added to main.tf and saved, we run the following command:</p><pre>terraform plan</pre><p>This command generates an execution plan without actually executing the provisioning. Think of it as a preview. The output will look something like this:</p><pre>Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:<br>  + create<br><br>Terraform will perform the following actions:<br><br>  # google_storage_bucket.gcs-learn-terraform-bucket will be created<br>  + resource &quot;google_storage_bucket&quot; &quot;gcs-learn-terraform-bucket&quot; {<br>      + effective_labels            = {<br>          + &quot;goog-terraform-provisioned&quot; = &quot;true&quot;<br>        }<br>      + force_destroy               = true<br>      + id                          = (known after apply)<br>      + location                    = &quot;US&quot;<br>      + name                        = &quot;learn-terraform-bucket&quot;<br>      + project                     = (known after apply)<br>      + project_number              = (known after apply)<br>      + public_access_prevention    = &quot;enforced&quot;<br>      + rpo                         = (known after apply)<br>      + self_link                   = (known after apply)<br>      + storage_class               = &quot;STANDARD&quot;<br>      + terraform_labels            = {<br>          + &quot;goog-terraform-provisioned&quot; = &quot;true&quot;<br>        }<br>      + time_created                = (known after apply)<br>      + uniform_bucket_level_access = (known after apply)<br>      + updated                     = (known after apply)<br>      + url                         = (known after apply)<br><br>      + soft_delete_policy (known after apply)<br><br>      + versioning (known after apply)<br><br>      + website (known after apply)<br>    }<br><br>Plan: 1 to add, 0 to change, 0 to destroy.</pre><p>The most important part of this output is the very last line: Plan: 1 to add, 0 to change, 0 to destroy.</p><p>This tells us what Terraform intends to do. It will create (add) one new resource, update (change) zero resources, and delete (destroy) zero resources.</p><p>Once you are satisfied with this preview, it is time to actually provision the resource (in this case, create the storage bucket). To do that, run the following command:</p><pre>terraform apply</pre><p>Terraform will prompt you to type yes to approve the actions it plans to take. Once it finishes, you will see an output like this:</p><pre>google_storage_bucket.gcs-learn-terraform-bucket: Creating...<br>google_storage_bucket.gcs-learn-terraform-bucket: Creation complete after 2s [id=learn-terraform-bucket]<br><br>Apply complete! Resources: 1 added, 0 changed, 0 destroyed.</pre><p>From the output, we can see that the bucket was created in just 2 seconds. Exactly 1 resource was added, 0 were updated (changed), and 0 were deleted (destroyed).</p><p>Finally, we can check the GCP Console to verify that our bucket was successfully created:</p><p>We can then check the GUI of the GCP console to see whether the bucket was created:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pE3IPG4_-3wKOVwDuiBj_A.png" /><figcaption>The GCP Console showing our newly created storage bucket.</figcaption></figure><p>Remember earlier when we said the Provider translates your code into API calls? If you check your APIs &amp; Services dashboard, you can actually see the spike in traffic from the exact moment Terraform made those calls to Google Cloud as shown in the image below (by the blue dot):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*lBlcfDnUWx3h2qYW-AsPkg.png" /><figcaption><em>The API traffic spike in GCP, showing the moment the Terraform Provider made its calls to the cloud.</em></figcaption></figure><h3>The State File (terraform.tfstate)</h3><p>When our Google Cloud storage bucket was created, Terraform automatically generated a new file in our project directory called terraform.tfstate.</p><p>This file acts as a snapshot. It keeps track of the state of the resources Terraform just built. This gives an advantage over using a cloud console. If you want to know exactly what is running in your project, you don’t have to waste time clicking through dozens of menus in the GUI; you can just look at your Terraform state.</p><h3>Conclusion</h3><p>To wrap up this beginner post on Terraform, we learned that it offers easier collaboration, simplifies multi-cloud projects, enables faster resource provisioning, and automatically keeps the state of the cloud resources we build. Combined, these features offer significant advantages over provisioning resources manually through a GUI.</p><p>Now that you have your staging area built, your next step could be using Terraform to automatically spin up the BigQuery tables or Cloud Functions that will process this data. <strong>A</strong>s you expand your infrastructure, you will also want to explore using variables to avoid hardcoding resource names, and learning how to manage dependencies so Terraform always builds your resources in the correct order.</p><p>Thank you for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2039ad0e9a4f" width="1" height="1" alt=""><hr><p><a href="https://blog.dataengineerthings.org/infrastructure-as-code-iac-2039ad0e9a4f">Infrastructure as Code (IaC) for Data Engineers: A Beginner’s Guide</a> was originally published in <a href="https://blog.dataengineerthings.org/">Data Engineer Things</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Flat Files to Relational Models: Architecting Oil & Gas Production Data]]></title>
            <link>https://blog.dataengineerthings.org/from-flat-files-to-relational-models-architecting-oil-gas-production-data-8c9c1e684408?source=rss-93855656ee5f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c9c1e684408</guid>
            <category><![CDATA[database-design]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[oil-and-gas]]></category>
            <category><![CDATA[data-architecture]]></category>
            <dc:creator><![CDATA[Oladayo]]></dc:creator>
            <pubDate>Tue, 07 Apr 2026 07:01:01 GMT</pubDate>
            <atom:updated>2026-08-02T20:50:32.714Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Oeh082yP5okqVimY_5uSug.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@zacharytheodore?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Zach Theo</a> on <a href="https://unsplash.com/photos/oil-rig-guADzpF9pDI?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>The Oil &amp; Gas industry generates a massive amount of data, but production data is arguably the most important because it directly translates to revenue. However, in some companies, this data still sits in flat files (like Excel), which creates severe data redundancy. Furthermore, production data is often siloed, meaning each oil field has its own isolated dataset. Running company-wide analytics in this environment means manually repeating the exact same calculations for every single field. In this post, I will walk through how to transform messy, flat-file production data into an efficient relational model.</p><p>When production data is stored in isolated flat files per field, the column headers typically look like this:</p><pre><strong>PRODUCTION TABLE</strong><br><br>+------------+-----------+----------------+----------------+------------------+----------------+<br>| Date       | Well_Name | Oil_Production | Gas_Production | Water_Production | Reservoir_Name |<br>+------------+-----------+----------------+----------------+------------------+----------------+<br>|            |           |                |                |                  |                |<br>+------------+-----------+----------------+----------------+------------------+----------------+</pre><p><strong><em>Table 1: Raw, unnormalized production data in a flat file.</em></strong></p><p>Before we begin normalizing this data, I am going to augment these headers with a few additional columns:</p><pre><strong>PRODUCTION TABLE </strong><br><br>+------------+---------+-----------+----------------+----------------+------------------+--------------+----------------+----------+------------+<br>| Date       | Well_ID | Well_Name | Oil_Production | Gas_Production | Water_Production | Reservoir_ID | Reservoir_Name | Field_ID | Field_Name |<br>+------------+---------+-----------+----------------+----------------+------------------+--------------+----------------+----------+------------+<br>|            |         |           |                |                |                  |              |                |          |            |<br>+------------+---------+-----------+----------------+----------------+------------------+--------------+----------------+----------+------------+</pre><p><strong><em>Table 2: Augmenting the raw data with Surrogate Keys.</em></strong></p><p>First, I added Field_ID and Field_Name columns, which allows us to consolidate data from multiple isolated files into a single, centralized production table.</p><p>More importantly, I introduced integer ID columns (Surrogate Keys) for every major entity: the Well, Reservoir, and Field. Using IDs instead of text names is a foundational database engineering practice. It guarantees unique records and protects the database from update anomalies, ensuring that if a well or reservoir gets renamed in the future, the historical production data links remain unbroken.</p><p>The process of transforming this flat file into a relational database relies on a three-step framework called Normalization.</p><h3><strong>Step 1: First Normal Form (1NF)</strong></h3><p>To achieve First Normal Form, a table must pass four tests:</p><ol><li>No multi-valued columns (each cell must hold only one piece of data).</li><li>No derived data (columns should not contain calculations based on other columns).</li><li>All data must be atomic (broken down to its lowest logical level).</li><li>The table must have a defined Primary Key.</li></ol><p>Looking at our production table, it actually passes the first three tests naturally. All data points are atomic, there are no calculated fields, and every cell contains a single value.</p><p>Our only task for 1NF is to identify the Primary Key: the unique identifier for each row that guarantees no exact duplicates can exist in the table.</p><p>In the Production table, a single Well_ID is not unique because a well produces oil on many different dates. Likewise, Date is not unique because many wells produce oil on the exact same day. However, a well only has one production record per day.</p><p>Therefore, our Primary Key must be a combination of the Well_ID and Date columns. Because it uses two columns to create one unique identifier, this is known as a Composite Key.</p><blockquote><strong>Note:</strong> This logic assumes that each well is a single completion, meaning that each well drains from only a single reservoir.</blockquote><h3><strong>Step 2: Second Normal Form (2NF)</strong></h3><p>To achieve Second Normal Form, a table must eliminate all partial dependencies<strong>.</strong> A partial dependency occurs when a non-key column depends on only a part of a composite Primary Key, rather than the entire key.</p><blockquote><strong>Note:</strong> When we say “Column B depends on Column A,” it means that if you know the value of A, there is only one possible corresponding value for B.</blockquote><p>Looking at our PRODUCTION table, our composite Primary Key is (Well_ID, Date). The Oil_Production, Gas_Production, and Water_Production columns depend on this full key: you need to know both the well and the date to find the correct production volumes.</p><p>However, columns like Well_Name, Reservoir_ID, Reservoir_Name, Field_ID, and Field_Name do not care about the Date. They depend only on the Well_ID. This is partial dependency.</p><p>To eliminate it, we break these well-specific columns out into their own separate table, which we will call the WELLS table. The Well_ID becomes the Primary Key of this new WELLS table, while remaining in the PRODUCTION table to serve as the link (Foreign Key) between the two.</p><pre><strong>PRODUCTION TABLE</strong><br><br>+------------+---------+----------------+----------------+------------------+<br>| Date       | Well_ID | Oil_Production | Gas_Production | Water_Production |<br>+------------+---------+----------------+----------------+------------------+<br>|            |         |                |                |                  |<br>+------------+---------+----------------+----------------+------------------+</pre><pre><strong>WELLS TABLE</strong><br><br>+---------+-----------+--------------+----------------+----------+------------+<br>| Well_ID | Well_Name | Reservoir_ID | Reservoir_Name | Field_ID | Field_Name |<br>+---------+-----------+--------------+----------------+----------+------------+<br>|         |           |              |                |          |            |<br>+---------+-----------+--------------+----------------+----------+------------+</pre><p><strong><em>Table 3: The 2NF Architecture, separating well attributes from production volumes.</em></strong></p><h3>Step 3: Third Normal Form (3NF)</h3><p>To achieve Third Normal Form, a table must eliminate all<strong> </strong>transitive dependencies<strong>. </strong>A transitive dependency occurs when a non-key column depends on the Primary Key indirectly, by passing through another non-key column.</p><p>Looking at our new WELLS table, columns like Reservoir_Name, Field_ID, and Field_Name do technically depend on the Well_ID: if you know the well, you know its field. However, this is an indirect dependency. They only depend on the Well_ID because they belong to a specific Reservoir_ID.</p><p>To eliminate this transitive dependency, we break the chain. We move these columns into a separate table called RESERVOIRS. The Reservoir_ID becomes the Primary Key of this new table, while remaining in the WELLS table to serve as a Foreign Key link between the two.</p><p>However, we are not quite finished. If we look at our newly created RESERVOIRS table, we have one final transitive dependency: Field_Name depends entirely on Field_ID. To completely satisfy 3NF, we must break this out one last time into a FIELDS table.</p><pre><strong>PRODUCTION TABLE</strong><br>+------------+---------+----------------+----------------+------------------+<br>| Date       | Well_ID | Oil_Production | Gas_Production | Water_Production |<br>+------------+---------+----------------+----------------+------------------+<br>|            |         |                |                |                  |<br>+------------+---------+----------------+----------------+------------------+</pre><pre><strong>WELLS TABLE</strong><br>+---------+-----------+--------------+<br>| Well_ID | Well_Name | Reservoir_ID |<br>+---------+-----------+--------------+<br>|         |           |              |<br>+---------+-----------+--------------+</pre><pre><strong>RESERVOIRS TABLE</strong><br>+--------------+----------------+----------+<br>| Reservoir_ID | Reservoir_Name | Field_ID |<br>+--------------+----------------+----------+<br>|              |                |          |<br>+--------------+----------------+----------+</pre><pre><strong>FIELDS TABLE</strong><br>+----------+------------+<br>| Field_ID | Field_Name |<br>+----------+------------+<br>|          |            |<br>+----------+------------+</pre><p><strong><em>Table 4: The final 3NF Architecture, eliminating transitive dependencies.</em></strong></p><h3>Physical Modeling &amp; The ERD</h3><p>In this final step, we translate our normalized logical design into a physical database schema. Below is the SQL used to create the tables, define the data types, and enforce the structural relationships using Primary and Foreign Keys.</p><pre>CREATE TYPE Data_Modeling.Field_Status AS ENUM (&#39;Exploration&#39;, &#39;Development&#39;, &#39;Production&#39;, &#39;Decommissioning&#39;);<br><br>CREATE TYPE Data_Modeling.Reservoir_Status AS ENUM (&#39;Discovered&#39;, &#39;Appraised&#39;, &#39;Production&#39;, &#39;Mature&#39;, &#39;Depleted&#39;);<br><br>CREATE TYPE Data_Modeling.Well_Status AS ENUM (&#39;Drilling&#39;, &#39;Completed&#39;, &#39;Producing&#39;, &#39;Injecting&#39;, &#39;Shut-in&#39;, &#39;Permanently Abandoned&#39;);<br><br>CREATE TABLE Data_Modeling.Fields<br>(<br>    Field_ID       INT PRIMARY KEY,<br>    Field_Name     VARCHAR(50)                NOT NULL,<br>    Discovery_Date DATE,<br>    Field_Status   data_modeling.Field_Status NOT NULL,<br>    Updated_at     TIMESTAMP DEFAULT CURRENT_TIMESTAMP<br>);<br><br>CREATE TABLE Data_Modeling.Reservoirs<br>(<br>    Reservoir_ID     INT PRIMARY KEY,<br>    Reservoir_Name   VARCHAR(50)                    NOT NULL,<br>    Field_ID         INT                            NOT NULL,<br>    Discovery_Date   DATE,<br>    Reservoir_Status data_modeling.Reservoir_Status NOT NULL,<br>    Updated_at       TIMESTAMP DEFAULT CURRENT_TIMESTAMP,<br>    FOREIGN KEY (Field_ID) REFERENCES Data_Modeling.Fields (Field_ID)<br>);<br><br>CREATE TABLE Data_Modeling.Wells<br>(<br>    Well_ID       INT PRIMARY KEY,<br>    Well_Name     VARCHAR(50)               NOT NULL,<br>    Reservoir_ID  INT                       NOT NULL,<br>    Well_Status   data_modeling.Well_Status NOT NULL,<br>    Drilling_Date DATE,<br>    Updated_at    TIMESTAMP DEFAULT CURRENT_TIMESTAMP,<br>    FOREIGN KEY (Reservoir_ID) REFERENCES Data_Modeling.Reservoirs (Reservoir_ID)<br>);<br><br>CREATE TABLE Data_Modeling.Production<br>(<br>    Date             DATE NOT NULL,<br>    Well_ID          INT  NOT NULL,<br>    Oil_Production   DECIMAL(10, 2) DEFAULT 0.00,<br>    Gas_Production   DECIMAL(10, 2) DEFAULT 0.00,<br>    Water_Production DECIMAL(10, 2) DEFAULT 0.00,<br>    PRIMARY KEY (Date, Well_ID),<br>    FOREIGN KEY (Well_ID) REFERENCES Data_Modeling.Wells (Well_ID)<br>);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*Li8nD5F6PlQ-sxI8K1Xdtw.png" /><figcaption><strong>Figure 1: The Entity Relationship Diagram (ERD) mapping the 3NF physical schema.</strong></figcaption></figure><h3>Architecting for Changing Business Rules (Multi-Completions)</h3><p>A good data model doesn’t just solve today’s problems; it anticipates tomorrow’s physical realities. What happens to our data models if the business explores dual or multi-completion wells, where a single well produces from multiple different reservoirs simultaneously?</p><p>Our underlying business logic has fundamentally changed, which means our database normalization must adapt:</p><ol><li><strong>1NF (The New Primary Key):</strong> A well now has multiple production records per day (one for each reservoir). Therefore, our Primary Key must expand to become a three-part composite key: Date, Well_ID, and Reservoir_ID</li><li><strong>2NF (Eliminating Partial Dependencies):</strong> Because our Primary Key expanded, our dependencies shift. Well_Name only depends on Well_ID, so we create a WELLS table (Well_ID, Well_Name). Notice that we must completely remove the Reservoir_ID from the WELLS table. Similarly, Reservoir_Name and Field_ID only depend on Reservoir_ID, so they break out into a RESERVOIRS table.</li><li><strong>3NF (Eliminating Transitive Dependencies):</strong> Just like our original model, Field_Name still depends transitively on Field_ID inside the RESERVOIRS table, meaning we still break it out into our final FIELDS table.</li></ol><p><strong>The Resulting Model:</strong></p><ol><li><strong>PRODUCTION:</strong> Date, Well_ID, Reservoir_ID (Composite PK) + Production Volumes</li><li><strong>WELLS:</strong> Well_ID (PK), Well_Name , Well_Status , Drilling_Date , Updated_at</li><li><strong>RESERVOIRS:</strong> Reservoir_ID (PK), Reservoir_Name, Field_ID , Discovery_Date , Reservoir_Status , Updated_at</li><li><strong>FIELDS:</strong> Field_ID (PK), Field_Name , Discovery_Date , Field_Status , Updated_at</li></ol><blockquote><strong>Note:</strong> I added columns to track the status and modification timestamp for fields, reservoirs, and wells. These will be useful when we model the data for analytical purposes</blockquote><h3>What Problems Did We Actually Solve?</h3><p>By moving from messy flat files to a strict 3NF relational model, we have successfully solved two bottlenecks:</p><ol><li><strong>Eliminated Data Silos:</strong> We can now store and analyze production data from every well, across multiple fields, inside a single centralized database. We no longer need to manage, clean, and consolidate dozens of isolated Excel files to run company-wide analytics.</li><li><strong>Prevented Update and Insert Anomalies:</strong> If a well or reservoir changes its name, we only have to update that text string in one single place (the WELLS or RESERVOIRS table), rather than updating thousands of daily historical production records. Similarly, if a new field is successfully explored, we can immediately insert it into the FIELDS table just once, even before any wells are drilled or production begins. This logic cascades perfectly: we can add new reservoirs to that field, and new wells to those reservoirs, long before any production data is ever recorded.</li></ol><p>While this 3NF architecture is a step up from messy flat files, it is still not fully optimized for analytics. Relational models are built for transactional systems; they are fantastic at handling quick INSERT and UPDATE operations without creating data anomalies.</p><p>However, because they store data in rows and require the database engine to perform numerous joins across multiple tables, running company-wide analytical queries can become heavy and slow.</p><p>To make this data ready for analytics, we need to completely reshape it one last time: moving from a Relational Model into a Dimensional Model. But that is a pipeline for another day.</p><p>In my next post, I will walk through how to extract this normalized production data and transform it into a high-performance analytical data warehouse.</p><p>Thank you for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c9c1e684408" width="1" height="1" alt=""><hr><p><a href="https://blog.dataengineerthings.org/from-flat-files-to-relational-models-architecting-oil-gas-production-data-8c9c1e684408">From Flat Files to Relational Models: Architecting Oil &amp; Gas Production Data</a> was originally published in <a href="https://blog.dataengineerthings.org/">Data Engineer Things</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Hands-On Dive into SQL Internals]]></title>
            <link>https://medium.com/@Oladayo/a-hands-on-dive-into-sql-internals-853449cd4fb7?source=rss-93855656ee5f------2</link>
            <guid isPermaLink="false">https://medium.com/p/853449cd4fb7</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Oladayo]]></dc:creator>
            <pubDate>Mon, 23 Feb 2026 00:13:39 GMT</pubDate>
            <atom:updated>2026-02-23T00:13:39.245Z</atom:updated>
            <content:encoded><![CDATA[<p>Knowing how to write a SQL query is one thing; knowing how the database engine executes it is another.</p><p>Recently, I have been learning about SQL internals — exploring different kinds of join algorithms, database data structures, clustered vs. non-clustered indexes, and reading execution plans (EXPLAIN ANALYZE).</p><p>To put this theoretical knowledge into practice, I leveraged Gemini (Google’s AI Assistant) to create a realistic testing environment. Gemini was used to generate the initial schema, populate the mock data, and simulate queries. My role in this project was executing the diagnostics using EXPLAIN ANALYZE, interpreting the execution plans, and writing the fixes (Indexing and Query Refactoring).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*htvoaciKfvs_x0cinJboLg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@sunder_2k25?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Sunder Muthukumaran</a> on <a href="https://unsplash.com/photos/a-stack-of-stacked-blue-and-white-plates-n7eJHQwefeI?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Before setting up the environment, here is a quick breakdown of the database concepts I will be referencing:</p><blockquote><strong>Index:</strong> A database structure that enables faster data retrieval. It does this by keeping specific data sorted. Indexes can be clustered or non-clustered.</blockquote><blockquote><strong>Clustered Index:</strong> This dictates the actual physical order of the data inside the table. When a Primary Key is specified, it automatically becomes the clustered index for that table.</blockquote><blockquote><strong>Non Clustered Index:</strong> A separate structure created from non-primary key columns. It takes columns that aren’t naturally sorted in the main table and stores a sorted copy of them.</blockquote><blockquote><strong>Covering Index:</strong> A non-clustered index that contains all the columns needed for a specific query. Because the index “covers” the entire request, it eliminates the cost of looking back at the main table for missing information.</blockquote><blockquote><strong>Table Scan (Full Table Scan):</strong> When a query is forced to check every single row in a table from top to bottom to find a match. As tables grow, this becomes a massive drag on query performance.</blockquote><blockquote><strong>SARGable (Search Argument Able):</strong> A query is said to be Search Argument Able (basically a filter) if the search argument can point to eliminating the need for a full table scan.</blockquote><blockquote><strong>Nested Loop Join:</strong> A join mechanism where the database checks the first row in Table A, and scans Table B for a match. It then repeats this loop for every single value being joined.</blockquote><h3><strong>The Business Context: The Streaming Database</strong></h3><p>To make the simulation realistic, I prompted Gemini to design a schema mimicking the backend of a global video streaming platform. The reporting dashboards we need to optimize rely on two core tables:</p><ol><li><strong>The Users Table (The Dimension Table):</strong> This tracks the subscriber base. It holds demographic and revenue data, including the CountryCode and SubscriptionType (Free, Basic, or Premium). In a real business, this table is relatively small but constantly joined to other tables for regional reporting.</li><li><strong>The WatchHistory Table (The Fact Table): </strong>Every time a user clicks &quot;Play,&quot; a new row is generated tracking the VideoID, the WatchDate, and the WatchDurationMinutes. At a scale of millions of users binge-watching content, this table grows exponentially.</li></ol><p>Here is the Data Definition Language (DDL) and the recursive logic Gemini generated to build and populate this massive testing environment:</p><pre>-- 1. Create the Table<br>CREATE TABLE WatchHistory (<br>    WatchID INT PRIMARY KEY,<br>    UserID INT,<br>    VideoID INT,<br>    WatchDate DATE,<br>    WatchDurationMinutes INT<br>);<br><br>-- 2. Generate 100,000 rows of test data for MySQL<br>INSERT INTO WatchHistory (WatchID, UserID, VideoID, WatchDate, WatchDurationMinutes)<br>WITH RECURSIVE digits AS (<br>    SELECT 0 AS n UNION ALL SELECT n + 1 FROM digits WHERE n &lt; 9<br>),<br>tally AS (<br>    SELECT d1.n + d2.n * 10 + d3.n * 100 + d4.n * 1000 + d5.n * 10000 AS num<br>    FROM digits d1<br>    CROSS JOIN digits d2<br>    CROSS JOIN digits d3<br>    CROSS JOIN digits d4<br>    CROSS JOIN digits d5<br>)<br>SELECT <br>    num + 1 AS WatchID,<br>    FLOOR(RAND() * 5000) + 1 AS UserID, <br>    FLOOR(RAND() * 1000) + 1 AS VideoID,<br>    DATE_SUB(&#39;2026-12-31&#39;, INTERVAL FLOOR(RAND() * 1000) DAY) AS WatchDate, <br>    FLOOR(RAND() * 120) + 1 AS WatchDurationMinutes<br>FROM tally;<br><br>-- 3. Create the Users Table<br>CREATE TABLE Users (<br>    UserID INT PRIMARY KEY,<br>    SignupDate DATE,<br>    CountryCode CHAR(2),<br>    SubscriptionType VARCHAR(10)<br>);<br><br>-- 4. Insert 5,000 rows of test data<br>INSERT INTO Users (UserID, SignupDate, CountryCode, SubscriptionType)<br>SELECT <br>    d1.n + d2.n * 10 + d3.n * 100 + d4.n * 1000 + 1 AS UserID,<br>    DATE_SUB(&#39;2026-12-31&#39;, INTERVAL FLOOR(RAND() * 1000) DAY) AS SignupDate,<br>    CASE FLOOR(RAND() * 4) WHEN 0 THEN &#39;US&#39; WHEN 1 THEN &#39;UK&#39; WHEN 2 THEN &#39;JP&#39; ELSE &#39;CA&#39; END AS CountryCode,<br>    CASE FLOOR(RAND() * 3) WHEN 0 THEN &#39;Free&#39; WHEN 1 THEN &#39;Basic&#39; ELSE &#39;Premium&#39; END AS SubscriptionType<br>FROM <br>    (SELECT 0 AS n UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) d1<br>CROSS JOIN <br>    (SELECT 0 AS n UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) d2<br>CROSS JOIN <br>    (SELECT 0 AS n UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) d3<br>CROSS JOIN <br>    (SELECT 0 AS n UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) d4<br>WHERE d1.n + d2.n * 10 + d3.n * 100 + d4.n * 1000 &lt; 5000;<br><br>-- 5. Pre-index the CountryCode<br>CREATE INDEX idx_Country ON Users(CountryCode);<br>```</pre><h3><strong>Scenario 1: The Daily Active Users</strong></h3><p>The CEO’s dashboard features a chart showing the total number of unique users who watched a video in February 2026. As the dataset grows, the query powering this metric is experiencing noticeable latency, and the execution time needs to be optimized to keep the dashboard responsive.</p><p><strong>The Current Query:</strong></p><pre>EXPLAIN ANALYZE<br>SELECT COUNT(DISTINCT UserID) <br>FROM WatchHistory <br>WHERE YEAR(WatchDate) = 2026 <br>  AND MONTH(WatchDate) = 2;</pre><p><strong>Diagnosis:</strong></p><p>Running EXPLAIN ANALYZEon the query produced the following execution plan:</p><pre>-&gt; Aggregate: count(distinct watchhistory.UserID)  (cost=15782 rows=1) (actual time=99.1..99.1 rows=1 loops=1)<br>    -&gt; Filter: ((year(watchhistory.WatchDate) = 2026) and (month(watchhistory.WatchDate) = 2))  (cost=7999 rows=77831) <br>        -&gt;<strong> </strong>Table scan on WatchHistory  (cost=7999 rows=77831) (actual time=4.16..72.7 rows=100000 loops=1)</pre><p>Looking at the execution plan, the root cause is a full Table Scan. The database was forced to scan all 100,000 rows to extract the Year and Month from the WatchDate column before it could filter the data. Using functions on the column made the query Non-SARGable, which increased the execution cost.</p><p><strong>Solution:</strong></p><p>To fix this, I took a two-step approach. First, I created a non-clustered composite index idxWatchDate_Useron the WatchHistorytable. I placed WatchDate first so the database could quickly find the date range, and included UserID to cover the SELECT clause.</p><pre>CREATE INDEX idx_WatchDate_User<br>ON WatchHistory(WatchDate, UserID);</pre><p>Second, I rewrote the query to make it SARGable by removing the functions and using a BETWEENoperator:</p><pre>EXPLAIN ANALYZE<br>SELECT COUNT(DISTINCT UserID) <br>FROM WatchHistory <br>WHERE WatchDate BETWEEN &#39;2026-02-01&#39; AND &#39;2026-02-28&#39;;</pre><p>Because the new index contains both the column we are filtering by and the column we are selecting, it acts as a Covering Index. This completely eliminates the need for a full table scan and avoids the cost of a key lookup back to the main table.</p><p><strong>Result:</strong></p><p>Re-running the query shows the following execution plan:</p><pre>&gt; Aggregate: count(distinct watchhistory.UserID)  (cost=822 rows=1) (actual time=2.54..2.54 rows=1 loops=1)<br>    -&gt; Filter: (watchhistory.WatchDate between &#39;2026-02-01&#39; and &#39;2026-02-28&#39;)  (cost=550 rows=2723) (actual time=0.0599..1.89 rows=2723 loops=1)<br>        -&gt; Covering index range scan on WatchHistory using idx_WatchDate_User over (&#39;2026-02-01&#39; &lt;= WatchDate &lt;= &#39;2026-02-28&#39;)  (cost=550 rows=2723) (actual time=0.0561..0.758 rows=2723 loops=1)</pre><p>By implementing a Covering Index and a SARGable query, the database shifted to an efficient index range scan, dropping the query cost from 15,782 down to 822, and cutting the execution time from 99.1ms to 2.54ms.</p><h3><strong>Scenario 2: The Binge Watchers</strong></h3><p>The dashboard features a real-time feed showing the Top 50 Longest Watch Sessions across the platform. As the dataset expands, the query powering this feed is experiencing noticeable latency and high execution costs. It needs to be optimized to ensure the list loads instantly for the end user.</p><p><strong>The Current Query:</strong></p><pre>EXPLAIN ANALYZE<br>SELECT VideoID, WatchDate, WatchDurationMinutes<br>FROM WatchHistory<br>ORDER BY WatchDurationMinutes DESC<br>LIMIT 50;</pre><p><strong>Diagnosis:</strong></p><p>Running EXPLAIN ANALYZEon the query produced the following execution plan:</p><pre>-&gt; Limit: 50 row(s)  (cost=7999 rows=50) (actual time=49.6..49.6 rows=50 loops=1)<br>    -&gt; Sort: watchhistory.WatchDurationMinutes DESC, limit input to 50 row(s) per chunk  (cost=7999 rows=77831) (actual time=49.6..49.6 rows=50 loops=1)<br>        -&gt; Table scan on WatchHistory  (cost=7999 rows=77831) (actual time=1.39..36.2 rows=100000 loops=1)<br>-- Warning: Sort operation exceeded memory grant and spilled to TempDB (Disk). (Simulated)</pre><p>The execution plan revealed that the database needed to sort the WatchHistory table using the WatchDurationMinutescolumn. The sorting operation forced the database into a full table scan. Because sorting massive amounts of rows takes significant memory, it exceeded the allocated RAM and spilled over to the hard disk storage (TempDB), causing performance delays.</p><p><strong>Solution:</strong></p><p>To fix this, I created a non-clustered composite index idx_WatchDurationMinuteson the WatchHistory table. I placed WatchDurationMinutes first so the index is physically pre-sorted by duration, allowing the database to instantly find the longest sessions. I then included VideoID and WatchDate to cover the rest of the query.</p><pre>CREATE INDEX idx_WatchDurationMinutes<br>ON WatchHistory(WatchDurationMinutes, VideoID, WatchDate);</pre><p>Because the new index contains both the column we are ordering by and the columns we are selecting, it acts as a Covering Index. This completely eliminates the need for a full table scan, bypasses the expensive sorting operation entirely, and avoids a key lookup back to the main table.</p><p>The query itself was sound and did not need to be rewritten.</p><p><strong>Result:</strong></p><p>Re-running the query shows the following execution plan:</p><pre>-&gt; Limit: 50 row(s)  (cost=0.142 rows=50) (actual time=0.0356..0.0423 rows=50 loops=1)<br>    -&gt; Covering index scan on WatchHistory using idx_WatchDurationMinutes (reverse)  (cost=0.142 rows=50) (actual time=0.0352..0.04 rows=50 loops=1)</pre><p>By implementing a pre-sorted Covering Index, the database shifted to a highly efficient index scan. This dropped the query cost from 7,999 down to 0.142, and slashed the execution time from 49.6ms to 0.0423ms.</p><h3><strong>Scenario 3: The International Report</strong></h3><p>The executive team needs a regional report tracking the WatchDate and WatchDurationMinutes specifically for users located in the UK. As the database grows, the query generating this report is experiencing severe latency and high execution costs, which need to be optimized for faster reporting.</p><p><strong>The Current Query:</strong></p><pre>EXPLAIN ANALYZE<br>SELECT w.WatchDate, w.WatchDurationMinutes<br>FROM WatchHistory w<br>JOIN Users u ON w.UserID = u.UserID<br>WHERE u.CountryCode = &#39;UK&#39;;</pre><p><strong>Diagnosis:</strong></p><p>Running EXPLAIN ANALYZEon the query produced the following execution plan:</p><pre>-&gt; Nested loop inner join  (cost=35240 rows=20573) (actual time=2.83..192 rows=25926 loops=1)<br>    -&gt; Filter: (w.UserID is not null)  (cost=7999 rows=77831) (actual time=2.75..49 rows=100000 loops=1)<br>        -&gt; Table scan on w  (cost=7999 rows=77831) (actual time=2.75..41.6 rows=100000 loops=1)<br>    -&gt; Filter: (u.CountryCode = &#39;UK&#39;)  (cost=0.25 rows=0.264) (actual time=0.0013..0.00132 rows=0.259 loops=100000)<br>        -&gt; Single-row index lookup on u using PRIMARY (UserID=w.UserID)  (cost=0.25 rows=1) (actual time=0.00104..0.00107 rows=1 loops=100000)</pre><p>The execution plan shows that while the UserID in the Users table is indexed (as the Primary Key), the UserID Foreign Key in the WatchHistory table was unindexed. Because of this missing index, the database optimizer couldn&#39;t efficiently isolate the UK users first. Instead, it was forced into an inefficient Nested Loop in the reverse order: it performed a massive Full Table Scan on all 100,000 rows in WatchHistory, and for every single row, it performed a lookup against the Users table just to check if that user was from the UK.</p><p><strong>Solution:</strong></p><p>To resolve this, I created a non-clustered composite index on the WatchHistory table. I placed the Foreign Key UserIDat the leading edge of the index so the database could instantly match the joined records. I then included WatchDateand WatchDurationMinutes to cover the SELECT clause.</p><pre>CREATE INDEX idx_UserId<br>ON WatchHistory(UserID, WatchDate, WatchDurationMinutes);</pre><p>The JOIN architecture of the query was perfectly fine, so the SQL itself did not need to be rewritten.</p><p>Because the new index contains all the necessary columns, it acts as a Covering Index, completely eliminating the need for the inner Table Scan.</p><p><strong>Result:</strong></p><p>Re-running the query shows the following execution plan:</p><pre>-&gt; Nested loop inner join  (cost=3503 rows=20289) (actual time=0.196..55.1 rows=25926 loops=1)<br>    -&gt; Filter: (u.CountryCode = &#39;UK&#39;)  (cost=133 rows=1300) (actual time=0.162..1.72 rows=1300 loops=1)<br>        -&gt; Covering index lookup on u using idx_Country (CountryCode=&#39;UK&#39;)  (cost=133 rows=1300) <br>    -&gt; Covering index lookup on w using idx_UserId (UserID=u.UserID)  (cost=1.03 rows=15.6) (actual time=0.0316..0.0394 rows=19.9 loops=1300)</pre><p>By indexing the Foreign Key, the database replaced the Table Scan with an efficient Covering Index Lookup. This optimization dropped the query cost by 90% (from 35,240 down to 3,503) and reduced the execution time from 192ms to 55.1ms, improving the report’s latency.</p><h3><strong>Takeaways</strong></h3><p>While these scenarios shows the power of indexing, database optimization is rarely a one-size-fits-all solution. During this case study, I noted a few important nuances:</p><ul><li>In Scenario 3, after creating the idx_UserId index, I expected the execution plan to shift from a Nested Loop Join to a Sort-Merge Join. However, I learned that MySQL does not currently support the Sort-Merge join algorithm. Because it relies on the Indexed Nested Loop Join instead, the covering index lookup I achieved was actually the best possible result.</li><li>While creating an index improved latency and query cost across all three scenarios, it is not a silver bullet. If I was to index a column with low cardinality (very few unique values, such as a boolean flag or a Gender column), it could actually degrade performance.</li></ul><p>Outside of the case study, one thing to add is that Indexing and query refactoring are not the only ways to improve database performance. When datasets grow massive, architectural strategies like table partitioning (splitting large tables into smaller chunks) or archiving (moving historical data to cold storage) often become necessary alongside good indexing strategies.</p><p>Working on this case study was a great way to bridge the gap between database theory and hands-on performance tuning. It reinforced that knowing how to write a query is only half the job; knowing how the engine executes is what makes it scalable.</p><p>Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=853449cd4fb7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Architecting a Strava Data Pipeline: Answering the ‘Why’ and Sharing What I Learned]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@Oladayo/architecting-a-strava-data-pipeline-answering-the-why-and-sharing-what-i-learned-25f8a42bfdd7?source=rss-93855656ee5f------2"><img src="https://cdn-images-1.medium.com/max/1508/1*5ax9HL3GQtH3piiV24rZUQ.jpeg" width="1508"></a></p><p class="medium-feed-snippet">Hi everyone,</p><p class="medium-feed-link"><a href="https://medium.com/@Oladayo/architecting-a-strava-data-pipeline-answering-the-why-and-sharing-what-i-learned-25f8a42bfdd7?source=rss-93855656ee5f------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@Oladayo/architecting-a-strava-data-pipeline-answering-the-why-and-sharing-what-i-learned-25f8a42bfdd7?source=rss-93855656ee5f------2</link>
            <guid isPermaLink="false">https://medium.com/p/25f8a42bfdd7</guid>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[pub-sub]]></category>
            <category><![CDATA[time-complexity]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Oladayo]]></dc:creator>
            <pubDate>Mon, 15 Sep 2025 09:35:23 GMT</pubDate>
            <atom:updated>2025-09-15T09:40:08.394Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Event-driven ELT Data Pipeline: Strava Data]]></title>
            <link>https://medium.com/@Oladayo/event-driven-elt-data-pipeline-strava-data-4ff1cf344b4f?source=rss-93855656ee5f------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ff1cf344b4f</guid>
            <category><![CDATA[metabase]]></category>
            <category><![CDATA[dbt]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Oladayo]]></dc:creator>
            <pubDate>Tue, 09 Sep 2025 11:02:06 GMT</pubDate>
            <atom:updated>2025-09-15T09:42:17.331Z</atom:updated>
            <content:encoded><![CDATA[<p><em>In order to read this for free, click this </em><a href="https://medium.com/@Oladayo/event-driven-elt-data-pipeline-strava-data-4ff1cf344b4f?source=friends_link&amp;sk=5081ab321d1510a5b3cef63ba748d47f"><em>link</em></a></p><p>It’s been a while since my last post. In that time, I have gone back to school, graduated, and started my job search. To stay sharp while on the market, I am getting back to what I enjoy: building data projects and writing about the process.</p><p>This post breaks down my latest project: an event-driven ELT (<strong>E</strong>xtract, <strong>L</strong>oad, <strong>T</strong>ransform) pipeline built to handle my personal Strava data. Let’s dive in.</p><p>Data engineers typically work with two main types of data:</p><ol><li><strong>Streaming Data:</strong> This is data that is generated continuously in real-time, often arriving in high volume. For example, on social media feeds, an average of 6,000 tweets are sent per second on X (formerly Twitter).</li><li><strong>Batch Data: </strong>This refers to data collected in discrete chunks or files. The arrival of these batches can be regular , following a fixed schedule (like a daily sales report), or irregular, tied to specific occurrences (like your Strava data only after you complete a run).</li></ol><p>When processing batch data, one common approach is polling. This involves running the data pipeline on a fixed schedule, for example, once a day or every hour. This is typically managed using a scheduler tool like a cron job or a cloud provider’s scheduling service (e.g., Google Cloud Scheduler).</p><p>While simple to set up, this approach forces a trade-off between two key factors: latency and cost.</p><p>Let’s use an example to illustrate the problem.</p><p>Imagine we expect a new data file from a source every morning at 8:00 AM.</p><ul><li><strong>High Latency: </strong>We schedule our pipeline to run at 8:05 AM daily. If the data arrives on time, everything is fine. But what if one day the file is delayed and doesn’t arrive until 8:10 AM? The pipeline runs at 8:05 AM, finds nothing new, and shuts down. The delayed data will now sit unprocessed until the pipeline runs again the next day, resulting in a 24-hour delay.</li><li><strong>High Cost:</strong> To avoid that long delay, we could change the schedule to run the pipeline every hour. In our scenario, the 9:00 AM run would successfully ingest the delayed data. The latency problem is solved! However, the pipeline would then continue to run 23 more times throughout the day, finding no new data to process. These runs waste computational resources and drive up costs, no matter how small each run is.</li></ul><p>This constant, inefficient trade-off between waiting for data (latency) or wasting money on empty runs (cost) is the primary drawback of the polling method.</p><p>The alternative to polling is the event-driven approach. In this approach, the data pipeline runs only when there is new data to process. It doesn’t follow a schedule; it reacts to an event.</p><p>This is typically implemented using a Function-as-a-Service (FaaS) platform such as Google Cloud Functions. The source code for the pipeline is deployed to one of these services and is connected to a specific trigger.</p><p>This trigger automatically executes the pipeline in response to an event. Common triggers include:</p><ul><li>A new file arriving in a cloud storage bucket e.g, Google Cloud Storage</li><li>A message being published to a messaging system e.g, Google Pub/Sub</li></ul><p>By only running when there is actual work to do, this approach solves the polling drawbacks. It achieves both minimal latency (processing data almost as soon as it arrives) and cost-efficiency (as there are no wasted, empty runs).</p><p>The image below describes the event-driven ELT data pipeline for the project:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5ax9HL3GQtH3piiV24rZUQ.jpeg" /><figcaption><strong>ELT event-driven data project architecture</strong></figcaption></figure><p>The Ingestion (EL) process begins the moment an activity is created or updated in my Strava account. Here’s how the pipeline handles it:</p><ol><li><strong>The Webhook Notification</strong>: Instead of my system constantly checking for new data, I use a Strava Webhook (The <a href="https://developers.strava.com/docs/webhooks/">Strava Webhook</a> communicates events (called POST e.g., run activity, an update to an activity) that happens within Strava to another application). This means Strava instantly sends a notification to a unique URL when a new event happens. This URL points directly to a small cloud function: the Webhook Receiver.</li><li><strong>Passing the Message:</strong> The Webhook Receiver’s job is simple; it catches the notification from the Webhook and immediately publishes the event payload to the Strava Activity Topic (a Google Pub/Sub message queue). This message is just an alert that something happened; it doesn’t contain the detailed run data yet.</li><li><strong>Extracting the Raw Data:</strong> The Activity Extractor function is subscribed to that topic. The moment a message is published to the topic, this function is automatically triggered. Its job is to connect to the API , fetch the detailed data for that specific activity, format this data into a Parquet file and saves it in the Activity Data Bucket in the cloud storage.</li><li><strong>Loading the Raw Data: </strong>The moment the Parquet file lands in the Activity Data Bucket, it automatically triggers the Activity Loader function. The function has one simple job: to read the data from that new file and loads it directly into the Activity Table inside the data warehouse, Google BigQuery.<strong> </strong>With this, the Extract and Load stages of the event-driven ELT pipeline are complete.</li></ol><p>With the ingestion stage completed, the next step is Transformation. The technology stack for this stage consists of <a href="https://docs.getdbt.com/docs/core/docker-install">dbt core</a> to define the transformations, packaged as a Docker image using Cloud Build, and executed as a serverless job on Cloud Run. This set up leads to the question for this stage: how can this transformation process be made event-driven?</p><ol><li><strong>Eventarc Listening:</strong> Loading data into BigQuery and querying a table both create the same generic “Job Completed” event in Cloud Audit Logs. To handle this, an Eventarc trigger is configured to listen for every one of these events from BigQuery. When an event is detected, Eventarc triggers a Cloud Workflow execution.</li><li><strong>Workflow Triggering: </strong>When the workflow executes, it first acts as a filter. It inspects the incoming event to determine if it originated from a data load job. If the event is from a load job, the workflow proceeds to execute the Cloud Run job; otherwise, the workflow terminates.</li><li><strong>Cloud Run Job</strong>: Finally the Cloud Run job executes the dbt transformations, building the final, analysis-ready models in BigQuery.</li></ol><p>That concludes the walk-through of the event-driven data pipeline. In a future post, I plan to write about some key lessons I learned during the implementation process.</p><p>You can find the project assets in the links below:</p><ul><li>The Code: The complete source code, including all Terraform configurations and dbt models, is available in the project’s <a href="https://github.com/0ladayo/strava-data-pipeline">GitHub Repository</a>.</li><li>The Visualization: A simple dashboard visualizing the final, transformed data can be viewed in <a href="http://34.14.45.37:3000/public/dashboard/e9a1ff11-170c-4344-aff4-9522558743bf">metabase</a>.</li><li>Pipeline Observability: A monitoring dashboard for the pipeline’s execution status across the GCP resources can be found at <a href="https://oladayosiyanbola.grafana.net/public-dashboards/f39bb0d5c6b142f2a0c4c3e36c2f7149">Observability Link.</a></li></ul><p>While this pipeline is functional, potential future enhancements include:</p><ul><li><strong>Ingesting Additional Data Sources:</strong> Adding data from other sources (e.g., Apple Health) would enable more complex transformation models.</li><li>Add data quality checks to the extracted data.</li></ul><p>Thank you for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ff1cf344b4f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Mentorship Program Project]]></title>
            <link>https://medium.com/codex/data-mentorship-program-project-1294f0db7a4b?source=rss-93855656ee5f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1294f0db7a4b</guid>
            <category><![CDATA[google-cloud-functions]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[google-cloud-storage]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Oladayo]]></dc:creator>
            <pubDate>Thu, 29 Jun 2023 16:37:31 GMT</pubDate>
            <atom:updated>2023-07-10T12:57:03.228Z</atom:updated>
            <content:encoded><![CDATA[<h4>Feedback 1 (we will just delete this at the end of the process but a comment doesn’t allow me to write this much):</h4><p>Hi Oladayo, thank you for submitting your article to DET! I’m Eduard and I will be you reviewer for your article. I think it’s a great idea to cover one of your projects, your journey and your learnings.</p><p>After reading the entire article I want to give you a couple of general remarks before diving into the details:</p><p>1. Try to make your article title a bit more interesting rather than just descriptive. What I mean is that people should read the title and think, “Oh, this sounds interesting, I should click on it”. This doesn’t mean you need to clickbait people but something a little more intriguing could help you reach I wider audience. Examples could be: “My Top 3 Learnings from Completing the Data Mentorship Program Project” -&gt; this is just the first thing that came to my mind, so please think of other options as well.</p><p>2. Try to give your article a bit more structure with the help of Titles / Headings. This way you can guide your reader through your article a better and it looks more professional.</p><p>3. It’s always great to include graphics in your article, but the ones you inserted are really hard to read. Would it be somehow possible to make them more legible?</p><p>4. You could maybe also consider adding a paragraph of what the next steps in the project could be i.e., other features you would like to add or how the solution could be improved. This could give you the potential to expand on the project in the future and shows the reader that you can evaluate your solution.</p><p>I would ask you to have a look at the points I mentioned and try to implement them. Once this is done, I will come back and give you some more details on that version.</p><p>All the best,</p><p>Eduard</p><p>Hi everyone,</p><p>I have been part of the <a href="https://www.linkedin.com/company/data-mentorship-program/">Data Mentorship Program</a> for the past two (2) months. During this time, I was paired with a data engineering mentor and it’s been great experience learning from someone who works in the field.</p><p>For my final activity in the program, I worked on a project. Rather than starting a new project from scratch, my mentor and I decided that I should focus on improving a previous project of mine.</p><blockquote>“Make it work, Make it right, Make it fast” — Kent Beck</blockquote><p>The project I chose to make improvement is <a href="https://medium.com/codex/building-a-web-application-for-active-low-earth-orbit-satellites-74fcafb16df">this.</a> The project aimed at displaying in near real-time the position and altitude of a selected individual active satellite in low earth orbit, and also showcases the trends in terms of purpose and launch years of these satellites. The architecture of the project is shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ceeVEvRD60ZZEJSMiUgJXA.png" /><figcaption><strong>architecture of the project</strong></figcaption></figure><p>The issues I identified looking at the architecture of the project are:</p><p>Lack of proper separation of concerns in the main.py module: The main.py module was intended for building the web application (dashboard) but it also contained transformation logic.</p><p>To address this, I moved the transformation logic in the main.py module to the etl.py module.</p><p>Hardcoding: In the etl.py module, I hardcoded lists web-hosted CSVs based on their purpose. However, this approach lacks flexibility and maintainability. If there is a need to update or modify these lists in the future, it would require modifying and recompiling the module.</p><p>To mitigate this issue, I moved the lists of web-hosted CSVs to a configuration file (config.yaml) and implemented logic to read the configuration file within the module.</p><p>Suboptimal scheduling approach for the etl.py Module: The etl.py module is scheduled to run at midnight. The ideal approach would be for the module to run whenever there is an update to the source file, a web-hosted CSV. However lacking the ideal approach (which will involve using a webhook), I had two options to allow for a timely update of data:</p><p>a. Run the etl.py module every hour.</p><p>b. Implement a trigger.py module: This module will handle the storage and update checks for the source file. The initial run of the trigger.py module will store the source file in a google cloud storage bucket.</p><p>Subsequent run of the module will compare the web-hosted CSV source file with the existing file in the bucket to check for update. If an update is detected, the module will overwrite the existing source file in the bucket with the updated version.</p><p>This action of overwriting the source file in the bucket will then trigger the execution of the etl.py module.</p><p>The trigger.py module is scheduled to run every hour.</p><p>I went with the second option because of cost. Cloud Function cost is a factor of the execution time and the memory utilization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LiS_Giy5xW6fdS0FTtFy6A.png" /><figcaption><strong>updated architecture of the project</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*1bonQNfnQvL8zoyWizvHYQ.png" /><figcaption><strong>metrics of the trigger.py module</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*_8vx6IyPeARg9dssu4GAMA.png" /><figcaption><strong>metrics of the etl-function.py module</strong></figcaption></figure><p>As shown in the images above, the median execution time per call of the trigger.py module is 3.0894s compared to 1.8136min for the etl-function.py. Also, the memory utilisation per call of the trigger.py is 256.58MiB compared to 289.78MiB for the etl-function.py.</p><p>Other improvements to the project were made in the form of additions:</p><p><strong>a.</strong>I implemented data validation checks in the etl.py module using the data_validation.py module. I used the pandera library to implement the checks.</p><p><strong>b.</strong> I also implemented alerting in the etl.py using the alert.py module. I used the sendgrid library to implement the alert. The implementation ensures that I receive an email notification whenever the etl.py module runs successfully or encounters a failure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*ja9rf9S2yvgQv7cUQphGYQ.jpeg" /><figcaption><strong>sample email from the etl.py module run</strong></figcaption></figure><p><strong>c.</strong> Finally, I ensured all files stored in the architecture are in the .parquet file format. This decision was made to take advantage of the columnar data format and compression properties inherent to parquet files. By utilizing parquet, I can effectively reduce storage cost.</p><p>You can view the <a href="https://leo-satellite-overview-project.nw.r.appspot.com/">web application here</a> and the <a href="https://github.com/0ladayo/Low-Earth-Orbit-Satellites-Project">github repository here</a>.</p><p>I want to say a big thank you to <a href="https://www.linkedin.com/in/rajvimehta/">Rajvi </a>for organizing and accepting me into the program. Also, a big thank you to <a href="https://www.linkedin.com/in/kunalteeda/">Kunal</a> for his time and for being a great mentor to me.</p><p>Thank you for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1294f0db7a4b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/data-mentorship-program-project-1294f0db7a4b">Data Mentorship Program Project</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Ingestion (Change Data Capture Demonstration)]]></title>
            <link>https://medium.com/codex/data-ingestion-change-data-capture-demonstration-5e1702a16b1?source=rss-93855656ee5f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e1702a16b1</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[change-data-capture]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-ingestion]]></category>
            <dc:creator><![CDATA[Oladayo]]></dc:creator>
            <pubDate>Thu, 23 Mar 2023 12:08:54 GMT</pubDate>
            <atom:updated>2023-03-27T10:48:06.827Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi Everyone,</p><p>Welcome to the last part of the four-part series on data ingestion. You can read the first part <a href="https://medium.com/codex/data-ingestion-full-data-ingestion-78f0dad296e9">here</a>, the second part <a href="https://medium.com/codex/data-ingestion-incremental-data-ingestion-ee9bc8e1f865">here</a> and the third part <a href="https://medium.com/@Oladayo/data-ingestion-change-data-capture-ce8aaa594ff9">here</a>.</p><p>In this post, I will demonstrate the change data capture approach to data ingestion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mh4TbJFTRZ32Ek1vS4-DhA.jpeg" /><figcaption>a simple diagram that depicts the demonstration architecture</figcaption></figure><p>I will be streaming data from a table in the PostgreSQL database to a table in the BigQuery dataset with the help of Kafka and connect clusters. The PostgreSQL, Kafka cluster and connect cluster will run in docker containers.</p><p><strong>Requirements</strong></p><p>Based on the demonstration architecture, the requirements to enable data ingestion via change data capture are:</p><ol><li>A docker desktop application.</li><li>a docker-compose file that has the following services:</li></ol><ul><li>zookeeper: manages the distributed environment and handles configuration across each service in the Kafka cluster.</li><li>broker: a Kafka server that runs within a Kafka cluster.</li><li>connect: is used to connect the broker with the source system (PostgreSQL) and the sink system (BigQuery) so data can be easily streamed via the Kafka cluster. The connect service will include the source connector (Debezium PostgreSQL CDC Source Connector) and the sink connector (Google BigQuery Sink Connector).</li><li>schema-registry: keeps track of the structure of the messages sent and received across the Kafka cluster.</li><li>control-center: provides a web-based tool for managing and monitoring the Kafka broker.</li></ul><p>The first four services (zookeeper, broker, connect and schema-registry) are crucial components of the Kafka system, while the fifth service (control center) is optional.</p><p>A place to find the docker-compose file that has all these services is the <a href="https://github.com/confluentinc/cp-all-in-one/blob/7.3.1-post/cp-all-in-one/docker-compose.yml">cp-all-in-one repository</a>, provided by Confluent Inc, on GitHub.</p><p>Additional service needed outside the Kafka and connect cluster is:</p><ul><li>postgresqlsource: provides an instance of the PostgreSQL relational database management system. This will serve as the source system for the data ingestion process. A user (root), password (root), and database (sourcedb) was defined in the environment.</li></ul><p>The docker-compose file I will use for data ingestion, which includes the postgresqlsource service, can be found <a href="https://github.com/0ladayo/data-ingestion/blob/master/Change%20Data%20Capture/docker-compose.yml">here along with some comments.</a></p><p>3. BigQuery: this will serve as the sink system for the data ingestion process.</p><p>Let’s create a dataset named demo in BigQuery for this purpose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*aYEuCcQMwJXPCzXf4MqGUA.png" /><figcaption>created a dataset named demo. It has no tables in it.</figcaption></figure><p>4. Two connector configuration files (one for the source and one for the sink).</p><p>The source connector configuration file provides instructions to the source connector on how to connect and read from the source system while the sink connector configuration file provides instructions to the sink connector on how to connect and write to the sink system.</p><p>Let’s get to the demonstration:</p><ol><li>start the services in the docker-compose file. To do that, I will navigate to the repository that contains the docker-compose file on the terminal and use the docker command below to start up the services.</li></ol><pre>docker-compose up -d</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mO_jdWpVHIKznb47o7oXaw.png" /><figcaption>snapshot showing all the services (containers) are running</figcaption></figure><p>2. run a PostgreSQL client within the postgresqlsource container. To do that, I will execute the command below.</p><pre> docker exec -it postgresqlsource psql -U root sourcedb</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*S0_Yu8HLdq6Qj9Kq9j4mHA.png" /><figcaption>running a PostgreSQL client within the postgresqlsource container</figcaption></figure><p>3. Let’s create a table named orders in the sourcedb database with two columns (ordersId and ordersValue) and insert random values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*sUvRyoO885nk3_DiursqSg.png" /><figcaption>orders table created and values inserted into the tables</figcaption></figure><p>4. Go to <a href="http://localhost:9021/">localhost:9021/ </a>on your browser. This is the port for the control-center container.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PGaMbZDfNn2hlMKBHkoHvA.png" /><figcaption>control-center cluster overview</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tzZId7_Sc03uSKTQ-6YotQ.png" /><figcaption>control-center cluster detailed overview</figcaption></figure><p>Let’s navigate to the Topics section to see the list of the topics in the Kafka cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3tMGyiYJef96jrB1YWCWjQ.png" /><figcaption>default Topics in the Kafka cluster</figcaption></figure><p>Let’s navigate to the Connect section and check out the list of connectors in Connect Clusters</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XvMU6KTpaEbXoz2GH31Log.png" /><figcaption>connectors in the Connect Clusters</figcaption></figure><p>We have the two connectors we need. The PostgresConnector (Source) and the BigQuery (Sink).</p><p>5. Let’s upload the connector configuration files.</p><p>First the source connector configuration file. The file is a JSON file with the contents.</p><pre>{<br>  &quot;name&quot;: &quot;postgresql-source&quot;,<br>  &quot;config&quot;: {<br>      &quot;connector.class&quot;: &quot;io.debezium.connector.postgresql.PostgresConnector&quot;,<br>      &quot;tasks.max&quot;: &quot;1&quot;,<br>      &quot;plugin.name&quot;: &quot;pgoutput&quot;,<br>      &quot;database.hostname&quot;: &quot;postgresqlsource&quot;,<br>      &quot;database.port&quot;: &quot;5432&quot;,<br>      &quot;database.user&quot;: &quot;root&quot;,<br>      &quot;database.password&quot;: &quot;root&quot;,<br>      &quot;database.dbname&quot; : &quot;sourcedb&quot;,<br>      &quot;database.server.name&quot;: &quot;postgresql&quot;,<br>      &quot;topic.prefix&quot;: &quot;postgresql&quot;<br><br>    }<br>  }<br></pre><p>You can read about the <a href="https://docs.confluent.io/kafka-connectors/debezium-postgres-source/current/postgres_source_connector_config.html#postgresql-source-connector-debezium-configuration-properties">PostgreSQL Source Connector (Debezium) Configuration Properties</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A8eIZTlmnFMIQ6O6i4jQjA.png" /><figcaption>The source connector running</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v1U5luG_a-2SrFxNU7TMRA.png" /><figcaption>updated Topics showing a new topic named postgresql.public.orders</figcaption></figure><p>The Topics list has a new topic named postgresql.public.orders (postgresql is the topic prefix in the source connector configuration file, and orders is the table&#39;s name).</p><p>Let’s upload the sink connector configuration file. The file is a JSON file with the following contents</p><pre>{<br>  &quot;name&quot;: &quot;bigquery-sink&quot;,<br>  &quot;config&quot;: {<br>      &quot;connector.class&quot;: &quot;com.wepay.kafka.connect.bigquery.BigQuerySinkConnector&quot;,<br>      &quot;tasks.max&quot;: &quot;1&quot;,<br>      &quot;topics&quot;: &quot;postgresql.public.orders&quot;,<br>      &quot;sanitizeTopics&quot;: true,<br>      &quot;autoCreateTables&quot;: true,<br>      &quot;autoUpdateSchemas&quot;: true,<br>      &quot;schemaRegistryLocation&quot;:&quot;http://schema-registry:8081&quot;,<br>      &quot;schemaRetriever&quot;: &quot;com.wepay.kafka.connect.bigquery.retrieve.IdentitySchemaRetriever&quot;,<br>      &quot;project&quot;: &quot;dummy-surveillance-project&quot;,<br>      &quot;defaultDataset&quot; : &quot;demo&quot;,<br>      &quot;keyfile&quot;: &quot;/service key.json&quot;,<br>      &quot;upsertEnabled&quot;: true,<br>      &quot;deleteEnabled&quot;: true,<br>      &quot;kafkaKeyFieldName&quot;: &quot;orderId&quot;,<br>      &quot;transforms&quot;: &quot;HoistFieldKey&quot;,<br>      &quot;transforms.HoistFieldKey.type&quot;: &quot;org.apache.kafka.connect.transforms.HoistField$Key&quot;,<br>      &quot;transforms.HoistFieldKey.field&quot;: &quot;orderId&quot;,<br>      &quot;key.converter&quot;: &quot;org.apache.kafka.connect.storage.StringConverter&quot;<br>    }<br>  }</pre><p>You can read about the <a href="https://docs.confluent.io/kafka-connectors/bigquery/current/kafka_connect_bigquery_config.html">Google BigQuery Sink Connector Configuration Properties</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f987CmUk5GEvHhyR_C31sQ.png" /><figcaption>The sink connector running</figcaption></figure><p>6. When the source connector is uploaded and running, it does an initial snapshot of the orders table in the sourcedb database in PostgreSQL and produces the initial snapshot to the postgresql.public.orders topic.</p><p>When the sink connector is uploaded and running, it consumes the initial snapshot of the orders table from the topic.</p><p>So let’s check the demo dataset in BigQuery for any table, if there is one, let’s query the table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gZXvKaB0hx2aJO4_dzirnw.png" /><figcaption>tables in the demo dataset in BigQuery</figcaption></figure><p>Now, we have two tables in the demo dataset but we are only interested in the first table named postgresql_public_orders.</p><p>Let’s check for the columns in the table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xBvJAavb_Bhw6xdPgpa-TA.png" /><figcaption>the columns in the postresql_public_orders table in BigQuery</figcaption></figure><p>We have quite a number of nested columns (column that has columns in them).</p><p>The reason for having this kind of data structure is that I used a Debezium source connector.</p><p>When using the Debezium source connector, it generates a Debezium envelope which contains the data from the source system as well as additional metadata.</p><p>We are only interested in two nested columns;</p><ol><li>the before column which has two columns in it (orderid and ordervalue)</li><li>the after column which has two columns in it (orderid and ordervalue)</li></ol><p>The orderid and ordervalue columns in the after column represent the current state of the two columns in the orders table in the source system database.</p><p>If an update is made to data records in the orders table in the source system, the initial state of the data records gets moved to the before column and the new update to the after column.</p><p>Let’s query those two columns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5S2LpEKas9o5Ig1ntK1dcQ.png" /><figcaption>postresql_public_orders table query result</figcaption></figure><p>Looking at the query result, the orderid and ordervalue columns in the after column represent the current state of the orderId and orderValue columns in the orders table in the source system database while the orderid and ordervalue columns in the before column are null which means no updates has been made to the data records.</p><p>Let’s insert more values to the orders table in the sourcedb database in PostgreSQL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*0c4I7fxExRs33Q0EBsZUNA.png" /><figcaption>updated orders table with 3 new records with orderId 6, 7 and 8 added</figcaption></figure><p>Let’s query the postgresql_public_orders table in BigQuery</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZPZYvdYcT3U8ve4-Od-paw.png" /><figcaption>updated postresql_public_orders query result</figcaption></figure><p>Looking at the query result, the orderid and ordervalue columns in the after column represent the current state of the orderId and orderValue columns in the orders table in the source system database.</p><p>Let’s update the two rows in the orders table in the sourcedb database in PostgreSQL;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*Ae7tSy913Eo38zIXz9oRCg.png" /><figcaption>updated orders table with update made to orderId 2 and 4</figcaption></figure><p>Let’s query the postgresql_public_orders table in BigQuery</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Phh6u3QwQErXUBphN0AVYg.png" /><figcaption>updated postresql_public_orders query result</figcaption></figure><p>Looking at the query result, the orderid and ordervalue columns in the after column are the current state of the orderId and orderValue columns in the orders table in the source system database while the initial state of data records of orderid 2 and orderid 4 are now in the before column.</p><p>Let’s delete two records from the orders table in the sourcedb database in PostgreSQL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*-dSULQkmjeQtsR6F__YRPQ.png" /><figcaption>updated orders table with deletion made to orderId 1 and 5 data records</figcaption></figure><p>Let’s query the postgresql_public_orders table in BigQuery</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Y4IMVr5suGtJalcx5UJMg.png" /><figcaption>updated postresql_public_orders query result</figcaption></figure><p>Looking at the query result, there are no longer data records for orderId 1 and orderId 5 in the postgresql_public_orders table. The after column orderid and ordervalue columns are the current state of the orderId and orderValue in the orders table in the source system.</p><p>Messages were produced to the topic (postgresql.public.orders) while carrying out the INSERT, UPDATE and DELETE operations. You can view it <a href="https://drive.google.com/file/d/17FsQSpjMAB6w8RpnXIUyurKWhQ4KGmAo/view?usp=share_link">here</a>.</p><p>In closing, I have demonstrated the change data capture approach to data ingestion. This demonstration is a log-based change data capture because I made use of the Debezium Source Connector. There are other connectors that can be used like the JDBC Source Connector for query-based change data capture.</p><p>The change data capture approach to data ingestion is scalable for frequent changes to the source system tables.</p><p>Thank you to everyone that has followed me through this series.</p><figure><a href="https://www.buymeacoffee.com/Oladayo"><img alt="" src="https://cdn-images-1.medium.com/max/423/1*ixLGNDdLtLJcxypBthJzRA.png" /></a></figure><p>Until next time, be good everyone.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e1702a16b1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/data-ingestion-change-data-capture-demonstration-5e1702a16b1">Data Ingestion (Change Data Capture Demonstration)</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Ingestion (Change Data Capture)]]></title>
            <link>https://medium.com/@Oladayo/data-ingestion-change-data-capture-ce8aaa594ff9?source=rss-93855656ee5f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce8aaa594ff9</guid>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[change-data-capture]]></category>
            <category><![CDATA[debezium]]></category>
            <category><![CDATA[data-ingestion]]></category>
            <category><![CDATA[bigquery]]></category>
            <dc:creator><![CDATA[Oladayo]]></dc:creator>
            <pubDate>Sun, 19 Mar 2023 23:04:00 GMT</pubDate>
            <atom:updated>2023-03-27T10:47:01.092Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi Everyone,</p><p>Welcome to the third part of the four-part series on data ingestion. You can read the first part <a href="https://medium.com/codex/data-ingestion-full-data-ingestion-78f0dad296e9">here</a> and the second part <a href="https://medium.com/codex/data-ingestion-incremental-data-ingestion-ee9bc8e1f865">here</a>.</p><p>In this post, I will be going over the change data capture approach to data ingestion.</p><p>In the full data ingestion and the incremental data ingestion;</p><ol><li>I had to write python scripts to enable the data ingestion.</li><li>In production, the python scripts will be deployed to a Function as a Service (FaaS) (such as Google Cloud Function) and a cloud scheduler enabled on the function or one can use Airflow to orchestrate the workflow. This makes both the full data ingestion and incremental data ingestion a batch data ingestion. (data ingestion happens at specified intervals).</li></ol><p>What if</p><ol><li>I didn’t have to write a python script to carry out the data ingestion.</li><li>the data ingestion happens in real-time.</li></ol><p>That’s where the change data capture approach comes in.</p><p><strong>Change Data Capture</strong></p><p>As the name suggests, the change data capture approach of data ingestion captures change events (such as inserting new rows, updating existing rows and deleting existing rows) in a source system (such as MySQL) database. It uses messaging system such as Kafka to stream these changes in real-time.</p><p>The source system (such as MySQL) produces these change events to a Kafka topic.</p><p>The sink system (such as BigQuery) consumes the change events from the Kafka topic to complete the data ingestion process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Co9d78GqMNiUuWJXbEq_A.jpeg" /><figcaption>a simple architecture of data ingestion using change data capture</figcaption></figure><p>There are two types of change data capture:</p><p><strong>Log-based CDC</strong></p><p>In log-based CDC, change events in the source system are captured from the log. MySQL has the binary log (binlog) and PostgreSQL has write-ahead logging (WAL) from which change events in the database will be captured.</p><p>Debezium is a popular open-source distributed platform for log-based CDC. It’s built on top of Confluent Kafka services :</p><ol><li>Apache Kafka: is a distributed streaming platform</li><li>Apache Zookeeper: manages the distributed environment and handles configuration across each service.</li><li>Apache Kafka Connect: is used to connect Kafka with other systems so data can be easily streamed via Kafka.</li></ol><p><strong>Query-based CDC</strong></p><p>In query-based CDC, change events in the source system database are captured from queries. Queries as specified are executed against tables in the database.</p><p>In the last part of this series, I will demonstrate the log-based change data capture approach to data ingestion.</p><p>Thank you for reading.</p><figure><a href="https://www.buymeacoffee.com/Oladayo"><img alt="" src="https://cdn-images-1.medium.com/max/423/1*ixLGNDdLtLJcxypBthJzRA.png" /></a></figure><p><strong>References</strong></p><p>Data Pipeline Pocket Reference by James Densmore (<a href="https://www.amazon.com/Data-Pipelines-Pocket-Reference-Processing/dp/1492087831">Get it here</a>)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce8aaa594ff9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Ingestion (Incremental Data Ingestion)]]></title>
            <link>https://medium.com/codex/data-ingestion-incremental-data-ingestion-ee9bc8e1f865?source=rss-93855656ee5f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee9bc8e1f865</guid>
            <category><![CDATA[data-ingestion]]></category>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Oladayo]]></dc:creator>
            <pubDate>Wed, 15 Mar 2023 11:01:33 GMT</pubDate>
            <atom:updated>2023-03-27T10:45:41.631Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi Everyone,</p><p>Welcome to the second part of the four-part series on data ingestion. You can read the first part <a href="https://medium.com/codex/data-ingestion-full-data-ingestion-78f0dad296e9"><strong>here</strong></a><strong>.</strong></p><p>In this post, I will be going over the incremental data ingestion approach and demonstrate the approach by ingesting data from a table in MySQL (source system) to a table in BigQuery (destination system) using an <a href="https://github.com/0ladayo/data-ingestion/blob/master/Incremental%20Data%20Ingestion/Incremental%20Ingestion.ipynb">incremental data ingestion script </a>(a python script)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nek4ksBl215q-IcF1yOroQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@ajonesyyyyy?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Aaron Jones</a> on <a href="https://unsplash.com/photos/IJbfutoo7_U?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><strong>Incremental Data Ingestion</strong></p><p>In an incremental data ingestion approach, any time the <a href="https://github.com/0ladayo/data-ingestion/blob/master/Incremental%20Data%20Ingestion/Incremental%20Ingestion%202.ipynb">incremental data ingestion script runs</a>, it reads only new data records that have been added to the specified table in a MySQL database since its previous run. The new data records are then appended to the specified table in a BigQuery dataset.</p><p>Trying to use this approach means that there has to be;</p><ol><li>A timestamp column in the specified table in a MySQL database. The timestamp for each data record row should be the time the data record was added to the table.</li><li>A table in BigQuery that stores the latest timestamp in the source system table on each run of the script. Every subsequent run of the script overwrites the previous table. The data stored in this table will be used in reading only the newly added (incremental) data records in the specified table in MySQL.</li></ol><p>Now, let’s demonstrate the incremental data ingestion in steps;</p><p>*Note: I have already dropped the database, tables and dataset we used in the full data ingestion demonstration.</p><ol><li>Let’s create a database named ‘demo’, select the database and create a table named ‘orders’ with three columns (orderId, orderValue and orderTimestamp) in the database in MySQL.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*2gZu_AMxr8z-wcIYz1qSSA.png" /><figcaption>creating database demo and orders table inside the database</figcaption></figure><p>We created the database named demo, selected the database and created the orders table with three columns named orderId, orderValue and orderTimestamp in the database.</p><p>The orderId column is of the integer data type and can not have a missing record. The first record starts from 1, while each new record after that automatically increments on the previous record by 1. orderId is also the unique identifier for the table.</p><p>The orderValue column is of the float data type. The column can take integer and decimal numerical values as records.</p><p>The orderTimestamp is of the TIMESTAMP data type. By default, the value for each data record is the timestamp at which data was added to the table orders. If an update is made to a data record, the orderTimestamp column changes to the timestamp when the update was made.</p><p>As we can see, when I query the table, it returns an empty set, meaning no records exist.</p><p>2. Let’s insert some random values into table orders.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*dyWC_zfwsnM6DMGjrhHFcQ.png" /><figcaption>inserting random values in the orders table and verifying it</figcaption></figure><p>We have inserted five records into the orders table. When I query the table this time, it returns the records in the table.</p><p>3. Let’s create a dataset named demo in BigQuery</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*CmClDZLA3PBayDEGvMNWQg.png" /><figcaption>creating dataset demo in BigQuery</figcaption></figure><p>4. Let’s create a table named latest_timestamp in the demo dataset in BigQuery. The latest_timestamp table stores the latest orderTimestamp data or value in the orders table in MySQL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/1*sFeMuCWftTWVBhD9ZMiL0w.png" /><figcaption>creating latest_timestamp table in the demo dataset in BigQuery</figcaption></figure><p>5. Next is to run the <a href="https://github.com/0ladayo/data-ingestion/blob/master/Incremental%20Data%20Ingestion/Incremental%20Ingestion.ipynb">ingestion data ingestion (python) script</a>. The script has an explanation of what each cell does.</p><p>6. Let’s check the demo dataset in BigQuery to see if we have a table named orders in it. If yes, let’s query the table</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*DOFswMdHfmZga5fOyDXJpg.png" /><figcaption>orders table with the ingested data in BigQuery</figcaption></figure><p>As shown above, the orders table has been created and querying the table displays the ingested data records.</p><p>We have successfully ingested data from the orders table in MySQL to the orders table in BigQuery.</p><p>7. Let’s also check the latest_timestamp table to see if there is any data in it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HYcsG-MM2PNshUs82Krf3A.png" /><figcaption>latest_timestamp table with the latest orderTimestamp data stored in it</figcaption></figure><p>Querying the data in the table shows we have the latest orderTimestamp data or value stored in it.</p><p>Next is to see what happens when we make changes to the orders table in MySQL. Three (3) SQL syntax account for such changes; INSERT, UPDATE and DELETE.</p><p>Let’s demonstrate that one after the other.</p><ol><li>Let’s add new records to the orders table in MySQL.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*RgDZBFjU4vMaVw9dwh9mDw.png" /><figcaption>updated orders table in MySQL with 2 new records</figcaption></figure><p>In the snapshot above, we inserted two new records with orderId 6 and orderId 7.</p><p>2. Run the <a href="https://github.com/0ladayo/data-ingestion/blob/master/Incremental%20Data%20Ingestion/Incremental%20Ingestion.ipynb">incremental data ingestion script</a> as before.</p><p>3. Let’s check to see what’s in the orders table in BigQuery</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7VjM1lOmw_MmK8-MROhPNA.png" /><figcaption>orders table with the ingested data (updated) in BigQuery</figcaption></figure><p>As shown above, the orders table in BigQuery has data records that exactly match the updated orders table in the source system.</p><p>In incremental data ingestion, new records (created by using INSERT syntax) are captured during the <a href="https://github.com/0ladayo/data-ingestion/blob/master/Incremental%20Data%20Ingestion/Incremental%20Ingestion.ipynb">incremental data ingestion script</a> run and the records are appended to the specified table in the destination system.</p><p>4. Let’s check to see what’s in the latest_timestamp table in BigQuery</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wkulhimbclQB31q7B6Lmmw.png" /><figcaption>latest_timestamp table with the updated latest orderTimestamp data stored in it</figcaption></figure><p>As shown above, the latest_timestamp table has the orderTimestamp data that matches the orderTimestamp for orderId 7 (latest orderTimestamp)in the orders table in MySQL.</p><p>Let’s demonstrate when updates are made to existing data records in the orders table in MySQL.</p><ol><li>Let’s update two existing records in the orders table in MySQL.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*XGLb0_0QR2Qn5jU5FeSLKg.png" /><figcaption>updated orders table in MySQL with two updates made</figcaption></figure><p>In the snapshot above, I updated the orderValue for orderId 1 and orderId 5.</p><p>2. Run the <a href="https://github.com/0ladayo/data-ingestion/blob/master/Incremental%20Data%20Ingestion/Incremental%20Ingestion.ipynb">incremental data ingestion script</a> as before.</p><p>3. Let’s check to see what’s in the orders table in BigQuery.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DTTFE--NkgSv4Ohd56eUHQ.png" /><figcaption>updated orders table in BigQuery</figcaption></figure><p>In the snapshot above, the orders table in BigQuery doesn’t exactly match the orders table in MySQL.</p><p>We have duplicates for orderId 1 and orderId 5 which are the rows that were updated in the orders table in MySQL. I will talk about a fix later.</p><p>Let’s demonstrate when a delete is made to an existing data record in the orders table in MySQL.</p><ol><li>Let’s delete a record in the orders table in MySQL.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*1Fi5Q_YkR_kN5OjIslbFdw.png" /><figcaption>updated orders table in MySQL with 1 deletion made</figcaption></figure><p>In the snapshot above, I deleted the row record for orderId 3.</p><p>2. Run the <a href="https://github.com/0ladayo/data-ingestion/blob/master/Incremental%20Data%20Ingestion/Incremental%20Ingestion.ipynb">incremental ingestion script</a> as before.</p><p>3. Let’s check to see what’s in the orders table in BigQuery.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*ikA9o-tRTk8STigYfjcSYg.png" /><figcaption>updated orders table in BigQuery</figcaption></figure><p>In the above snapshot, the orders table in BigQuery still has a row record for orderId3. This means the delete operation that was carried out on the orders Table in MySQL is not reflected in the orders Table in Big Query.</p><p>In summary, the INSERT operation works fine, the UPDATE operation created duplicates and the DELETE operation is not reflected in the destination table.</p><p>How does one fix this? new additions will be made to the incremental data ingestion script as follows:</p><ol><li>read the incremental data records in the orders table in MySQL into a DataFrame (orders_mysql_df).</li><li>read the orders table in BigQuery into a DataFrame (orders_bq_df).</li><li>read the full data records for the primary key column (orderId) in the orders table in MySQL into a Series (ordersId_mysql).</li></ol><p>To fix the UPDATE operation causing duplicates in the destination table, one will have to:</p><ol><li>check if the primary key (orderId) data records of orders_mysql_df are in the primary key (orderId) data records of orders_bq_df.</li><li>If yes, update the orders Table in BigQuery for such primary key with the new data records in orders_mysql_df.</li><li>If no, append such primary key data records in orders_mysql_df to the orders table in BigQuery.</li></ol><p>To fix the DELETE operation not reflecting in the destination table, one will have to:</p><ol><li>check to see if the primary key (orderId) data records of orders_bq_df are in ordersId_mysql.</li><li>If yes, do nothing.</li><li>If no, it implies that such primary key records has been deleted in the orders table in the source system. Therefore one has to delete such primary key data records in the orders table in BigQuery.</li></ol><p>Making these changes leads to a <a href="https://github.com/0ladayo/data-ingestion/blob/master/Incremental%20Data%20Ingestion/Modified%20Incremental%20Ingestion.ipynb">modified incremental data ingestion script</a>.</p><p>Now let’s see the modified script in action.</p><ol><li>I have truncated the orders table in MySQL and BigQuery.</li><li>Let’s insert the same values as before into the orders table in MySQL with new orderTimestam values.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*BrJOOw_XeQhALm_jCrI8cw.png" /><figcaption>orders table in MySQL with the same values but different orderTimestamp as before</figcaption></figure><p>3. Run the <a href="https://github.com/0ladayo/data-ingestion/blob/master/Incremental%20Data%20Ingestion/Modified%20Incremental%20Ingestion.ipynb">modified incremental data ingestion script</a></p><p>4. Let’s check the data in the orders table in BigQuery</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*j29Wjkb2QcK7F8SOmt8Cjw.png" /><figcaption>orders table in BigQuery</figcaption></figure><p>The orders table in BigQuery has exactly the same data as the orders table in MySQL. We have successfully ingested data from the orders table in MySQL to the orders table in BigQuery using the modified incremental data ingestion script.</p><ol><li>Now, let’s insert new data records, update existing data records and delete a data record in the orders table in MySQL</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*PwHToYdT8jSVGOvU6gyp_A.png" /><figcaption>updated orders table in MySQL</figcaption></figure><p>As shown in the snapshot above, we inserted two new data records with orderId 6 and orderId 7, updated orderValue for orderId 1 and orderId 5 and deleted the data record for orderId 3.</p><p>2. Run the <a href="https://github.com/0ladayo/data-ingestion/blob/master/Incremental%20Data%20Ingestion/Modified%20Incremental%20Ingestion.ipynb">modified incremental data ingestion script</a></p><p>3. Let’s check the data in the orders table in BigQuery</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wMnyWXojr6-uEQWRYEoWTQ.png" /><figcaption>updated orders table in BigQuery</figcaption></figure><p>The updated orders table in BigQuery has the same exact data as the updated orders table in MySQL.</p><p>There are no duplicate data records and a deleted row record in the orders table in MySQL reflected in the orders table in BigQuery.</p><p>In summary,</p><p>Incremental data ingestion is supposed to have better performance when compared with full data ingestion but that only works with INSERT operation.</p><p>When one has to deal with UPDATE and DELETE operations in incremental data ingestion, it introduces a whole new complexity where one has to do primary key matching between the table in the source system and the table in the destination system which in turn defeats the better performance expected.</p><p>In the next part of this series, I will write about the third approach, the change data capture.</p><p>Thank you for reading.</p><figure><a href="https://www.buymeacoffee.com/Oladayo"><img alt="" src="https://cdn-images-1.medium.com/max/423/1*ixLGNDdLtLJcxypBthJzRA.png" /></a></figure><p><strong>References</strong></p><p>Data Pipeline Pocket Reference by James Densmore (<a href="https://www.amazon.com/Data-Pipelines-Pocket-Reference-Processing/dp/1492087831">Get it here</a>)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee9bc8e1f865" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/data-ingestion-incremental-data-ingestion-ee9bc8e1f865">Data Ingestion (Incremental Data Ingestion)</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>