<?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[Apolitical Engineering - Medium]]></title>
        <description><![CDATA[Technical thoughts from the Apolitical engineering team - Medium]]></description>
        <link>https://medium.com/apolitical-engineering?source=rss----3a76c3396db5---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Apolitical Engineering - Medium</title>
            <link>https://medium.com/apolitical-engineering?source=rss----3a76c3396db5---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 17:28:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/apolitical-engineering" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How we use DBT and BigQuery External Connections to easily and reliably warehouse Cloud SQL data]]></title>
            <link>https://medium.com/apolitical-engineering/how-we-use-dbt-and-bigquery-external-connections-to-easily-and-reliably-warehouse-cloud-sql-data-b0f68e873aad?source=rss----3a76c3396db5---4</link>
            <guid isPermaLink="false">https://medium.com/p/b0f68e873aad</guid>
            <category><![CDATA[cloud-sql]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[dbt]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Paddy Alton]]></dc:creator>
            <pubDate>Mon, 22 May 2023 12:16:28 GMT</pubDate>
            <atom:updated>2023-05-22T12:16:27.859Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Like many data teams, we have spent our fair share of time figuring out how to retrieve data from the <em>many</em> places it’s generated and pool it all in one central location — a data warehouse— so that our data can be easily <strong>activated by the business.</strong></p><p><strong>Activation</strong> <strong>of data</strong> may mean</p><ul><li>passing it to a business intelligence tool</li><li>retrieving it for analysis</li><li>using it to train a machine learning model</li><li>sending recombined data back out to the third party tools we use</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PxLnNlaGScbJgh1qzIG-pg.png" /></figure><p>This ‘hub and spoke’ model is in widespread use. There are huge advantages to having up-to-date, reliable data all available in one place, ready to be queried and retrieved with one set of tools. The data warehouse acts as <strong>a central exchange for data.</strong></p><p>If it weren’t for this, any tool we wanted to use to activate our data would have to be compatible with many different data sources.</p><h3>In practice</h3><p>We do a lot of our work in Google Cloud Platform (GCP), which supports a our operations in a variety of ways. Two GCP services are relevant for this article.</p><p>First, GCP operates a popular data warehouse service, <a href="https://cloud.google.com/bigquery"><strong>Google BigQuery</strong></a><strong>. </strong>It’s optimised for data analysis, supports SQL queries, and integrates directly with a wide variety of other tools.</p><p>Secondly, GCP provides a <a href="https://cloud.google.com/sql/docs/introduction"><strong>Cloud SQL</strong></a> service — managed infrastructure that makes it easy to securely and reliably operate relational databases. SQL databases are ubiquitous, acting as the back end for many web applications, including some parts of <a href="https://apolitical.co/home/"><strong>the Apolitical platform</strong></a>.</p><p>If we follow the hub and spoke approach, clearly we <strong>must load data from Cloud SQL into BigQuery.</strong> That way, data from our platform can be combined with data from other systems and used for business intelligence purposes etc.</p><p>How might we do this?</p><p>Historically, we took a standard approach:</p><ul><li>set up infrastructure to reliably run a series of scheduled tasks</li><li>export data from each table in our databases to a file</li><li>load data from the latest file into the warehouse, transforming as needed</li></ul><p>This was simple but reliable. It gave us a daily backup of our data (stored in a third GCP service, the Google Cloud Storage blob-store) and an up-to-date snapshot of each table. There wasn’t a strong business need for fully-fledged change data capture (CDC), but a history of each table was available if needed, as was reasonably fresh (i.e. less than 1 day old) data for each table.</p><h4>What changed?</h4><p>In 2022 we overhauled our data infrastructure, increasing capacity and bringing more order to our data.</p><p>As part of this work, <strong>we introduced </strong><a href="https://www.getdbt.com/"><strong>DBT (Data Build Tool)</strong></a><strong> to our stack.</strong></p><p>This had a number of advantages. By executing data transformation in the warehouse itself, we were able to decouple data loads from data transformation.</p><p>This allowed us to</p><ul><li>store near-raw <em>and</em> fully processed data in BigQuery</li><li>adopt <a href="https://airbyte.com/">Airbyte</a>, speeding up pipeline development (since we removed the need for bespoke transformations in our pipelines, an off-the-shelf option for pipelines became feasible)</li><li>keep better track of data lineage, since all the transformations now occur in one place (DBT and BigQuery both have built-in table-level lineage tools)</li></ul><p>Further,</p><ul><li>common data transformations were captured in version control in a reusable form</li><li>we were able to easily apply more complex transformations to our data tables and therefore create proper data models for different business uses</li></ul><p>In short, DBT enabled a paradigm shift — unlocking many new abilities for our small data team.</p><p><strong>In this article, I will describe one particular way in which DBT allowed us to simplify our data pipelines.</strong></p><h3>Replacing our pipelines with direct connections</h3><p>One other change we took advantage of was the introduction of <a href="https://cloud.google.com/bigquery/docs/connect-to-sql">direct Cloud SQL to BigQuery connections</a> and federated querying.</p><p>By setting up such a connection from BigQuery to our Cloud SQL instances, we can write queries that retrieve data from our SQL databases, via BigQuery. These are known as <strong>federated queries</strong>.</p><p>(as an aside, we in fact configured these connections to target<a href="https://cloud.google.com/sql/docs/postgres/replication/create-replica"> a read replica instance</a> — this is good practice as it means federated queries don’t place any load directly on production databases)</p><p>The syntax for such a query might look something like this:</p><pre>    SELECT<br>        customerId AS customer_id,<br>        customerName AS customer_name,<br>        subscriptionType AS subscription_type,<br>        email,<br>        JSON_EXTRACT_SCALAR(location, &quot;$.countryCode&quot;) AS country_code,<br>        createdAt AS created_at,<br>      FROM<br>        EXTERNAL_QUERY(<br>          &quot;&lt;project-id&gt;.&lt;external-connection&gt;&quot;,<br>          &quot;&quot;&quot;<br>          SELECT<br>              -- double quotes interpreted by postgreSQL as<br>              -- a case-sensitive identifier name:<br>              &quot;customerName&quot;,<br>              -- some postgreSQL types (e.g. UUID, Enum) are not<br>              -- supported by BigQuery, and must be coerced:<br>              CAST(&quot;customerId&quot; AS TEXT),<br>              CAST(&quot;subscriptionType&quot; AS TEXT),<br>              -- other types are handled transparently by BigQuery:<br>              email,<br>              location,<br>              &quot;createdAt&quot;<br>            FROM<br>              customers;<br>          &quot;&quot;&quot;<br>        )</pre><p>Here I have tried to provide a realistic (though fictional) example of how a table called customers in a CloudSQL PostgreSQL database could be read via BigQuery.</p><p>It’s especially salient to discuss the structure of this example:</p><ul><li>there is an inner query (which the reader will note is written in the PostgreSQL dialect) wrapped inside the EXTERNAL_QUERY() expression</li><li>there is an outer query that <strong>selects from</strong> the output of the EXTERNAL_QUERY() expression</li></ul><p>Queries like this can be executed in the same way as a regular query. <strong>That means we can store them as DBT models.</strong></p><h4>What we did</h4><p>We created DBT base models that use the federated query syntax described above.</p><p>By materialising these models as tables, we can create a snapshot of a table in CloudSQL every time DBT is run.</p><p>This effectively recreates the existing warehousing workflow, but in a simpler manner. We don’t need to ensure the scheduled data loads complete before DBT runs, because DBT will handle that for us naturally. The only additional infrastructure is the external connection, which GCP maintains for us.</p><h3>Tradeoffs</h3><p>There are some drawbacks to our approach.</p><p>First, we have elided the distinction between a source table and a base model in DBT.</p><p>Federated CloudSQL queries are not currently supported by <a href="https://github.com/dbt-labs/dbt-external-tables">the dbt-external-tables package</a>, which allows some DBT sources to reference external datasets that the warehouse can directly access. However, this might change in future.</p><p>Secondly, on its own, our approach does not allow us to maintain a history of the external table. DBT supports <a href="https://docs.getdbt.com/docs/build/snapshots">snapshots</a>, which would allow a history of the base model to be captured (but not the source itself).</p><h3>The future</h3><p>We’re keeping an eye on GCP DataStream for BigQuery, <a href="https://cloud.google.com/blog/products/databases/serverless-replication-of-operational-data-into-bigquery">which became generally available</a> not long before this article was written.</p><p>DataStream promises to replicate data directly into BigQuery continuously (rather than in batches) and to provide a built-in, exact history of changes to source data.</p><p>As a fully-managed service, this would be similarly straightforward to set up and use as our federated query approach. Furthermore, such a deployment would cleanly separate raw, source tables from base models.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0f68e873aad" width="1" height="1" alt=""><hr><p><a href="https://medium.com/apolitical-engineering/how-we-use-dbt-and-bigquery-external-connections-to-easily-and-reliably-warehouse-cloud-sql-data-b0f68e873aad">How we use DBT and BigQuery External Connections to easily and reliably warehouse Cloud SQL data</a> was originally published in <a href="https://medium.com/apolitical-engineering">Apolitical Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Modelling for Startups (Part III)]]></title>
            <link>https://medium.com/apolitical-engineering/data-modelling-for-startups-part-iii-aca31e0f4176?source=rss----3a76c3396db5---4</link>
            <guid isPermaLink="false">https://medium.com/p/aca31e0f4176</guid>
            <category><![CDATA[data-infrastructure]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[data-modeling]]></category>
            <category><![CDATA[data-modelling]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Paddy Alton]]></dc:creator>
            <pubDate>Mon, 15 May 2023 12:05:16 GMT</pubDate>
            <atom:updated>2023-05-19T22:31:27.790Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This is the final article in a three-part series.</em></p><h3>Introduction — data in practice</h3><p>Over the last five years at <a href="https://apolitical.co/home/">Apolitical</a>, the global platform for government, I and my team had the chance to do something exciting: to build up the company’s data infrastructure and systems from scratch. In this trilogy of articles I’m taking the time to reflect on that experience.</p><p><a href="https://medium.com/apolitical-engineering/data-modelling-for-startups-part-i-f566af2a88ca">In the first article</a> of the series I discussed data modelling theory and why data modelling is worthwhile.</p><p><a href="https://medium.com/apolitical-engineering/data-modelling-for-startups-part-ii-1b1fa58700e4">In the second article</a> I focused on infrastructure. In particular, I discussed how modern tools allow small teams to quickly set up a chain of infrastructure to extract data from sources, load it into a data warehouse, transform it into data models, and serve it via a business intelligence tool.</p><h3>Putting it together</h3><p>I now want to bring together the first article (which discussed data modelling in theory) with the second, which covered the <em>prerequisites</em> for doing data modelling as a startup.</p><p>First, a warning:</p><h4>Don’t try to do everything at once</h4><p>If you try to make everything perfect you’ll be at it <em>forever — </em>without anyone seeing any benefit.</p><p>Worse (and this is especially relevant to startups): the data in your source systems is <em>liable to change</em>. If you yourself don’t have full control over the source data, you’re eventually going to need some processes to govern these changes. But there is no point trying to design that framework and getting everyone to abide by it up-front: <strong>you need to give people a source of value <em>before</em> you put in place processes to <em>protect</em> that source of value</strong>.</p><p>So: talk to senior business leaders (or, if you are one, have yourself a good think). You need to identify the areas where the business wants to improve.</p><p>Once you’ve figured that out, here’s what you do …</p><h3>A bold advance</h3><p>The point of data modelling is to morph data into a form that</p><ul><li>matches business intuition about how things are</li><li>can be readily consumed by BI tools and/or data analysts</li><li>acts as a single source-of-truth</li></ul><p><em>In this section I’m going to assume you have set up your data warehouse and identified a BI tool you could use immediately on data in that warehouse.</em></p><h4><strong>Setting a course</strong></h4><p>We want to find a <em>business process</em> that the company lacks insight into, where that insight would help the company to make important decisions.</p><p>(not ‘understand the landscape better’; not ‘give us some insight into how things are going’; <em>make decisions.</em>)</p><h4><strong>Planning a data model</strong></h4><p>Once you’ve identified such a process, you can model all the data related to it. First, you need to have a chat with whomever is the (closest thing to an) <em>owner</em> of that process. This is important because you need to understand how that person sees the business. It’s <em>their </em>intuition your data model needs to match.</p><p>Relating this back to the first article in the series, perhaps you choose to model the company’s sales data, and your stakeholder affirms that they need to understand sales broken down by time period and attributes of customers and products:</p><figure><img alt="A blue square labelled ‘Sales’ is surrounded by three red squares labelled customers, products, and dates. Arrows point from these to the central blue square." src="https://cdn-images-1.medium.com/max/713/1*cVrSOAcqZkKiYe_om-b69w.png" /><figcaption>N.B. you may not need a ‘dates’ table if your BI tool can handle that for you. Most will.</figcaption></figure><p>You may to have guide them through this process. One way to do that is to ask them for a list of open questions that are on their mind, and then talk to them about how the answers would help them to make business decisions (for example, where to spend money on advertising).</p><p>So, we have a target data model — we need a fact table to capture the business process (the completion of sales) and we need dimension tables to slice-and-dice that data.</p><h4><strong>What are you working with?</strong></h4><p>Next, you need to inventory the various data assets that exist in source systems that are related to your data models:</p><ul><li>where are data about customers and products stored? A database? Different databases? A CRM system?</li><li>where are data about sales stored? A payment provider? A database you control?</li></ul><p>(if you don’t have the assets you need, you need to have a data engineering conversation before anything else, and you may need to get on with some other data modelling project while that proceeds)</p><h4><strong>Centralising</strong></h4><p>The point of figuring out what data is available and where it resides is that you need to <em>figure out how you will get it into your data warehouse</em>.</p><p>For example, with BigQuery it’s actually possible to bring in data from Cloud SQL and Google Analytics 4 without <em>any</em> third-party tools or bespoke code.</p><p>For other sources — especially things like payment providers and CRMs — you may not be able to create a direct connection and will need to set something else up. This is usually the point to try out some managed pipeline tools.</p><p>(N.B. you can/should pick a managed pipeline tool based on whether they support the sources you actually have! You may need to have a few more conversations with stakeholders to figure out what sources you might need to accommodate later.)</p><p>Whatever you do, the key thing is to get as much relevant data into the warehouse as you can <em>without</em> spending obscene amounts of time on it.</p><h4><strong>Modelling</strong></h4><p>Remember, the point of landing data in your warehouse in close-to-raw form and doing the transformation <em>in situ</em> with SQL is that you can always quite easily <em>change</em> how the transformation is done. So don’t sweat this bit too much.</p><p>You can do the first version of your first model with SQL views or scheduled queries (if your warehouse supports them and if it’s easier than setting up DBT). Or you can set up DBT (<a href="https://dataform.co/">alternatives</a> are <a href="https://sqlmesh.com/">available</a>) and take a little longer initially, in exchange for less messing around later.</p><p>It’s best to create models via a few separate steps. DBT <a href="https://docs.getdbt.com/guides/best-practices/how-we-structure/1-guide-overview">best practices</a> suggest (for good reason) that you consider creating data models in three stages:</p><ol><li>base/staging models apply light cleaning and tidying to your incoming source tables (e.g. renaming columns, removing invalid rows and irrelevant columns, changing data types by parsing dates etc.)</li><li>intermediate models apply key transformations (combining related base tables into fewer, less-normalised tables, pivoting base tables with key/value columns</li><li>fact and dimension tables built by combining intermediate models into a form that matches the business understanding of the data</li></ol><p>Here is an updated diagram of the full system, reflecting this multi-stage transformation:</p><figure><img alt="A diagram showing data flowing from source, via pipelines, to a warehouse; then being transformed into data models in the warehouse in stages (raw to base to intermediate to models) using a data transformation tool; then being read out of the warehouse into a business intelligence tool." src="https://cdn-images-1.medium.com/max/973/1*H9sAyTuqEGMn7hRU3erUkg.png" /></figure><p>If you do it this way, you will tend to find that you spend less time copy/pasting SQL, because you can reuse the base and intermediate models.</p><p>Remember, dimension tables need a unique ID. If there isn’t an existing unique ID a <strong>surrogate key</strong> should be created. This is done by <a href="https://dataspace.com/big-data-applications/what-does-it-mean-to-hash-data/">hashing</a> (combinations of) <em>immutable</em> attributes that together uniquely identify the entity represented by the table.</p><p>(for this purpose, I found the generate_surrogate_key macro provided by <a href="https://github.com/dbt-labs/dbt-utils">the dbt-utils package</a> invaluable)</p><p><strong>An example</strong></p><p>It may help to recap what we’ve covered so far with an example. Let us imagine we have three source systems holding relevant data:</p><ol><li>SQL database (holds customer and product data)</li><li>CRM system (holds customer data)</li><li>Payment provider (holds customer, product, and sales data)</li></ol><p>We then set up off-the-shelf data pipelines and land tables from these three systems in our warehouse. We call these ‘source tables’.</p><p>Next we define DBT models:</p><ul><li>the base models simply capture the source tables with irrelevant data dropped, consistent naming conventions applied, and some parsing of data implemented— models are grouped by source system</li><li>the intermediate models combine data from different sources and denormalise the SQL schema as needed, executing joins to create tables related to customers, products, and sales</li><li>finally, three dimension tables (customers, products, dates) and one fact table (sales) are assembled</li></ul><p>These DBT models are then materialised on schedule in the warehouse.</p><h4><strong>Analysis</strong></h4><p>The above setup ensures that</p><ul><li>reasonably fresh data will always be available</li><li>data will be in a form that matches the business understanding of the data</li><li>there is a single source-of-truth for the data</li></ul><p>At this point you want to load the data into your data visualisation tool and bring your stakeholder back into the room — they are the person best-placed to interrogate and take action based on the data, after all.</p><p>The best outcome at this stage is that</p><ol><li>you are able to quickly answer many of their immediate questions</li><li>you can pick a few charts that will make a good dashboard (much like a car dashboard, a good business dashboard is one whose contents are readily actionable: think ‘refill engine oil’, not ‘inspiring quotes on a stock photo’)</li><li>you leave with a big pile of <em>new</em> questions that your model can’t answer (yet)</li></ol><p>That last one is important. I entitled this section ‘<strong>a bold advance</strong>’ because we leapt forward, delivering a specific piece of value in one narrow ‘vertical’.</p><figure><img alt="Systems are stacked in layers, with business intelligence at the top, data warehouse/transformation in the middle, and pipelines/source systems at the bottom. Arrows show the flow of information up into the BI layer. The diagram makes clear that there are other source systems that haven’t been used yet, and room for plenty more data models to be built." src="https://cdn-images-1.medium.com/max/480/1*Q5tpNQ47t-TeRiTbUPNJvA.png" /><figcaption>Building out a vertical. There’s plenty of room to grow sideways.</figcaption></figure><p>The thing to do <em>next </em>is to work with your stakeholder to iterate your models, to grow them out <em>horizontally </em>— i.e. add new pipelines for other source tables, expand the models, add new facts and dimensions, create new charts and reports.</p><h3>The future</h3><p><strong>In the short term</strong>, you now have business-ready definitions of customers, products, and sales. It seems likely you can reuse those later. We often refer to a collection of related data models as a ‘<strong>data mart</strong>’ (figuratively: a market stall for a certain kind of data). This is what you build via that process of horizontal iteration.</p><p>You should be sure to spend at least some time with your first stakeholder, iterating and growing their models — you want to ensure they are happy with what you’ve delivered!</p><p>That said, you need to follow the 80/20 principle: <strong>20% of the effort needed to make it perfect will get your stakeholder 80% of the available value</strong>. Eventually you need to move on to other areas where there is high urgency, high impact work to be done.</p><p><strong>In the medium term</strong>, you can start talking to other stakeholders — you now have a case-study for what you can do for them, and the infrastructure in place to do it faster. You can follow the same prioritisation process as before.</p><p><strong>And then the trouble will start.</strong></p><h3>What will go wrong?</h3><p>If you’ve followed the plan so far, you’ve put yourself in a good position. Multiple areas of the business are now being served high quality, consistent data that helps your colleagues to be more effective at their jobs. <em>So much so </em>that they now <em>rely</em> on their data, the reports and dashboards you’ve built.</p><p>So what happens when it breaks?</p><p>There are a bunch of reasons why this can happen. Broadly speaking, they fall into three categories:</p><ul><li>change to the source data</li><li>infrastructure failure</li><li>data modelling bug/failure to understand the source data</li></ul><p>Different sorts of problem require different sorts of tactics.</p><h4>Change to the source data</h4><p>A data pipeline is only as good as the source. There are lots of potential problems lurking:</p><ul><li>expired access credentials</li><li>dataset moves/is renamed</li><li>dataset schema changes (columns deleted/renamed, data type changes)</li><li>previously unencountered values added to dataset (that your pipeline — or BI tool! — can’t handle)</li></ul><p>If your pipeline is a ‘pure’ pipeline that doesn’t do any nonessential transformation, you at least decouple potential data modelling problems from the above.</p><p>How can you fix these problems? Usually prevention is better than a cure, but you’ll be called on to do both.</p><p><strong>Prevention:</strong> talk to the people in charge of the source systems! You may be able to protect the source system from unexpected changes through a combination of access controls and processes, but you need to make sure the stewards of those systems understand why those controls and processes are important. <em>Try to get them to involve you at the planning stage when there are changes to be made to the source.</em></p><p>You may even be able to get tests put into the system that run at the point-of-deployment and that ensure certain guarantees will be met (essentially, unit tests for data production).</p><p><strong>Cure:</strong> you want to avoid picking up pipeline problems after a week when someone realises their report is broken.</p><p>You should consider adding monitoring and alerting to your pipelines so that you get a warning as soon as it breaks. Many off-the-shelf tools come with such capabilities built in.</p><p>For a low-lift approach: DBT itself ships with data tests and source freshness tests. So if you’re using it (or a tool with similar capabilities) you can</p><ul><li>check that your source datasets (as landed in your warehouse) are as fresh as you expect (this can catch pipeline problems)</li><li>check that the data matches your expectations (e.g. no null values, only certain categorical values in a column, only unique values in a column)</li></ul><h4>Infrastructure failure</h4><p>There may be nothing wrong with the source data, but the infrastructure may just let you down.</p><p>I’ve tried to head this off by suggesting you avoid managing too much of it yourself (although vendors can also let you down …) — at least at first. Monitoring and alerting is the solution here, too.</p><h4>Data modelling bug</h4><p>Or alternatively, ‘<em>failure to understand the source data</em>’.</p><p>This occurs when</p><ul><li>your pipelines deliver all the data to your warehouse on time without experiencing any failures</li><li>the automated checks you’ve put in place all pass, suggesting everything should be fine</li><li>but an angry stakeholder <em>still</em> comes to you with a broken report!</li></ul><p>This can be related to the issue of encountering new, unhandled data values, if you didn’t exclude dangerous values via your tests.</p><p>Alternatively, maybe that source table doesn’t <em>quite </em>represent what you think it does, and maybe that only becomes clear under certain circumstances (is there <em>really</em> a 1–1 relationship between customers and delivery addresses?)</p><p><strong>Prevention:</strong> take a good long look at that source system, chat to whomever owns it, and make sure you understand how it’s being used/how it will be used in future. In other words: it pays to put in effort when you’re building the models.</p><p><strong>Cure:</strong> tweak the data model (tools like DBT make this easy) to reflect your new understanding. If you’re lucky, the multiple layers of transformation will allow you to keep the structure of your actual data models the same, with the tweaks made to base and intermediate model. If so, you won’t have to update your actual reports.</p><h3>The future (redux)</h3><p>To recap:</p><ul><li>short term: iterate, build out a data mart</li><li>medium term: engage new stakeholders and start building marts for them; start implementing data management tooling and processes</li></ul><p>What about the <strong>long term</strong>?</p><p>If all goes well, you should be able to keep building out new marts while providing reasonable guarantees about data availability.</p><p>Naturally, success brings new problems — as the organisation scales, and the data models grow in numbers, you may encounter discoverability problems. How do people know what datasets are available? What the lineage of your data models is? How they ought to query those models? And so on.</p><p>The way to mitigate this is simple: <strong>documentation</strong>. As you build your data systems and models, you should document them so that others can get up to speed quickly.</p><p>As well as centralised documentation, the tools you choose may well have some built-in ability to document aspects of the data. Some examples:</p><ul><li>DBT comes with a built-in lineage view and a documentation UI</li><li>BigQuery now has a lineage view revealing where data came from</li><li>many BI tools allow you to add some level of documentation</li><li>GCP has a separate tool, <a href="https://cloud.google.com/dataplex">Dataplex</a>, that is interoperable with BigQuery and supports your defining data dictionaries and associating entries with BigQuery tables</li></ul><p>It’s important to try to keep on top of this as you go. At first, you’ll only need minimal documentation, but as your data models become more complex, the need will grow.</p><h3>Conclusion</h3><p>So there it is — a large number of lessons learnt (some painfully) distilled into three chunky articles.</p><p>We’ve covered</p><ul><li><a href="https://medium.com/apolitical-engineering/data-modelling-for-startups-part-i-f566af2a88ca">what data modelling is and why you need to do it</a></li><li><a href="https://medium.com/apolitical-engineering/data-modelling-for-startups-part-ii-1b1fa58700e4">how to set up some ‘minimum viable infrastructure’</a> to help you deploy and use data models</li><li>how to put it into practice, with examples and pitfalls (this article)</li></ul><p>This series has by no means covered everything — it was tough to decide what to leave out — and nor should it try. In the end there’s no substitute for practical experience. However, I hope that these articles will point you in the right direction. Good luck on your own data journey!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aca31e0f4176" width="1" height="1" alt=""><hr><p><a href="https://medium.com/apolitical-engineering/data-modelling-for-startups-part-iii-aca31e0f4176">Data Modelling for Startups (Part III)</a> was originally published in <a href="https://medium.com/apolitical-engineering">Apolitical Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Modelling for Startups (Part II)]]></title>
            <link>https://medium.com/apolitical-engineering/data-modelling-for-startups-part-ii-1b1fa58700e4?source=rss----3a76c3396db5---4</link>
            <guid isPermaLink="false">https://medium.com/p/1b1fa58700e4</guid>
            <category><![CDATA[modern-data-stack]]></category>
            <category><![CDATA[data-infrastructure]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[data-modeling]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Paddy Alton]]></dc:creator>
            <pubDate>Mon, 15 May 2023 12:04:10 GMT</pubDate>
            <atom:updated>2023-05-15T12:07:52.125Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This is the second article in a three-part series.</em></p><h3>Introduction — data infrastructure</h3><p>Over the last five years at <a href="https://apolitical.co/home/">Apolitical</a>, the global platform for government, I and my team had the chance to do something exciting: to build up the company’s data infrastructure and systems from scratch. I’m taking the time, in this trilogy of articles, to reflect on that experience.</p><p><a href="https://medium.com/apolitical-engineering/data-modelling-for-startups-part-i-f566af2a88ca">In the first article</a> I discussed</p><ul><li>what data modelling is</li><li>why it’s worth doing</li><li>some of the thornier issues you’ll encounter in the real world</li></ul><p>In short: I covered some essential information for those new to data modelling.</p><p>In this second part, I want to move on to talk about <strong>infrastructure</strong>. When you’re starting from scratch, what do you need to build in order to create data models as quickly as possible and start deriving benefit from them?</p><p><a href="https://medium.com/apolitical-engineering/data-modelling-for-startups-part-iii-aca31e0f4176">In the third and final article</a> I will draw these two strands together, offering examples and practical advice.</p><h3>Why are we here?</h3><p>The goal of your efforts is to take the data the company collects, and use it to inform business decision-making so that the company can achieve its objectives.</p><p>If you come to this with <em>nothing</em> already in place, you might feel as though you’ve been given a plan like this:</p><ol><li>data in source databases</li><li>???</li><li>business insights!</li></ol><p>Let’s talk about how we fill out that bit in the middle.</p><h4>Let me give you some advice…</h4><p>Here’s the most important thing to remember: <strong>you need to deliver value continuously, from the beginning.</strong></p><p>It’s no good planning a big project to set up the perfect system and <em>then</em> help the business. The company needs to see value in weeks, not months.</p><p>Fortunately, modern tools give us a way to achieve this.</p><h3>The modern data stack</h3><p>You’re going to hear a lot about ‘the modern data stack’, and for good reason — new approaches allow small teams to do so much more than would have been possible in the past.</p><p>But what <em>is</em> the modern data stack? Put simply, it is a collection of cloud-based tools that, working together, bridge that gap in your plan!</p><p><a href="https://www.moderndatastack.xyz/categories">There are loads of options</a> for the different parts of your stack, and some of those parts are optional. Here is what I think you need for a ‘minimum viable stack’:</p><figure><img alt="A diagram showing data flowing from source, via pipelines, to a warehouse; then being transformed into data models in the warehouse by a data transformation tool; then being read out of the warehouse into a business intelligence tool." src="https://cdn-images-1.medium.com/max/932/1*W50b_-0xS5XI0u-ZHWriSw.png" /></figure><p>This is the order in which I suggest you set them up:</p><ol><li>a data warehouse (this is the heart of the system)</li><li>a pipeline tool (a way of loading data from your source systems into your warehouse)</li><li>a business intelligence/data visualisation tool</li><li>a data transformation tool (convert raw data into data models)</li></ol><p><strong>Let’s unpack that.</strong></p><p>First, a note: I won’t tell you what the best options to use are, because I don’t know! Things move fast. Also, your organisation may have already made some technical choices that dictate what you do. But I <em>will </em>tell you what we use.</p><h4>Data Warehouse</h4><p>At Apolitical, Google <a href="https://cloud.google.com/bigquery">BigQuery</a> is our data warehouse. Most <a href="https://dgtlinfra.com/top-10-cloud-service-providers-2022/">cloud providers</a> have some sort of data warehouse solution: AWS has Redshift, Azure has Synapse, and GCP has BigQuery. We use GCP, so we went with BigQuery.</p><p>Often, people will consider a third party solution separate to what cloud providers offer (e.g. <a href="https://www.snowflake.com/en/">Snowflake</a>, <a href="https://www.databricks.com/">Databricks</a>) to avoid vendor lock-in and get improved functionality; this will increase costs. In our case BigQuery suits our needs.</p><p>The data warehouse is the first thing you set up, because you need a central location to store all your data. The idea is this: by combining data from different source systems, you make it much easier to analyse. Combining data from, say, a backend database and a CRM tool becomes a matter of a SQL join between two tables in the warehouse, rather than a complex script that pulls directly from both sources.</p><p>A data warehouse should be optimised for crunching analytical queries. If you see the terms ‘columnar database’ or ‘OLAP database’ get thrown about, that is all they mean: a database that’s optimised for processing a column of data (e.g. computing aggregates).</p><p>(that’s the opposite tradeoff to a typical SQL — ‘OLTP’ — database, which is optimised for retrieving a <em>row</em> of data)</p><p>You <em>could</em> self-host your data warehouse, but I’d advise against it. This isn’t the place to cut corners. You’ll create a maintenance nightmare because</p><ul><li>all your other tools have to be compatible with your warehouse</li><li>you have to worry about things like storage capacity</li><li>it’s likely to be less robust than a fully-managed solution</li></ul><p>In any case, <a href="https://cloud.google.com/bigquery/pricing">last time I looked</a>, BigQuery had a free tier that allowed for up to 10GB of free storage + 1TB of total data processed per month, which may be enough for your purposes.</p><h4>Pipeline Tool</h4><p>Once you’ve got somewhere to put your data, you need to get it in there.</p><p>Naturally, it’s not enough to do it once! You need a tool that will pull data out of your source systems and put it into your warehouse either <em>regularly</em> or <em>continuously</em>.</p><p>Continuous data ingestion is ideal, but often (not always) more complicated than regularly loading batches of data into the warehouse. You should have a quick think about your business requirements. Often it’s enough for data to be at most a day old: a daily load job is sufficient.</p><p>There are a few approaches that work well for startups (in my order of preference):</p><ul><li>built-in connections between source systems and warehouses</li><li>an off-the-shelf solution (fully managed or self-hosted)</li><li>‘serverless’ code set up to listen to a webhook</li><li>simple scripts running in a cloud scheduler</li></ul><p>I’ve used all of these approaches at various times, but most recently we adopted <a href="https://airbyte.com/">Airbyte</a>, which falls into the second category. I would recommend something like Airbyte (or its competitors, such as <a href="https://www.fivetran.com/">Fivetran</a>) if</p><ul><li>your data isn’t that ‘big’ (Gigabytes, not Terabytes)</li><li>your data is split across a lot of different sources</li><li>there isn’t a built-in connection between the source system and your warehouse</li></ul><p>Naturally if you are paying for pipelines, your provider will have their own margin to consider. An advantage of an open-source system like Airbyte is that you can self-host (which is what we do). You’re still paying for compute (and for engineering time to set up and maintain the self-hosted version), but it can make economic sense to move to self-hosting later. The tradeoff of self-hosting is that you can’t expect any customer support.</p><p><strong>An aside about data transformation</strong></p><p>In a <em>traditional</em> data stack, your pipeline tool and transformation tool might be the same thing. And you might be tempted to take that approach, rather than set up two different systems.</p><p>This is especially true if you ended up writing your own pipeline code. Here is how it will happen: your data won’t be ready for use in its raw form, so you may think<em> “I have this script that extracts data from source systems and loads it into the warehouse, and the script does a bit of tweaking for compatibility reasons … so why don’t I just tweak it a bit more?”</em></p><p>This will work! You absolutely <em>can</em> transform data inside your pipelines, executing joins, applying filtering etc. to get it into a usable form. That’s ETL.</p><p>However, I can tell you right now that eventually you’ll have to <em>change</em> how those transformations work. It’s a fact of life. And when you <em>do</em> make that change, you may find it harder than you’d like to apply the transformation to all your historic data. For example, what if you load a batch of data every day? All the old batches will have had the old logic applied. You’d need to reload all of them with the new transformation logic — a backfill.</p><p>That’s why the ‘modern’ approach (ELT) is to land the data in a close-to-raw form and transform inside the data warehouse. <strong>You don’t necessarily need a special tool to do that, though!</strong> A warehouse such as BigQuery allows you to</p><ul><li>define <em>views</em>, which are essentially saved SQL queries masquerading as a table</li><li>create saved queries that run on a schedule (and which can do things like create/overwrite tables)</li></ul><p>This means you have built-in ways to use SQL to transform raw data into useful models. I’m going to go out on a limb and suggest you may even <em>want </em>to do it that way, at least for a few weeks or months.</p><p>But eventually you will run into the same problem that everyone does: the colossal tower of views collapses into spaghetti. More on that in a moment, when I talk about transformation tools …</p><h4>Business intelligence tool</h4><p>My suggestion here is that you start out with something free, if you can.</p><p>In the early days, we used <a href="https://colab.research.google.com/">Colab notebooks</a> to create analyses and visualisations. We still use this for our data science work: shareable Python code that runs the same for everyone, that can include documentation, and that can be version-controlled? It’s a good option.</p><p>However, you <em>will</em> find yourself reusing a lot of code, and you need people who can write Python, and many less-technical colleagues are not going to enjoy being sent a sharing link for a notebook.</p><p>For a long time we used <a href="https://lookerstudio.google.com/">Looker Studio</a> (<em>née</em> Google Data Studio), because</p><ul><li>it’s a lot friendlier for less-technical colleagues</li><li>it integrates out of the box with BigQuery, so getting started was <em>fast</em></li></ul><p>For example, you can write custom SQL to pull data into the report, then (when you’re happy with the report) put that SQL into a BigQuery view and connect to that instead. The view can then be reused.</p><p>These days, we use <a href="https://www.thoughtspot.com/">ThoughtSpot</a> — a self-serve business intelligence tool. Self-serve tools such as ThoughtSpot (or <a href="https://www.lightdash.com/">Lightdash</a> if you want an open-source, self-hostable alternative) are certainly an interesting approach for data-hungry startups … but make sure your data are well-modelled (see the other articles in this series!) before you even <em>think</em> about adopting one.</p><h4>Data transformation tool</h4><p>So, why do you need this? Let’s say you took my advice so far. You</p><ul><li>set up a fully-managed data warehouse</li><li>connected some of your sources directly and implemented managed pipelines for the others</li><li>hooked up a data visualisation tool that suits your needs</li><li>started building SQL views/saved queries to turn your raw data into a form that works for your purposes</li></ul><p>The problem is, the last step is <em>ongoing</em>. You get new requests for data all the time. Soon there’s a tonne of views — there’s duplication of SQL everywhere, everything’s interdependent and hard to change, and if you make a bad change it’s hard to fix.</p><p>But this should be a solved problem! All of those issues apply to regular software, and we have tools and processes that address them. This is where data transformation tools come in.</p><p>At Apolitical, <a href="https://www.getdbt.com/">we use DBT</a> to</p><ul><li>define our data models using (templated) SQL captured in version control</li><li>materialise all our data models as tables on a regular schedule</li></ul><p>(We could have used BigQuery <em>views</em> instead of <em>tables</em> to materialise our models. Because views execute the SQL in their definition at the point you query them, this would improve <em>data freshness</em> but impact <em>query latency</em>; for us, the latter is more important.)</p><p>DBT has an advantage for startups in that it’s another of those tools where the fully-managed platform can be replaced by a self-hosted version (in which case it instead costs you in compute, engineering time, and not having customer support). Increasingly, you will find that BI tools are designed to integrate with DBT as well as your warehouse, which can reduce friction.</p><p>I recommend that if you do adopt DBT, you take some time to read <a href="https://docs.getdbt.com/guides/best-practices/how-we-structure/1-guide-overview">their guide</a> to structuring a DBT project. Remember, we’re trying to impose order on chaos here! You may also want to read <a href="https://docs.getdbt.com/blog/kimball-dimensional-model">their blog on data modelling with DBT</a>, which pairs well with the first article in this series.</p><h3>How does that stack up?</h3><p>There are a bunch of choices to be made here, mostly around cost vs. speed.</p><p>If you’re willing to pay for the fully-managed versions of all these services, you could have the whole stack up and running (in a minimal way) in less than a week!</p><p>You can still move pretty fast, while spending less money, if you have the technical skills to self-host the various parts of the stack — but bear in mind that</p><ul><li>the stack is <em>modular</em></li><li>the stack is only useful when you have <em>all the parts </em>in place</li><li>your time is also money</li></ul><p>So, if you can afford it, it’s better to get things up and running quickly and then switch out the most expensive parts as you go along. If you’re worried about costs, you may wish to focus on open-source options that you could move to self-hosted if need be.</p><h3>Conclusion</h3><p><a href="https://medium.com/apolitical-engineering/data-modelling-for-startups-part-i-f566af2a88ca">In the first article</a> in this series, I explained why data modelling is important and covered the theory behind it. All the theory in the world is useless if you don’t have a way to put it into practice. In this article I’ve focused on how you can get into a position to run an effective business intelligence operation as quickly as possible, without compromising on the basic approach.</p><p><a href="https://medium.com/apolitical-engineering/data-modelling-for-startups-part-iii-aca31e0f4176">In the next article</a>, I will draw these two threads together, showing you how you can deliver value quickly and continuously using the modern data stack and data modelling.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b1fa58700e4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/apolitical-engineering/data-modelling-for-startups-part-ii-1b1fa58700e4">Data Modelling for Startups (Part II)</a> was originally published in <a href="https://medium.com/apolitical-engineering">Apolitical Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Modelling for Startups (Part I)]]></title>
            <link>https://medium.com/apolitical-engineering/data-modelling-for-startups-part-i-f566af2a88ca?source=rss----3a76c3396db5---4</link>
            <guid isPermaLink="false">https://medium.com/p/f566af2a88ca</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-modeling]]></category>
            <category><![CDATA[data-modelling]]></category>
            <category><![CDATA[startup]]></category>
            <dc:creator><![CDATA[Paddy Alton]]></dc:creator>
            <pubDate>Mon, 15 May 2023 12:03:17 GMT</pubDate>
            <atom:updated>2023-05-15T12:26:08.515Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This is the first article in a three-part series.</em></p><h3>Why read these articles?</h3><p>Over the last five years at <a href="https://apolitical.co/home/">Apolitical</a>, the global platform for government, I and my team had the chance to do something exciting: to build up the company’s data infrastructure and systems from scratch.</p><p>Always a small team, we had to keep it lean — building only what was necessary to get the job done at the time. As the company has matured, so has our data operation. But if I were doing it all again, I wouldn’t do it the same way—data tooling has come a long way in half a decade!</p><p>In these articles I will try to distil a few lessons for startups beginning to grapple with their data, based on how I’d do it <em>now</em>.</p><h3>Introduction — data modelling</h3><p>Here’s something we’ve changed recently: in 2022 we took the leap <a href="https://www.snowflake.com/guides/etl-vs-elt">from ETL to ELT</a>. In other words, we now aggregate all our data in a central data warehouse (in as close to its ‘raw’ form as possible), then transform it <em>in situ</em>.</p><p>This change to our working methods has been revolutionary. The transformation step entails bringing together data that originated in different sources, then executing joins, aggregates, filters etc. to bring it into a form that</p><ol><li>matches the <em>business understanding</em> of the data as closely as possible</li><li>is suitable for ingestion by business intelligence (BI) tools, machine-learning workflows, and regular-old data analysts</li></ol><p>This process is what I mean by <strong>data modelling.</strong></p><p>Under the old ETL model, doing it well requires a lot of up-front planning — which puts a startup in a tricky spot. But there are real benefits to proper data modelling. Our switch to ELT has greatly improved our situation, because we can now quickly iterate our transformation logic without painstakingly backfilling data.</p><p>In turn, this has allowed us to introduce more powerful BI tools that expect and require well-modelled data in order to be effective.</p><p>There are many articles ‘out there’ about data modelling. However, I have tended to find that these present idealised cases, rather than dealing with some of the more complex situations one encounters in the real world.</p><p>This makes sense. Writing about complexity takes a lot more time … and a lot more words. I hope that a summary of what I’ve learnt over the last year will offer a new and different perspective — one that I trust will be relevant to others working in small, lean teams. In short: it’s the article I wish I’d read a year ago.</p><p><strong>This is the first article in a three-part series. </strong>This article focuses on the necessary background needed to understand <em>the point</em> of data modelling and to participate in discussions about it. I include some of the thornier issues that don’t always get a mention in introductory articles.</p><p><a href="https://medium.com/apolitical-engineering/data-modelling-for-startups-part-ii-1b1fa58700e4">The second article</a> will cover how you might put the necessary infrastructure in place in order to do data modelling properly and to get the benefits of it.</p><p><a href="https://medium.com/apolitical-engineering/data-modelling-for-startups-part-iii-aca31e0f4176">The final article</a> will draw these two strands together, offering examples and practical advice.</p><h3>First, some theory</h3><p>From now on I will use the term <strong>data models</strong> to refer to the final products of the data transformation process. Typically, these will be <strong>tables</strong> stored in your <strong>data warehouse</strong>.</p><p>Data models in a warehouse (a.k.a. an OLAP database) do not need to follow the <a href="https://www.techopedia.com/definition/22561/third-normal-form-3nf">highly normalised schema</a> typical of a production SQL database (a.k.a. an OLTP database). Instead, data should be <strong>denormalised</strong> into a relatively small number of large tables.</p><p>We generally stop denormalising when we achieve something called a <strong>star schema</strong>, which is what you get when you morph your data into <strong>fact</strong> and <strong>dimension</strong> tables (sometimes with additional <strong>bridge</strong> tables, a.k.a. junction tables).</p><h4>Facts, dimensions, bridges, stars ..?</h4><p>A <strong>dimension</strong> table represents <em>a business entity of a particular type</em>.</p><p>Each row represents <em>a single entity</em>, and each column <em>an attribute</em> of such entities. There should be a unique ID (primary key) to act as a stable identifier for the entity.</p><figure><img alt="A table with three columns: ID, Name, and Country" src="https://cdn-images-1.medium.com/max/530/1*sQprvuCGBvzG09ejz8E1yg.png" /><figcaption>Every row represents a specific customer. The ID doesn’t have to be numeric, it could be a UUID.</figcaption></figure><p><strong>For example:</strong> in a table of customers, every row should represent a single customer. The table should have a ‘customer ID’ column. Any other columns will represent <em>attributes</em>: things we know about that customer (e.g. given name, country of residence).</p><p>We would expect dimension tables to change over time, since some attributes may be <strong><em>mutable</em></strong>. For example, a customer can change their contact details, or even their name.</p><p>A <strong>fact</strong> table represents<strong> a business process </strong>we want to measure and monitor.</p><p>A row in such a table represents an event or measurement (or perhaps an aggregated group of events/measurements). A ‘pure’ fact table row should consist of</p><ul><li>identifiers (foreign keys) representing links to various dimension tables</li><li>any measures (numeric values) associated with the fact</li></ul><figure><img alt="A table with four columns: Customer ID, Timestamp, Tax, and Gross Value" src="https://cdn-images-1.medium.com/max/580/1*sD_LMHZXm5IS5dI-fY3BBQ.png" /><figcaption>Every row represents a specific sale that took place.</figcaption></figure><p><strong>For example: </strong>in a table of sales, every row would represent a single sale. The table might have a ‘customer ID’ column, containing IDs from the <em>customers</em> (dimension) table. The table could also have ‘timestamp’ column (indicating when the sale took place) and a ‘value’ column, capturing the value of the sale. We can imagine other measure columns capturing things like tax applied to the sale etc.</p><p>We would not generally expect facts to change after they are first recorded (unless some kind of correction is issued). New facts can be simply appended to the rest of the data.</p><p>A <strong>bridge</strong> table can be used to represent many-to-many relationships between dimension tables (i.e. mutable relationships that aren’t considered to be a ‘fact’).</p><figure><img alt="Two ‘dimension’ tables with ID columns (one has a ‘Name’ column, the other an ‘Address’ column). Arrows point from the ID columns to a third (bridge) table. It has two columns, Customer ID and Address ID. It pairs customers with addresses." src="https://cdn-images-1.medium.com/max/1024/1*y5VC1tF64EeJPj4-sxg2MA.png" /><figcaption>This bridge table simply maps IDs from one dimension to another, representing a many-to-many relationship.</figcaption></figure><p><strong>For example:</strong> if multiple customers live at the same address, and some customers have multiple delivery addresses, we might have an Address dimension and a Customer dimension, with a mapping table matching Addresses to Customers.</p><p>Alternative ways to deal with this issue:</p><ul><li>use a nested data-type on the dimension table, i.e. an array of addresses on the customer table (but not many BI tools can handle this)</li><li>change the ‘grain’ — create a ‘Localised Customers’ dimension table representing everything we know about a particular customer in a particular place, with a surrogate key generated for each unique customer/place pair (but this abstraction is hard for end users to reason about)</li><li>rethink the model to disassociate the dimensions by putting a fact table between them, e.g. in this case a ‘deliveries’ fact table can reference an Address and a Customer without creating an additional link between the two (but of course this is not always possible)</li></ul><p>Because of the drawbacks to these alternatives, bridge tables have their place.</p><p>A <strong>star</strong> schema imagines a fact table (representing a particular business process) with many dimensions hanging off it (each fact table column is either a measure or references a single dimension table). Thus, the fact table is the centre of the star and the dimension tables are the points.</p><figure><img alt="A blue square labelled ‘Sales’ is surrounded by three red squares labelled customers, products, and dates. Arrows point from these to the central blue square." src="https://cdn-images-1.medium.com/max/796/1*m8ndSlJbezda7qA1tpBNPg.png" /><figcaption>Primary keys in the dimension tables target lookup columns in the fact table (more on treating dates as a dimension later in the article). In practice, fact tables capture a many-to-many relationship (e.g. a product may be bought by many customers, and a customer may buy many products).</figcaption></figure><p>In practice, the situation is often more complex:</p><ul><li>we may be using multiple tables, with a bridge table, to capture all the relevant information about a particular dimension</li><li>multiple facts may reference the <strong>same</strong> dimensions. We call these ‘<strong>conformed dimensions</strong>’ (they act as a single-source-of-truth for the entities they represent across <strong><em>all</em></strong> analysis contexts).</li><li>often we want to compare facts (e.g. different actions such as subscriptions and purchases) with a common dimension … or more than one common dimension</li></ul><p>This final pattern is sometimes called the ‘chasm trap’. It looks like this:</p><figure><img alt="A blue square labelled Sales is on the left, and another labelled Reviews is on the right. Three red squares form a vertical line between the two blue squares, dividing them. The red squares are labelled Customers, Products, and Dates. Two arrows start at each red square, pointing at each of the blue squares." src="https://cdn-images-1.medium.com/max/850/1*-WbqSnJQ1WxUBZqWPPJcIg.png" /><figcaption>If we want to compare two fact tables, we have to work out how to ‘cross the chasm’ (i.e. understand the relationship between the two based on their shared dimensions and join them appropriately).</figcaption></figure><p>The reason it’s a ‘trap’ is because when you have multiple ‘join paths’ between fact tables, it’s very easy to end up double counting facts. Some business intelligence software can manage this issue.</p><p>Things can get a bit more dangerous when we create a ‘galaxy’ schema — a set of star schemas connected via conformed (shared) dimensions:</p><figure><img alt="Four red squares represent dimensions as follows: dates, products, customers, and subscriptions. Three blue squares represent facts as follows: sales, reviews, and subscription creations. Sales and reviews facts both link to dates, products, and customers dimensions. Subscription creations facts link to dates, subscriptions, and customers." src="https://cdn-images-1.medium.com/max/1008/1*cFrGfjVWzRlp-b3S-muqKQ.png" /><figcaption>An example ‘galaxy schema’. Note that queries including the ‘Subscription Creation’ fact could reference the ‘Subscriptions’ dimension, which is NOT shared with the other fact tables.</figcaption></figure><p>This can sometimes cause problems if queries regarding multiple <em>different</em> facts reference dimensions that are <em>not</em> shared.</p><p>In these scenarios, care needs to be taken that the query makes meaningful sense! As a rule of thumb, filtering by an attribute of a dimension that isn’t shared is <em>usually</em> okay (consider, for example, counting sales made to customers with a particular <em>type</em> of subscription). However, queries that attempt to aggregate by such attributes should be checked carefully.</p><p>One way to avoid this is to find a way (e.g. in a business intelligence tool) to expose coherent groups of data models that avoid such pitfalls. These model groups would contain either</p><ul><li>a single star</li><li>a single chasm</li></ul><figure><img alt="This is like the previous diagram, with two overlapping shaded areas. An orange shaded area groups dates, customers, and subscriptions dimensions with the subscription creations fact (a star). A purple shaded area groups dates, customers, and products dimensions with sales and reviews facts (a chasm)." src="https://cdn-images-1.medium.com/max/935/1*3BCLwxvlABKhDb2h_n8Qsg.png" /><figcaption>The orange area represents a single star schema, the purple area represents a single chasm schema.</figcaption></figure><p>Queries executed against such model groups are much more likely to produce meaningful results.</p><h4>To OBT or not to OBT?</h4><p>Perhaps the simplest way to create a reliable model group is to construct an OBT model — that stands for ‘One Big Table’.</p><p>In the era of cloud data warehouses, a rule of thumb is that storage is cheap, processing is expensive. Therefore it may make a lot of sense to <em>pre-join</em> your data models into One Big Table: process everything you need once, store the results for later.</p><p>This is easiest to think about in the case of the star schema. Let us say you have a fact table, <em>sales</em>, linked to dimension tables <em>customers</em>, <em>products</em>, and <em>dates</em>.</p><figure><img alt="A blue square labelled ‘Sales’ is surrounded by three red squares labelled customers, products, and dates. Arrows point from these to the central blue square." src="https://cdn-images-1.medium.com/max/796/1*m8ndSlJbezda7qA1tpBNPg.png" /></figure><p>You could create a SQL query to join all of these into One Big <em>Sales</em> Table:</p><pre>-- models/obt/obt_sales.sql<br><br>    SELECT *<br>      FROM {{ ref(&#39;sales&#39;) }} AS s<br>RIGHT JOIN {{ ref(&#39;customers&#39;) }} USING(customer_id)<br>RIGHT JOIN {{ ref(&#39;products&#39;) }} USING(product_id)<br>RIGHT JOIN {{ ref(&#39;dates&#39;) }} AS d ON s.sale_date = d.calendar_date</pre><p>I have written this in the style of a DBT model.</p><p>Note the (somewhat unusual) use of a RIGHT JOIN. This is a convention I picked up from our BI tool:</p><ul><li>the tool encourages us to think of fact tables — such as <em>sales</em> — as the principal table from which we select data, onto which dimensions will be joined (if needed — a simple COUNT can be done without joins)</li><li>we can expect (if we’ve done our modelling properly) that there will never be any rows in our fact table that relate to <em>nonexistent </em>rows in our dimension tables</li><li>however, there <em>may </em>be rows in our dimension tables that are <em>not</em> linked to <em>any</em> rows in the <em>sales</em> table (some products could be very unpopular and have no sales)</li></ul><p>We could use an INNER JOIN (and then every row would represent a sale, complete with all associated information) … but what if we want to use our OBT model to compute the total value of sales <em>per product</em>?</p><pre>    SELECT<br>           product_id,<br>           IFNULL(SUM(sale_value), 0) AS total_value<br>      FROM obt_sales<br>  GROUP BY product_id<br>  ORDER BY total_value</pre><p>Because we used RIGHT JOIN to construct our OBT model, some rows have dimension attributes, but NULL sales measures. We can use the query above to reveal which products have zero sales value associated with them. It all depends on your use cases for the model!</p><p>You can hopefully see that OBT models, though not as flexible as the more fundamental facts and dimensions, offer convenience and safety.</p><p>The downsides become clearer when you try to construct an OBT model for a chasm schema.</p><p>Let us imagine we have two fact tables, <em>sales</em> and <em>reviews</em>. Both fact tables are linked to the dimension tables <em>customers</em> and <em>products</em>. That is to say:</p><ul><li>customers can buy products</li><li>customers can review products</li></ul><figure><img alt="Two red squares (dimensions) labelled Customers and Products at the top and bottom, two blue squares (facts) labelled Sales and Reviews on the left and right. Arrows connect each dimension to each fact." src="https://cdn-images-1.medium.com/max/516/1*Sj81EMgn9QLsHRlqd02HWg.png" /><figcaption>A diagram displaying the chasm trap schema just described.</figcaption></figure><p>Perhaps we want to answer questions like ‘<em>do people with repeat purchases leave better reviews?</em>’ In order to construct a single table that correctly exposes this collection of dimensions and facts, we’d need to ensure it contained all information on sales and reviews.</p><p>However, it’s not clear that a review can be linked <em>directly</em> to a sale. Indeed, your company may allow someone to buy the same product multiple times, but to review it only once: the link only exists via the dimension tables.</p><p>There are different ways to handle this. One would be:</p><ul><li>for every combination of customer and product, create a row</li><li>join aggregated sales data (derived from any ‘sale’ facts that exist for that combination of customer and product)</li><li>join reviews data (derived from any ‘review’ fact that exists for that combination of customer and product)</li></ul><p>You can see that this particular choice depended closely on the business logic.</p><p>If instead customers can write multiple reviews of a single product, we could also aggregate our reviews data before joining. But <em>aggregation loses information.</em> Will you store the average score? The maximum score? The most recent score?</p><h4>Welcome to the date dimension</h4><p>There is another approach I want to mention at this point.</p><p>It is usual in data modelling to consider a <strong>date</strong> to be a dimension. It has the right properties:</p><ul><li>fact tables will often have a date (or timestamp) column</li><li>each date is unique, immutable identifier for a day</li><li>each day has attributes that we could list (for example, what day of the week is it? In which calendar quarter does it lie?) and use for filtering, grouping etc</li></ul><p>It may very well make sense to create a ‘calendar table’, treating the date as the primary key (and any date columns in fact tables as references to this key). <a href="https://sql-snippets.count.co/t/basic-date-dimension/261">Here’s an example</a> the good people at Count have provided, which you could use yourself.</p><p>In the case just discussed, it may well be that sales and reviews are <em>additionally</em> related via a date. This would look like the first example of a chasm schema from earlier in the article:</p><figure><img alt="A blue square labelled Sales is on the left, and another labelled Reviews is on the right. Three red squares form a vertical line between the two blue squares, dividing them. The red squares are labelled Customers, Products, and Dates. Two arrows start at each red square, pointing at each of the blue squares." src="https://cdn-images-1.medium.com/max/745/1*1mH79bo-Pp6t0_j1MARcMw.png" /></figure><p>In that case, we could build an OBT model by creating combinations of customers, products, <em>and dates</em>. Such a model avoids aggregating <em>all</em> the data … at least, it avoids aggregating it so much that we lose important information. We would describe the resulting table as being at the <strong>customer/product/daily grain</strong>. This is a more ‘fine grained’ table than the version at the <strong>customer/product grain</strong>.</p><p>This table does what is required. However, the drawbacks are clear:</p><ol><li>such tables could end up being very large, especially if they become more fine-grained</li><li>we still needed to aggregate the table at some level — e.g. if two sales of the same product are made to the same customer on the same day, we’d need to aggregate those sales. We could go to the hour (or even minute!) grain, but that makes problem (1) worse.</li></ol><p><strong>All-in-all, perhaps it would be better just to stick with separate fact and dimension tables in this case.</strong></p><p>This does highlight the slightly odd status of the date dimension:</p><ul><li>many BI tools don’t require you to bring your own date dimension table in order to work properly — after all, the ‘foreign key’ for a date is usually just the date (2023-01-05 is a compact, immutable ID for a day), and any BI tool worth its salt can derive useful aggregations and filters (e.g. by month, ‘business day’ etc) from that information alone</li><li>many fact tables contain a timestamp column with very high resolution (e.g. to the microsecond). It would be ridiculously impractical to create a ‘microsecond dimension table’, so in this case you can either convert the timestamp to a date (you might ask yourself whether business intelligence use cases <em>need</em> higher resolution — this depends on the business!) or simply leave it as-is, expecting your BI tool to handle it</li></ul><h3>Conclusion</h3><p>Data modelling is a big subject, but I hope this article provides something of a map for the start of your journey. To recap, I’ve covered:</p><ul><li>the different components of data modelling (facts, dimensions, and bridges)</li><li>data model schemas (star schemas, chasm traps, ‘galaxy’ schemas) and the role of conformed dimensions</li><li>OBT models and the tradeoffs involved in creating them</li><li>some data modelling pitfalls that you’re likely to encounter</li></ul><p><a href="https://medium.com/apolitical-engineering/data-modelling-for-startups-part-ii-1b1fa58700e4">In the next article</a> I’ll move on from data modelling theory. I will offer practical advice for teams just getting started with building a fit-for-purpose data infrastructure.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f566af2a88ca" width="1" height="1" alt=""><hr><p><a href="https://medium.com/apolitical-engineering/data-modelling-for-startups-part-i-f566af2a88ca">Data Modelling for Startups (Part I)</a> was originally published in <a href="https://medium.com/apolitical-engineering">Apolitical Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Power of Cloud Load Balancing]]></title>
            <link>https://medium.com/apolitical-engineering/the-power-of-cloud-load-balancing-5ff3fc03731f?source=rss----3a76c3396db5---4</link>
            <guid isPermaLink="false">https://medium.com/p/5ff3fc03731f</guid>
            <category><![CDATA[cloud-armor]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[cdn]]></category>
            <category><![CDATA[traefik]]></category>
            <category><![CDATA[load-balancing]]></category>
            <dc:creator><![CDATA[Renzo Rozza]]></dc:creator>
            <pubDate>Fri, 24 Feb 2023 09:41:03 GMT</pubDate>
            <atom:updated>2023-02-24T09:41:03.891Z</atom:updated>
            <content:encoded><![CDATA[<h4>Run and scale your services behind a single external IP address</h4><p>Apolitical’s mission is to help build 21st-century governments that work for people and the planet. Our web platform upskills public servants across the globe to tackle the pressing challenges they face in their jobs.</p><p>To scale our web platform to serve that global audience, our engineering teams are constantly improving the quality of its features, security, and availability — amongst other things. In particular, to achieve our mission, we need to be able to provide public servants with fast and reliable access to our system.</p><p>Apolitical’s infrastructure runs on the Google Cloud Platform (GCP), which offers multiple hosting alternatives and networking products. In this blog post, you’ll learn how we improved our infrastructure using GCP’s managed services to simplify our deployment and seamlessly deliver the scale and high availability that we need.</p><blockquote><strong>TL;DR</strong>: To scale our web platform we revamped the way we handle traffic by using <a href="https://cloud.google.com/load-balancing">Cloud Load Balancing</a>. We now enable <a href="https://cloud.google.com/cdn">Cloud CDN</a> to allow caching of web assets. And we also define <a href="https://cloud.google.com/armor">Cloud Armor</a> rules for protection against DDoS attacks.</blockquote><h3>How we used to handle traffic</h3><p>In the past, all incoming traffic to the Apolitical web platform was handled by our Reverse Proxy, built with <a href="https://github.com/traefik/traefik">Traefik Proxy</a> (a modern and open-source implementation of a reverse proxy). By definition, a reverse proxy is a server that sits in front of web servers and forwards client (e.g. web browser) requests to those web servers. It typically sits behind the firewall in a private network and provides an additional level of abstraction and control to ensure the smooth flow of network traffic between clients and servers.</p><p>Our Reverse Proxy also included a <a href="https://kubernetes.io/docs/concepts/services-networking/service/#loadbalancer">Load Balancer Service</a>, which is the standard way to expose a <a href="https://kubernetes.io/docs/concepts/services-networking/service/">Service</a> to the Internet from a Google Kubernetes Engine (GKE) cluster. A Load Balancer Service will spin up a network Load Balancer with a single IP address allowing all incoming traffic to be directly forwarded to the Reverse Proxy <a href="https://kubernetes.io/docs/concepts/workloads/pods/">Pods</a>.</p><p>Take a look at the diagram below to see what our previous architecture looked like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Xv0hgqKI9pzb5EO-" /><figcaption><strong>Figure 1.</strong> Diagram of our previous architecture, which used a Load Balancer Service to handle traffic</figcaption></figure><p>The big downside of a Load Balancer Service is its lack of integration with GCP networking products (technologies that make the infrastructure easier to scale, secure and modernise) such as<a href="https://cloud.google.com/network-tiers#tab1"> global anycast external IP address</a>,<a href="https://cloud.google.com/cdn"> Cloud CDN</a>,<a href="https://cloud.google.com/armor"> Cloud Armor</a>, and more. This means that we were limited to a reduced set of features and an increasing cost of maintenance. For that reason, using a Load Balancer Service became an obstacle to scaling our web platform.</p><h3>How we revamped our setup</h3><p>In GKE, an <a href="https://kubernetes.io/docs/concepts/services-networking/ingress/">Ingress</a> defines rules for routing HTTP(S) traffic to <a href="https://kubernetes.io/docs/concepts/workloads/">Workloads</a> (applications) running in a cluster. See the <a href="https://cloud.google.com/kubernetes-engine/docs/concepts/service-networking">Service networking overview</a> to learn more about how an Ingress exposes applications using Services.</p><p>Unlike the Load Balancer Service, an Ingress is not a type of Service. Instead, it sits in front of multiple Services and acts as a “smart router” within a GKE cluster. The default Ingress controller will spin up a GCP <a href="https://cloud.google.com/compute/docs/load-balancing/http/">HTTP(S) Load Balancer</a>, and because it’s a native GCP component, it can use the networking products mentioned above out-of-the-box.</p><p>It’s important to note that <a href="https://cloud.google.com/kubernetes-engine/docs/concepts/alias-ips">VPC-native traffic routing</a> is essential for you to be able to use an Ingress. Older versions of GKE didn’t come with this function enabled by default. Furthermore, the VPC-native traffic routing feature is immutable, which means that if a GKE cluster has been created without that feature, the only way to use an Ingress will be to recreate the GKE cluster from scratch.</p><p>For us, that meant a huge opportunity to revamp our previous architecture to a more robust and scalable architecture. But, as simple as it sounds, replacing the Load Balancer Service with an Ingress involved a few technical challenges and trade-offs. In the following sections, we’ll unravel each of these and explain the solutions that we came up with.</p><h3>Routing</h3><p>Our routing is configured to use <a href="https://doc.traefik.io/traefik/reference/dynamic-configuration/kubernetes-crd/">Traefik Proxy Kubernetes Customer Resource Definition</a> (CRDs). We thought that Traefik Proxy was providing a good level of service for our needs. So we decided to keep the routing untouched and take a “catch-all” approach, where the GKE Ingress delegates all the routing decisions to Traefik Proxy.</p><h3>Transport Layer Security (TLS)</h3><p>TLS is a security protocol that provides privacy and data integrity for Internet communications. Previously, our TLS configurations were built into the Traefik Proxy. By replacing the Load Balancer Service with a GKE Ingress, the TLS configurations would have to sit at the Ingress level. To do so, we simplified our Traefik Proxy setup to only define and use HTTP connections and to delegate all the TLS configurations to the GKE Ingress.</p><h3>Cache</h3><p>Cloud CDN offers a massive improvement to a web platform’s scalability and performance, and GKE Ingress makes it easy to<a href="https://cloud.google.com/kubernetes-engine/docs/how-to/ingress-features#cloud_cdn"> plug this feature in</a>. Consequently, we decided to use Cloud CDN to cache all of our <a href="https://cloud.google.com/cdn/docs/caching#static">static content</a>, e.g. web assets (.js, .css, etc), fonts, images, and more.</p><h3>Security Policies</h3><p>GKE Ingress also makes it easy to enhance security by simply <a href="https://cloud.google.com/kubernetes-engine/docs/how-to/ingress-features#cloud_armor">plugging in</a> Cloud Armor. Consequently, we decided to use Cloud Armor to protect the web platform against DDoS and other attacks.</p><p>See how this differs from our previous architecture in the diagram below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*g380Ul-hiYcmfCHy" /><figcaption><strong>Figure 2.</strong> Diagram of our current architecture using an Ingress to handle traffic</figcaption></figure><h3>What we learnt</h3><p>I’m pleased to say that although implementing our load-balancing improvements was challenging, it was very much worth it! The benefits of handling our web platform’s traffic through Cloud Load Balancing are evident.</p><p>To show the results in numbers:</p><ul><li>85% of total traffic is now served from Cloud CDN</li><li>Page loads are at least 3 times faster in EU regions (and estimated to be even faster in non-EU regions)</li><li>API latency is at least 2 times faster for non-EU regions</li></ul><p>This has greatly contributed to getting better performance scores for Core Web Vitals metrics on Google Search Console. And more importantly, this allows Apolitical to keep expanding its reach to public servants, providing them with a great experience.</p><p>To see what our web platform is like, <a href="https://apolitical.co/home/">visit us here</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ff3fc03731f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/apolitical-engineering/the-power-of-cloud-load-balancing-5ff3fc03731f">The Power of Cloud Load Balancing</a> was originally published in <a href="https://medium.com/apolitical-engineering">Apolitical Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Code reviews at Apolitical]]></title>
            <link>https://medium.com/apolitical-engineering/code-reviews-at-apolitical-37dad421ace4?source=rss----3a76c3396db5---4</link>
            <guid isPermaLink="false">https://medium.com/p/37dad421ace4</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[code-review]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[code-review-process]]></category>
            <dc:creator><![CDATA[Paddy Alton]]></dc:creator>
            <pubDate>Fri, 09 Dec 2022 16:49:25 GMT</pubDate>
            <atom:updated>2022-12-09T16:49:25.108Z</atom:updated>
            <content:encoded><![CDATA[<p>At Apolitical we recently spent some time trying to codify ‘the way we do things’. Out of those discussions have come various sets of principles and best practices.</p><h3>Introduction</h3><p>One area that sparked a deep and thoughtful discussion was <em>code review</em> — a crucial part of any engineering team’s workflow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lKaHF2A8SYtVp6DVhSyRFA.png" /><figcaption>Schematic view of the stages in our develop-and-deploy process</figcaption></figure><p>We were motivated by questions such as</p><ul><li>how can we get the most value out of code reviews ?</li><li>how can we avoid code reviews being a simple ‘rubber stamp’?</li><li>how can we make sure code reviews don’t slow us down?</li><li>how can we improve the developer experience of code reviews?</li></ul><p>Following our discussion, <strong>we outlined these principles for code authors and reviewers.</strong></p><h3>Our principles</h3><h4>Reviewing code trumps writing code…</h4><p>Writing new code is the easy part. Delivering it to production is harder. Until it’s delivered, it’s not doing anyone any good.</p><p>The ‘last mile’ of delivery is often the most painful. We can deliver more value to the organisation by prioritising review of work that’s been done over starting something new.</p><p>Receiving a review when what you wrote is still fresh in your mind also makes it easier to action the comments!</p><p><strong>So: we should spend a lot of time reviewing code!</strong> Code review is a great thing to do following a meeting/lunch, or at the start or end of the day.</p><blockquote>This will only work if we recognise good, prompt code reviews as critical contributions to the team.</blockquote><blockquote><em>What doesn’t get measured, doesn’t exist. Track how long people should expect to wait for review and agree what is good.</em></blockquote><blockquote><em>For example, we could aim to ensure no-one waits more than 24 hours for their code to be reviewed (for this purpose we pretend the weekend doesn’t exist, so code submitted at 5pm on Friday should be reviewed by 5pm on Monday).</em></blockquote><h4>…but reviewing code is writing code</h4><p>Reviewers should always go into review with the objective of <strong>improving</strong> what’s been submitted.</p><p>Reviewers should see themselves as <strong>collaborating on writing the code</strong>, not just rubber stamping it as ‘good enough’.</p><blockquote><em>For juniors, improving a more senior person’s code may be too lofty an aspiration — but it’s still a good learning opportunity.</em></blockquote><h4>Comments should indicate severity…</h4><p>The comments you leave in code review serve a number of purposes:</p><ol><li>does the code work?</li><li>is the code efficient?</li><li>is it easy to maintain?</li><li>is anything missing?</li><li>ask a question about the code</li><li>knowledge sharing</li><li>kudos</li></ol><p><strong>Some comments may highlight critical problems, others require no action, and most lie somewhere in between.</strong></p><p>It is good to triage your comments for the author. In descending order:</p><ol><li>blocking (“I’m not going to approve this until you change it”)</li><li>recommended (“if it’s too much right now, at least write a ticket to do it later”)</li><li>not blocking (“this is more of a suggestion”) / question / did you know? / high five!</li></ol><blockquote><strong><em>Seniors reviewing juniors</em></strong><em> should be especially mindful of this.</em></blockquote><blockquote><em>There is inherent, unspoken pressure to spend time making changes when someone with more information/experience suggests them. Juniors may not yet be equipped to make the judgement themselves.</em></blockquote><h4>…but all comments are suggestions</h4><p><strong>Responsibility for the code lies with the author, not the reviewer.</strong></p><p>The reviewer <strong>does</strong> have a veto — they can withhold approval — but this should be used sparingly.</p><p>If there is a genuine dispute we should usually side with the author (because they have more context).</p><h4>If it can be automated, it should be automated</h4><p>We can make code reviews more useful by automating as many quality checks as possible. <strong>This allows reviewers to focus on adding value to the code.</strong></p><p>Examples of checks that can be automated (e.g. via Git hooks) include</p><ul><li>formatting/linting</li><li>static type checking</li><li>unit tests/test coverage</li></ul><p>This <strong>doesn’t</strong> mean reviewers shouldn’t comment on code format etc. if it doesn’t meet our standards, but</p><ul><li>where possible, built-in ‘suggestions’ should be used (so the author can simply accept the change rather than spend time interpreting the reviewer’s directives)</li><li>if reviewers are regularly commenting on the same sorts of simple problem, they should surface this and propose a way to automate it</li></ul><blockquote><em>Spotting whether something is missing (e.g. a version bump, changelog entry, or test case) is hard for reviewers!</em></blockquote><blockquote><em>We can use checklists for the author (e.g. in issue templates) to try and catch some of these things if we can’t check automatically.</em></blockquote><h4>Simple sanity checks are essential…</h4><p>It should be rare for code to reach the QA stage and be straightforwardly rejected. <strong>This indicates a process problem.</strong></p><p>Every piece of code is bespoke. The write → review → QA → deploy process <strong>is not a production line</strong>. It is costly for a person to orient themselves when they perform any of these steps.</p><p>If we pay that cost, only to reject code for a reason that could have been caught at an earlier step by someone already working with it:</p><ul><li>that is a poor experience for the person rejecting the code, distracting them unnecessarily and for little return on the investment of their time</li><li>code may be bounced back to the author where this might otherwise have been avoided entirely</li></ul><p>In short, it <strong>slows us down.</strong></p><p>It is <strong>faster</strong> overall to spend <strong><em>more time</em></strong> on the earlier stages and to ensure later stages are as streamlined and valuable as possible.</p><blockquote><strong><em>Authors</em></strong><em> should make sure automated checks pass and follow any relevant checklists to avoid reviewers catching simple problems</em></blockquote><blockquote><strong><em>Reviewers</em></strong><em> should check that front-ends render properly and that APIs don’t throw trivial errors before approving code</em></blockquote><h4>…and, especially, value your reviewer’s time</h4><p>This advice sounds obvious, but it’s common to see authors treat their reviewers like personal quality assurance technicians. These authors make little effort to catch their own errors or to design their checklist to get merge requests ready for review.</p><p>Your colleague arrives at work each day with a finite supply of focus. If they allocate some of it to you, that’s time they can’t spend on their own work. It’s only fair that you maximise the value of their time.</p><p>Reviews drastically improve when <strong>both participants trust each other</strong>. Your reviewer puts in more effort when they can count on you to take their feedback seriously. Viewing your reviewer as an obstacle you have to overcome limits the value they offer you.</p><blockquote><strong><em>Authors</em></strong><em> should read and review the code changes themselves. Don’t just check for mistakes, imagine reading the code for the first time.</em></blockquote><h3>Conclusion</h3><p>We hope that by codifying these principles we can continue to improve the way we do code reviews at Apolitical.</p><p>By publishing them, we hope to help other engineering teams improve their working methods.</p><p>How do these principles sound to you? Get in touch via the comments!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37dad421ace4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/apolitical-engineering/code-reviews-at-apolitical-37dad421ace4">Code reviews at Apolitical</a> was originally published in <a href="https://medium.com/apolitical-engineering">Apolitical Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Painkillers for Local Development of Microservices]]></title>
            <link>https://medium.com/apolitical-engineering/painkillers-for-local-development-of-microservices-4ef97bc275de?source=rss----3a76c3396db5---4</link>
            <guid isPermaLink="false">https://medium.com/p/4ef97bc275de</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[local-development]]></category>
            <category><![CDATA[tilt]]></category>
            <category><![CDATA[developer-experience]]></category>
            <dc:creator><![CDATA[Renzo Rozza]]></dc:creator>
            <pubDate>Tue, 29 Nov 2022 09:07:05 GMT</pubDate>
            <atom:updated>2022-11-30T09:12:31.964Z</atom:updated>
            <content:encoded><![CDATA[<h4>The strategies and tools you need to work faster and smarter</h4><p>Since its inception, the <a href="https://apolitical.co/home/">Apolitical platform</a> has been expanding its reach to an ever-increasing number of public servants across the globe. Alongside this growth, the platform’s functionality has also been evolving to meet user needs. And in the same way, to ensure we succeed in our user-centred mission, the engineering teams have grown continuously and continue to do so (On an unrelated side note, if you are interested in joining our team, don’t hesitate to get in touch. <a href="https://www.linkedin.com/company/apolitical/jobs/">We’re hiring!</a>).</p><p>Now back to the more technical side, where growth is always easier said than done. The Apolitical platform is designed following a <a href="https://microservices.io/">microservice architecture</a> (also known as microservices). And as you may know, this architectural style structures an application as a collection of small services that are easy to maintain and test, loosely coupled, independently deployable, and much more.</p><p>The microservice architecture has many advantages, but it’s not always plain sailing. For instance, providing engineering teams with a good developer experience can sometimes be challenging. In particular, one of our biggest challenges at Apolitical was putting forward the right strategy and tools to iterate at speed. I’ll share more about how we managed to overcome this challenge later.</p><blockquote><strong>TL;DR:</strong> To stop doing tedious and repetitive tasks as part of our local development workflow: We implemented a monorepo with Git submodules to centralise access and standardise the synchronisation of multiple repos. We incorporated Tilt with Docker Compose to codify a common development path and ensure reproducibility with continuous feedback loops. And, we extended interoperability by connecting locally-running services to third parties and databases on the cloud.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wd70H53LE2Njtu84" /><figcaption><strong>Figure 1.</strong> Diagram of local development platform</figcaption></figure><h3>How we implemented a monorepo</h3><p>A <a href="https://monorepo.tools/">monorepo</a> is, to a certain extent, a simple concept: one version-controlled code repo that holds many distinct projects with well-defined relationships.</p><p>A common misconception is that following a monorepo is <a href="https://blog.nrwl.io/misconceptions-about-monorepos-monorepo-monolith-df1250d4b03c">the same as</a> following a monolithic architecture. Conversely, a monorepo simplifies code-sharing and cross-project refactorings. It also significantly lowers the cost of creating and maintaining microservices.</p><p>A simplified example of a monorepo’s structure would look like this:</p><pre>/dev-platform<br>  /apis<br>    /api-1<br>    /api-2<br>  /uis<br>    /ui-1<br>    /ui-2</pre><p>Simple, right? But… that’s not all! We want to take things one step further. And, rather than just moving all the code from every repo within our codebase to a monorepo, we decided to implement a monorepo with the use of Git submodules.</p><p>Submodules allow you to keep a Git repo as a subdirectory of another Git repo, whereby you can clone multiple repos into a monorepo and keep your commits separately. Following the example above, the dev-platform is the monorepo and it’s defined as its own Git repo. Then, api-1, api-2, ui-1, and ui-2 are added to the dev-platform as <a href="https://git-scm.com/book/en/v2/Git-Tools-Submodules">Git submodules</a>.</p><p>Therefore, the commands executed inside a Git submodule, such as api-1, will change the submodule’s Git history, not the parent (dev-platform). Thus, executing commands inside the parent changes the parent’s Git history, not the submodule’s. For that reason, projects are nicely isolated on the repository layer. Still, the working trees put the source files side-by-side on your filesystem, allowing you to work as if everything is coming from one place.</p><h3>How we redefined the development path</h3><p>Implementing a monorepo was only the first part of improving the developer experience. In the second part, we decided to provide the engineering teams with the right tooling to locally orchestrate the required services to implement new functionalities faster.</p><p>For clarity, imagine that we have the following scenario: a feature request that requires changing the front-end ui-1.</p><p>In our old workflow, developers would have to:</p><ol><li>Clone the front-end ui-1 repo</li><li>But also, clone the back-ends used by ui-1, in this case, the api-1 and api-2 repos</li><li>Set up the right environment variables for each repo individually</li><li>Then, spin up each service individually</li><li>And finally, check the external dependencies. (Note that databases running locally may need to be populated at this point)</li></ol><p>It became clear that going through that process was very prone to misconfigurations. And, as it doesn’t scale — there are too many tedious and repetitive tasks. It gets even worse when having to keep 20 or more repos up-to-date as the platform evolves at a very fast pace.</p><p>To overcome this, we introduced Tilt with Docker Compose into our local development workflow.</p><p><a href="https://docs.docker.com/compose/">Docker Compose</a> is a tool for defining and running multi-container Docker applications. It allows you to configure each service and its dependencies. In addition, <a href="https://docs.tilt.dev/">Tilt</a> adds a layer on top of Docker Compose to automate all the steps from a code change to external dependencies: watching files, building container images, and bringing your local environment up-to-date.</p><p>At this point, the example monorepo’s structure shown above would have been updated to look like this:</p><pre>/dev-platform<br>  /apis<br>    /api-1<br>    /api-2<br>  /uis<br>    /ui-1<br>    /ui-2<br>  .env<br>  docker-compose.yml<br>  Tiltfile</pre><p>The .env file defines the environment variables, which are used by the docker-compose.yml to define how each of the microservices (UIs and APIs) are meant to be built and run. The Tiltfile simply watches the .env for changes and then loads the services defined on the Compose file.</p><p>Now, let’s go back to the previous scenario: a feature request that requires changing the front-end ui-1.</p><p>In our new workflow, developers would only have to:</p><ol><li>Clone the dev-platform repo</li><li>Initialise the submodules with one command: git submodule update</li><li>Set up the right environment variables for the dev-platform</li><li>And finally, spin up all the services with one command: tilt up</li></ol><p>It’s easy to see that the number of steps is fewer and simpler, but more importantly, these steps are the same no matter how many microservices (UIs or APIs) your application has. In addition, one of the most exciting features of Tilt is that the live dashboard allows you to look at all your microservices at once, and get an instant feedback loop from your logs, broken builds, and runtime errors.</p><p>The final cherry on the cake was integrating Traefik Proxy and Cloud SQL Proxy into the dev-platform. These two proxies can be defined as part of the Docker Compose services. <a href="https://github.com/traefik/traefik">Traefik Proxy</a> allows routing the traffic to every service under the same local host domain (including adding self-signed HTTPS certificates). On top of this, <a href="https://github.com/GoogleCloudPlatform/cloud-sql-proxy">Cloud SQL Proxy</a> allows the services running locally to connect to the databases on the cloud. In short, these two proxies allowed us to locally replicate the same behaviour as deploying and running the services in one of the staging environments. The consequences of this for the engineering teams were that they get to spend more time coding without having to push changes to staging environments.</p><h3>What we learnt</h3><p>At Apolitical, we care about having a good developer experience for our engineering teams. But we also know that’s tricky to measure. Therefore, it’s sometimes hard to get buy-in from the wider company for these types of projects. Despite microservices being the best way to architect our web platform, it was clear that time and effort had to be put into designing the right local development strategy and tools to make our workflows more efficient.</p><p>Using a monorepo with Git submodules to structure all the code of our web platform plus using Tilt with Docker Compose to locally spin up services has completely transformed how we work. Our onboarding process for new joiners is a lot smoother than before, and lots of time has been shaved off from our development loops. Additionally, best practices have been codified to give our engineering teams a fast and reliable workflow.</p><p>If it sounds like this could work for you and your team, what are you waiting for?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ef97bc275de" width="1" height="1" alt=""><hr><p><a href="https://medium.com/apolitical-engineering/painkillers-for-local-development-of-microservices-4ef97bc275de">Painkillers for Local Development of Microservices</a> was originally published in <a href="https://medium.com/apolitical-engineering">Apolitical Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to optimise your front-end by reducing the chattiness to APIs]]></title>
            <link>https://medium.com/apolitical-engineering/how-to-optimise-your-front-end-by-reducing-the-chattiness-to-apis-c7a72f0b68e2?source=rss----3a76c3396db5---4</link>
            <guid isPermaLink="false">https://medium.com/p/c7a72f0b68e2</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Renzo Rozza]]></dc:creator>
            <pubDate>Tue, 08 Nov 2022 09:12:48 GMT</pubDate>
            <atom:updated>2022-11-08T09:12:47.978Z</atom:updated>
            <content:encoded><![CDATA[<h4>Rewriting Reg/Auth with the help of a Management API</h4><p>About a year ago, the Apolitical engineering teams began rewriting the user registration and authorisation system on the platform. Or, as we internally called it, the “Reg/Auth re-architecture” project.</p><p><a href="https://apolitical.co/home/">Apolitical</a> is a global social learning network for government. By connecting public servants with knowledge, skills and connections, we aim to help them build a better world for citizens. There are around 200,000 people on Apolitical, and we only allow public servants to create accounts. This volume and focus mean that we need a user-friendly yet robust account creation and verification system.</p><p>The platform is designed to approve user registrations from trusted government domains automatically. Plus, it allows for manual vetting of registrations that don’t fall under the category.</p><p>So, why did we undertake this project?</p><p>Firstly, from a business perspective, we wanted to reduce the drop-off rate in the Reg/Auth process as well as the time spent by the customer support team helping users to complete it. Secondly, from a technical perspective, we wanted to improve the implementation of some critical aspects of the Reg/Auth lifecycle and the way data was stored and consumed.</p><blockquote><strong>TL;DR: </strong>A common problem is making multiple API calls that need to be sequenced and assembled on the front-end. If you are facing that, then, you can consider implementing a Management API to push the front-end logic to the back-end. With this simple but powerful concept, you will be able to optimise the processing with server-side parallelism, embrace observability, and reduce networking costs. And more importantly, make your users happier!</blockquote><h3>What a Management API did for us</h3><p>When we started on this project, our <a href="https://microservices.io/">microservice architecture</a> meant that we had a very complex and technical jigsaw puzzle to solve. We wanted to improve the implementation of some critical aspects, but perhaps that’s a little too broad.</p><p>So, although there are many exciting aspects of this project, the focus here will be on exploring the benefits of a Management API: an API to manage other APIs.</p><p><a href="https://netflixtechblog.com/optimizing-the-netflix-api-5c9ac715cf19">As the Netflix API team highlighted in their blog</a>, one of the motivations for implementing a Management API was to reduce the chatty nature of the client/server communication, which was slowing down the performance and making it harder to diagnose incidents.</p><p>To give an example, we can explore one of the first things that happen when a user <a href="https://apolitical.co/signup/?ref=medium-engineering">signs up for the Apolitical platform</a>. The user would input the email address in the front-end, and then some business logic would verify that the email address is valid. For the sake of simplicity, the following diagram illustrates a possible implementation of this validation process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ncmWV2d62UgMJ73u" /><figcaption><strong>Figure 1.</strong> Diagram of email validation with multiple API calls</figcaption></figure><p>In Figure 1 shown above, there are three API calls, and each of them is made to different APIs: <em>API 1</em>, <em>API 2</em>, and <em>API 3</em>. It’s important to note that the sequence of the API calls is fixed. This means we need first to call <em>API 1</em>, then <em>API 2</em>, and lastly <em>API 3</em>. In addition to this sequence, the final validation logic gets executed in the front-end and will depend on the result of all of the API responses.</p><p>For the case of an email address validation, you may be wondering, why isn’t a single API doing all of that? Unfortunately, the complete answer to that question is outside of the scope of this blog post. But, as mentioned before, our platform implements a complex process with auto-approval and manual vetting of registrations. And, on top of that, our platform relies on some third-party services, such as <a href="https://auth0.com/">Auth0</a> and <a href="https://www.hubspot.com/">HubSpot</a>, and internal databases. Therefore, for our microservice architecture, it makes more sense to keep a good separation of concerns between APIs to have consistency in the way each API talks with each third-party service or database.</p><p>Now, the suggested improvement for the previous implementation would require collapsing those three requests into a single request optimised for the specific use case:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aXwxv0RFPrv2lnyf" /><figcaption><strong>Figure 2.</strong> Diagram of email validation with Management API</figcaption></figure><p>That way, the front-end pays the price of the networking latency only once and makes better use of the more powerful hardware of the back-end to compute the validation logic. Also, because the Management API is running in the same network as the other APIs, each call should be more efficient than if it was executed from the front-end. In this case, we are assuming that the API calls are HTTP-based but the Management API would allow the use of alternative, more reliable protocols, such as <a href="https://microservices.io/patterns/communication-style/messaging.html">messaging</a> or <a href="https://microservices.io/patterns/communication-style/rpi.html">remote procedure invocations</a>.</p><p>Another big advantage of moving the validation logic to the Management API is that implementing logging and monitoring on the back-end side is more robust than tracing events on the front-end. It also allows the implementation of retries, and other more advanced concepts, such as <a href="https://microservices.io/patterns/reliability/circuit-breaker.html">circuit breaking</a>, that you may be able to get out-of-the-box with the use of a modern <a href="https://servicemesh.es/">service mesh</a>.</p><h3>What we learnt</h3><p>Despite not having the chance to flesh out the whole spectrum of the Reg/Auth re-architecture project, I can say that the project was a success!</p><p>The customer support team has stopped receiving as many user requests as before. And not only that, for most of the incidents that have happened since then, the engineering teams have been able to get full traces of where the issues were for 90% of the incidents. There’s a newfound confidence in the platform.</p><p>From a technical perspective, the incorporation of the Management API into our microservice architecture has helped us significantly improve the performance of our front-end. More importantly, it has brought a powerful layer of control over the most complex parts of our business logic across the platform.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7a72f0b68e2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/apolitical-engineering/how-to-optimise-your-front-end-by-reducing-the-chattiness-to-apis-c7a72f0b68e2">How to optimise your front-end by reducing the chattiness to APIs</a> was originally published in <a href="https://medium.com/apolitical-engineering">Apolitical Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to migrate digital projects from WordPress to Contentful]]></title>
            <link>https://medium.com/apolitical-engineering/how-to-migrate-digital-projects-from-wordpress-to-contentful-f1be97b673d?source=rss----3a76c3396db5---4</link>
            <guid isPermaLink="false">https://medium.com/p/f1be97b673d</guid>
            <category><![CDATA[headless-cms]]></category>
            <category><![CDATA[contentful]]></category>
            <category><![CDATA[data-migration]]></category>
            <category><![CDATA[cms]]></category>
            <category><![CDATA[wordpress]]></category>
            <dc:creator><![CDATA[Renzo Rozza]]></dc:creator>
            <pubDate>Tue, 24 Aug 2021 08:08:30 GMT</pubDate>
            <atom:updated>2021-08-24T08:08:30.165Z</atom:updated>
            <content:encoded><![CDATA[<h4>The obvious and the not so obvious you need to know about moving content around</h4><p>It’s been a while since my last blog post about <a href="https://medium.com/apolitical-engineering/apolitical-building-the-people-api-finale-rest-1c7a2e53487b">Building a People API for a Growing Platform</a>, and a lot has happened since then. The <a href="https://apolitical.co/home">Apolitical</a> platform allows public servants across the globe to discover knowledge and learn from the community, and it continues to grow.</p><p>Let’s take a minute to talk about the context of this new blog post. Big changes were underway at the start of 2021 regarding <a href="https://en.wikipedia.org/wiki/Content_management_system">Content Management Systems</a> (CMS), driven by frustration with our self-hosted CMS’s inability to scale, and a desire to build and ship faster. The blog post about the <a href="https://medium.com/apolitical-engineering/a-journey-to-finding-the-right-cms-66bcb14dbfb1">Journey to Finding the Right CMS</a> has covered the reasons behind the decision-making process to adopt <a href="https://www.contentful.com/">Contentful</a> into Apolitical’s tech stack. As a result, the focus of this blog post will be to look at how the engineering team accomplished the migration of already existing digital projects from <a href="https://wordpress.org/">WordPress</a> to Contentful.</p><blockquote><strong>TL;DR</strong>: Do not underestimate the time and effort required to migrate digital projects. Start by designing your content model, then spend some time building internal tooling to handle the migrations. And finally, make use of the Contentful APIs to present the content on your website or any other channel. There is light at the end of the tunnel. And some trees.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hATDA2hNu69cgzQO" /><figcaption>Tunnel in The Smokies. Photo by Ryan Wallace. <a href="https://unsplash.com/photos/e7r0wTz3ZHU">Unsplash</a></figcaption></figure><h3>Getting started with Contentful</h3><p>This section guides you through some steps to help you get started with Contentful as well as providing useful resources to help you manage the projects successfully and smoothly.</p><p>If you are new to Contentful, there’s no better way to learn about it than by taking some of the free courses at the <a href="https://training.contentful.com/student/catalog">Learning Center</a>. Contentful has a very low barrier to entry: you can create your own account for free and start experimenting with it straightaway. The course <a href="https://training.contentful.com/student/path/752268-managing-content-at-scale">Managing Content at Scale</a> can be a great source of inspiration to understand how to use <a href="https://www.contentful.com/help/spaces-and-organizations/">Spaces</a> and <a href="https://www.contentful.com/developers/docs/concepts/multiple-environments/">Environments</a> on Contentful. Start by putting the focus on choosing the best space modelling strategy, and on using environments to create an agile development process.</p><p>Contentful spaces allow you to group all the related resources for a project together. Space modelling is the concept of utilizing spaces to design the best architecture for your project. A space is not only a collection of content, it can be configured individually using <a href="https://www.contentful.com/developers/docs/concepts/webhooks/">Webhooks</a>, API keys, <a href="https://www.contentful.com/developers/docs/concepts/locales/">Locales</a>, and more. There are different space modelling patterns, such as <em>one space to rule them all</em>; <em>separate space per project,</em> and <em>multi-tier</em>. At Apolitical, it was decided to implement the space modelling pattern of <em>one space to rule them all</em>, which was a perfect fit for all of our requirements, including content types and entries being reusable across projects that have the same localization needs, and multiple teams being able to collaborate across projects. From the expenses perspective, it is also important to bear in mind that because spaces are billed individually, this space modelling pattern is more affordable.</p><p>Now that you have seen different space architecture, it’s time to think about how to use environments to implement an agile deployment pipeline that adheres to <a href="https://en.wikipedia.org/wiki/CI/CD">CI/CD</a> best practices. Space environments are entities within a space that allow you to create and maintain multiple versions of the space-specific data, and make changes to them in isolation. By default, every space has one environment, called <em>master</em>. Additionally, multiple <em>sandbox environments</em> can be created. And <em>sandbox environments</em> start as exact copies of the <em>master</em> environment.</p><p>At Apolitical, it was required to host multiple <a href="https://en.wikipedia.org/wiki/Deployment_environment">Staging Environments</a> for testing, and, as a consequence, one <em>sandbox environment</em> for each of the staging environments was created. In addition, environment aliases were activated, causing the <em>master</em> to no longer be an environment but rather an alias for a different environment. In this case, the <em>master </em>environment initially pointed to <em>live-v0.0.1</em> and allowed serving the production content from it.</p><p>You might wonder: why would I do that? Well, there are lots of benefits from using environment aliases, such as minimizing downtime and allowing instant rollbacks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_WdgEG6rRLFgWDB2" /><figcaption>Promote an environment to master. Graphic by Contentful</figcaption></figure><p>Our biggest challenge was to automate keeping the staging environments synchronised with all the content that would be created day after day by the content team on the <em>live</em> environment. For this task, there is no built-in way of solving the synchronization process, and the engineering team decided to create an internal <a href="https://en.wikipedia.org/wiki/Command-line_interface">Command-line Interface</a> (CLI) tool to handle it. The CLI tool was implemented in <a href="https://nodejs.org/en/">Node.js</a> with the use of the <a href="https://github.com/contentful/contentful-management.js#readme">contentful-management</a> module, which allows you to use Contentful’s <a href="https://www.contentful.com/developers/docs/references/content-management-api/">Content Management API</a> (CMA) to expose a <em>recreate</em> command, which automatically deletes a staging environment and creates a new instance of it from <em>live</em>. The CLI tool was integrated with <a href="https://about.gitlab.com/">GitLab</a> CI/CD <a href="https://docs.gitlab.com/ee/ci/pipelines/schedules.html">scheduled pipelines</a> so that all the content types and entries are transferred from <em>live</em> to the staging environments nightly. It’s still very impressive how quickly and reliably Contentful can handle the environment recreation process.</p><p>Finally, another command was added to the CLI tool to backup the content from Contentful to <a href="https://cloud.google.com/products/storage">Google Cloud Storage</a> (GCS). The <em>backup</em> command was implemented with the use of the <a href="https://github.com/contentful/contentful-export#readme">contentful-export</a> module, which nightly exports everything from the <em>live</em> environment into a JSON file, and then uploads the file to GCS.</p><h3>Designing the content model</h3><p>If that sounded a bit discouraging and boring, don’t worry, here comes the fun stuff. In this section, you will delve into the content modelling design process. Depending on the circumstances, you may want to follow a strict <a href="https://training.contentful.com/student/path/752257-content-modeling-design-process">Content Modeling Design Process</a>, involving steps such as: agreeing on strategic objectives and creating a content model. However, in Apolitical’s case, the digital projects were already well defined and live on the platform, which allowed for this journey to be shorter, and the process could start straight from the creation of the <a href="https://www.contentful.com/help/content-modelling-basics/">Content Model</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*04rkd5vofgaj6-tQ" /><figcaption>Content modelling design process. Graphic by Contentful</figcaption></figure><p>In the beginning, as described in this related <a href="https://www.contentful.com/r/knowledgebase/contentful-vs-wordpress-vs-drupal/">blog post</a>, it’s difficult to switch from the traditional CMSes approach, where the content and code are still combined in web-centric frameworks, to the <a href="https://en.wikipedia.org/wiki/Headless_content_management_system">headless CMS</a>es approach, where the content is stored separately from the code used to build the presentation layer.</p><p>When thinking about content, it is easy to focus too much on where the content will live, leading to a fixation on the interface: a website, a mobile device, a digital screen. But this interface-centric thinking is what often leads to trouble, endless redesigns, siloed content, and wasted time and money.</p><p>Using content models can help you to separate the content from context (the interface or presentation layer). Start by taking a look at the <a href="https://training.contentful.com/student/path/752272-intro-to-content-modeling">Intro to Content Modelling</a> and <a href="https://training.contentful.com/student/path/752256-content-modeling-design-patterns">Content Modelling Design Patterns</a> courses to understand all the required and relevant concepts and vocabulary. The key to succeeding at creating your content model is breaking down the content into small, well defined and reusable pieces. The use of <a href="https://contentmodel.io/">contentmodel.io</a> was incredibly useful to visualise and iterate the content model for Apolitical’s digital projects.</p><p>The first content model was designed by the Apolitical engineering team for the <a href="https://apolitical.co/microcourses">Microcourses</a> digital project. It was not a simple content model. For example, the <em>Microcourse</em> content type includes multiple fields with nested content types such as the <em>Summary</em>, <em>Editions</em>, and <em>Sections</em>. And at the same time, the <em>Section</em> content type includes the field <em>Lessons </em>linked to another nested content type. The following image partially illustrates the mapping between the Microcourse content type and the Microcourse Overview page for one of the Mircorourses on the platform: <a href="https://apolitical.co/microcourses/en/strategic-thinking">Applying Strategic Thinking in Government</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NTe3ZXxgN0KXyx2c" /><figcaption>Microcourse Overview page and Microcourse content type mapping</figcaption></figure><h3>Building the content migration script</h3><p>Once you have designed and created the content model on Contentful, it’s time to write some more code. The focus of this section is the transfer of the content from source to target, or in other words, from WordPress to Contentful.</p><p>The migration scripts are exposed through the internal CLI tool, for instance through the <em>migrate-microcourse</em> command being implemented. There are numerous ways of storing your content on WordPress and even more ways to access the content. For example, content can be accessed through REST APIs, such as the Articles API on the Apolitical platform, or even by directly connecting to the database. Yet, to keep the blog post relevant to all readers, emphasis will not be placed on how to access the content, but rather on how to structure the migration script and how to reformat and convert the content.</p><p>The first problem is around how to reformat WordPress posts from HTML to markdown. To solve that, a helper function was implemented based on this <a href="https://ashcroft.dev/blog/script-migrate-wordpress-posts-contentful/">related blog post</a> and with the use of the <a href="https://github.com/mixmark-io/turndown#readme">turndown</a>, <a href="https://github.com/mixmark-io/turndown-plugin-gfm#readme">turndown-plugin-gfm</a> modules, and the <a href="https://github.com/andymantell/node-wpautop#readme">node-wpautop</a> module. Additionally, it is required to extract all the references to assets stored in WordPress and convert them into Contentful assets. You can imagine how many of the WordPress posts would contain images or any other media files. Those files would need to be uploaded to Contentful. The <em>asset.type.js</em> file handles uploading media files, and, in the same way, the <em>microcourse.type.js</em> file handles uploading the Microcourse content type. At this point, the concept of <em>.type.js </em>files needs to be introduced. The concept of <em>.type.js</em> files is an arbitrary structure designed to contain all the necessary logic that is required to upload individual content types. The following image partially illustrates the <em>microcourse.type.js</em> file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_HXQrwsA8a1e_T3v" /><figcaption><em>Microcourse.type.js</em> file</figcaption></figure><p>Each <em>.type.js</em> function exposes an object with the <em>build</em> function which handles the complete process, and internally, the <em>build</em> function would first execute the <em>preprocess</em> function and then the <em>upload</em> function:</p><ul><li>The <em>preprocess</em> function is in charge of parsing the inputs, content coming from WordPress and mapping the content to match the content type fields. In the case of fields with nested content types, calling the <em>build</em> function of the relevant <em>.type.js</em> file would make sure the nested entry is uploaded and available on Contentful before uploading the current one. This guarantees that the links between entries are in place.</li><li>The <em>upload</em> function is in charge of uploading the entries by calling the <em>uploadEntry</em> function which uses the CMA to upload and publish entries.</li></ul><p>Apart from that, the <em>assetModel</em> and <em>entryModel</em> would simply read the entry <em>sys.id</em> and create the JSON object required to link nested assets or entries.</p><h3>Presenting the content from apps</h3><p>You have made it to the last section! It is time for the most rewarding part of the migration process. All the content has now been stored on Contentful and all the benefits from using Contentful APIs will start to shine.</p><p>It is a good idea to study the different content delivery architectures and their optimal use cases. The <a href="https://training.contentful.com/student/path/752264-apis-and-delivery-architectures">APIs and Delivery Architectures</a> course covers everything you need to know. The frontend of the Apolitical platform is implemented with single-page <a href="https://reactjs.org/">React</a> apps, and those apps are bootstrapped with <a href="https://create-react-app.dev/">Create React App</a> (CRA). For that reason, with the use of the dynamic on-device delivery architecture, the apps directly make Contentful API calls and fully leverage Contentful’s <a href="https://en.wikipedia.org/wiki/Content_delivery_network">Content Delivery Network</a> (CDN). It is important to note that <a href="https://developers.google.com/search/docs/beginner/seo-starter-guide">Search Engine Optimisation</a> (SEO) support requires more effort when using this architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/0*rwfT2nfUL3msMIWR" /><figcaption>Dynamic on device delivery architecture. Graphic by Contentful</figcaption></figure><p>The <a href="https://github.com/contentful/contentful.js#readme">contentful.js</a> module can fetch the content by making use of Contentful’s <a href="https://www.contentful.com/developers/docs/references/content-delivery-api/">Content Delivery API</a> (CDA), which is very easy to integrate with React apps. However, at Apolitical, a wrapper function was internally developed to flatten the JSON objects returned by the module because they are cumbersome to work with, given that every entry contains system data that is rarely used.</p><h3>Conclusion</h3><p>This blog post has covered the obvious and the not so obvious of moving content around. You have taken a close look at the steps required in the process of migrating digital projects from WordPress to Contentful: getting started with Contentful; designing the content model; building the content migration script; and presenting the content from apps.</p><p>It would be very unfair to have come so far and to end the blog post without an explanation of our results at Apolitical. On one hand, it’s important to highlight that the migration process is not as easy as you may think it is. You should not underestimate the time and effort required to complete it. On the other hand, the user experience was notably improved by reducing the <a href="https://web.dev/interactive/">Time to Interact</a> (TTI) by half. The <a href="https://developers.google.com/web/tools/lighthouse">Lighthouse</a> reports showed an increase in performance of about 20%. The overall scalability and maintainability of the platform were improved. There is no more having to deal with database CPU usage spikes caused by the Articles API, as desired at the start of the <a href="https://medium.com/apolitical-engineering/a-journey-to-finding-the-right-cms-66bcb14dbfb1">Journey to Finding the Right CMS</a>.</p><p>Perhaps the most important benefit from the migration was that the content team workflow was completely revamped. The introduction of a new headless CMS with a great visual editor (the <a href="https://www.contentful.com/help/contentful-web-app-overview/">Contentful Web App</a>) was a great success and makes it really stand out. Some of the major improvements here include the ability for content to be previewed before publishing; the navigation and search of content run smoothly; localisation can be easily extended; and many more additional content management capabilities.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1be97b673d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/apolitical-engineering/how-to-migrate-digital-projects-from-wordpress-to-contentful-f1be97b673d">How to migrate digital projects from WordPress to Contentful</a> was originally published in <a href="https://medium.com/apolitical-engineering">Apolitical Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Windows Subsystem for Linux 2 with Docker Desktop]]></title>
            <link>https://medium.com/apolitical-engineering/windows-subsystem-for-linux-2-with-docker-desktop-4f766e7f5472?source=rss----3a76c3396db5---4</link>
            <guid isPermaLink="false">https://medium.com/p/4f766e7f5472</guid>
            <category><![CDATA[wsl-2]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[wsl]]></category>
            <category><![CDATA[how-to]]></category>
            <dc:creator><![CDATA[Charlotte Crabb]]></dc:creator>
            <pubDate>Mon, 01 Mar 2021 12:27:00 GMT</pubDate>
            <atom:updated>2021-03-01T12:27:00.237Z</atom:updated>
            <content:encoded><![CDATA[<h4>A step-by-step guide to setting up Windows Subsystem for Linux 2 and integrating Docker Desktop</h4><p>When I joined Apolitical, it was my first data science role — I couldn’t wait to get started. A month or so in and I was pretty comfortable working in my Windows dev environment, quietly pleased that I had finally conquered my inexplicable fear of the command line.</p><p>Despite this, there was a recurring theme causing me problems: not having Linux. In particular, in a Windows environment I was unable to easily spin up Docker containers, which we use to deploy code to our production environment. The solution? Windows Subsystem for Linux (WSL) integrated with Docker Desktop.</p><p>This blog post covers installation and setup of WSL 2, followed by how to integrate it with Docker Desktop.</p><h4><strong>Windows Subsystem For Linux</strong></h4><p>WSL enables you to run a Linux environment directly on a Windows operating system, so you can take advantage of Linux command-line tools, utilities and applications. At the time of writing, WSL 2 is the most recent version of WSL.</p><h4><strong>Docker Desktop</strong></h4><p>Docker Desktop is a piece of software that allows you to build containerised applications and services on your own computer. For production services that run in Docker containers, this is great for testing, since it means your development environment is very similar to the production environment.</p><h3><strong>Installing WSL 2</strong></h3><h4><strong>Step 1: Check prerequisites</strong></h4><p>The prerequisite for installation is Windows 10 with version 1903 or higher. You can check your Windows version by entering ver in Windows Command Prompt.</p><h4><strong>Step 2: Enable WSL and virtualisation</strong></h4><p>WSL and the Virtual Machine Platform are optional features on Windows. To enable them, first open PowerShell as Administrator. To do this, press the <strong>Windows Logo key</strong> to enter the search field in the taskbar, then type ‘PowerShell’, right click on the Windows PowerShell app and select ‘Run as administrator’.</p><figure><img alt="Opening Windows PowerShell as administrator" src="https://cdn-images-1.medium.com/max/347/0*9KVHOD1eMT4ankDq" /></figure><p>In PowerShell, run the following command to enable WSL:</p><pre>dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart</pre><p>Next, run this second command to enable the Virtual Machine Platform:</p><pre>dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart</pre><p>After running both of these, restart your computer.</p><h4><strong>Step 3: Download the Linux kernel update package</strong></h4><p>This step ensures you have the latest features installed for WSL. You can download the Linux kernel update package from the <a href="https://docs.microsoft.com/en-us/windows/wsl/install-win10#step-4---download-the-linux-kernel-update-package">WSL installation instructions here</a>. After downloading, run the package by double clicking on it, and select ‘yes’ to allow permissions.</p><h4><strong>Step 4: Set WSL 2 as default</strong></h4><p>To use WSL 2 as the default version of WSL, open PowerShell again and run:</p><pre>wsl --set-default-version 2</pre><h4><strong>Step 5: Install a Linux distribution</strong></h4><p>You can install a Linux distribution from the Microsoft Store. Open the Microsoft Store, search ‘Linux’ and select a distribution of your choice. On the distribution’s page, click ‘Get’ to install. On our team, we use Ubuntu. The most recent version of Ubuntu in the Microsoft Store at the time of writing is shown below.</p><figure><img alt="Ubuntu 20.04 LTS in the Microsoft Store" src="https://cdn-images-1.medium.com/max/1024/0*OgYIREEVi5LOnOhI" /></figure><h4><strong>Step 6: Launch your Linux distribution</strong></h4><p>The first time you launch your Linux distribution, it will ask you to create a username and password. Enter these to complete the setup of WSL 2.</p><p><strong>Note:</strong> It’s possible you may receive an error when you first launch your Linux distribution. It might look something like this:</p><figure><img alt="An Ubuntu console window showing an error on first launch" src="https://cdn-images-1.medium.com/max/840/0*idBtkYUxyV9iz2mQ" /></figure><p>In this case, check the error code (above, it’s 0x80370102) and refer to the handy <a href="https://docs.microsoft.com/en-us/windows/wsl/install-win10#troubleshooting-installation">troubleshooting section</a> in the WSL installation guide. On some computers you will need to enable virtualisation within the computer’s BIOS. How to do this varies with different computers and there are plenty of guides for this online, such as <a href="https://www.bleepingcomputer.com/tutorials/how-to-enable-cpu-virtualization-in-your-computer-bios/">this one</a>.</p><h3><strong>Installing Docker Desktop</strong></h3><p>Now that we have WSL 2 set up, we can install Docker Desktop and integrate it with WSL 2.</p><h4><strong>Step 1: Download Docker Desktop</strong></h4><p>Download Docker Desktop for Windows from <a href="https://hub.docker.com/editions/community/docker-ce-desktop-windows/">the Docker website</a>. Run the downloaded file and follow the installation instructions.</p><h4><strong>Step 2: Configure Docker to use WSL 2</strong></h4><p>Once installed, start Docker Desktop and navigate to <strong>Settings &gt; General</strong>. Check the box next to ‘Use WSL2 based engine’. Click ‘Apply &amp; Restart’.</p><figure><img alt="Selecting ‘Use WSL2 based engine’ in the General Settings tab" src="https://cdn-images-1.medium.com/max/1024/0*QplcilBu_VBHWGuX" /></figure><h4><strong>Step 3: Integrate Docker with your Linux distribution</strong></h4><p>Once Docker Desktop restarts, navigate to <strong>Settings &gt; Resources &gt; WSL Integration</strong>. Check the box next to ‘Enable integration with my default WSL distro’ and select any distributions on which you wish to integrate Docker with WSL. Click ‘Apply &amp; Restart’ to finish the integration of Docker Desktop with WSL.</p><figure><img alt="Enabling integration with the default WSL distro in the Resources Settings tab" src="https://cdn-images-1.medium.com/max/1024/0*KzAXipnshyzdEN5V" /></figure><h4><strong>A Note on Memory</strong></h4><p>You might find that you encounter ‘out of memory’ errors when using Docker with WSL 2. This could be because your Linux distribution has a limit on the amount of your computer’s RAM it can access. One way to resolve these issues is to create a swap file that will allow your Linux distribution to access additional RAM. You can find <a href="https://linuxize.com/post/create-a-linux-swap-file/">instructions for adding swap space here</a>.</p><p><strong>That’s it </strong>— this completes the setup of WSL 2 integrated with Docker Desktop. Happy developing!</p><h3><strong>Useful Links:</strong></h3><ul><li><a href="https://docs.microsoft.com/en-us/windows/wsl/install-win10">WSL installation guide</a></li><li><a href="https://docs.docker.com/docker-for-windows/wsl/">Docker Desktop installation with WSL2</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f766e7f5472" width="1" height="1" alt=""><hr><p><a href="https://medium.com/apolitical-engineering/windows-subsystem-for-linux-2-with-docker-desktop-4f766e7f5472">Windows Subsystem for Linux 2 with Docker Desktop</a> was originally published in <a href="https://medium.com/apolitical-engineering">Apolitical Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>